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
28d23e4278f8023fa6acc8eb1d17cea8907dd7c2
poppaw/tic_tac
/tic_tac_toe.py
UTF-8
1,116
3.703125
4
[]
no_license
import random def print_playing_board(lista): for item in lista: print(' '.join(item).center(40),'\n') def main(): #player1= input("Enter your name: ") players = ['player1', 'player2'] begginer = random.randint(0,1) print("Start player: ", players[begginer], '\n') '''tic_tac =...
true
de32ca2616dbffdc51773b4e2be31e8499855363
4ntonin/quiz
/BDD.py
UTF-8
611
2.765625
3
[]
no_license
import sqlite3 class BDD: def __init__(self, nom): self.conn = sqlite3.connect(f'{nom}.db') self.cur = self.conn.cursor() def get_cursor(self): return self.cur def requetesql(self, commande, variables=None): if variables: self.cur.execute(commande, variables) ...
true
3da3a41db086455a663990d65b0cb62777f4c205
lsrios/tcc-analu
/PlateScanner.py
UTF-8
6,597
3.109375
3
[]
no_license
# ========================================================== import cv2 # "Biblioteca" OpenCV import pytesseract # Módulo para a utilização da tecnologia OCR import time # "Biblioteca" nativa de Python para calcularmos quantos frames por segundo from PIL import Image # Importando o módulo Pillow para abrir a image...
true
4d752cc849e7076fc56dd01dbdebc1567482ab36
pinaki-das-sage/assignments
/app.py
UTF-8
2,281
2.65625
3
[]
no_license
import os from flask import Flask, render_template import pandas as pd from assignment5 import Assignment5 from assignment9 import Assignment9 from assignment10 import Assignment10 from assignment11 import Assignment11 from assignment12 import Assignment12 from assignment16 import Assignment16 from assignment17 impor...
true
165603f430c3f51bf3494fbc3b5a50e9e347037a
piexchange/datatypes
/datatypes/types/regex.py
UTF-8
510
3
3
[ "MIT" ]
permissive
import re import typing.re from .type import Type __all__ = ['RegexPattern'] class RegexPattern(Type): python_type = re.Pattern if hasattr(re, 'Pattern') else re._pattern_type typing_type = typing.re.Pattern @classmethod def parse(cls, value): if isinstance(value, (str, bytes)): ...
true
450e6a25d0f8f8d6f8e6d32d1796b397e3a6bd0f
rpm1995/LeetCode
/1057_Campus_Bikes.py
UTF-8
1,012
3.328125
3
[ "MIT" ]
permissive
import heapq class Solution: def assignBikes(self, workers: List[List[int]], bikes: List[List[int]]) -> List[int]: distances = [] for worker, (work_x, work_y) in enumerate(workers): distance = [] for bike, (bike_x, bike_y) in enumerate(bikes): manhattan =...
true
628883c53577d013a1c1296f1dfd93fa18b17dc1
ddecker618/practice-python
/passgen.py
UTF-8
697
4.03125
4
[]
no_license
import random #A function do shuffle all the characters of a string def shuffle(string): templist = list(string) random.shuffle(templist) return ''.join(templist) #Main program stars here uppercaseLetter1=chr(random.randint(65,90)) #Generate a random Uppercase letter (based on ASCII code) uppercaseLetter2...
true
9a3e5d7f0896b01a1b3a44158abcdc813d00e582
shreyaskar123/NextCare
/MotorQuantifications/Visualization.py
UTF-8
961
2.609375
3
[]
no_license
def create_plot(param_values, title_value, entity_value, figure_title): '''Creates separate plots from manually entered values''' param_plot = params[param_values].plot(figsize=(20,5), title=figure_title, grid = pref_grid_visible) param_plot.set_xlabel('Time (seconds)') param_plot.set_ylabel(title_value...
true
39b2e92f20967fa21fe90461aa35fb338bfb7441
yami-five/SPOJ
/_663.py
UTF-8
791
3.265625
3
[]
no_license
from math import pow def distance(n): points=[] for x in range(0,n): points.append(input('').split(" ")) points[x].append(pow(pow(float(points[x][1]),2.0)+pow(float(points[x][2]),2.0),0.5)) return points def sort(points,n): for x in range(0,n): for y in range(0,n): ...
true
b662f38e00e72ed640e33154c37087488068ecd4
srtfix/srtfix
/srtfix/srtfix.py
UTF-8
1,634
2.734375
3
[ "MIT" ]
permissive
import argparse import os from pathlib import Path from typing import List from typing import Iterable, List from termcolor import colored from srtfix.text import matching def p2s(*pathss: Iterable[Path]) -> List[str]: return sum([[ str(path) for paths in pathss for path in paths ]]...
true
aa184df31761946445adccc3207b44155336ea47
simondale/databricks-testing
/notebooks/source/dlt_workflow.py
UTF-8
2,357
2.578125
3
[ "MIT" ]
permissive
# Databricks notebook source from pyspark.sql.types import StructType, StructField, StringType, DoubleType, IntegerType from pyspark.sql.functions import when, col, array, array_union, lit, size, current_timestamp import dlt import pandas as pd @dlt.table(comment="Bronze airports data") def bronze_airport_data(): ...
true
dbccbc809568cb6939abf5b01cf3deed14ef2b83
danieljtait/funicular-expert-machine
/univarfem/fem.py
UTF-8
3,775
2.984375
3
[]
no_license
import numpy as np from .gaussquad import (IntervalGaussianQuadrature, RectangleGaussianQuadrature) class FEMSolver: """ Base FEM solver class. """ def __init__(self, mesh): self._mesh = mesh @property def mesh(self): """ Mesh on which to solve the problem. """...
true
63f7039c6d1034d6706b9e5d90f5498f3dd6e2a9
CandiceD17/Leetcode-Everyday
/NG_leetcode_prac/752.py
UTF-8
1,160
2.859375
3
[]
no_license
class Solution: def openLock(self, deadends: List[str], target: str) -> int: q = deque() visited = set() steps = 0 if '0000' not in deadends: q.append('0000') visited.add('0000') while q: size = len(q) for i in range(size): ...
true
700baab81ebfda27f54120238533be884960545a
twhughes/Script_My_Workout
/workout/workouts.py
UTF-8
1,053
3.125
3
[ "Apache-2.0" ]
permissive
import pyfiglet import caffeine from .progress import say, display, timed_rest, untimed_rest from .trainers import Rishi """ A 'workout' defines a full exercise regime. It consists of several 'programs', each containing a set of excercises executed in a `routine`. """ class workout(): def __init__(self, na...
true
2b92512b6b1a0e7a4423041d5e8b57c33af9274c
AleksandraMilic/traffic-light-optimization
/benchmarks.py
UTF-8
6,379
2.59375
3
[]
no_license
# -*- coding: utf-8 -*- """ Python code of Gravitational Search Algorithm (GSA) Reference: Rashedi, Esmat, Hossein Nezamabadi-Pour, and Saeid Saryazdi. "GSA: a gravitational search algorithm." Information sciences 179.13 (2009): 2232-2248. Coded by: Mukesh Saraswat (saraswatmukesh@gmail.com), Himanshu Mittal (emaili...
true
391520678bf816673e52f1de1a02b8118ac40988
jhyao/SOF_analysis
/analysis/cluster_tag_v1.py
UTF-8
4,690
2.734375
3
[]
no_license
""" step1: filtrate related weight step2: make weighted graph step3: adjust weight with adjust_weight_file step4: get laplacian matrix, get eigvecs step4: clustering using KMeans step5: draw graph, save file """ import functools import networkx as nx from scipy.sparse.linalg import eigs import matplotlib.pyplot as pl...
true
34a96e04b586dd8e9aea31708cbff938902d2aae
rotuloveio/CursoEmVideoPython
/Mundo2/Aula13/ex050.py
UTF-8
260
4.25
4
[]
no_license
# Desenvolva um programa que leia seis números inteiros e mostre a soma apenas daqueles que forem pares. s = 0 for i in range(0, 6): n = int(input(f'Digite o {i+1}º número: ')) if n % 2 == 0: s += n print(f'A soma dos pares é {s}.')
true
1a94c41df84107717990071433f656ae66d47012
rejithry/class
/algo2_misc/index.py
UTF-8
565
2.765625
3
[]
no_license
''' Created on Mar 19, 2012 @author: Rejith ''' def add_to_index(index,keyword,url): for i in index: if i[0] == keyword: if url not in i[1]: i[1].append(url) return index.append([keyword,[url]]) return index = [] add_to_i...
true
0ae51fb6c4775804e1a29ecf168b6501699fbb02
sophea/stop_start_ec2_instances_aws_cronjob
/lambda_handler.py
UTF-8
1,670
2.546875
3
[]
no_license
import json import boto3 import os #region = "ap-southeast-1" region = os.getenv('REGION') ec2 = boto3.client("ec2", region_name=region) def get_ec2_instance_ids(project, state): #print(project + ',' + state) ec2 = boto3.client("ec2", region_name=region) filters = [ { 'Name' : "tag:project", ...
true
94b6e2fa33193e2f209f6abb3fbbc83b0c9cbbf4
felipereyel/public-data-analysis
/q2/main.py
UTF-8
838
2.734375
3
[]
no_license
from utils.dataset_manipulation import get_dataset, generate_options, join_filter_dataset from utils.graph_builder import create_disper_graph filter_headers = ['Região', 'UF', 'Código do Município', 'Localização', 'Rede'] result_headers = ['TOTAL FUNDAMENTAL 8 E 9 ANOS', 'Total Aprovação Fundamental'] hora_aula = get...
true
e6fb40d0642034104996c1f111d6a09716b9fa92
sevithabhanu/Critical-Traffic-Accident-Prediction
/trafficapp/views.py
UTF-8
3,109
2.75
3
[]
no_license
# Libraries from django.shortcuts import render import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier ...
true
dd26ffd92e9d32ca2f9ce462571c2b9bc852ec8b
websvey1/TIL
/project_1/project_01/me/test.py
UTF-8
2,726
2.640625
3
[]
no_license
lunch = { '용성돌솥비빔밥':'054-474-7119', '별난짬뽕':'054-473-3040', '매콤돈가스':'054-472-2030' } # 1. string formatting with open('lunch.csv','w') as f: for item in lunch.items(): print(f.write(f'{item[0]},{item[1]}\r\n')) # 2. join with open('lunch.csv','w') as f: for item in lunch.items(): pri...
true
f7f035fdcf4d3c4e8ea422c8bc2c2ee762cf3994
mostafa-K-raihan/cp
/edu100/A.py
UTF-8
251
3.21875
3
[]
no_license
for _ in range(int(input())): a, b, c = map(int, input().split()) sum = a + b + c total_enhanced_shots = sum // 9 remaining_shots = sum % 9 if (remaining_shots == 0 and min(a, b, c) >= total_enhanced_shots): print('YES') else: print('NO')
true
66e0166376eb1ecc0ecfa0adf2a330a54efb4ac7
346644054/Smart-Mobility-Prediction
/ST3DNet/prepareData.py
UTF-8
44,729
2.640625
3
[]
no_license
import pandas as pd from datetime import datetime import os import six.moves.cPickle as pickle import numpy as np import h5py import time from utils import * from copy import copy def remove_incomplete_days(data, timestamps, T=48): # remove a certain day which has not 48 timestamps days = [] # available days...
true
513c462cccb814f53334811fd8473db3cd24cd1a
geonsangyoo/algorithm
/#5052/code.py
UTF-8
1,302
2.84375
3
[]
no_license
import sys DEBUG = True # DEBUG = False if DEBUG: f = open("#5052/input.txt") else: f = sys.stdin class phone_number: def __init__(self, number): self.number = number self.nextNumbers = {} self.end = False def get_number(self): return self.number def get_nextNumbers(s...
true
b8835a931304e1ccf20f1d1f0c75eabca131e1b5
vSahakian/kappabay
/run_wfDL.py
UTF-8
5,079
2.71875
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 31 15:52:42 2019 @author: vjs """ ## Runtime file for downloading waveforms #Now make synthetics for source/station pairs def run_parallel_dataDL(software_location,main_flatfile_path,mpi_flatfile_directory,ncpus,eventdir_unfiltered,eventdir_filter...
true
21dc82ad8f8b9e15cae341ae768df2eb8e5311ec
crystalattice/Fantasy_RPG
/Adv_Dark_Deep/Mount/basic_mount.py
UTF-8
619
2.859375
3
[]
no_license
from dataclasses import dataclass @dataclass() class Mount: """Basic information for character mounts, war dogs, etc.""" def __init__(self, mount_name="", mount_type="", mount_hp=0, mount_armour="", mount_ac=0,): self._mount_name: str = mount_name self._mount_type: str = mount_type sel...
true
4b350113c8399daf0caf70605798def6ed848907
stormstone/LEARN-PYTHON
/MINE_PY27/ThePracticeOfML/SeondEditionMaster/10-14.py
UTF-8
276
2.515625
3
[]
no_license
#10-14.py import cv2 fn="test3.jpg" myimg=cv2.imread(fn) img=cv2.cvtColor(myimg,cv2.COLOR_BGR2GRAY) newimg=cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,5,2) cv2.imshow('preview',newimg) cv2.waitKey() cv2.destroyAllWindows()
true
1eb3571b8027113028e5ae0d5f8551f567a48ff0
NiranjanRaaj/Python
/bin to hex.py
UTF-8
55
3.03125
3
[]
no_license
i=input() i=int(i,2) h=hex(i) print(h.replace('0x',''))
true
133e7f8bf6cf5c6cd2c01cbfa891d583b20f12e5
bkey/Utils
/currency_convert.py
UTF-8
384
2.59375
3
[]
no_license
import urllib2 import re import csv import operator import os URL = 'http://www.google.com/ig/calculator?hl=en&q=1' def convert(curr_from, curr_to): try: data=urllib2.urlopen( URL + curr_from + '%3D%3F' + curr_to).read() except urllib2.URLError: return None result = re.search(".*rhs: \"(...
true
ec310afc79fc04356a6e2209c2d5e7a1ad6b9ebe
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/4_operators/4.3_if-elif-else/5.py
UTF-8
370
3.78125
4
[]
no_license
""" Даны три различных целых числа. Напишите программу, которая находит среднее по величине число. """ a, b, c = int(input()), int(input()), int(input()) if a < b < c or c < b < a: print(b) elif b < a < c or c < a < b: print(a) else: if a < c < b or b < c < a: print(c)
true
c92c87b74aa6601d29eaee1cb740cbc6376cd4b0
BeyondEvil/AoC2017
/2017/day_14/solution.py
UTF-8
2,908
3.28125
3
[]
no_license
from collections import deque from itertools import izip_longest from functools import reduce from operator import xor class Node(object): def __init__(self, x, y, data): self.x = x self.y = y self.data = data self.neighbours = [] def find_neighbours(self, grid): if s...
true
353fc6de75a3d9ae5d323d1c4bad3c8e0c2b3d94
ChernelEvgeni/Web
/Task_1/venv/main.py
UTF-8
1,109
2.984375
3
[]
no_license
import json import networkx as nx import matplotlib.pyplot as plt def parse(json_file): graph = nx.Graph(); graph.add_nodes_from([i['idx'] for i in json_file['points']]) graph.add_weighted_edges_from([(i['points'][0], i['points'][1], i['length']) for i in json_file['lines']]) return graph, json_file["...
true
3fa78a8c44baf6592e00689024b6b99beff03b6c
khaoulabelahsen/MVA-AlteGrad
/lab6/code/part2/utils.py
UTF-8
2,102
2.9375
3
[ "MIT" ]
permissive
""" Deep Learning on Graphs - ALTEGRAD - Dec 2019 """ import scipy.sparse as sp import numpy as np def normalize_adjacency(A): ############## Task 9 A = np.array(A) n, p = A.shape A_tilde = A + np.ones((n, p)) D = np.sqrt(1/np.sum(A_tilde, axis=1)) d = np.diag(D) A_normalized = np.dot...
true
6d899a92620b34c3cd1f80a7e34fe769c7853f6c
Allan-Perez/insert-a-creative-name-here-2
/old/multiple.py
UTF-8
1,585
2.734375
3
[]
no_license
import argparse import logging import random from demo import ServerComms, ServerMessageTypes # Parse command line args parser = argparse.ArgumentParser() parser.add_argument('-d', '--debug', action='store_true', help='Enable debug output') parser.add_argument('-H', '--hostname', default='127.0.0.1', help='Hostname to...
true
5aac66f0bb4e1c79e02d8a49bfb7a2b3bb079c32
Edward-HE/SDUWH_DIP_2020
/Dip_func/gray_histogram.py
UTF-8
2,191
3.0625
3
[ "MIT" ]
permissive
import cv2 import matplotlib.pyplot as plt from io import BytesIO import numpy as np import PIL def method_choose(img, method): hist = None if method == 'hist_gray': hist = draw_hist_gray(img) elif method == 'hist_rgb': hist = draw_hist_rgb(img) elif method == 'hist_equal_gray': ...
true
abc86b4ae186ca6f1c1ee9e5989096322d7c5b4d
RodrigoSolorzano/Solucion-Ejercicio-2
/FinanzasApp.py
UTF-8
3,075
3.671875
4
[]
no_license
from tusFinanzas import Finanzas, Ingresos, Egresos # 1. iniciar un proyecto de finanzas personales con cuenta a 0.00 # 2. dar opcion para registrar un ingreso o un egreso # 3. si es un ingreso sumarlo a la cuenta # 4. si es un egreso restarlo a la cuenta # 5. verficar que si es un egreso y la cuenta esta a 0.0 debe ...
true
6cb518abb7165ec843484f94a29b114460d8eb98
PeyWn/tdda69
/kl/klib/lexer/token.py
UTF-8
1,651
2.90625
3
[]
no_license
class token: ''' Represent a token ''' Invalid = -4 UnterminatedString = -3 EndOfStream = -2 # Identifiers Identifier = 1 RuleVariable = 2 # Literals String = 10 Number = 11 # Special characters...
true
25ee8d66feb1244b2cfa7d05ff83064d422bbf64
jaqxues/AL_Info
/Cours_1ere/Chapter2/Ex2_3.py
UTF-8
1,413
4.0625
4
[]
no_license
def ackermann(m, n): if m == 0: return n + 1 if n == 0: return ackermann(m - 1, 1) return ackermann(m - 1, ackermann(m, n - 1)) def ackermann_optimized(m, n): """ Optimizing Ackermann by "Direct Computation" Calculating Ackermann more efficiently by replacing frequently calcula...
true
ec80cb91bb478eeeb7a8f5fe241465b01ba813e1
Philex5/codingPractice
/DrasticPlan/uniquePaths2.py
UTF-8
3,367
3.78125
4
[]
no_license
# -*- coding: utf-8 -*- # @Time : 2019/5/29 下午8:24 # @Author : Philex # @File : uniquePaths2.py # @Software: PyCharm """ 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径? 网格中的障碍物和空位置分别用 1 和 0 来表示。 说明:m 和 n 的值均不超过 100。 示例 1: 输入...
true
73557213fb55e1645e05e018950c2052c25bc9ef
liugongfeng/Offer66
/offer23.py
UTF-8
633
2.953125
3
[]
no_license
class Solution: def VerifySquenceOfBST(self, sequence): if len(sequence) == 0: return False root = sequence[-1] i = 0 for i, v in enumerate(sequence): if v > root: break for node in sequence[i:-1]: ...
true
710ca9cfcf34cda449b8ed38a278c64475ca7c7d
ChrisCarini/jetbrains-ide-release-dates
/release_date_fetcher/generate_markdown_files.py
UTF-8
2,666
2.953125
3
[ "Apache-2.0" ]
permissive
from typing import List import numpy as np import pandas as pd import requests from packaging.version import Version # curl -s "https://data.services.jetbrains.com/products?release.type=release" | jq '.[] | "\(.code) -> \(.name)"' IDES = [ "AC", # AppCode "CL", # CLion "GO", # GoLand "IIU", # Int...
true
a78ac6c774aa7817a4898bb83662bdbbe24f8d7c
madsaloise/speciale2020
/Skraldespand/CHMedGambit.py
UTF-8
4,598
2.921875
3
[]
no_license
from __future__ import print_function import math import scipy.optimize import scipy.stats class Solution(object): """ Generic object representing a strategy profile which is (part of) a solution of a game. """ def __init__(self, profile): self._profile = profile def __len__(self): ...
true
96eeaa837a810bd7dbcdbd826e3a68b4f1d163a8
jayhack/inventar.io
/inventario/messaging/mandrill_client.py
UTF-8
599
2.59375
3
[]
no_license
from mandrill import Mandrill from mandrill_utils import make_message from secrets import MANDRILL_API_KEY class MandrillClient(object): """ Class: MandrillClient ===================== Abstract class implementing patterns that both EmailClient and SMSClient will be using """ def __init__(self): self.client =...
true
4187c5ba338103353304c546d47b7a4cbea592c6
yuri-flower/GoogleSTEP2020
/week4/sns_moduled.py
UTF-8
1,928
3.8125
4
[]
no_license
# ある人からある人にたどり着けるか判定するプログラム # 同ディレクトリ下にlinks.txtとnicknamesを置いた上で from collections import deque list = [[] for i in range (54)] # 格人がフォローをしている人を格納 visited = [0 for i in range (54)] # その人を探索していない場合0, した場合1 dict = {} # 次に探索すべき人を格納するqueue d = deque() # nicknames.txtから名前と番号の辞書を作成 def makenamedict(dict): with open(...
true
33bfb2ce42c6332b598db4c8fc792a2550b03e80
meejah/txtorcon
/examples/hidden_echo.py
UTF-8
1,049
2.5625
3
[ "MIT" ]
permissive
from __future__ import print_function from twisted.internet import protocol, reactor, endpoints # like the echo-server example on the front page of # https://twistedmatrix.com except this makes a Tor onion-service # that's an echo server. # # Note the *only* difference is the string we give to "serverFromString"! cl...
true
c04827f8c8e4c79a855553181d02a220f96a35e0
ramonastef28/Raspberry_pi_motor
/motor_test.py
UTF-8
1,248
3.15625
3
[]
no_license
import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BOARD) # ===========================================================================^M # Raspberry Pi pin11, 12, 13 and 15 to realize the clockwise/counterclockwise^M # rotation and forward and backward movements^M # ===================================...
true
0fa92bc3035187171e06bcf47dc73675917cee79
Sync271/Self-Updating-FB-Post
/fbpost.py
UTF-8
869
2.578125
3
[]
no_license
import facebook import time import reactions import comments import requests from collections import Counter access_token = 'your_access_token' graph = facebook.GraphAPI(access_token=access_token) # graph.put_object( # parent_object = "me", # connection_name="feed", # message="Test#1") # feed = graph.get_con...
true
81092dff7ac7deb6eccc945271c9c29da5bc4987
sharmaji27/InterviewBit-Problems
/Trees/Remove Half Nodes.py
UTF-8
1,495
3.90625
4
[]
no_license
''' Problem Description Given a binary tree A with N nodes. You have to remove all the half nodes and return the final binary tree. NOTE: Half nodes are nodes which have only one child. Leaves should not be touched as they have both children as NULL. Problem Constraints 1 <= N <= 105 Input Fo...
true
1465ac66cdbc849c8d83d9cab9c2c0e8b7e8c5aa
Jecosine/python-couse
/3/1.py
UTF-8
762
3.9375
4
[]
no_license
import random, time def get_rand(n): random.seed(time.time()) r = [] while n > 0: n -= 1 r.append(random.randint(-100, 100)) return r if __name__ == "__main__": r = get_rand(20) print("Instaniate 20 random int:") max = r.max() min = r.min() sum = r.sum() a = sum...
true
e5b06107a6e2667f064ded97249aa64f7c2aec1a
ajaytani/python
/algo/stringCombinations.py
UTF-8
922
3.015625
3
[]
no_license
def stringCombination(S): output = ['']*len(S) countMap = {} i = 0 k = 0 uString = [] while i < len(S): if S[i] in countMap: countMap[S[i]] +=1 else: uString.append(S[i]) countMap[S[i]] = 1 i +=1 cnt = [] print(uString) for ...
true
a5a47e620a17578a37b197d325dd1904c7277376
bevishe/Leetcode
/leetcode/easy/demo58.py
UTF-8
266
3.171875
3
[]
no_license
import re class Solution: def lengthOfLastWord(self, s: str) -> int: pattern = '\S*\S' res = re.findall(pattern,s) return len(res[-1]) if len(res) != 0 else 0 if __name__ == '__main__': print(Solution().lengthOfLastWord('he kij '))
true
c9fa21bd10ecb378c7e080804e83f70fa3bdb967
git-guozhijia/Python006-006
/week03/ini_read.py
UTF-8
2,235
3.03125
3
[]
no_license
import configparser,pathlib from week01 import logging_t class read_ini_config(): def __init__(self): self.log = logging_t.log().mylog() self.path = str(pathlib.Path(__file__).parent.resolve()) self.file = f"{self.path}/config_file/config.ini" self.config = configparser.ConfigParser...
true
871c7ecbc8072d5948c5e3726bb3ff0b7abe44eb
SoheilKhodayari/Kaggle-aquire-valued-shoppers-challenge
/RFM_based_feature_extraction.py
UTF-8
5,513
2.765625
3
[]
no_license
######################################################################## # Task: This script generates appropriate features for the data. # # reads the .CSV files chunk by chunk to tweak memory # # limits and to gain speed. # # ...
true
47aa25df9bc3a32e4d8e7f87d476bd1b9d1d9a02
HansGiesen/hudson
/hudson/models/randomforest.py
UTF-8
4,159
3.0625
3
[ "MIT" ]
permissive
""" Random Forest Model Author: Hans Giesen (giesen@seas.upenn.edu) """ # Amount of time that we would like to spend on training in seconds TRAINING_TIME = 60.0 # Factor for slowing down updates of number of trees used by random forest UPDATE_FACTOR = 0.2 import logging import numpy as np import sys import time fro...
true
a3fb03c6ab7c052eb136106b948047751238cce0
exploringNewThings/ObjectDetection
/dataset/readers/COCOReader.py
UTF-8
3,145
2.671875
3
[]
no_license
import os import logging import json import pandas as pd from .ReaderBase import BaseReader from utils.timing import timeit class COCOReader(BaseReader): def __init__(self, categories="all"): super(COCOReader, self).__init__("MS-COCO Reader", categories) def readfile(self, filename, **kwargs): ...
true
eb19d1f56c947ac8a204a7b25376004cbc57f341
diogojapinto/ade-drugs-side-effects
/auxiliary/querypmid.py
UTF-8
629
2.859375
3
[]
no_license
import mysql.connector as mysql import sys def get_abstract(pmid): """ Retrieves the abstract for a given pmid """ print(pmid) cnx = mysql.connect(user='dpinto', password='dpinto', host='porto.fe.up.pt', database='medline') query = """SELECT article_title, abstract_text FROM medline_cit...
true
f65dbbfe4b619801f87ba41799aa4a3c32d0221b
ZaneRoberge/Year9DesignCS-PythonZR
/LoopDemo02.py
UTF-8
1,006
4.34375
4
[]
no_license
# loop demo structure is a structure that allows us to run a section of code a number of times. It is great for when we need to repeat a process it is #also great when we need to run a pattern print("0") print("1") print("2") print("3") print("4") print("5") print("*************************************") for i in ra...
true
040e964a30926d004d2124c917b7117d2cb53f58
WHO-A-U/Programmers
/python/주식가격.py
UTF-8
443
2.71875
3
[]
no_license
def solution(prices): answer,s=[0 for i in range(len(prices))],[] for idx,val in enumerate(prices): if len(s)==0: s.append([val,idx]); else: if s[-1][0] > val: while len(s)!=0 and s[-1][0] >val: answer[s[-1][1]]=idx-s[-1][1] ...
true
e1fce9f9601de88c501d04e58aac63ec14b9adc3
Reazul137/275th-prblm
/variables.py
UTF-8
41
3.109375
3
[]
no_license
name = "Reaz" age = 22 print(name, age)
true
603f3f09a22f7d47ff798de81017156fbb4c50bb
soura49/Python
/hackerrank/Arrays-DS.py
UTF-8
365
3.3125
3
[]
no_license
array_length = int(raw_input()) array_list = [0] * array_length final_list = [] bala = ' ' print input_list = raw_input().strip().split() j = len(input_list) - 1 if j+1 == array_length: for i in xrange(j+1): final_list.append(input_list[j]) j = j-1 else: print "can't have more items than the num...
true
8699e14fb6ea42cf0d93c80d74018e6af4e803aa
kiansweeney11/ca117-programming2
/Hailstone.py
UTF-8
112
3.3125
3
[]
no_license
#!/usr/bin/env python n = input() if n % 2 == 0: m = n / 2 else: m = (n * 3) + 1 print n , m
true
0387336850ac369387a94635259a18f65027b0a7
sillybbbbb/leetcode
/215.py
UTF-8
523
3.421875
3
[]
no_license
''' 215. 数组中的第K个最大元素 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。 示例 1: 输入: [3,2,1,5,6,4] 和 k = 2 输出: 5 示例 2: 输入: [3,2,3,1,2,4,5,5,6] 和 k = 4 输出: 4 说明: 你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。 ''' import random import List def findKthLargest(nums, k): nums = [3,2,1,5,6,4] k = 2 findKthLargest(nums...
true
0b6520e072d617b7fd029c300d290d1c19e49e4b
bbqgonewrong/Storm-Kafka-Mongo
/multilang/resources/splitbolt.py
UTF-8
628
2.90625
3
[ "MIT" ]
permissive
import storm class SplitBolt(storm.BasicBolt): # There's nothing to initialize here, # since this is just a split and emit # Initialize this instance def initialize(self, conf, context): self._conf = conf self._context = context storm.logInfo("Split bolt instance starting...") ...
true
ab14a7a2e5378def9871e62f59fd1d302f6e29d8
flbrack/disease-modelling
/Agent/AgentAgeProfileSIRQD.py
UTF-8
3,749
3.359375
3
[]
no_license
''' Many diseases affect people in older age groups more than younger age groups. This simulation implements this possibility inside a regular agent based SIRQD model. A population is created with two age profiles. Agents can be either old or young. The agents in the old population have a higher death rate. The results...
true
824a415655307eda5173259e019160aa5a7d79a3
June0619/python-algorithm
/section4/9_증가수열 만들기(그리디).py
UTF-8
1,372
3.4375
3
[]
no_license
import sys import time import random as r sys.stdin = open('input.txt', 'rt') start_time = time.time() n = int(input()) inputs = list(map(int, input().split())) lt = 0 rt = n - 1 max_value = 0 answer = '' # 반복 조건 # 1. 배열의 모든 값이 소진되지 않았어야 함(rt >= lt) # 2. lt rt 둘이 가르키는 값 중 하나는 최대값이어야 함 while lt <= rt: # 둘 다 대상일 ...
true
839eb570a396257f5aca17603eff8e38df3709ad
QI1002/exampool
/Leetcode/339.py
UTF-8
588
3.859375
4
[]
no_license
#339. Nested List Weight Sum def nestedSum(data): l = data.split(',') d = 0 s = 0 #print(l) for x in l: xx = x dd = d if '[' in x: while(len(xx) > 0 and '[' == xx[0]): xx = xx[1:] d += 1 dd = d if ']' in x:...
true
cb55e3a684f738bb1a89b7181db97c7d30f7097a
DrRic/GDDCPP
/code/GDDCPP05/Mnist.py
UTF-8
2,700
2.859375
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[1]: import random from ctypes import cdll,c_double,c_int,POINTER lib = cdll.LoadLibrary('./libmlpc.so') lib.add_x_data.argtypes = (c_int, POINTER(c_double)) lib.add_y_data.argtypes = (c_int, POINTER(c_double)) lib.get_x_data_size.restype = c_int lib.get_y_data_size.restype =...
true
b7c65781c38ef83592c610ce0260f687f3b2afaf
jkennedy-usgs/sgp-utils
/ingestor/cosmos.py
UTF-8
3,250
2.6875
3
[ "CC0-1.0", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
import pandas as pd from PyQt5.QtWidgets import QMessageBox DIST_CRITERIA = 0.002 SPEED_CRITERIA = 0.5 class CR_data: cosmos_fields = ['RecordNum', 'Date Time(UTC)', 'PTB110_mb', 'P4_mb', 'P1_mb', 'T1_C', 'RH1', 'T_CS215', 'RH_CS215', 'Vbat', 'N1Cts', 'N2Cts', 'N1ETsec ', 'N2ETsec ', 'N1T(C)'...
true
c3510f219be20a3efeb721588cac52f91ec15c1d
shkipan/pitcoin
/pitcoin/tx_validator.py
UTF-8
3,135
2.671875
3
[]
no_license
import binascii, base58, hashlib from transaction import Transaction from wallet import checksum, verify from script import Script from utxo_set import utxo_get_script def check_aval(trans): try: if (trans.sender == ''): trans.sender = str('0' * 34) if (len(trans.sender) > 35 or len(t...
true
d8a7d37a79ae8c87583c8609e7a876ec97b241e3
Chaojidahoufeng/TsinghuaBookCrawler
/main.py
UTF-8
5,324
2.703125
3
[]
no_license
# coding:utf-8 import sys import argparse import getpass import requests import re import os from urllib.parse import urljoin from auth_get import auth_get from download_imgs import download_imgs from img2pdf import img2pdf from utils import get_fmt def get_input(): """ 获得输入的各参数 :return: [u...
true
7be3cc0f9922d900965defaafe587d87f53858be
KaplenkoAnastasiia/python_course
/tasks/task02/task02.py
UTF-8
1,672
4.28125
4
[]
no_license
import math msg1 = "Enter base and height:" msg2 = "Enter 2 sides and angle(degrees) between them:" msg3 = "Goodbye!" welcomeMsg = "Welcome to the triangle area calculation tool." menuItems= f"""\nMenu: 1. Calculate triangle area by base and height 2. Calculate triangle area by 2 sides and angle between them 3. Exit"...
true
1dee652107177b21e26a2af98311064bad8e95cc
eric102004/Statistics_Final
/report_preprocess.py
UTF-8
7,839
2.5625
3
[]
no_license
import os import parameters from preprocess import Dataset import matplotlib.pyplot as plt import numpy as np class RDataset: def __init__(self): self.val_inc_set = parameters.full_val_inc_set self.net_income_dict = None self.count_dict = None self.val_inc_count = None self....
true
d40f75063633fe96ab6f6c684702de8ad63e8df9
S4CH/Algo101
/Day9/Valid Anagram/valid_anagram.py
UTF-8
269
3.25
3
[]
no_license
class Solution: def isAnagram(self, s: str, t: str) -> bool: ns, nt = len(s), len(t) if ns != nt: return False if ns == 0 and nt == 0: return True elif ns == 0 or nt == 0: return False return self.isAnagram(s.replace(s[0], ''), t.replace(s[0], ''))
true
b58a3cca7cc65000663f1c6174e1d98a43b118f2
nickmcadden/Kaggle
/NCAA/2016-17/code/massey_ratings.py
UTF-8
1,123
2.9375
3
[]
no_license
import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) # Input data files are available in the "../input/" directory. # For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory data_dir = '../input/' df_massey = ...
true
fd807b354afb0d612007fdd08ca8de6deb98f145
pichu0528/Python
/Mock Interview Problems/Stacks Queues and Deques/Implement a Queue -Using Two Stacks.py
UTF-8
1,118
4.1875
4
[]
no_license
''' Given the Stack class below, implement a Queue class using two stacks! Note, this is a "classic" interview problem. Use a Python list data structure as your Stack. ''' # Solution 1 class Queue2Stacks(object): def __init__(self): # Two Stacks self.stack1 = [] self.stack2 =...
true
c7274c8542d9fb41f29a99a6212d3e9133a4f9e6
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_116/1045.py
UTF-8
3,050
2.90625
3
[]
no_license
def solv(x): #if x!=5: # return #print array for k in xrange(4): #print 'checking raws' val=1 if array[k][0]!='T': temp=array[k][0] else: temp=array[k][1] if temp=='.': continue for l in xrange(4): i...
true
a4bc11965da7ec5799574f4cecd78b925d861b8f
AdarshNamdev/Python-Practice-Files
/OuterInnerClass.py
UTF-8
1,341
4.09375
4
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Mar 5 21:45:33 2021 @author: adarsh """ """ For More Refer: https://www.datacamp.com/community/tutorials/inner-classes-python """ class person(object): def __init__(self, name, age): self.name = name self.age = age day, month, year = str.s...
true
5aa0c0577d75fbb4a7bb53063732e7867a8c6dbf
agustinavila/Curso-Python-UNSAM
/Clase05/generala.py
UTF-8
3,849
3.8125
4
[]
no_license
#%% # imports import random from collections import Counter #%% # tira una cantidad de dados dada def tirar(cant_dados): tirada=[] for i in range(cant_dados): tirada.append(random.randint(1,6)) return tirada #%% # Funcion para comprobar si la tirada es una generala def es_generala(tirada): ...
true
1267681a5e33c2649baeb4c09d9ecb9fbd03e258
zhankq/pythonlearn
/fenkpython/02/2.4/bytes_test.py
UTF-8
442
4.1875
4
[]
no_license
#创建一个空的bytes b1 = bytes() #创建一个空的bytes b2=b'' #通过b前缀指定hello是bytes类型的值 b3= b'hello' print(b3) print(b3[0]) print(b3[2:4]) #调用bytes方法将字符串转换成bytes对象 b4 = bytes('我爱Python编程',encoding='utf-8') print(b4) #利用字符 串的encode()方法编码成bytes,默认使用utf-8字符集 b5 = "学习Python很有趣".encode("utf-8") print(b5) print(b5.decode("utf-8"))
true
34af8f81d9cc05bdacd843a5638d1dd33aeb7741
nanareyes/CicloUno-Python
/Acumuladores Contadores/5_ejercicio_contadores.py
UTF-8
369
4.1875
4
[]
no_license
# 5 ''' Diseñe un algoritmo que reciba números digitados por el usuario y al final imprima la suma de los números digitados, el programa debe terminar cuando el usuario digite 0 (cero) ''' numero = 1 suma = 0 while numero != 0 : numero = float(input("digite un número: ")) suma = suma + numero #respuesta...
true
2a893befd456183628270cb0623034b221838070
yaramohajerani/read-GRACE-harmonics
/gravity_toolkit/read_tellus_geocenter.py
UTF-8
7,256
2.953125
3
[ "CC-BY-4.0", "MIT" ]
permissive
#!/usr/bin/env python u""" read_tellus_geocenter.py Written by Tyler Sutterley (08/2020) Reads monthly geocenter spherical harmonic data files from GRACE Tellus Technical Notes (TN-13) calculated using GRACE/GRACE-FO measurements and Ocean Models of Degree 1 Datasets distributed by NASA PO.DAAC https://podaac...
true
4ef3f731c222e5bcf4c573dc44555647e5a9c5d5
SoniaFilozop/Python_programs
/suprematizm.py
UTF-8
2,248
2.84375
3
[]
no_license
import sys from PyQt5.QtWidgets import QWidget, QApplication, QLabel from PyQt5.QtGui import QPainter, QColor, QPolygon from random import randint from PyQt5.QtCore import Qt, QPoint class Example(QWidget): def __init__(self): self.colors = ['green', 'red', 'purple', 'blue', 'yellow', 'black'] ...
true
ab6e2af13b4000d808380a59d39b93b175f6934b
dglass710/Coin-Problem
/quads.py
UTF-8
9,764
3.484375
3
[]
no_license
import time from HumanTime import TimeAutoShort '''Usage: When creating a dadabase, simply call Frobenius(n) where n is the largest such d for <a,b,c,d> It will store one of four messages depending on 3 and 4 element reduction If gcd(a,b,c,d) != 1, it will say all four elements share a common factor (there...
true
0a94cba416ad90989ed2bc1c54870eebeb405ab6
justinkreft/research_scraper
/Project_instance.py
UTF-8
2,084
2.625
3
[]
no_license
__author__ = 'justinkreft' import sqlite3 class Project_instance: def __init__(self, scraped_project_url, project_title, date_scraped, days_left, current_investors, current_raised, project_goal, location, category, phase, full_scraped_description, funded): self.scraped_project_url = scraped_project_url ...
true
8eca16e251db20f5e9694fadf758bc73194b4874
jakemayeux/Prism-Software
/src/gcode-to-color.py
UTF-8
990
2.5625
3
[]
no_license
# Jake Mayeux # July 2017 # gcode-to-color.py import re import sys import getopt from os import walk infile = '' outfile = '' opts, extraparams = getopt.getopt( sys.argv[1:], 'f:') for o, p in opts: if o == '-f': infile = p if infile[infile.find('.'):] != '.gcode': print('.gcode files only') ...
true
81cafcf5e60939fad67a986945bf390f4d056d6f
andrgje/Project-1
/oppgave1d.py
UTF-8
681
2.78125
3
[]
no_license
import sys import numpy as np def genSolution(a, b, c, b_tilde): for i in range(len(a)-1): faktor = a[i]/b[i] b[i+1] -= faktor*c[i] b_tilde[i+1] -= faktor*b_tilde[i] for i in range(len(a)-1,0,-1): faktor = c[i-1]/b[i] b_tilde[i-1] -= faktor*b_tilde[i] for i in range(len(b_tilde)): b_tilde[i] = b_til...
true
9d9383fa2c7cbe62aa693fc33131f29ef6359a18
mobulture/Mobile-3d-Printing-Snippets
/PythonCodeSnippets/drawing test.py
UTF-8
2,442
3.59375
4
[]
no_license
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import cv2 as cv import numpy as np W = 400 def my_ellipse(img, angle): thickness = 2 line_type = 8 cv.ellipse(img, (int(W / 2),int( W / 2)), (int(W / 4), int(W / 16)), ...
true
b31aeab2ec76398623a4e43a95ed6d2d904158df
robertotejado/python
/Random_module.py
UTF-8
1,985
4.03125
4
[]
no_license
print("Random Module") import random print("imprime entero aleatorio entre 0 y 5") print(random.randint(0,5)) ############################### import random print("imprime numero de punto flotante aleatorio entre 0 y 100") print(random.random() * 100) ############################### import random print("Elige de...
true
662746cfef739ebd4123bf15e328d1f9b0d9d2ee
vijay-lab/FSDP2019
/Flask/Demo/server.py
UTF-8
1,230
2.75
3
[]
no_license
from flask import Flask, render_template, request, url_for app = Flask(__name__) @app.route("/home") def home_page(): return "<h1>Welcome to Forsk</h1>" @app.route("/view") def view_template(): return render_template("index.html") @app.route("/data/<name>/<age>") def get_data(name,age): output = {"Name":...
true
e686e079d471b4d0b9b9699770dcce99b7d21f3e
tonhathuy/PTS-clone-API
/filter/cold/cold.py
UTF-8
977
2.75
3
[]
no_license
import cv2 import copy import numpy as np import os from scipy.interpolate import UnivariateSpline def spreadLookupTable(x, y): spline = UnivariateSpline(x, y) return spline(range(256)) def coldImage(image): increaseLookupTable = spreadLookupTable( [0, 64, 128, 256], [0, 80, 160, 256]) decre...
true
541d1a3dcfa586a0ebbd59cac0d3b7a86399e3df
SRG08/DesignPatternsInPython
/BehavioralPatternsInPython/Mediator.py
UTF-8
1,540
3.375
3
[]
no_license
''' Credits: seanwasere ytbe ''' # With the mediator pattern communication between the objects are encapsulated within a mediator object. # Objects communicate with each other rather than communicating directly with each other. # Analogy: Bulk Message notification from abc import ABCMeta , abstractmethod class Met...
true
593707fb36dc70d55bb13fc80575fcc106598499
Brian0009/Restaurant-Distri-II
/Protagonista.py
UTF-8
2,770
3
3
[]
no_license
#--------------------------------------------------------------------------- import pygame from Objetos import Objeto #---------------------------------------------------------------------------******** class protagonista: #--------------------------------------------------------------------------- def __init...
true
db23fc4f3c90a9b57007a6bba1db73da60d092de
Jianqiang/tmp
/seg2char.py
UTF-8
521
3.046875
3
[]
no_license
# # seg2char.py # import codecs import sys print('\n>>>Converting segmented sentences into white-spaced character sentences') print('\n@Arg: 1. input_segmented_corpus, 2.output_char_corpus') print('\nReading segmented corpus from ', sys.argv[1]) f=codecs.open(sys.argv[1],'rU','utf-8') charSeq=[' '.join(''.join(line....
true
0513fe9548e83e75fdf8be85dec57f4e4132e71d
atomec-project/atoMEC
/atoMEC/staticKS.py
UTF-8
56,495
2.9375
3
[ "BSD-3-Clause" ]
permissive
""" The staticKS module handles time-indepenent KS quantities such as the KS orbitals. This module is a 'workhouse' for much of the average-atom functionality. Computation of static KS quantities is designed to be quite general. The main assumption used everywhere is that we have a logarithmically spaced grid. Classe...
true
ca60cd299f99144f612cfb4bdf744a82bc375bb5
Jayshri-Rathod/loop
/weird.py
UTF-8
299
3.484375
3
[]
no_license
# NUM=int(input("enter number")) # i=0 # while i<1: # if NUM%2==0 and NUM>=2 and NUM<5: # print("Not Weird") # elif NUM%2==0 and NUM>=6 and NUM<=20: # print("Weird") # elif NUM%2==0 and NUM>20: # print("not Weird") # else: # print("weird") # i+=1
true
abec17a42152fea74a9dc10c8d671ee9d369e480
Schult1/gau
/geo_api_utils/api/inrix.py
UTF-8
4,048
3.09375
3
[]
no_license
"""Functions for INRIX Traffic APIs. See the link http://docs.inrix.com for documentation. Json usage is recommended. """ import os from datetime import datetime, timedelta import json import requests class ApiCall(object): """Use to call INRIX APIs in python. Vendor and consumer ids must be set as environ...
true
d055088853d9c3d02dec5201e985fe88dc9ed6f5
anoken/maix_maniax
/03_maixpy_basic/08_numpy_like_calcurate_ulab.py
UTF-8
1,309
3.046875
3
[]
no_license
## Copyright (c) 2019 aNoken import ulab as np import random clock = time.clock() a = [] b = [] for i in range(100): a.append(random.random()) b.append(random.random()) print("a=",a) print("b=",b) c = [] for i in range(100): c.append(0) #Normal Calculate Plus start = time.ticks_us() for i in range(100):...
true
8114032b1511e973b40a7b5659a2c9310a4ba83c
sm44500/WizualizacjaAlgorytmow
/WizualizacjaAlgorytmow/Widgets/NodZWidget.py
UTF-8
2,776
2.578125
3
[]
no_license
from PyQt5.QtWidgets import QGridLayout, QLabel from PyQt5.QtCore import QPointF from Snapshot import Snapshot from Node import Node from Widgets.BaseWidget import BaseWidget import NodZ.Main as nodz_main class NodZWidget(BaseWidget): """ Widget wizualizacji opartej na bibliotece NodZ. Parametry: parent - widge...
true
b86f4ef06c578f2672a068156574c9de1885e385
MohAhm/mancala
/player.py
UTF-8
635
3.296875
3
[]
no_license
from move import Move class Player: def __init__(self, player): self.player = player def turn(self): # Return the player whose move it is in this state return self.player def other(self): return Player(1) if self.player == 2 else Player(2) def holes(self, board): ...
true