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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
4f4031b0a795349a0a61f652a78bbf9178d65a5d | Python | baberarjumand/fundamentals-of-computing-specialization | /C1 - An Intro to Interactive Programming in Python P1/week 2 project GUESS THE NUMBER GAME.py | UTF-8 | 2,490 | 3.796875 | 4 | [] | no_license | # http://www.codeskulptor.org/#user47_RfwliOq092_0.py
# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
# helper function to start and restart the game
def new_game(rangeLimit):
... | true |
d220f776185e6a595c81c8f599c32b5e6a358c80 | Python | mhcomm/pypeman | /pypeman/contrib/hl7.py | UTF-8 | 6,750 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | import asyncio
import logging
import sys
import warnings
import hl7
from pypeman import endpoints, channels, nodes, message
from pypeman.errors import PypemanParamError
logger = logging.getLogger(__name__)
class MLLPProtocol(asyncio.Protocol):
"""
Minimal Lower-Layer Protocol (MLLP) takes the form:
... | true |
12028df2983830d776ebe990bb68d81428b62458 | Python | maddymb/PythonBasics | /basics/boolean_datatype.py | UTF-8 | 123 | 3.21875 | 3 | [] | no_license | a = True
b = False
print(a)
print(b)
print(bool(1)) # bool function
c = 'jhn'
print(bool(c))
c = ''
print(bool(c))
| true |
8d73fbaf12b71c1c2759ba46107fba39cafacf2a | Python | luizferreira/cmed | /src/wres.theme/wres/theme/skins/wres_theme_scripts/getAllergiesData.py | UTF-8 | 506 | 2.6875 | 3 | [] | no_license | ## coding=utf-8
def divideAllergies(allergies):
active = []
inactive = []
for allergy in allergies.values():
allergy = allergy['data']
if allergy.get('state') == 'active':
active.append(allergy)
else:
inactive.append(allergy)
return active, inactive
... | true |
80f5f067a414e43082212b865af391f49cdb1b76 | Python | sharingov/workspace | /leetcode/finding-users.py | UTF-8 | 425 | 2.96875 | 3 | [] | no_license | # https://leetcode.com/contest/weekly-contest-235/problems/finding-the-users-active-minutes/
class Solution:
def findingUsersActiveMinutes(
self, logs: list[list[int]],
k: int) -> list[int]:
d = {}
for a, b in logs:
d.setdefault(a, set()).add(b)
_list = [0... | true |
60551df36598381775dd24ea83fabd289097541f | Python | WillisMD/SeaIceMaps | /Plot_NSIDC_dailyseaice.py | UTF-8 | 4,047 | 2.8125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Imports and Plots NSIDC sea ice for each day from a netCDF file
Created on Fri September 9,2016
@author: meganwillis
"""
################################
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
import cmocean ... | true |
e3040bd1af11f94cbe1986d6a014a5ec53c899fd | Python | Sheryl96/eShopping | /src/responseHelper/oder_details_response_helper.py | UTF-8 | 3,060 | 2.859375 | 3 | [] | no_license | import datetime
from dateutil.relativedelta import relativedelta
class OrderDetailsResponseHelper:
def __init__(self, order_details, start_date, end_date):
self.order_details = order_details
self.start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
self.end_date = datetime.date... | true |
de69c0c27dd842987fa9d4d0f1048e95dba7ba89 | Python | arayabrain/multi-modal-integration | /src/plotting/plotMutualInfo_alongLayers.py | UTF-8 | 3,953 | 2.609375 | 3 | [] | no_license | import pylab as plt
import numpy as np
import pickle
layerList =['Layer 1','Layer 2','Layer 3','Layer 4'];
MI_list_untrained = [];
MI_list_trained = [];
MI_list_shuffled = [];
MI_list_untrained_top10 = [];
MI_list_trained_top10 = [];
MI_list_shuffled_top10 = [];
for l in range(4):
pkl_file = open... | true |
448b7199e8fe1e2cc3aeaac1381c519e05cdc080 | Python | guojixu/interview | /leetcode/剑指 Offer 53 - I. 在排序数组中查找数字 I.py | UTF-8 | 441 | 3.296875 | 3 | [] | no_license |
nums = [int(_) for _ in input().split(',')]
target = int(input())
i = 0
j = len(nums) - 1
while i <= j:
m = (i + j) // 2
if nums[m] <= target:
i = m + 1
else:
j = m - 1
right = i
if j >= 0 and nums[j] != target:
print('no')
exit(0)
i = 0
j = len(nums) - 1
while i <= j:
m ... | true |
2f11dedc0c3c5e393b0ad0228ca82171f5797f9a | Python | contactpunit/python_sample_exercises | /ds/ds/averager.py | UTF-8 | 266 | 3.21875 | 3 | [] | no_license | def averager():
count = 0
total = 0
avg = 0
while True:
num = yield avg
total += num
count += 1
avg = total/count
a = averager()
print(a)
print(next(a))
print(a.send(20))
print(a.send(10))
print(a.send(12))
a.close() | true |
aa0c80d62f24a30c1bf02a29dd6d6b93f716de42 | Python | prashant4nov/algorithms-playground | /codility/CommonPrimeDivisors.py | UTF-8 | 743 | 3.46875 | 3 | [] | no_license | # link: https://codility.com/demo/take-sample-test/common_prime_divisors
# name: Common Prime Divisors
def solution(A, B):
# write your code in Python 2.7
z = len(A)
result = 0
for index in xrange(z):
a = A[index]
b = B[index]
d = gcd(a, b)
if has_diff_factor(d, a)... | true |
0802f6da124ee190341c66d6268a61ff512ca6e6 | Python | joao-conde/competitive-programming | /online-judges/leetcode/search-insert-position.py | UTF-8 | 723 | 3.75 | 4 | [] | no_license | # https://leetcode.com/problems/search-insert-position/
class Solution:
def searchInsert(self, nums: list[int], target: int) -> int:
lb, ub = 0, len(nums)
mid = lb + (ub - lb) // 2
while lb < ub:
if nums[mid] < target:
lb = mid + 1
elif nums[mid] > t... | true |
9a78cb33f818a32686b5300b436f10368ba98035 | Python | limecrime/decrypting-Challenge | /decrypting-Challenge.py | UTF-8 | 309 | 3.640625 | 4 | [] | no_license | def decode(encodedMessage):
message = ''
lencount = 0
for i in encodedMessage:
lencount += 1
if i.isdecimal():
message += encodedMessage[(lencount + int(i))]
return message
userMessage = input('Input the message that needs decoding:')
print(decode(userMessage)) | true |
42bae309dc535e553f9a8c807459a594cc105ac9 | Python | cloew/WiiCanDoIt-Framework | /src/WiiEventParser/Accelerometer.py | UTF-8 | 2,752 | 2.859375 | 3 | [] | no_license | #Accelerometer Class
#Keeps track of timestamps on a particular wiimote accelerometer,
#fires events when the parser passes a certain threshold
import cwiid
import AccMagTracker
import WiiEvent
import sys,os
try:
import ParserSettings
except:
filepath = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.... | true |
3ce51d596ae4e6cd15490c921f739a429d794686 | Python | Pablitinho/CarND-Capstone | /ros/src/twist_controller/twist_controller.py | UTF-8 | 2,573 | 2.515625 | 3 | [
"MIT"
] | permissive |
import rospy
from pid import PID
from lowpass import LowPassFilter
from yaw_controller import YawController
GAS_DENSITY = 2.858
ONE_MPH = 0.44704
class Controller(object):
def __init__(self, *args, **kwargs):
#Controllers
yaw_param = {}
for key in ["wheel_base", "steer_ratio", "min_speed... | true |
71cd9de56ae8682e686baf47116794e3335ae58e | Python | anil8358/work | /rssfeed/UpdateRSS.py | UTF-8 | 3,641 | 2.6875 | 3 | [] | no_license | # This file writes the links to the a file inside the Logs folder.
# It calls necessary methods from RssFetch file to write in proper file
# It also compresses in form of Tinyurl
# Run this file periodically to Update the RSS
# Example Usage - python UpdateRSS.py
# Author - ayush_awasthi
# fp is file pointe... | true |
8ce6b1e7f7b70a1232eed798070c3aac3891f180 | Python | chemacortes/pymonad | /pymonad.py | UTF-8 | 3,997 | 3.515625 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 15 17:23:42 2015
@author: chema
"""
from __future__ import print_function
from collections import Iterable
from functools import partial
from itertools import tee
from abc import abstractmethod
###
### Monad abstract class
###
class Monad(Iterable):
def __init... | true |
ef3320ed31d8762f633f0336b797a6779f329296 | Python | mmazz/Problemas-Fisica | /Gravedad/Gravedad.py | UTF-8 | 15,527 | 2.59375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import numpy as np
import scipy.integrate as integrate
import matplotlib.pyplot as plt
import scipy as sc
FontLabel = 30
FontTicks = 30
FontLegend = 20
d = 0.25
n = 64
x = np.linspace(0,1,n)
b = np.zeros(len(x))
f = np.zeros(len(x))
error = 5*np.random.uniform(-1,1,size=(len(f)))/1000000
norm... | true |
dc95f0a1734e3177dedfc4cf2f88da211722d14b | Python | XFLWilliam/deep-dark-fantasy | /第三次作业/3.py | UTF-8 | 385 | 3.015625 | 3 | [] | no_license | from tkinter import * # 导入 Tkinter 库
root = Tk()
root.title('coding')
A = ['C', 'python', 'php', 'html', 'SQL', 'java']
B = ['CSS', 'jQuery', 'Bootstrap']
list1 = Listbox(root) # 创建两个列表组件
list2 = Listbox(root)
for item in A:
list1.insert(0, item)
for item in B:
list2.insert(0, item)
list1.pack()
list2.pa... | true |
cdf83eae6a25307018ef6c5d5ee76f65d044c87c | Python | julianje/Bunny | /Bunny/Experiment.py | UTF-8 | 10,387 | 3.0625 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""
Experiment objects bind Participant and DataTest object together with supporting functions.
"""
__license__ = "MIT"
from Participant import *
from DataTest import *
from TestResult import *
import numpy as np
import warnings
class Experiment(object):
def __init__(self, Participants... | true |
1d0e275befbba55c2010d755a73c59c7a18727e2 | Python | ArtemEvstafev/2021_Evstafev_Python | /lab1/2ex2.py | UTF-8 | 2,646 | 3.421875 | 3 | [] | no_license | import turtle as t
def Number(num):
n = 20
if (num == 0):
C0(n)
while num > 0:
q = num % 10
num //= 10
if q == 0:
C0(n)
elif q == 1:
C1(n)
elif q == 2:
C2(n)
elif q == 3:
C3(n)
elif q == 4:
... | true |
fb743983d2fa8df5bbbf43196c324be70bd6f8f1 | Python | MichaelSel/wrong_note_MEG_pilot | /stat_funcs.py | UTF-8 | 6,321 | 3.171875 | 3 | [] | no_license | # Set of functions for statistics. Main function to perform permutation tests for various statistical comparisons
from statistics import mean, stdev
from numpy import std, mean, sqrt
from statsmodels.stats.anova import AnovaRM
import numpy as np
from scipy import stats
from copy import deepcopy as dc
import matplotlib.... | true |
9421ecd6d4e8b25797bc7190535510b03c94c836 | Python | qgyyohj/hellopython | /src/set_learning.py | UTF-8 | 378 | 3.609375 | 4 | [] | no_license | set1 = {4, 1, 2, 3}
print(len(set1))
print(set1)
set1.add(4)
print(set1)
set1.update([5, 6])
print(set1)
# 使用discard和remove都可以删除set当中的元素,区别就是remove的元素在set当中没有的话会报错,而discard不会
set1.discard(6)
set2 = {4, 5, 6, 7, 8}
print(set1, set2)
print(set1 & set2)
print(set1 | set2)
print(set1 - set2)
print(set1 ^ set2)
| true |
d6c654135b61c668b95180b38565e15150b03424 | Python | IvanIsCoding/OlympiadSolutions | /beecrowd/1146.py | UTF-8 | 266 | 2.75 | 3 | [] | no_license | # Ivan Carvalho
# Solution to https://www.beecrowd.com.br/judge/problems/view/1146
#!/usr/bin/env python
# encoding : utf-8
while True:
entrada = int(input())
if entrada == 0:
break
else:
print(" ".join([str(i) for i in range(1, entrada + 1)]))
| true |
b108db80b429a3751e050b8d57c1f1cad63f911e | Python | sugihaya/pytorch-example | /train.py | UTF-8 | 3,924 | 2.84375 | 3 | [] | no_license | import numpy as np
import json
from PIL import Image
import matplotlib.pyplot as plt
import os.path as osp
import glob
import random
# torch
import torch
import torchvision
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
from torchvision import models, transforms
# 入力画像の前処理 (データ拡張含む... | true |
f95454f413067312a481433f7b3cb55da4917dc9 | Python | Danit251/n_gram_project | /main.py | UTF-8 | 1,822 | 2.796875 | 3 | [] | no_license | from nltk.corpus import brown
import statistics, viterbi_algo
corpus_tagged_sentences = brown.tagged_sents(categories='news')
corpus_sentences = brown.sents(categories='news')
training_size = round(len(corpus_sentences) * 0.9)
training_set = corpus_tagged_sentences[:training_size]
test_set = corpus_tagged_sentences[t... | true |
2d1317449e71b610bb2fbae910afe944db62e364 | Python | yichuanluanma/DayDayUP | /plan/codes/leetcode/204_countPrimes.py | UTF-8 | 444 | 3.453125 | 3 | [] | no_license | # coding=utf-8
class Solution:
def countPrimers(self, n):
"""
:param n: int
:return: int
"""
if n < 3:
return 0
prime = [True] * n
prime[0] = prime[1] = False
for i in range(2, int(n ** 0.5) +1):
if prime[i] == 1:
... | true |
4179fa2958fef62fb893272eeafe95a48d809737 | Python | guylich/cytoreason_home_assignment | /experiment_summary.py | UTF-8 | 5,494 | 2.5625 | 3 | [] | no_license | import requests
import pandas as pd
import xmltodict
import json
ENTREZ_SEARCH_URL = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db={db_name}&term={search_term}&retmode=json&retmax=1000'
ENTREZ_SUMMARY_URL = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db={db_name}&id={ids}&retmode=json... | true |
bc43be2fbb327f2ea9ce349c68c09440423a9926 | Python | RedFlowerYeah/Selenium | /checkbox/checkbox1_css_xpath.py | UTF-8 | 907 | 3.484375 | 3 | [] | no_license | from selenium import webdriver
import os,time
'''
利用Xpath和css找到页面元素
'''
driver=webdriver.Firefox()
file_path='file:///'+os.path.abspath('checkbox.html')
driver.get(file_path)
'''
通过Xpath找到type=checkbox的元素
checkboxes=driver.find_elements_by_tag_name("//input[@type='checkbox']")
'''
#通过css元素来找到type=checkbox的元素
checkbo... | true |
fd1948c0be689073069e98f02121f4cf442cae03 | Python | tea1013/preferential-gp | /src/functions/gp_sample_path.py | UTF-8 | 1,817 | 2.921875 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
from .function import Function
from scipydirect import minimize
from sklearn.kernel_approximation import RBFSampler
class GPSamplePath(Function):
def __init__(self, seed=1):
self.dim = 1
self.bounds = [[-3, 3]]
self.y_bounds = [-2, 2]
... | true |
98b61c066143b6ac49562d2c5e58d3140690243f | Python | thurn/dungeonstrike | /scripts/generate_asset_references.py | UTF-8 | 6,042 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | #!/usr/bin/env python2.7
from __future__ import print_function
import os
import lib
import json
import re
import collections
env = lib.init()
if not os.path.isfile(env.asset_config_path):
print("Error: assets.json not found!")
exit(1)
asset_config = json.load(open(env.asset_config_path, "r"))
class Printer:
d... | true |
207208abd3a3ca7009907ec6e205c5e4e47956c1 | Python | rHermes/adventofcode | /2016/05/y2016_d05_p02.py | UTF-8 | 499 | 2.984375 | 3 | [] | no_license | import fileinput as fi
import hashlib
# Input parsing
INPUT = "".join(fi.input()).strip().encode('ascii')
ans = ['' for _ in range(8)]
added = 0
for i in range(100000000000000):
hsh = hashlib.md5(INPUT + str(i).encode("ascii")).hexdigest()
if hsh.startswith("00000"):
if not hsh[5].isnumeric() or int... | true |
2725159d2749bdf721cdf138e7283843e6c8a939 | Python | numberone0001/CV-course | /proj6_v1/proj6_code/stats_helper.py | UTF-8 | 1,818 | 2.953125 | 3 | [] | no_license | import glob
import os
import numpy as np
from PIL import Image
from sklearn.preprocessing import StandardScaler
def compute_mean_and_std(dir_name: str) -> (np.array, np.array):
'''
Compute the mean and the standard deviation of the dataset.
Note: convert the image in grayscale and then in [0,1] before c... | true |
39cba39f24accac69fd72e8d850fb8b5d23821f5 | Python | Anwesh43/cv2-demos | /blob-detector.py | UTF-8 | 605 | 2.734375 | 3 | [] | no_license | import cv2
import numpy as np
def get_detector():
return cv2.SimpleBlobDetector()
def get_keypoints(file_name):
im = cv2.imread(file_name,0)
detector = get_detector()
return detector.detect(im)
def draw_keypoints_from_file_name(file_name):
keypoints = get_keypoints(file_name)
im = cv2.imread(f... | true |
073b75b411e4b8299fcfeb1bc259ef90753b1cd1 | Python | cqworker/DailySummary | /1-5/登录邮箱.py | UTF-8 | 894 | 2.671875 | 3 | [] | no_license | #coding:utf-8
from splinter import Browser
import time, threading
def qq_mail_login(url=None, username=None, password=None):
with Browser(driver_name="chrome") as browser:
browser.visit(url)
browser.find_by_id(u"userNameIpt").first.fill(username)
browser.find_by_id(u"pwdInput").first.fill(pa... | true |
dacf9b5fe8c743cdd19101f8b5e53980c5fc2f9d | Python | HHansi/Event-Data-Extractor | /data_extract_archive/main.py | UTF-8 | 4,741 | 2.515625 | 3 | [] | no_license | # Created by Hansi at 10/13/2020
import os
from data_extract.tweet_util import merge_without_duplicates, merge_without_duplicates_json
from data_extract_archive.tweet_extract_archive import filter_data, filter_data_multiple
from data_extract_archive.tweet_info_extract import get_tweet_summary
from util.file_util impor... | true |
9eb59d48737ab34fef755666aa9c564f047a3fbc | Python | xichenli/traffic-congestion-project | /explore.py | UTF-8 | 12,354 | 2.65625 | 3 | [] | no_license | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.preprocessing import OneHotEncoder
import math,time,gc
start = time.time()
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
train['UniqueID']=train["City"]+train['Latitude'].astype(str).str[4:7]+train['Longitude'].astype... | true |
3be2ef459aefa36f48ae124b8cb7b70b220d6afb | Python | junqueira/concurrency | /countries/flags_await.py | UTF-8 | 1,234 | 2.765625 | 3 | [
"MIT",
"LicenseRef-scancode-public-domain"
] | permissive | #!/usr/bin/env python3
"""Download flags of top 20 countries by population
asyncio await + aiottp version
Sample run::
$ python3 flags_asyncio.py
EG VN IN TR RU ID US DE CN MX JP BD NG ET FR BR PH PK CD IR
20 flags downloaded in 1.07s
"""
import asyncio
import aiohttp # <1>
from flags import BASE_U... | true |
0b935edad2dc2bb88763459f919b1bbf36e1856d | Python | Martin-Ruggeri-Bio/Desarrollo_Personal | /python/Decoradores/decoradores_complejitos.py | UTF-8 | 735 | 3.71875 | 4 | [] | no_license | loggeado = True
class Decorador(object):
def __init__(self, funcion):
self.funcion = funcion
def __call__(self, *args, **kwargs):
print("Se crea el objeto operacion")
self.funcion(*args, **kwargs)
def descripcion(funcion):
def funcionDecorada(*args, **kwargs):
print("Fun... | true |
50a1eb1b353c62e33e23ed2c654ff05e89bb6d7f | Python | Gabrielomn/DS-learning | /myscripts/medidas_de_centralidade.py | UTF-8 | 322 | 2.703125 | 3 | [] | no_license | import numpy as np
from scipy import stats
jogadores = [40000, 18000, 12000, 250000, 30000, 140000, 300000, 40000, 800000]
media = np.mean(jogadores)
mediana = np.median(jogadores)
quartis = np.quantile(jogadores, [0, 0.25, 0.5, 0.75, 1])
standartDeviation = np.std(jogadores, ddof = 1)
print(stats.describe(jogadores... | true |
db7c6db5227f1999f5554f5d73a38583afe2eee7 | Python | verhovsky/squircle | /test_squircle.py | UTF-8 | 4,516 | 3.03125 | 3 | [
"MIT"
] | permissive | import squircle
from PIL import Image
import numpy as np
from pathlib import Path
import pytest
from collections.abc import Iterable
from numbers import Number
TEST_IMAGE_PATH = Path("test_images")
if not TEST_IMAGE_PATH.is_dir():
raise SystemExit("ERROR: Couldn't find the directory containing the test images")
S... | true |
9f3b210999c542f5ef660a0fbfba23f27a57e6a2 | Python | dooblad/Station13 | /import_unuser.py | UTF-8 | 4,569 | 2.890625 | 3 | [] | no_license | import re
WARN_LOC_RE = re.compile('--> (.*):([0-9]*):([0-9]*)')
IMPORT_ITEM_RE = re.compile('warning: unused imports?: (`.*`)*')
# TODO: Actually run `cargo check`, rather than grabbing from a file.
def main():
unused_import_blocks = parse_unused_import_blocks()
# Group warn blocks by the file they occur in.... | true |
b21f3dc6b913c8b152eaf1259f8839e9afe48234 | Python | jiadaizhao/LeetCode | /0501-0600/0524-Longest Word in Dictionary through Deleting/0524-Longest Word in Dictionary through Deleting.py | UTF-8 | 537 | 3.34375 | 3 | [
"MIT"
] | permissive | class Solution:
def findLongestWord(self, s: str, d: List[str]) -> str:
def isSubstring(a, b):
i = j = 0
while i < len(a) and j < len(b):
if a[i] == b[j]:
i += 1
j += 1
return i == len(a)
longestWord = '... | true |
de36290f504c80fc718653fed57cc66e312f7185 | Python | alanross/basics-ml-sklearn | /Sklearn/src/lessons/04-loading-data/load_csv_np.py | UTF-8 | 188 | 2.765625 | 3 | [] | no_license | # Load CSV using NumPy
from numpy import loadtxt
filename = 'pima-indians-diabetes.data.csv'
raw_data = open( filename, 'rb' )
data = loadtxt( raw_data, delimiter="," )
print(data.shape)
| true |
5a59bcc1894c7f9435c8b29ddd9c8306f54887c9 | Python | akoerner/LarkUtility | /ISO_3166-1-alpha-2_Geolocation.py | UTF-8 | 1,297 | 3.0625 | 3 | [] | no_license |
import re
import sys
import urllib2
import BeautifulSoup
usage = "Run the script: ./ISO_3166-1-alpha-2_Geolocation.py IPAddress "
def normalize_whitespace(str):
import re
str = str.strip()
str = re.sub(r'\s+', ' ', str)
return str
if len(sys.argv)!=2:
print(usage)
sys.exit(0)
if len(sys.a... | true |
852bd5ad04380d072f2db979f39d15e08660e185 | Python | cqann/PRGM | /Python/Stock/yfinance/api.py | UTF-8 | 1,395 | 3.21875 | 3 | [] | no_license | import yfinance as yf
import bisect as bs
def check_if_valid(code):
try:
test = yf.Ticker(code)
var = test.info
return True
except:
return False
stock_names = []
stocks_history = []
codes = open("codes.txt","r")
index = 0
days = 0
cl = 573
for code in codes:
code = code[:-1]... | true |
9f996d6e375c4a2738a42b129412917f745acd86 | Python | Chaeng/simpleML | /ClassifyingIris_TrainTestData.py | UTF-8 | 864 | 3.15625 | 3 | [] | no_license | #
# Simple python project for classifying Iris flower: 2/2
# Credit: Introduction to Machine Learning with Python by Andreas C. Muller & Sarah Guido
# Purpose: To study Machine Learning concepts and applications. The original code was created
# by Muller & Guido and modified by the author for educational pur... | true |
4c5ed6961614f5e0f8aca65fb74fbe785be1fa60 | Python | UWGlaciology/CommunityFirnModel | /CFM_main/RCMpkl_to_spin.py | UTF-8 | 12,880 | 2.921875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
2/24/2021
This script takes a pandas dataframe containing climate data for a particular
site and generates climate histories to feed into CFM as forcing.
The script resamples the data to the specified time step (e.g. if you have
hourly data and you want a daily run, it r... | true |
6defe29f315e61643209d3b5e5baf9b96737deb4 | Python | anirudhr95/OpenStreetMap-Data-wrangling---Philadelphia-PA | /Audits_Checks/audit_state.py | UTF-8 | 357 | 2.515625 | 3 | [] | no_license | import xml.etree.cElementTree as ET
from collections import defaultdict
x = defaultdict(lambda : 0)
for _,element in ET.iterparse('philadelphia_pennsylvania.osm'):
for tag in element:
attr = tag.attrib
try:
if(attr['k']=='addr:state'):
x[attr['v']] = x[attr['v']] + 1
except KeyError:
pass
if element... | true |
247fa0543495af553f0bf538668e6c367c09ef99 | Python | Timaos123/KaggleFraud2019 | /A1_featureEngineer.py | UTF-8 | 4,789 | 2.859375 | 3 | [] | no_license | #coding:utf8
import pandas as pd
import numpy as np
import re
def getRandItem(x,myMean,myStd):
if np.isnan(x)==True:
return myStd*np.random.randn()+myMean
else:
return x
def getRandSer(mySer):
myMean=mySer.mean()
myStd=mySer.std()
return mySer.apply(lambda x:getRand... | true |
695712b5a3e26998e342af39b91d6ad5412257d8 | Python | vittorfp/production-ml-model | /app/tests/test_app.py | UTF-8 | 3,353 | 2.640625 | 3 | [] | no_license | from .common import *
def test_health_check(client):
""" Test app health """
response = client.get('/health')
assert response.status_code == 200
def test_input_completeness_1(client):
""" Missing lat and lng """
response = client.get('/predict')
assert response.status_code == 400
def test_... | true |
299d360b8ef406b8b1d547e2fb21ae0271fb22f3 | Python | ypark66/MapleJuice | /mjapplications/maple_word_count.py | UTF-8 | 221 | 2.890625 | 3 | [] | no_license | import collections
def maple(data):
data = data.replace("\n", " ")
data = data.replace("\t", " ")
data = data.split(' ')
d = collections.defaultdict(int)
for c in data:
d[c] += 1
return d
| true |
1e5967b50a6172b08461f15f24719699f8d3d924 | Python | mohammed0115/NLP | /classify.py | UTF-8 | 466 | 2.890625 | 3 | [] | no_license |
from textblob import TextBlob
with open('train.json', 'r') as fp:
cl = NaiveBayesClassifier(fp, format="json")
clasif=cl.classify("This is an amazing library!")
prob_dist.max()
round(prob_dist.prob("pos"), 2)
round(prob_dist.prob("neg"), 2)
blob = TextBlob("The beer is good. But the hangover is horrible.", cl... | true |
bfb00749b2c1c3edfcbb0a5941eaac24225c6067 | Python | goj/slist | /src/slist.py | UTF-8 | 1,218 | 3.109375 | 3 | [] | no_license | __all__ = ['cons', 'slist', 'nil']
class EmptyList:
def __iter__(self):
return iter(())
def __bool__(self):
return False
def __len__(self):
return 0
def __repr__(self):
return 'nil'
nil = EmptyList()
class ConsCell:
def __init__(self, hd, tl=nil):
self.h... | true |
55e68439772b6c9075669b21e8d8183a4ce03db2 | Python | twistedmove/contrastive-equilibrium-learning | /loss/uniform.py | UTF-8 | 1,633 | 2.53125 | 3 | [] | no_license | #! /usr/bin/python
# -*- encoding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
import time, pdb, numpy
from accuracy import accuracy
class Uniformity(nn.Module):
def __init__(self, uniform_t=2, sample_type='PoN'):
super(Uniformity, self).__init__()
self.t = unifor... | true |
7edfad3f071edf7c539be603ad8fb2d67a3c7856 | Python | code-impactor/arque | /arque/__init__.py | UTF-8 | 13,017 | 2.765625 | 3 | [
"MIT"
] | permissive | """
Asynchronous Reliable Queue (based on redis)
Inspired by Tom DeWire' article "Reliable Queueing in Redis (Part 1)" [1] and the "torrelque" python module [2].
Features:
- Asynchronous: based on asyncio and aioredis
- Reliable: at any moment task data presents in redis database
- Throttling: controls nu... | true |
9b13c6742e2cdd74b14090381aaf0e5c6cf0b5c2 | Python | halysl/python_module_study_code | /src/study_cookbook/14测试调试与异常/调试基本的程序崩溃错误.py | UTF-8 | 424 | 3.078125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import traceback
import sys
def func(n):
return n + 10
# func('Hello')
# python3 -i 调试基本的程序崩溃错误.py
# 以上指令会打开 Python shell
try:
func('hello')
except:
print('**** AN ERROR OCCURRED ****')
traceback.print_exc(file=sys.stderr)
def sample(n):
if n > 0:
sample(n-1)
... | true |
e0aa156f3289ac227894f0707b6aeceead95e2ca | Python | kivy/kivy | /kivy/garden/__init__.py | UTF-8 | 6,390 | 2.671875 | 3 | [
"LGPL-2.1-only",
"MIT",
"Apache-2.0"
] | permissive | '''
Garden
======
.. versionadded:: 1.7.0
.. versionchanged:: 1.11.1
Garden is a project to centralize addons for Kivy maintained by users. You can
find more information at `Kivy Garden <http://kivy-garden.github.io/>`_. All
the garden packages are centralized on the `kivy-garden Github
<https://github.com/kivy-gard... | true |
65c0827fed0e06114f30a9dd194703eab573328d | Python | louwjlabuschagne/basic-python-api-ci | /django_on_cloudrun/basicapi/tests.py | UTF-8 | 297 | 2.515625 | 3 | [
"MIT"
] | permissive | from django.test import TestCase
class SimpleModelTests(TestCase):
def test_simple(self):
"""
Basic Test
"""
self.assertIs(True, True)
# def test_simple_fail(self):
# """
# Basic Test
# """
# self.assertIs(True, False)
| true |
b10f2b6d52ffa2db3722ca25b0be87a0ecbc76b5 | Python | caposcar1998/NDFA-DFA | /extractDataFile.py | UTF-8 | 2,491 | 3.234375 | 3 | [] | no_license | def getLetter(line):
letter = line[line.find(",")+1:line.find("=")]
return letter
def getStates(line):
state = line.split(',')[0]
state.strip()
return state
def getElements(line):
splitWith = ">"
res = line.partition(splitWith)[2]
return res
def createDictionary(initialNode, finalNod... | true |
1366a13dc93e1f5b5fe01850708a9c66c0830fa8 | Python | Stone1231/py-sample | /dsa/array_matrix.py | UTF-8 | 554 | 3.546875 | 4 | [] | no_license | from numpy import *
#from array import * 不是這個
#adding a column
m = array([
['Mon',18,20,22,17],
['Tue',11,18,21,18],
['Wed',15,21,20,19],
['Thu',11,20,22,21],
['Fri',18,17,23,22],
['Sat',12,22,20,18],
['Sun',13,15,19,16]])
m_c = insert(m,[5],[[1],[2],[3],[4],[5],[6],[7]],1)
print(m)
p... | true |
3dc4933bb5f614e984f128a75efeaf998191af34 | Python | Tomekske/Serie-Directory | /Add-serie.py | UTF-8 | 7,171 | 3.03125 | 3 | [] | no_license | #==============================================================================#
#Title :Add-serie #
#Date :14/09/2017 #
#Version :1.1 #... | true |
034c6e69e224d5fea8d0bfd3fa5552d0ba472d34 | Python | t-mart/aes-tux | /aes_tux.py | UTF-8 | 1,747 | 2.90625 | 3 | [
"MIT"
] | permissive | from pathlib import Path
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from PIL import Image
root = Path(__file__).parent
source_image_path = root / "tux.png"
output_dir_path = root / "output"
key = b"Careful with ECB"
iv = b"Instead, use CBC"
resize_scale_factor = 16
# make the outp... | true |
ead5dc1fdd15c3e5fa936711c3a693c3f75d86f4 | Python | Brikwerk/cvpr-explorer | /explorer.py | UTF-8 | 6,535 | 2.859375 | 3 | [
"MIT"
] | permissive | import os
import requests
import json
from rich import print
from rich.console import Console
import webbrowser
from tqdm import tqdm
def clear():
if os.name == 'nt':
os.system("cls")
else:
os.system("clear")
def strip(x):
return x.strip()
def manually_filter(publications):
con... | true |
a66c3600f11a847d74e1ac3cce5c4a305532cfa6 | Python | GsekarGuna/Gunasekar | /Set 3-24.py | UTF-8 | 65 | 2.578125 | 3 | [] | no_license | num = [1,10,4,20,9,7,2];
num.sort();
print ("shortList : ", num)
| true |
bfde835a94b69499a2b38e10239021afeacc111e | Python | poob/RealPython | /Chapter 3/translate.py | UTF-8 | 414 | 3.28125 | 3 | [] | no_license | '''
Created on Jun 9, 2014
@author: Poob
'''
# This program will turn any string into "l33t h4x04" format
input = raw_input("Enter some text for transform:")
input = input.replace('a', '4')
input = input.replace('b', '8')
input = input.replace('e', '3')
input = input.replace('l', '1')
input = input.repl... | true |
e7bcb27ae56cdb490a2b00001c4b892c677ec639 | Python | aminul788/NSL-RAShip-Programm | /python-basic/Problem-Solving/triangleQuest.py | UTF-8 | 628 | 3.875 | 4 | [] | no_license | '''
Date : 16/10/2020
Day : Friday
Author : Md. Aminul Islam
Topic : Problem Solving
Problem : Triangle Quest
Problem link : https://www.hackerrank.com/challenges/python-quest-1/problem
'''
# ## using mathematical logic
for i in range(1,int(input())):
prin... | true |
e8762b48e5f96d7b6c1b9386e44937b74ed31743 | Python | rainoffallingstar/kidneycaRunDemon | /create record.py | UTF-8 | 3,252 | 3.03125 | 3 | [
"MIT"
] | permissive | # 将原始图片转换成需要的大小,并将其保存
# ========================================================================================
import os
import tensorflow as tf
from PIL import Image
# 原始图片的存储位置
orig_picture = '/content/gdrive/My Drive/twokidneyca/rawdata'
# 生成图片的存储位置
gen_picture = '/content/gdrive/My Drive/twokidneyca/inputdata'
... | true |
f52b34c75cfa37895bef00311bacec15f37b68a7 | Python | nickfang/classes | /projectEuler/webScraping/problemTemplates/248.py | UTF-8 | 264 | 3.390625 | 3 | [] | no_license | # Numbers for which Euler’s totient function equals 13!
#
#The first number n for which φ(n)=13! is 6227180929.
#Find the 150,000th such number.
#
import time
startTime = time.time()
print('Elapsed time: ' + str(time.time()-startTime)) | true |
59b4261670797137f82aee8cd80976b91a6c3661 | Python | shjang1013/Algorithm | /Programmers/Level1/짝수와 홀수.py | UTF-8 | 180 | 3 | 3 | [] | no_license | # 나의 코드
def solution(num):
if num & 1:
return 'Odd'
else:
return 'Even'
# 다른 코드
def solution(num):
return 'Odd' if num & 1 else 'Even'
| true |
33feef4a759ea2658e782dbc09ffdbe31ee60609 | Python | bea3/crowdsource-spring18 | /mod2/runner.py | UTF-8 | 3,222 | 2.953125 | 3 | [] | no_license | import networkx as nx
import community
import networkx.algorithms as nx_alg
import matplotlib.pyplot as plt
import csv
import random
# Read in CSV and turn into dictionary
tweets = []
with open('prochoice.csv', 'r') as csvfile:
reader = csv.reader(csvfile, delimiter='|')
reader.next()
for row in reader:
... | true |
b9c2b4bbc44f5ede294dfd98310455f7504a9b78 | Python | Matt-Robinson-byte/DigitalCrafts-classes | /python-exercises/n-m.py | UTF-8 | 123 | 3.984375 | 4 | [] | no_license | n = float(input("Enter starting point: "))
m = float(input("Enter ending point: "))
while n <= m:
print (n)
n += 1 | true |
78f4b167b4a13b45468e6c3b3cd4dfaa903854ec | Python | MSiletzky/AutoWordpress | /WordpressFunctions.py | UTF-8 | 5,273 | 2.703125 | 3 | [] | no_license | import pyautogui
import time
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import StaleElementReferenceException
# Loads the webp... | true |
82ad0de52377a1ff54a78107c88ea2a28732541b | Python | Brandon-Valley/subprocess_utils | /subprocess_utils.py | UTF-8 | 6,425 | 2.546875 | 3 | [] | no_license | from __future__ import print_function
import subprocess
import os
import time
# TEMP_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '//temp.txt'
''' VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV '''
'''
... | true |
0651c576f7cc9792a0349ce1cc72d6cfe941c691 | Python | shubhamguptasr/EyeBraille | /Programs/First Dictionary Test/braille_Sentence.py | UTF-8 | 1,960 | 3.0625 | 3 | [] | no_license | dict = {}
dict[str('A')] = [1,0,0,0,0,0]
dict[str('B')] = [1,1,0,0,0,0]
dict[str('C')] = [1,0,0,1,0,0]
dict[str('D')] = [1,0,0,1,1,0]
dict[str('E')] = [1,0,0,0,1,0]
dict[str('F')] = [1,1,0,1,0,0]
dict[str('G')] = [1,1,0,1,1,0]
dict[str('H')] = [1,1,0,0,1,0]
dict[str('I')] = [0,1,0,1,0,0]
dict[str('J')] = [0,1,0,1,1,0]
... | true |
ce4de8fa62516c1b7d4274340a2a11dd21de9996 | Python | J0/python-typing-koans | /koans/py/114-medium-factory-pattern.py | UTF-8 | 4,760 | 2.953125 | 3 | [] | no_license | """
Koan to learn annotating the factory method and overriding methods return types
"""
"""The code is copied from https://github.com/benoitc/gunicorn/blob/master/gunicorn/sock.py
with modification.
A lot of code is removed here for sake of understanding.
"""
import errno
import logging
import os
import socket
import ... | true |
be237e977d424effd7932b516e491ae8163651a3 | Python | cati97/BattleShip | /battle.py | UTF-8 | 5,791 | 3.671875 | 4 | [] | no_license |
import time # time.sleep(10) - number of seconds blocks the program
from battleship.print_information import *
from battleship.useful import *
from battleship.player import *
import random
def roll_dice():
return random.randint(1, 6)
def who_starts(player1, player2):
print("Let's roll a dice to see wh... | true |
29dca027860bca2a0946d55f7250e82466d377c6 | Python | JakobSeidl/pyneMeas | /pyneMeas/Instruments/USB6216In.py | UTF-8 | 2,031 | 2.6875 | 3 | [
"MIT"
] | permissive | """
@author: Adam Micolich
Updated by Jakob Seidl
This module does the input handling for the USB-6216, which is effectively a pair of analog outputs
and a set of 8 analog inputs. The output handling is done by a separate .py.
"""
import pyneMeas.Instruments.Instrument as Instrument
import nidaqmx as nmx
... | true |
b6c57b3e512fd1cc4e7d492c69153669aff0df93 | Python | BrendaSpalenza/algoritmos | /procurandoVogais.py | UTF-8 | 259 | 3.671875 | 4 | [] | no_license | palavras = ('Mario', 'Luigi', 'Peach', 'Yoshi', 'Bowser')
for palavra in palavras:
print('\nPalavra: {}. Vogais: ' .format(palavra.upper()), end='')
for letra in palavra:
if letra.lower() in 'aeiou':
print(letra.upper(), end=' ')
| true |
dd30f1503440cca150eac66bcd319d76120dc635 | Python | jaebee94/TIL | /BAEKJOON/단계별로 풀어보기/11재귀/11729_하노이탑이동순서.py | UTF-8 | 370 | 3.171875 | 3 | [] | no_license | cnt = 0
def hanoi(block, a, b, c):
global cnt
if block == 1:
process.append([a, c])
cnt += 1
else:
hanoi(block - 1, a, c, b)
process.append([a, c])
cnt += 1
hanoi(block - 1, b, a, c)
process = []
hanoi(int(input()), 1, 2, 3)
print(cnt)
for i in range(len(pro... | true |
49b36d74d099b18d69eaaf378bb6bbe8467e4282 | Python | YutingYao/crater_lakes | /bin/plot_scatter_v0.1.py | UTF-8 | 498 | 3.015625 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
plot_scatter.py
Created on Mon Feb 13 19:01:40 2017
@author: sam
"""
import pandas as pd
import matplotlib.pylab as plt
x = 'T'
y = 'T'
# opens excel file
df = pd.read_excel('/home/sam/Dropbox/HIGP/Crater_Lakes/Dmitri_Sam/data/Yugama/Yugama.xlsx')
# scatter plot... | true |
c28c7617738514761b70f14b3aefdc438ecc9034 | Python | Nightfurex/viadot | /viadot/sources/sqlite.py | UTF-8 | 1,372 | 2.96875 | 3 | [
"MIT"
] | permissive | from .base import SQL
class SQLite(SQL):
"""A SQLite source
Args:
server (str): server string, usually localhost
db (str): the file path to the db e.g. /home/somedb.sqlite
"""
def __init__(
self,
query_timeout: int = 60,
*args,
**kwargs,
):
... | true |
5a56400e7b17be2ced085d70ac4f3c2fb7ad5cb6 | Python | Bharanij27/bharanirep | /PyhuntS26.py | UTF-8 | 152 | 3.1875 | 3 | [] | no_license | n=int(input())
r=list(map(int,input().split()))
q=r[::-1]
for i in range(0,n):
if i==n-1:
print(q[i],end="")
else: print(q[i],end="->")
| true |
e49da59845bdf764dd3a9469f094051cb0756761 | Python | lulukoukou/EE-596B-Conversational-AI | /lambdaFunc/helper.py | UTF-8 | 4,657 | 2.984375 | 3 | [] | no_license |
from __future__ import print_function
import sys
sys.path.append("verification/verification1/")
import base # the base class derived by all classes in derived
import derived # directory file containing imports for derived classes
import word_db # dynamo-db wrapper class
import verificati... | true |
0a56c898123533990799089bf2a9005086f32b81 | Python | mbat113114/python- | /project_main.py | UTF-8 | 1,001 | 3.109375 | 3 | [] | no_license |
import random
import colorama
from colorama import Fore,Back,Style
im
colorama.init(autoreset = True)
#class is not there
def dec1(fun):
def exc():
print(f"{Fore.GREEN} excuting know")
fun()
print(f"{Fore.GREEN} excuted")
return exc
#class
title = f"{Fore.GREEN}W" + f"{Fore.RED}E" + f"{Fore... | true |
8d32507dafe4d7a40edc0b6de1f471092b129e75 | Python | kelfan/PythonAI | /ANN workshop2/Q5-6 K-fold.py | UTF-8 | 1,722 | 3.140625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 9 21:25:13 2017
@author: chaofanz
"""
# Create your first MLP in Keras
from keras.models import Sequential
from keras.layers import Dense
import numpy
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import StratifiedKFold... | true |
3743388e78945cb26c6af147d17d44bee6da90fd | Python | Shivendra2407/cart_apis | /cart_apis/cart_data_api/views.py | UTF-8 | 2,630 | 2.53125 | 3 | [] | no_license | from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST, HTTP_201_CREATED
from .models import Cart
from .serializers import AddItemToCartSerializer, CartSerializer, RemoveItemFromCartSerializer
from rest_framework.permissions import IsAuthenticated
from rest_fram... | true |
8d5a5b24d02d14f24d0a4d485132e98f6b3b6728 | Python | McCoubs/project_euler | /smallest_continuous_multiple/main.py | UTF-8 | 530 | 3.640625 | 4 | [
"MIT"
] | permissive | import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from smallest_continuous_multiple import smallest_continuous_multiple
if __name__ == "__main__":
# get inputs form user
multiple = input("Please enter a number: ")
# call func with inputs
smallest_int = ... | true |
1db53c7aeace60e9eece8457d7cbcc0239586fe0 | Python | kkkkkaran/BouquetFlowers | /Data Preparation/Mods for Tensorflow-yolov3/modScript.py | UTF-8 | 1,920 | 2.78125 | 3 | [] | no_license | import csv
def flowerId(row_label):
if row_label == 'Rose':
return '0'
elif row_label == 'Carnation':
return '1'
elif row_label == 'Daffodil':
return '2'
elif row_label == 'Sunflower':
return '3'
elif row_label == 'Tulip':
return '4'
elif row... | true |
5becfc078212eb77b9a7193c8772c7a31258b71a | Python | Duncan-tree-zhou/scripts4ML | /Analysis_note/1.1.MonteCarloOptionValuation.py | UTF-8 | 2,294 | 3.15625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from __future__ import division, print_function
from math import log, sqrt, exp
from scipy import stats
from time import time
from random import gauss, seed
import numpy as np
def bsm_call_values(S0, K, T, r, sigma):
"""
根据BSM公式计算期权估值
参数
======
S0: 初始标... | true |
c447028dd8fcc53dbc5cae5ff2fe21551de11fc1 | Python | steffemb/INF4331 | /Assignement3/polynomials.py | UTF-8 | 7,750 | 3.71875 | 4 | [] | no_license | class Polynomial:
#polynomials are defined p = a_0 + a_1 x + .... + a_n x^n
def __init__(self, coefficients):
"""coefficients should be a list of numbers with
the i-th element being the coefficient a_i."""
#raise NotImplemented
self.coefficients = coefficients
def degree... | true |
71f4a664ae462d8d3fdf5fbbabd3b0f9d85851fb | Python | j16949/Programming-in-Python-princeton | /2.4/11/estimate.py | UTF-8 | 2,086 | 3.265625 | 3 | [] | no_license | #-----------------------------------------------------------------------
# estimate.py
#-----------------------------------------------------------------------
import sys
import stdio
import percolation
import math
import stdarray
import stddraw
import stdrandom
import stdstats
import gaussian
import percolationio
#-... | true |
2357d58cf9ef977ff86df35bf1358c4d77181819 | Python | lcsdn/ML-kernels | /kernel_code/kernels.py | UTF-8 | 7,307 | 3.609375 | 4 | [] | no_license | import numpy as np
from time import time
class Kernel:
"""General class of kernels."""
@staticmethod
def _precomputations(set1, set2, same_sets):
return set1, set2
def _lazy_kernel(self, precomputations, i, j):
set1, set2 = precomputations
return self(set1[i], set2[j])
... | true |
6c7c7ec2e1f775d0b27f50094be5e9eab0b23ea5 | Python | chaudharyaditi2022/DSA-Solution-repo | /Recursion/staircase.py | UTF-8 | 381 | 3.171875 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
# In[7]:
def countways(height, maxsteps):
if height <= 1:
return 1
count = 0
for h in range(1, min(maxsteps,height)+1):
count += countways(height - h, maxsteps)
return count
def staircase(height, maxsteps):
return countways(height, maxsteps)
... | true |
9fc0ffaa5aee844e7b768a89da7deb3108f87b92 | Python | ASU-CompMethodsPhysics-PHY494/activity_10_numbers_sine_series | /series.py | UTF-8 | 418 | 3.109375 | 3 | [] | no_license | # implementation
def sin_recursive(x, eps=1e-16):
"""Calculate sin(x) to precision eps.
Arguments
---------
x : float
argument of sin(x)
eps : float, optional
desired precision
Returns
-------
func_value, N
where func_value = sin(x) and N is the number
of term... | true |
b327f2e0671a2063ea952a93cc990ae1c60624a4 | Python | LucasXavierChurchman/KOBE-Bot | /src/image_processing.py | UTF-8 | 2,585 | 2.921875 | 3 | [] | no_license | import os
from tempfile import TemporaryFile
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from google_images_download import google_images_download
from skimage.color import gray2rgb, rgb2gray, rgba2rgb
from skimage.io import imread, imread_collection
from skimage.transform import resize
def do... | true |
24680f21adf9282c0753f398a2b5b339071c1792 | Python | SharpShooter17/Python | /Programy na kolokwium/zadanie_pil.py | UTF-8 | 1,710 | 3.140625 | 3 | [] | no_license | import PIL
from PIL import Image
im = Image.open("audi.jpg")
print im.format, im.size, im.mode
"""PRZY DOWOLNYM MIESZANIU ODKOMENTUJ PONIZSZE"""
"""list_of_regions = [[0 for x in range(0,3)] for y in range(0,3)]
list_of_boxes = [[0 for x in range(0,3)] for y in range(0,3)]
for x in range(0,3):
for y in range(0,3):... | true |
70e6bcde90621b05a01c0144198af3299a3f1a80 | Python | zerghua/leetcode-python | /N976_LargestPerimeterTriangle.py | UTF-8 | 1,064 | 4 | 4 | [] | no_license | #
# Create by Hua on 5/7/22.
#
"""
Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0.
Example 1:
Input: nums = [2,1,2]
Output: 5
Example 2:
Input: nums = [1,2,1]
O... | true |
2857584dfb4fec59ee5c85f91b26336e00234e81 | Python | charlie0829/Python3 | /Excercice/Class.py | UTF-8 | 1,289 | 4.1875 | 4 | [] | no_license | class MyClass:
"""一个简单的类实例"""
i = 12345
def f(self):
return 'hello world'
# 实例化类
x = MyClass()
# 访问类的属性和方法
print("MyClass 类的属性 i 为:", x.i)
print("MyClass 类的方法 f 输出为:", x.f())
#类定义
class people:
#定义基本属性
name = ''
age = 0
#定义私有属性,私有属性在类外部无法直接进行访问
__weight = 0
#定义构造方法
d... | true |
79638cbca6914dbb302209b452fb229f603d401d | Python | nexuslrf/NLP_MathWordProblem | /codes-run/main.py | UTF-8 | 3,020 | 2.609375 | 3 | [] | no_license | import argparse
import torch
from data import Data
from embedding_google import Get_Embedding
from manhattan_lstm import Manhattan_LSTM
from train_network import Train_Network
from run_iterations import Run_Iterations
use_cuda = torch.cuda.is_available()
if __name__ == "__main__":
parser = argparse.ArgumentPar... | true |