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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
566e40984a3403a78906bda753981b785e5ab9fa | Python | mbhs/mbit | /archive/2021s/solutions/AppleOrchard.py | UTF-8 | 312 | 2.765625 | 3 | [] | no_license | from sys import stdin, stdout
n, m, x, y, a, b, c, d = (int(x) for x in stdin.readline().split())
def ans(n, m):
global a, b, x, y
return max(0, a-n)*x + max(0, b-m)*y
best = 10**10
for trade in range(-20000, 20000):
best = min(best, ans(n-c*trade, m+d*trade))
stdout.write(str(best) + "\n") | true |
06a1cdfc3d07fe2bda067a95ed494717ec8ebb57 | Python | JesusGuadiana/Nansus | /functions/pushOperand.py | UTF-8 | 1,354 | 2.5625 | 3 | [] | no_license | import sys
def push_operand_to_stack(current_program, identifier, index = 0):
#if current_program.current_dim == 0:
operand = current_program.func_directory.get_function_variable(current_program.scope_l, identifier)
if operand is None:
operand = current_program.func_directory.get_function_variable(current_prog... | true |
474941dae06f79bda21d44e4ec6c11e79820631b | Python | ivoryli/myproject | /class/phase1/project_month01/game2048_01.py | UTF-8 | 3,975 | 3.625 | 4 | [] | no_license | '''
2048核心算法
'''
#-------------------------------------------------------------------------------------------------
#练习1:定义函数,将零元素移动到末尾
#20 20 --> 2200
#02 20 --> 2200
#myself ok
# def move_zero_right(L):
# for x in range(len(L) - 1):
# for y in range(x + 1,len(L)):
# if L[x] == 0:
# ... | true |
c151bde9351f1a5c958ef0c2803b6950b19e5766 | Python | takaratruong/Intelligent-Tutor-System-for-Algebraic-problems | /additional code used for the project/BankGenerator.py | UTF-8 | 822 | 2.890625 | 3 | [] | no_license | import sys
import FeatureExtractor
import csv
from csv import reader
KEY = "key"
VALUES = "values"
def import_feature_to_bank():
dict_map = FeatureExtractor.bins
w = csv.writer(open("data/problemBank.csv", "w"))
for key, val in dict_map.items():
w.writerow([key, val])
def update_feature_metrics... | true |
aa1c3af5bf6c659bb351f77aed492d51d5dbdb05 | Python | Clint-Portfolio/Graph-coloring | /Code/generate_random_valid_graph.py | UTF-8 | 1,426 | 2.953125 | 3 | [] | no_license | import sys
from helpers import generate_random_country, provinces, country_to_number, cost
if __name__ == '__main__':
countries, neighbors = provinces(sys.argv[1])
neighborlist = country_to_number(countries, neighbors)
full_transmitter_list = ["A", "B", "C", "D", "E", "F", "G"]
transmitter_cost_list = ... | true |
9b0db4121f601c48fd81e86c97aa1c4c641d0f51 | Python | krist7599555/2110101 | /03_P.py | UTF-8 | 2,584 | 3.109375 | 3 | [] | no_license | # 03_P1
from operator import mul
from functools import reduce
def fac(n): return reduce(mul, range(1, n + 1))
print(fac(int(input())))
# 03_P2
from operator import mul
from functools import reduce
def fac(n): return reduce(mul, range(1, n + 1))
n, k, cm = map(int, input().split())
print (fac(n) // fac(n-k) // fac(1 ... | true |
afeaa7e6babdf4dcc2c1ab7cb42c190ae9da8d3a | Python | reasonsolo/zchess | /chess/state.py | UTF-8 | 1,711 | 3.1875 | 3 | [
"MIT"
] | permissive | # ref http://mcts.ai/code/python.html
from chess.board import Board
import itertools
class InvalidActionError(Exception):
pass
class Action:
def __init__(self, piece, to):
self.piece = piece
self.piece_code = str(self.piece)
self._from = (self.piece.x, self.piece.y)
self._to = ... | true |
bec433367f0e1ed5b12a1c0420f0a5a7dc263a3e | Python | JosephLipinski/LeetCode-Problem-Solutions | /Median.py | UTF-8 | 1,612 | 3.03125 | 3 | [] | no_license | class Median:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
import numpy as np
m = nums1
n = nums2
len_m = len(m)
len_n = len(n)
total_len = len_m + len_n
if total_len == 2:
if m != [] and n != []:
r... | true |
d7bdceb2e45518dba303ad4cd0d182a31a91af4e | Python | Tvo-Po/algorithms | /algotest/test_insort.py | UTF-8 | 804 | 2.71875 | 3 | [] | no_license | from .test_sort import BaseSortTestCases
from algo.insort import insert_sort
class TestInsertSort(BaseSortTestCases.TestSort):
sorting_function = {'foo': insert_sort}
def test_amount_of_operations(self):
insert_sort_amount_operations = (self.STRING_ARRAY_AMOUNT_ELEMENTS ** 2 +
... | true |
0846e39a59b6e33eb41d8c4369bf8f2edb22192d | Python | orange-eng/Leetcode | /easy/1523_Count_Odd_Numbers.py | UTF-8 | 532 | 3.359375 | 3 | [] | no_license |
# 递归法
# 会超时
# class Solution:
# def countOdds(self, low: int, high: int) -> int:
# if low == high:
# if low % 2 == 1:
# return 1
# else:
# return 0
# mid = (low + high)//2
# return self.countOdds(low,mid) + self.countOdds(mid + 1,high... | true |
e8b01c7038016f74cc3258e97f125921edb85f56 | Python | Hazeliii/DeepLearningClassWork | /MYWORK/work2/aaa.py | UTF-8 | 9,317 | 2.71875 | 3 | [] | no_license | # coding=utf-8
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.utils import plot_model
from tensorflow.keras import Sequential,Model
from tensorflow.keras.layers import Dense, Flatten, Conv2D, concatenate,Input,add
import numpy as np
import os
num_classes=19
#由于需要本地读取MN... | true |
e4d1b524314fa36ccc70799a513cc9b2c69dd544 | Python | WengTzu/LeetCode | /Algorithm/29_Divide_Two_Integers/29_fast.py | UTF-8 | 1,216 | 3.40625 | 3 | [] | no_license | class Solution(object):
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
quotient = 0
sign = 1
if divisor < 0:
divisor = -divisor
sign = -sign
if dividend < 0:
... | true |
77ac6bcf6af297270b35f39c190b506f1a80e28f | Python | crackkillz/pokemonBatch | /assets/sprites/image_processorBACK.py | UTF-8 | 1,357 | 3.296875 | 3 | [] | no_license | '''
Description: Converts Gen I pokemon sprites to text for pokemonBatch
Author: Soda Adlmayer
Date: 2017.02.26
'''
from PIL import Image
#set filepath
'''
print ("POKEMON NAME")
poke = input(":")
print ("BACK SPRITE OR FRONT SPRITE (B/F)")
x = input(":")
if x == 'B' or 'b':
end = '_backSprite'
elif x =... | true |
d097baaa2970334a6eb86925e736e82f442d2249 | Python | adityamagarde/TTH | /BaggageFitment/baggageFitmentIndex.py | UTF-8 | 1,315 | 3 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 14 19:17:43 2018
@author: ADITYA
"""
#BAGGAGE FITMENT INDEX:
import cv2
import serial
import numpy as np
#as soon as the bag crosses IR
arduinoData = serial.Serial('com29', 9600) #Here com29 is the port and 9600 is the baud rate
while(1 == 1):
myData = (ardui... | true |
7de8c5676c23e27450e2e586e4964677a57b1da5 | Python | ozericyer/class2-module-assigment-week05 | /battleship/WEEK5-Q6(calculator using try except).py | UTF-8 | 1,562 | 4.46875 | 4 | [] | no_license | #print out the options you have
print("Welcome to calculator")
i=1
while i==1: #We set while loop for ask choices again.
print("1)Addition 2)Subtraction 3)Multiplication 4)Division 5)Quit calculator")
choice = input("choose your option: ") #print out the options you have
try: #We use try-except fo... | true |
bd9e7795cfb6c119b9267e9bbf436a76681dcb61 | Python | dair-iitd/TourismQA | /src/custom/process/Processor2.py | UTF-8 | 2,196 | 2.984375 | 3 | [
"Apache-2.0"
] | permissive | # https://arxiv.org/pdf/1909.03527.pdf
# Extracting entities for post
import nltk
from fuzzywuzzy import fuzz
from typing import Dict, List
from collections import defaultdict
class Processor:
def __init__(self, cities: List[str], city_entities: Dict[str, Dict[str, dict]], neighborhood_words: List[str]) -> None:
s... | true |
283d8417a79527663a3a0764272deb275b1e98bb | Python | predsci/CHMAP | /chmap/data/corrections/degradation/dev/05_aia_timedepend_standalone_example.py | UTF-8 | 3,990 | 3.234375 | 3 | [
"Apache-2.0"
] | permissive | """
Script to load in individual AIA 193 FITS files specified by the COSPAR
ISWAT team and perform our LBC transformation and EZseg detection directly
on the file.
** RUN THIS SCRIPT USING THE CHD INTERPRETER IN PYCHARM!
"""
import numpy as np
import json
import scipy.interpolate
import astropy.time
# --------------... | true |
aa95c4ee531eeb8ec3f7cebb7c587b390000b39f | Python | karan2808/Python-Data-Structures-and-Algorithms | /Arrays/PartitionEqualSubsetSum.py | UTF-8 | 1,316 | 3.578125 | 4 | [
"MIT"
] | permissive | class Solution:
def canPartition(self, nums):
sz = len(nums)
if sz == 1:
return False
# find the total sum
sum_ = 0
for i in range(sz):
sum_ += nums[i]
# if the sum is not divisible by 2 return false
if (sum_ % 2) != 0:
... | true |
03c22d111e37687a3025c04fb7765b10e8612b61 | Python | bigdata202005/PythonProject | /Selenium/test2.py | UTF-8 | 455 | 2.796875 | 3 | [] | no_license | import os
import time
import cv2
# pip install opencv-python
# 다운받을 이미지 url
url = "https://dispatch.cdnser.be/cms-content/uploads/2020/04/09/a26f4b7b-9769-49dd-aed3-b7067fbc5a8c.jpg"
# time check
# start = time.time()
# curl 요청
os.system("curl " + url + " > test.png")
# 이미지 다운로드 시간 체크
# print(time.time() - start)
#... | true |
3525b72918a5f83e5f4cee57be21d62467700e00 | Python | DrakeMistBorn/Asynchronous-Python-Client-Server-Chat | /root/client_v2.py | UTF-8 | 4,160 | 3.34375 | 3 | [] | no_license | import asyncio
import time
def close():
"""
Function used to close the connection between the client and the server.
"""
print('[!] Closing connection')
time.sleep(1)
print('[!] Exiting')
time.sleep(1)
print("------------- Connection Closed -------------\n")
d... | true |
bc5fe5a787d1060aa6afe5a44e41ada38356027e | Python | steffejr/ExperimentalStimuli | /PartialTrialDIR/Scripts/PsychoPyTask/FileSelectClass.py | UTF-8 | 849 | 2.6875 | 3 | [] | no_license | from PySide import QtGui
# This is used to select the file(s) of interest
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
#self.initUI()
def initUI(self):
self.btn = QtGui.QPushButton('Dialog', self)
self.btn.move(20... | true |
364bd4f2871a0735cb09e7b656429b313c2079a7 | Python | jzsiggy/python-server-client | /test_request.py | UTF-8 | 540 | 2.796875 | 3 | [] | no_license | import requests
import random
import time
import requests
import json
import sys
def randomize():
bool = random.choice([True, False])
return bool
while True:
# time.sleep(0.1)
bool = randomize()
for i in range(10):
bool = str(bool)
try:
payload = {'cam0'... | true |
2cbdfb1664ba177a2dba497a11e8c6cc20ae046e | Python | Sindhu983/Dictionary | /saral7.py | UTF-8 | 283 | 2.96875 | 3 | [] | no_license | dic={
"first":"1",
"second": "2",
"third": "1",
"four": "5",
"five":"5",
"six":"9",
"seven":"7"
}
result={}
for key,value in dic.items():
if value not in result.values():
result[key]=value
print(result)
| true |
a77c3d9f0b9817a64d51ac4cdd643003783a7ceb | Python | iitzex/tsedraw | /crawl.py | UTF-8 | 6,562 | 2.796875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import csv
import time
import logging
import requests
import argparse
from lxml import html
from datetime import datetime, timedelta
from os import mkdir
from os.path import isdir
class Crawler():
def __init__(self, prefix="data"):
""" Make directory if not exist when initialize ""... | true |
7f4aa05464dc39b98ce020d7c5e424adc0c9fa9d | Python | charliephsu/bkbdrs_first_load | /ref_image.py | UTF-8 | 2,767 | 2.671875 | 3 | [] | no_license | import csv
import os
from shutil import copyfile
import re
infile = 'saved_output/out_with_id.csv'
img_src_dir = 'orig_data/attachments/bbdir_entry'
out_image_dir = 'saved_output/images/'
image_load_file = 'saved_output/image_load.tsv'
image_prefix = 'directory/'
def read_id_from_table():
data_old_id = {}
... | true |
82386828e06a85350e834c807cd003896a97446e | Python | georgiedignan/she_codes_python | /Session2/conditionals_exercises.py | UTF-8 | 747 | 3.453125 | 3 | [] | no_license | #Exercise 1
# moths_in_house = bool(input("Are there moths in the hosue? "))
# if moths_in_house == True:
# print("Get the moths")
# else:
# print("No threats detected")
#Exercise 2
# light_color = "red"
# if light_color is "red":
# print("correct")
#Exercise 3
#Exercise 4
# height = 164
# if heigh... | true |
48ab208577eae9346735afe1503d56f9680649a2 | Python | xyztank/Appium_Test | /page_objects/base_page.py | UTF-8 | 2,925 | 2.90625 | 3 | [] | no_license | from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from appium.webdriver.common.touch_action import TouchAction
from appium.webdriver.common.multi_action import MultiAction
from locators.iOS.siri_locators import SiriLocators
class BasePage(object... | true |
ef4cfb63a271d80fdfde22ff912cc866c49f344e | Python | whooie/scripts | /random_select.py | UTF-8 | 2,674 | 2.921875 | 3 | [] | no_license | #!/usr/bin/python2
# random_select.py
import os
import random
import getopt
import sys
#pDir = os.path.dirname(os.path.realpath(__file__))
pDir = os.getcwd()
ask1 = True
ask2 = True
save = ""
isDone = "n"
isFirst = True
listAll = False
help = "Usage: \033[1mrandom_select.py\033[0m [ -n \033[4mnum\033[0m ] [ -P ]\n ... | true |
ea801404650045bb1eedc8a06f10d8e06e33b2b8 | Python | MatthewHallPena/FlightSoftware | /drivers/power/HITL_testing/HITL_table_test.py | UTF-8 | 4,741 | 2.625 | 3 | [] | no_license | # Commands we want to test on the HITL table in SP2020
import power_controller as pc
import power_structs as ps
import time
HITL_test = pc.Power()
ps.gom_logger.debug("Turning off all outputs")
OUTPUTS = ["comms", "burnwire_1", "glowplug_2", "glowplug", "solenoid", "electrolyzer"]
for i in range(0, 6):
HITL_test... | true |
b8946ba9f9c81c79c3bf51295c428c7a17586215 | Python | leohanwww/Python-Scripts | /keras_fashion_mnist.py | UTF-8 | 1,114 | 2.828125 | 3 | [] | no_license |
import tensorflow as tf
import keras
import numpy as np
import matplotlib.pyplot as plt
fashion = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneak... | true |
bef4ec5f48743ef1ad4551e2079746c26ba8953e | Python | Harsha2319/Estimation-of-Rainfall-Quantity-using-Hybrid-Ensemble-Regression | /codes/Main - BAG WA.py | UTF-8 | 1,623 | 2.609375 | 3 | [] | no_license | import pandas as pd
from sklearn.metrics import mean_squared_error as mse
from sklearn.metrics import mean_absolute_error as mae
from sklearn.metrics import median_absolute_error as mdae
from sklearn.metrics import explained_variance_score as evs
from sklearn.metrics import r2_score as r2
from itertools import co... | true |
a0182be7e619f5bc16119879d11fb3f65e43a08d | Python | diedrebrown/pfch-spring2020-blue | /Code/Blue_GetRijksmuseum2-1.py | UTF-8 | 2,686 | 3.21875 | 3 | [
"MIT"
] | permissive | # Blue at the Rijksmuseum - Get Data
# This code is based on lessons from Matt Miller's INFO 644 Programming for Cultural Heritage Course at Pratt Institute
# Objectives:
# 1. Get information about blue objects at the Rijksmuseum using the Rijksmuseum API.
# 2. Store information as text dictionary.
# 3. Access th... | true |
8da95bc87a2b2f73f7c7b1e29ca13fbd02f3c374 | Python | masfell/AAyMineria | /Práctica 6/Parte 2.py | UTF-8 | 5,451 | 2.625 | 3 | [] | no_license | from process_email import email2TokenList
import codecs
from get_vocab_dict import getVocabDict
import numpy as np
import os
from sklearn import svm
import matplotlib.pyplot as plt
vocab_dict = getVocabDict()
def convertToIndices(token):
indicesOfWords = [vocab_dict[t] for t in token if t in vocab_dict]
re... | true |
a28385f19bc05f9fd5e634091292eb5df0ff6253 | Python | abbalcerek/nbd4 | /zadanie11/rozwiazanie.py | UTF-8 | 1,302 | 2.9375 | 3 | [] | no_license | #!/usr/bin/env python
from datetime import datetime
import string
import riak
# initialize riak client
client = riak.RiakClient(pb_port=8087, protocol='pbc')
marleen = {'user_name': 'marleenmgr',
'full_name': 'Marleen Manager',
'email': 'marleen.manager@riak.com'}
# create new bucket
myBucket ... | true |
5b4fcb433d8aca94169fb7f1b0018d61a637d6fd | Python | ludansir/py290_course | /py290_魯業群_hw3.py | UTF-8 | 2,885 | 3.0625 | 3 | [] | no_license | text = '''2015年7月21日蘋果公司發表2015年第二季財報,Apple Watch的銷售狀況和營收與iPod、
Beats耳機和機上盒化為「其他產品」統計,蘋果公司未公開這款產品的具體銷售狀況,各類研究機構對於
Apple Watch的銷量評估也大相徑庭,單季銷量從190萬台到430萬台不等,顯然 Apple Watch 的銷量並沒有達到市場預期。
在蘋果公司的財報會議上,CEO Tim Cook 沒有正面回應分析師有關 Apple Watch 銷量的問題,蘋果公司暫時不關注
Apple Watch 的銷量,重點是打造一個生態體系,為 2015 年的聖誕購物季做準備。之前曾有消息稱 Apple Watch
進... | true |
92f700d67e263a06d18253bdf77807134054282d | Python | usnistgov/core_explore_example_app | /core_explore_example_app/utils/query_builder.py | UTF-8 | 10,108 | 2.625 | 3 | [
"NIST-Software",
"BSD-3-Clause"
] | permissive | """Utils for the query builder
"""
from os.path import join
from django.template import loader
from core_main_app.settings import MONGODB_INDEXING
from xml_utils.xsd_types.xsd_types import (
get_xsd_numbers,
get_xsd_gregorian_types,
)
from core_explore_example_app.utils.xml import get_enumerations
class Bra... | true |
ca4ae8be723218d9dc499b5ee4622580efce0834 | Python | Kolwankar-Siddhiraj/MushroomClassificationProjectML | /Mashroom/Logger/logger.py | UTF-8 | 697 | 2.96875 | 3 | [] | no_license | from datetime import datetime
class Logs:
def __init__(self, file):
self.filename = file
now = datetime.now()
current_time = now.strftime("%Y-%m-%d <> %H:%M:%S")
file_obj = open(self.filename, "a+")
file_obj.write("\n"+ current_time+ "<:>" +"New Logger instance created !\n... | true |
b740b1143d72ca43750a47af25bd194132756084 | Python | DataScienceResearchPeru/epidemiologic-calculator | /epical/models/covid_seir_d.py | UTF-8 | 1,839 | 2.59375 | 3 | [] | no_license | import numpy as np
from scipy.integrate import odeint
from .base import Covid19Interface
# Parametros Epidemiologicos
A1 = 0.415 # contagio de SUSCEPTIBLE con INFECTADO
A2 = 0.70 # Periodo latente
A3 = 0.05 # Recuperacion
A4 = 0.00 # Muerte
class CovidSeirD(Covid19Interface):
def model(self, initial_conditi... | true |
8a2c0b7ec3d0b02c1a8073959a01408531790b71 | Python | Lash-360/Coursera_Capstone | /Week 2/Analysis.py | UTF-8 | 5,194 | 2.8125 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter
import pandas as pd
import matplotlib as mpl
import matplotlib.ticker as ticker
from sklearn import preprocessing
%matplotlib inline
!conda install -c anaconda xlrd --yes
#Download Seattle Police Department Accident data
!w... | true |
4075cbec01ec1e955e752f1e08ede5be06e29ccf | Python | prarthanasigedar/CARLA_2 | /navigation/local_planner_behavior.py | UTF-8 | 13,333 | 2.71875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# Copyright (c) 2018 Intel Labs.
# authors: German Ros (german.ros@intel.com)
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
""" This module contains a local planner to perform
low-level waypoint following based on PID contr... | true |
a4d0f98ca74e931a054881d6ff608f0631a0772a | Python | andrewreece/gauging-debate | /streaming/jobs/utils.py | UTF-8 | 17,281 | 2.5625 | 3 | [
"LicenseRef-scancode-other-permissive",
"MIT"
] | permissive | import time, json, boto3, re
from dateutil import parser, tz
from datetime import datetime, timedelta
from sentiment import *
from pyspark.sql import SQLContext, Row
import pyspark.sql.functions as sqlfunc
from pyspark.sql.types import *
search_terms = []
n_parts = 10 # number of paritions for RDD
def get_search_json... | true |
10e7acf216e7068dc184ca07d36a68b537e0accd | Python | Aasthaengg/IBMdataset | /Python_codes/p03145/s678078916.py | UTF-8 | 67 | 2.59375 | 3 | [] | no_license | abc = list(map(int, input().split()))
print((abc[0] * abc[1]) // 2) | true |
d3960d5662f223d4dd9c5e23b2f2db2033897b07 | Python | developer579/Practice | /Python/Python Lesson/Second/Lesson9/Sample4.py | UTF-8 | 298 | 4 | 4 | [] | no_license | str = input("文字列を入力してください。")
key = input("検索する文字を入力してください。")
res = str.find(key)
if res != -1:
print(str,"の",res,"の位置に",key,"がみつかりました。")
else:
print(str,"の中に",key,"はみつかりませんでした。") | true |
29021130cb8bd712d2427d2772f5ed003d3cc6dc | Python | clodiap/PY4E | /15_sqlite.py | UTF-8 | 1,771 | 3.796875 | 4 | [] | no_license | import sqlite3
#The connect operation makes a "connection" to the database stored in the file music.sqlite3 in the current directory. If the file does not exist, it will be created. The reason this is called a "connection" is that sometimes the database is stored on a separate "database server" from the server on whic... | true |
f61b1d315656aa3226467b755421d614aa04f969 | Python | Jtaylorapps/Python-Algorithm-Practice | /recursivePractice.py | UTF-8 | 1,290 | 4.21875 | 4 | [
"Apache-2.0"
] | permissive | # Recursively reverse a string
def reverse_string(s):
if len(s) < 2:
return s
return reverse_string(s[1:]) + s[0]
print(reverse_string("1234") == "4321") # True
# Maps a given function over nested list
def map_f(f, arr, result=None):
if result is None:
result = []
for x in arr:
... | true |
a47b9a1b251674c750a1f307f063136a006e62d9 | Python | FloLangenfeld/RosettaSilentToolbox | /rstoolbox/analysis/sequence.py | UTF-8 | 30,382 | 2.640625 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""
.. codeauthor:: Jaume Bonet <jaume.bonet@gmail.com>
.. affiliation::
Laboratory of Protein Design and Immunoengineering <lpdi.epfl.ch>
Bruno Correia <bruno.correia@epfl.ch>
.. func:: sequential_frequencies
.. func:: sequence_similarity
.. func:: positional_sequence_similarity
.. fu... | true |
98671700fd0dc0de7f9f5aa93d5edac157de70ab | Python | julianandrews/adventofcode | /2017/d06.py | UTF-8 | 1,235 | 3.265625 | 3 | [] | no_license | from utils import read_data
from utils.iterables import cycle_detect, repeat_apply
def redistribute(memory_banks):
result = list(memory_banks)
max_value = max(memory_banks)
max_ix = memory_banks.index(max_value)
result[max_ix] = 0
value, remainder = divmod(max_value, len(memory_banks))
for i ... | true |
db6166931fd13e2a55fe645c8b39ae5b5a97b03a | Python | jkelly37/Jack-kelly-portfolio | /CSCI-University of Minnesota Work/UMN-1133/Labs/py.py | UTF-8 | 159 | 3.03125 | 3 | [] | no_license | # CSci 1133 lecture2
# Jack Kelly
# Tf to tc
import random
list1 = [1]
i=0
while i<100:
list1.append(i+1) = random.rand(1,1000)
i = i + 1
print(list1) | true |
2ea327e55fe5813f15c1979ad08daa0c37463eab | Python | NormanGadenya/DateOfBirthCode | /DateOfBirth.py | UTF-8 | 674 | 3.140625 | 3 | [] | no_license | # DateOfBirthCode
import calendar
from datetime import datetime
now=datetime.now()
ne=now.date()
yea=list(str(ne))
year=int(yea[0]+yea[1]+yea[2]+yea[3])
age=input('Enter your age: ')
yr=int(year)-int(age)
mt=input('Enter the month: ')
dy=input('Enter the date of the month: ')
cal=calendar.weekday(int(yr),int(mt... | true |
478dc4a4920e61abc12b829cbd635b8c981bcaa8 | Python | YodhaJi/MY-PROJECTS | /stat4.py | UTF-8 | 595 | 4.125 | 4 | [] | no_license | #digits = [1, 2, 3] # digits: Sample input
def stat4(digits): # stat1(): function for statment 1
import random
#digits = (1, 2, 3) # digits: Sample input in the form of tuple so that it won't change its value.
s1 = list(digits) # s1: a variable used to store the value of digits in the form of list so... | true |
f7d1910afa187b7121e818fbe24fff0721245e4f | Python | yeesian/NUS-Bidding-History | /scripts/process_bidding_summary.py | UTF-8 | 2,533 | 2.890625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <markdowncell>
# Cleaning NUS Bidding Summary
# ---
# (this is a continuation of the instructions (from step 7 onwards) at the [NUS-Bidding-History](https://github.com/yeesian/NUS-Bidding-History) repository.)
#
#
# libraries used:
# <codecell>
import pandas as... | true |
4b893c3555ff812b23628cb4cba15a6633d6a88d | Python | nathancy/stackoverflow | /57850107-preprocess-text-remove-noise/preprocess_text_remove_noise.py | UTF-8 | 693 | 2.796875 | 3 | [
"MIT"
] | permissive | import cv2
import numpy as np
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1)
... | true |
142fd5ce4a1a1fc44646e721f0765cd8ee8239e4 | Python | greenorca/ECMan | /ui/ecLoginWizard.py | UTF-8 | 4,965 | 2.96875 | 3 | [
"MIT"
] | permissive | """
Created on Feb 22, 2019
@author: sven
"""
from socket import gaierror
from PySide2.QtWidgets import QLabel, QLineEdit, QWizard, QWizardPage, QApplication, \
QGridLayout
from worker.sharebrowser import ShareBrowser
class EcLoginWizard(QWizard):
"""
wizard for selection of CIFS/SMB based exam shares... | true |
0b88a4bd64df0717ec2c4763bc4d2d7003a4008a | Python | VikonLBR/tkinter_tutorial | /t1.py | UTF-8 | 490 | 3.3125 | 3 | [] | no_license | import tkinter as tk
win = tk.Tk()
win.title('my 1s tk window')
win.geometry('400x500')
var = tk.StringVar()
label = tk.Label(win, textvariable=var, bg='orange', font=('Arial', 12), width=12, height=2)
label.pack()
flag = False
def hit_me():
global flag
if not flag:
flag = True
var.set('I\... | true |
9a2b8ba620bda3ba1e8ad77d0041dae1899945e8 | Python | Carl-Chinatomby/ridecell | /api/v1/scooters/models.py | UTF-8 | 2,463 | 2.828125 | 3 | [] | no_license | from django.db import models
from django.utils import timezone
class Scooter(models.Model):
latitude = models.DecimalField(max_digits=9, decimal_places=6) # ideally use a spatial db and geodjango
longitude = models.DecimalField(max_digits=9, decimal_places=6)
is_reserved = models.BooleanField(default=Fal... | true |
a9634816e3deb4eaa97b6b97ed3b790619ed82ed | Python | danelia/CS131 | /hw6_release/compression.py | UTF-8 | 1,106 | 3.609375 | 4 | [] | no_license | import numpy as np
def compress_image(image, num_values):
"""Compress an image using SVD and keeping the top `num_values` singular values.
Args:
image: numpy array of shape (H, W)
num_values: number of singular values to keep
Returns:
compressed_image: numpy array of shape (H, W)... | true |
a71866d5049b9b675fa61fd7d9bad96c63f8fea6 | Python | limingzhang513/lmzrepository | /train_module/src/Data_Processing/DataSet/token/auths.py | UTF-8 | 3,044 | 2.515625 | 3 | [] | no_license | # !/usr/bin/python2
# -*- coding:utf-8 -*-
import jwt
import json
import requests
from flask import current_app, g
from DataSet.utils.serial_code import RET
from DataSet.utils import commons
class Auth():
@staticmethod
def encode_auth_token(user_id, login_time):
"""
生成认证Token
:param u... | true |
8ef6a0d4566acbc7e7749111fa265bf4ef16c1c9 | Python | ngudkov/sdp | /factory_method/concrete_workers.py | UTF-8 | 1,263 | 2.9375 | 3 | [
"Apache-2.0"
] | permissive | #!/usr/bin/env python3
from __future__ import annotations
from abstract_workers import WorkerCreator, Job
class DocManCreator(WorkerCreator):
"""
Класс инициализации работника
Работник документалист. Хочет производить документы, но только собирает их
"""
def factory_method(self) -> DocMan1:
... | true |
805836b396164c8a1ef317285fb1e40cbeb1ffee | Python | grrrr/nsgt | /nsgt/audio.py | UTF-8 | 5,014 | 2.515625 | 3 | [
"Artistic-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # -*- coding: utf-8
"""
Python implementation of Non-Stationary Gabor Transform (NSGT)
derived from MATLAB code by NUHAG, University of Vienna, Austria
Thomas Grill, 2011-2021
http://grrrr.org/nsgt
Austrian Research Institute for Artificial Intelligence (OFAI)
AudioMiner project, supported by Vienna Science and Tech... | true |
7d3e959f480ddcc0b3125317128a551524734d5f | Python | yuedy/TensorFlow-cn | /source/_static/code/en/basic/graph/variable.py | UTF-8 | 510 | 3.3125 | 3 | [] | no_license | import tensorflow as tf
a = tf.get_variable(name='a', shape=[])
initializer = tf.assign(a, 0) # tf.assign(x, y) will return a operation “assign Tensor y's value to Tensor x”
a_plus_1 = a + 1 # Equal to a + tf.constant(1)
plus_one_op = tf.assign(a, a_plus_1)
sess = tf.Session()
sess.run(initializer)
for i in rang... | true |
e9a3d23194f94daf8b83dfd0e22288d9579562a5 | Python | samyev/clientes_django | /projeto/projeto/views.py | UTF-8 | 1,260 | 3.390625 | 3 | [] | no_license | from django.http import HttpResponse
from django.shortcuts import render
def hello(request):
# função que retorna um 'olá mundo! importado de index.html'
return render(request, 'index.html')
def articles(request, year):
# função que retorna o ano que o usuário informar na url
return HttpResponse("O an... | true |
318650c57544bff716e847ae2002f79962bbd3af | Python | ericlavega96/Python-Tutorial | /Django - Python Course/PythonBootcamp/app.py | UTF-8 | 8,599 | 4.21875 | 4 | [] | no_license | # First exercise
# name = 'John Smith'
# age = 20
# is_new = True
#
# name = input('What is your name? ')
# print('Hi ' + name)
# favorite_color = input('What is your favorite color? ')
# print(name + ' likes '+ favorite_color)
# Second Exersice
# birth_year = input('Birth year: ')
# age = 2019 - int(birth_year)
# pri... | true |
1b4920be99ae83218f513aec1d53715715ae3524 | Python | Masluss2903/covid19_report | /covid/get_summary_database.py | UTF-8 | 2,025 | 2.9375 | 3 | [] | no_license | import json
import boto3
from urllib.parse import parse_qs
def get_global_summary(covid_summary):
global_data = covid_summary['Item']['Global_information']
answer = 'Right now there are {:,} new confirmed cases, {:,} total confirmed, {:,} new deaths, {:,} total deaths and {:,} total recovered.'.format(
... | true |
2587609f83a4156eb57b22d450c2d4b62b7a691b | Python | VieetBubbles/holbertonschool-higher_level_programming | /0x05-python-exceptions/4-list_division.py | UTF-8 | 695 | 3.578125 | 4 | [] | no_license | #!/usr/bin/python3
def list_division(my_list_1, my_list_2, list_length):
new = []
for _ in range(list_length):
try:
result = my_list_1[_] / my_list_2[_]
new.append(result)
except ValueError:
result = 0
new.append(result)
except ZeroDivis... | true |
8403890a896f39cbecd7af056e2e39ae43dd9843 | Python | Grinch101/dentist_website | /t1.py | UTF-8 | 2,857 | 2.75 | 3 | [] | no_license | import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
def updater(fig=None, title='TITLE', xaxistitle='x title', yaxistitle='y title', font='Arial', fontsize=12):
... | true |
e5abd95d0840587743bb0f779afd3f2b89748f61 | Python | sipocz/ImageManipulation | /04_hazi.py | UTF-8 | 2,307 | 2.859375 | 3 | [] | no_license | from sklearn.datasets import load_wine
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
wine = load_wine()
#print(data.DESCR)
cols=["Alcohol","Malic acid","Ash","Alcalionity","Magnesium","Total Phenol","Flavanoids",
"Nonflavor","Proanthocyanins","Col... | true |
a6476108d4cf99bec2b51ce2cd145e1f6faaf045 | Python | martinber/agglomerate | /agglomerate/settings.py | UTF-8 | 7,926 | 3.375 | 3 | [
"MIT"
] | permissive | import agglomerate.math
import agglomerate.util
class Settings:
"""
Keeps track of a group settings, this instance is for algorithms, can
represent an entire sheet or a group.
**Settings**
algorithm
name of the algorithm to use
allow
dictionary containing allowed settings
... | true |
e792589e4c043a1f2fb6d41dd1a6b418afa569a7 | Python | kho903/data-structure-and-algorithm-in-Python | /정렬, 탐색/이진탐색(Binary Search).py | UTF-8 | 594 | 3.75 | 4 | [] | no_license | # 탐색하려는 리스트가 이미 정렬되어 있는 경우에만 적용 가능
# 크기 순으로 정렬되어 있다는 성질 이용
# 한 번 비교가 일어날 때마다 리스트를 반씩 줄임
# O(log n)
def solution(L, x):
answer = -1
lower = 0
upper = len(L) - 1
while lower <= upper:
middle = (lower + upper) // 2
if L[middle] == x:
return middle
elif L[middle] < x:
... | true |
518731afed6a833dbe3802bcb27958973b79fcca | Python | shayhan-ameen/Beecrowd-URI | /Beginner/URI 1064.py | UTF-8 | 250 | 3.953125 | 4 | [] | no_license |
numbers = []
for _ in range(6):
numbers.append(float(input()))
count = 0
sum = 0.0
for number in numbers:
if number >= 0:
sum += number
count += 1
print(f'{count} valores positivos')
print(f'{sum/count:.1f}') | true |
a6b8d5387b61accfdb79bcd0230f4159c135eadb | Python | IUCVLab/ctscan | /src/data/Dataset.py | UTF-8 | 2,519 | 2.59375 | 3 | [] | no_license | import h5py as h5
from pathlib import Path
from pydicom import dcmread
import numpy as np
class TagError(KeyError):
pass
class Dataset:
def __init__ (self, file='dataset.hdf5'):
self.__file = h5.File(file)
if "counter" not in self.__file.attrs:
self.__file.attrs['counter'] = 0
... | true |
d4b4d2ca19d29873e27699a8d43595f0bdaecc5f | Python | SamuelMiddendorp/SamieTools | /lib/helpers.py | UTF-8 | 348 | 2.765625 | 3 | [] | no_license | import json
def load_assets() -> dict:
"""Returns key-value pairs from the json configuration file"""
try:
with open("cfg/assets.json", "r") as f:
return f.json()
except Exception as e:
print(f"An error has been encountered while loading a file of type {type(e)}")
exit()
... | true |
0c1b4515556d1bced032cc31c7a8d1fb67d27b35 | Python | TangoJP/BasicFeatureAnalysis | /feature_comparison.py | UTF-8 | 8,989 | 2.90625 | 3 | [] | no_license | import numpy as np
import pandas as pd
import statsmodels.api as sm
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import cm
from .feature import (ColumnData, Feature, CategoricalFeature,
OrdinalFeature, ClassTarget)
from .feature_collection import (FeatureCollection,
... | true |
c3c0ab902bc199eb716917ca5a85c62b1d13f6d3 | Python | Team5892Steamworks/FRC2017 | /pi_pixy_vision/get_blocks.py | UTF-8 | 2,818 | 3.234375 | 3 | [] | no_license | """
Uses NetworkTables and the Pixy camera to send the raw block data to the robot.
More specifically, it sends the x and y positions of the two biggest blocks, which should be the boiler tape.
Presumably later I will make a program that gives the robot more directly useful information.
However, right now I just want t... | true |
4f20348a0672c5d8a68dfe59703451446167c202 | Python | YorikSar/gh-mirror | /gh-mirror.py | UTF-8 | 4,817 | 2.640625 | 3 | [] | no_license | #!/usr/bin/env python
"""Mirrors number of GitHub repositories."""
import argparse
import logging
import os.path
import re
import shutil
import signal
import subprocess
import sys
import urllib2
import HTMLParser
class GHRepoListParser(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__in... | true |
553fe516352b922e2cae3240f9668c5f9b90786f | Python | papalagichen/leet-code | /0190 - Reverse Bits.py | UTF-8 | 776 | 3.234375 | 3 | [] | no_license | class Solution:
def reverseBits(self, n):
s = "{:b}".format(n)
return int(('0' * (32 - len(s)) + s)[::-1], 2)
class Solution2:
def reverseBits(self, n):
s = self.int_to_binary_string(n)
return self.binary_string_to_int(('0' * (32 - len(s)) + s)[::-1])
def binary_string_to_... | true |
fb06cea0c548c34f800478c91b87cb4b199736b9 | Python | lyyanjiu1jia1/OrderPreservingEncryption | /plot/analysis_tools.py | UTF-8 | 319 | 3.234375 | 3 | [] | no_license | import numpy as np
def linear_regression(x, y):
"""
:param x: n-by-m matrix, will be expanded to (m + 1)-columns
:param y: n-by-1 matrix
:return:
"""
x = np.concatenate((x, np.ones((x.shape[0], 1))), axis=1)
w = np.linalg.inv(x.transpose().dot(x)).dot(x.transpose()).dot(y)
return w
| true |
bb9e8b681880bc64c93133b2626ab4c2c36e95d8 | Python | Edixon112/EBGYM | /altiria/rest/restPythonAltiriaCert.py | UTF-8 | 3,371 | 2.703125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# Copyright (c) 2020, Altiria TIC SL
# All rights reserved.
# El uso de este código de ejemplo es solamente para mostrar el uso de la pasarela de envío de SMS de Altiria
# Para un uso personalizado del código, es necesario consultar la API de especificaciones técnicas, donde también podrás enco... | true |
64525ed451267a374985aaf26a81befe828c7533 | Python | AlpesMachines/mpd-utils | /utils/keygroup.py | UTF-8 | 8,274 | 2.78125 | 3 | [] | no_license | '''
Python script to manipulate keygroups for MPCv2.3 and MPC Essentials.
A keygroup file is XML which declares how samples will be trigger from
the midi data and how they are tuned. This script allows the triggers
to be moved around the keyboard and to merge keygroup files - effectively
creating a keyboard split betw... | true |
8006721ac6e9adb1060c889f3a4eafbbdd3e7735 | Python | dantsub/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/101-square_matrix_map.py | UTF-8 | 126 | 2.828125 | 3 | [] | no_license | #!/usr/bin/python3
def square_matrix_map(matrix=[]):
return list(map(lambda a: list(map(lambda n: n * n, a)), matrix[:]))
| true |
0e991a46a638912fc6585967a81aab6452431422 | Python | compagnb/SP20-IntermediatePython | /codeExercises/wk1_moonFunction.py | UTF-8 | 222 | 3.703125 | 4 | [] | no_license | def moon_weight(weight, increase, years):
years = years + 1
for year in range(1, years):
weight = weight + increase
moon_weight = weight * 0.165
print('Year %s is %s' % (year, moon_weight))
moon_weight(35, 0.3, 5) | true |
8f97bc2e181bb2bf2095660e55e60e76884d4ab9 | Python | JonasJR/examen | /MachineLearning/errorRate/testCrossVal.py | UTF-8 | 5,945 | 3.34375 | 3 | [] | no_license | from sklearn.datasets import load_digits, load_iris
from sklearn.svm import SVC
from sklearn import tree
from sklearn import linear_model
from sklearn import neighbors
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import ShuffleSplit
from sklearn.model_selection import train_test_spli... | true |
daa532d1e3b1376324786614d00af53ee59e1024 | Python | FaisalWant/ObjectOrientedPython | /Threading/IntSet.py | UTF-8 | 1,189 | 3.671875 | 4 | [] | no_license | class IntSet(object):
""" An intset is a set of integers"""
# Information about the implementation (not abstraction)
# The value of the et is represented by a list of ints
# Each int in thin set occurs in self.vals exactly once
def __init__(self):
self.vals=[]
def insert(self, e):
""" Assume e is... | true |
58955630df0c3c52faaa17216b025e14610bcf99 | Python | duddles/nytimes_set_puzzle | /nytimes_set_puzzle.py | UTF-8 | 871 | 3.03125 | 3 | [] | no_license | import itertools
class Shape(object):
def __init__(self, index, symbol, color, number, shading):
self.index = index
self.symbol = symbol
self.color = color
self.number = number
self.shading = shading
def check_combo(combo):
# to do
shapes = ... | true |
1aef5abff96878aa72a5fc8930520190ceb6a923 | Python | mbollmann/perceptron | /mmb_perceptron/feature_extractor/pos_honnibal.py | UTF-8 | 2,844 | 2.625 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
from .feature_extractor import FeatureExtractor
class Honnibal(FeatureExtractor):
"""Feature extractor based on the POS tagger by Matthew Honnibal.
<https://honnibal.wordpress.com/2013/09/11/a-good-part-of-speechpos-tagger-in-about-200-lines-of-python/>
"""
_minimum_left_conte... | true |
923923c14af690754bd6d329afc70ce7634e12bb | Python | ahmadraouf/oop_exercise | /oop_exercises.py | UTF-8 | 1,539 | 3.75 | 4 | [] | no_license | class Employee:
def __init__(self , employee_number, name, address, salary, job_title):
self.employee_number = employee_number
self.__name = name
self.__address = address
self.__salary = salary
self.__job_title = job_title
def get_name(self):
return ... | true |
f2d368525021c5a2d1a01bfcfb31e21d90adcd94 | Python | ddtkra/atcoder | /abc076/C/main.py | UTF-8 | 580 | 2.703125 | 3 | [] | no_license | #!/usr/bin/env python3
# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools (tips: You use the default template now. You can remove this line by using your custom template)
def main():
# Failed to predict input format
S = input().replace('?', '.')
T = input()
import re
import sys... | true |
c774de124f79f545af197812c70eacb83585d451 | Python | bochuxt/mini_psp | /src/mini_psp/utils/metric_utils.py | UTF-8 | 4,026 | 3.03125 | 3 | [] | no_license | import numpy as np
from sklearn import metrics
def get_iou(target,prediction):
'''Returns Intersection over Union (IoU).'''
intersection = np.logical_and(target, prediction)
union = np.logical_or(target, prediction)
iou_score = np.sum(intersection) / np.sum(union)
return iou_score
def get_clas... | true |
421169389393a8288bbb04a72ccaf56716057b35 | Python | Matheus-Barros/Objects_Recognition | /Detect_Objects.py | UTF-8 | 3,742 | 2.546875 | 3 | [] | no_license | import sys
import dlib
import cv2
import time
from datetime import datetime
import pandas as pd
import warnings
import glob
warnings.filterwarnings("ignore")
def Percent(value):
if value >= 1.0:
return 100
else:
x = str('{:.0%}'.format(value))
return int(x.split('%')[0])
#INICIALIZAÇ... | true |
55065c6dfccd66bc724deac4ff9eda85afd04860 | Python | MageJohn/EMPR_Scanner | /src/python/remote_function_call.py | UTF-8 | 743 | 2.984375 | 3 | [] | no_license | import serial
from exceptions import *
port = '/dev/ttyACM0'
baud = 9600
ser = serial.Serial(port,baud)
func_codes = {} # e.g dico = {'funcname': b'\x01'}
func_params = {} # e.g dico = {'funcname': [b'param1', b'param2', ...]}
def check_func_param_match(funcname, params):
if (func_params[funcname] == params):
... | true |
587a383a1c84c2242457bad9a949fe7c7dd8dabf | Python | tynski/Algorithms | /Sorting/mergeSort.py | UTF-8 | 686 | 3.8125 | 4 | [] | no_license | def mergeSort(array):
N = len(array)
if N == 1:
return array
arrayHalf = N // 2
firstHalf = mergeSort(array[arrayHalf:])
secondHalf = mergeSort(array[:arrayHalf])
return merge(firstHalf, secondHalf)
def merge(p, r):
i = 0
j = 0
sortedArray = []
while i < len(p) and j <... | true |
dc32ef5520de3a2aa2f2105d363df1a4cd7403af | Python | Stefan228/Simich-PM20-6 | /Зачччет цсв.py | UTF-8 | 856 | 3.015625 | 3 | [] | no_license | import csv
def availability(name_of_book, adress_of_store):
store_id = ''
try:
with open('shops.csv') as f:
reader = csv.reader(f, delimiter=';')
head = next(reader)
body = [line for line in reader]
for store in body:
if store[1] == ... | true |
7aa3fd54ae219a8c3324e2118c2c26d2b8cd85f7 | Python | actcheng/leetcode-solutions | /0388_Longest_Absolute_File_Path.py | UTF-8 | 581 | 3.109375 | 3 | [] | no_license | # Problem 388
# Date completed: 2019/11/11
# 28 ms (96%)
class Solution:
def lengthLongestPath(self, input: str) -> int:
arr = input.split('\n')
longest = 0
stack = []
level = 0
while arr:
a = arr.pop(0)
split = a.split('\t')
nt = len(spl... | true |
cec85a5dd76df207e06a9b777b79f0cf9afad4f8 | Python | scottenriquez/jitterbug | /jitterbug.py | UTF-8 | 118 | 2.671875 | 3 | [] | no_license | import pyautogui
import time
while True:
pyautogui.moveRel(0, 10)
pyautogui.moveRel(0, -10)
time.sleep(5) | true |
cec88dfc73674af60900ee3757a0bc9bda9b092a | Python | Hyperdraw/FridayClub | /ai/generate.py | UTF-8 | 1,321 | 3.25 | 3 | [] | no_license | from json import loads, dumps
from os.path import exists
print('=====')
print('This tool will help you ceate an NPC JSON file.')
print('You will be continuously asked for questions and responses until you press stop.')
print('=====')
npc_path = input('Enter the name of a file to edit or create. (Should end in .json): ... | true |
2a9f9bee3a96782f0ff81544e206d7a6f2f13603 | Python | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_78/127.py | UTF-8 | 1,106 | 3.078125 | 3 | [] | no_license | #! /usr/bin/python
import sys
cases = int(sys.stdin.readline()[:-1])
actual_case = 0
while actual_case < cases:
# reading and so
actual_case += 1
#nacteni 2 cisel
numbers = sys.stdin.readline()[:-1].split()
n = int(numbers[0])
pd = int(numbers[1])
pg = int(numbers[2])
ok_pd = Fal... | true |
bbab972ce09308c01e2641fc35004ac7bac96487 | Python | AlishaKochhar/KnowYourWords | /ProjectGUI.py | UTF-8 | 3,252 | 3.078125 | 3 | [] | no_license | from tkinter import *
import tkinter
from PIL import Image,ImageTk
import sqlite3
root=Tk()
image=Image.open("Background.JPG")
tkimage=ImageTk.PhotoImage(image)
w = tkimage.width()
h = tkimage.height()
root.geometry("%dx%d+0+0" % (w, h))
MainLabel=Label(root,image=tkimage)
MainLabel.pack(side='top', ... | true |
92fb970b22c6832fe2c9190e956cd17676196bd6 | Python | sergiooli1997/lector-escritor | /lector-escritor.py | UTF-8 | 2,067 | 3.234375 | 3 | [] | no_license | import logging
import threading
import time
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-10s) %(message)s',
)
class Dato(object):
def __init__(self, start=''):
self.value = start
def cambiar(self, variable):
self.value = variable
d... | true |
1352006645380cf930cb2e8b9f897e8a77dab920 | Python | Sangheun/programming-dev-5th | /decorators2.py | UTF-8 | 191 | 2.78125 | 3 | [] | no_license | import time
def memoize(fn):
cached = {}
def wrap(x,y):
key = (x,y)
if key not in cached:
cached[key] = fn(x,y)
return cached[key]
return wrap | true |
d62d67f8f95803d8c85f6edb7d7232d59f100340 | Python | teriyakichicken/doublemeat | /test.py | UTF-8 | 4,499 | 2.640625 | 3 | [] | no_license | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from itertools import product
from sklearn.ensemble import RandomForestRegressor
def read_district(filename):
cols = ['district_hash', 'district_id']
df = pd.read_csv(filename, header=None, sep='\t', names=cols)
return df
def read_orde... | true |
5c7edda17893603a0d3c43251a4bbf85eb14df3d | Python | kltjrcks/move_test | /programmers/pSolution36.py | UTF-8 | 360 | 3.53125 | 4 | [] | no_license | # -*- coding : utf-8 -*-
# 올바른 괄호
def solution(s):
answer = 0
for i in s:
if answer == -1:
return False
else:
if i == "(":
answer += 1
elif i == ")":
answer -= 1
if answer != 0:
return False
else:
return ... | true |