seq_id
stringlengths
4
11
text
stringlengths
113
2.92M
repo_name
stringlengths
4
125
sub_path
stringlengths
3
214
file_name
stringlengths
3
160
file_ext
stringclasses
18 values
file_size_in_byte
int64
113
2.92M
program_lang
stringclasses
1 value
lang
stringclasses
93 values
doc_type
stringclasses
1 value
stars
int64
0
179k
dataset
stringclasses
3 values
pt
stringclasses
78 values
74630975144
import math import os.path import re import html def calcScore(now, best): if now<1e-9: return 0 #return now / best return best / now def isBetter(now, best): if now<1e-9: return False #return best < now return now < best def main(): import sqlite3 db = sqlite3.connect...
colun/mmlang
src/mmhttpd.py
mmhttpd.py
py
15,984
python
en
code
21
github-code
36
70010896105
# 구구단2단 출력하는 함수를 만들어 보세요 # gugudan def gugudan(dan) : for j in range(1,10): print(dan,'x', j, '=', dan*j) for dan in range(2, 20+1): gugudan(dan) # 이거 하는데 1시간 걸림
Kyeongrok/python_yla
com/week2/am/01_gugudan.py
01_gugudan.py
py
232
python
ko
code
1
github-code
36
4578620215
import numpy as np def main(x): result = 1 k = 2 while x> 1.99: if int(x**(1/k)) == 1: break elif int(x**(1/k)) == x**(1/k): result *= k x = x**(1/k) k = 2 else: k+=1 if result<=1: return "NO" return result ...
naphattar/Betaprogramming
Chapter 1/1043.py
1043.py
py
428
python
en
code
0
github-code
36
38715715582
#!/usr/bin/env python3 import hashlib key = 'iwrupvqb' i = 1 while True: s = '{}{}'.format(key, i) h = hashlib.md5(s.encode('ascii')).hexdigest() if h.startswith('00000'): print("Answer for 5 zeros is {} ({})".format(i, s)) break i += 1 i = 1 while True: s = '{}{}'.format(key, i) ...
lvaughn/advent
2015/4/advent_coin.py
advent_coin.py
py
488
python
en
code
1
github-code
36
8660975044
from PYmodule import * log10Ms = [9,10,11,12] typenames = ['H'+r'$_2$', 'H-H'+r'$_2$', 'H-H'] pres = ['./data/1e9','./data/1e10','./data/1e11','./data/1e12','./data/1e13'] print('z=6 to 4, t in Myr: ', (t_from_z(4)-t_from_z(6))/Myr) M_grow_ratio = 5. f_lambda = np.log(M_grow_ratio) * t_Edd / (t_from_z(4)-t_from_z...
lovetomatoes/BHMF
Mdist_grow.py
Mdist_grow.py
py
4,788
python
en
code
0
github-code
36
26425710929
#coding: latin-1 import numpy as np def shell_tube_eff(NTU,Cr,nshell=1): # # shell and tube (nshell shell pass) # NTU is the total NTU NTUn = NTU/nshell G = np.sqrt(1+Cr**2) y = np.exp(-NTUn*G) ep1 = 2/(1+Cr+G*(1+y)/(1-y)) if nshell > 1: if Cr == 1: ep = nshell*ep1/(1+ep1*(n-1))...
LouisLamarche/Fundamentals-of-Geothermal-Heat-Pump-Systems
lib/heat_exchanger_md.py
heat_exchanger_md.py
py
1,678
python
en
code
1
github-code
36
38930582027
import torch from torch import nn def conv_block(in_channel, channel, kernel_size=3, stride=1, padding=1, inplace=False): norm = nn.InstanceNorm2d return nn.Sequential( nn.Conv2d(in_channel, channel, kernel_size=kernel_size, stride=stride, padding=padding, bias=True), norm(channel, affine=True,...
QiliangFan/Drive
models/resnetx.py
resnetx.py
py
2,452
python
en
code
0
github-code
36
8230873640
import sys import parser ''' Grammar: program = statement statement = seq | single seq = single; seq | single; single single = assign | if | for assign = var = expr var = x | y const = 0 | 1 expr = var | const | expr + var | expr + const if = if cmp then statement else statement endif for = for var = expr; cm...
lsiddiqsunny/Undergraduate-Thesis
Code and data set of Tree to tree neural network progration/Tree2Tree-master/src/For2Lam/lang_for.py
lang_for.py
py
4,461
python
en
code
3
github-code
36
14825110137
import sys import os import itertools import numpy as np import enum OUTPUT_FILE = 'vector_type_predef.hpp' STATIC_BUFFER_TYPE = 'static_buffer' DEVICE_HOST_MACRO = 'DEVICE_HOST' def gen_p2_array(n): i = 1 rtn = [] while i <= n: rtn.append(i) i = i * 2 return rtn class vector_type(obj...
carlushuang/gcnasm
hgemm_mfma/gen_vec_type.py
gen_vec_type.py
py
2,420
python
en
code
6
github-code
36
27900592036
# -*- coding: utf-8 -*- import numpy as np def moranI(W,X): ''' W:空间权重矩阵 X:观测值矩阵 归一化空间权重矩阵后进行moran检验 ''' W = np.array(W) X = np.array(X) X = X.reshape(1,-1) print('===========w:{}',W) print('===========x:{}',X) #归一化 print('W.sum:{}',W.sum(axis=1)) W = W/W.sum(axis=1...
fangweilong/python-algorithm
莫兰指数/MoranI.py
MoranI.py
py
2,858
python
en
code
0
github-code
36
31243963609
import argparse import datetime import pycloudlib CI_DEFAULT_TAG = "uaclient" def get_parser(): parser = argparse.ArgumentParser() parser.add_argument( "-t", "--tag", dest="tag", action="store", default=CI_DEFAULT_TAG, help=( "Tag to determine which instances will be dele...
canonical/server-test-scripts
ubuntu-advantage-client/gcp_cleanup.py
gcp_cleanup.py
py
3,138
python
en
code
8
github-code
36
36955105209
import wttest from suite_subprocess import suite_subprocess from wtdataset import SimpleDataSet, ComplexDataSet from wiredtiger import stat from wtscenario import make_scenarios # test_compact.py # session level compact operation class test_compact(wttest.WiredTigerTestCase, suite_subprocess): name = 'test_comp...
mongodb/mongo
src/third_party/wiredtiger/test/suite/test_compact01.py
test_compact01.py
py
4,370
python
en
code
24,670
github-code
36
28657759948
from torchvision import transforms from torch.utils.data import dataset, dataloader from torchvision.datasets.folder import default_loader from utils.RandomErasing import RandomErasing from utils.RandomSampler import RandomSampler from opt import opt import glob import pandas as pd import numpy as np import os.path as ...
DavisonHu/AICity-track2-Re-id
loader/Evaluation_AICity_data.py
Evaluation_AICity_data.py
py
4,017
python
en
code
1
github-code
36
37217931593
def time_main(): from mult_optim_cython import main import timeit import numpy as np time_arr = timeit.repeat(main, repeat=5, number=1) print('Times:', time_arr) print('Median:', np.median(time_arr)) return if __name__ == "__main__": time_main()
RohanBh/cs263_project
programs/cython_np/time_mult_optim.py
time_mult_optim.py
py
280
python
en
code
0
github-code
36
25822109904
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def read_info(file): while True: data = file.readline(); if not data: break yield data class Contact: def __init__(self, first_name = '', last_name = '', number = 0): self.first_name = first_name self.last_name ...
LiudaShevliuk/python
lab14_2/lab14_2.py
lab14_2.py
py
3,254
python
en
code
0
github-code
36
43046392244
import sys def search_value(my_dict, elem): for key, value in my_dict.items(): if value.lower() == elem.lower(): return value return None def search_key(my_dict, elem): for key, value in my_dict.items(): if key.lower() == elem.lower(): return key return None de...
GoryachevDaniil/ft_Python_Django_Piscine
day01/ex05/all_in.py
all_in.py
py
1,368
python
en
code
0
github-code
36
22450452976
""" Team 46 Haoyue Xie 1003068 @Melbourne Jiayu Li 713551 @Melbourne Ruqi Li 1008342 @Melbourne Yi Zhang 1032768 @Melbourne Zimeng Jia 978322 @Hebei, China """ import json from shapely.geometry import shape, Point #current_region is a dictionary def streaming_region(current_region, tweet): if current_region != {...
yzzhan4/COMP90024-AuzLife
TwitterStreaming/streaming_region.py
streaming_region.py
py
1,436
python
en
code
0
github-code
36
21366302281
""" URL: https://www.lintcode.com/problem/invert-binary-tree/description Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ # My own solution, simple recursion. class Solution: """ @param root: a TreeNode, the root of the b...
simonfqy/SimonfqyGitHub
lintcode/easy/175_invert_binary_tree.py
175_invert_binary_tree.py
py
1,448
python
en
code
2
github-code
36
37655164252
from django.shortcuts import render from django.http import HttpResponse from hello.models import User import random # Create your views here. count = 0 def World(request): return HttpResponse('this is app2') def Add_user(request): global count count += 1 user = User() user.user_age = ...
yy1110/Mydjango
django_first/app2/views.py
views.py
py
2,338
python
en
code
1
github-code
36
22714296408
import sys sys.path += ['.'] # noqa from unittest.mock import Mock from mycroft.services.paths_service import resolve_refs, StringGetter from mycroft.services import paths_service PathsManager = paths_service.PathsService paths_service.resource_filename = lambda *args: '' class TestResolver: def test_1(self): ...
MatthewScholefield/mycroft-light
tests/managers/test_paths_manager.py
test_paths_manager.py
py
1,517
python
en
code
6
github-code
36
38336151204
from streamlit_webrtc import webrtc_streamer import av import cv2 cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") class VideoProcessor: def recv(self, frame): frm = frame.to_ndarray(format="bgr24") CONFIDENCE = 0.5 SCORE_THRESHOLD = 0.5 IOU_THRESHOL...
NeTRooo/CyberGarden2022-Atom
rtc_test.py
rtc_test.py
py
1,710
python
en
code
0
github-code
36
4201928823
class Game: # def __init__(self): # self. def run_game (self): self.display_title () self.game_rules() self.display_winner() self.play_mode () def display_title (self): print("\nWelcome to Rock, Paper, Scissors, Lizard, Spock \n") ...
Lorena-Valdez/RPSLS_1
RPSLS/game.py
game.py
py
1,694
python
en
code
0
github-code
36
20858123687
#https://leetcode.com/problems/masking-personal-information/ class Solution: def solveEmail(self,s): print(s) name,domain=s.split("@")[0].lower(),s.split("@")[1].lower() print(name,domain) name=name[0:1]+"*****"+name[-1] return name+"@"+domain def solvePhon...
manu-karenite/Problem-Solving
Strings/maskingPersonalInformation.py
maskingPersonalInformation.py
py
1,091
python
en
code
0
github-code
36
639825382
# Description: 2. project 'Bulls and cows' in Engeto Online Python Academy # Author: Jiri Gloza # Define basic variables nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] Welcome_message = ''' Hi there ! I've generated a random 4 digit number for you. Let's play a bulls and cows game. Enter a number''' import random # Define ma...
Globerx/Engeto_academy_Project2
Project2.py
Project2.py
py
2,291
python
en
code
0
github-code
36
24888015371
from typing import Iterable import torch import numpy as np from scipy.spatial.distance import cdist from tqdm import tqdm import ot def cost_matrix( data: np.ndarray, cost: str = 'correlation', normalize_features: bool = True) -> np.ndarray: """Compute an empirical ground cost matrix, i.e. a pairwise distance m...
cantinilab/OT-scOmics
src/otscomics/__init__.py
__init__.py
py
5,668
python
en
code
31
github-code
36
71404383785
import random, sys # random.seed(42) from person import Person from logger import Logger from virus import Virus import argparse class Simulation(object): def __init__(self, pop_size, vacc_percentage, initial_infected, virus): # TODO: Create a Logger object and bind it to self.logger. # Remember t...
b3fr4nk/Herd-Immunity-Sim
simulation.py
simulation.py
py
9,203
python
en
code
0
github-code
36
73011952423
#-*- coding: utf-8 -*- import csv import os import pymysql import pandas as pd # 一个根据pandas自动识别type来设定table的type def make_table_sql(df): columns = df.columns.tolist() types = df.ftypes # 添加id 制动递增主键模式 make_table = [] for item in columns: if 'int' in types[item]: char = item + ' ...
cyj-user/MedData
sampleData/data_input.py
data_input.py
py
2,208
python
en
code
0
github-code
36
10350206274
#************************************************************************* # 2. Dictionary #************************************************************************* # How to define an empty dictionary mydict = {} # How to initialize a dictionary # setdefault(key, default_value) returns default value for the associate...
gregsurber/Practice
Week_2/wk2_code_demo.py
wk2_code_demo.py
py
4,444
python
en
code
0
github-code
36
556091123
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html import os import scrapy import json from urllib.parse import urlparse from pymongo import MongoClient from scrapy.pipelines.im...
GruXsqK/Methods_scraping
Lesson_6/Youla_parser_project/youlaparser/pipelines.py
pipelines.py
py
1,918
python
en
code
0
github-code
36
4413470363
''' xを数字とセットにした二次元配列を作る sを数字に置き換えたものと、元のままのものの三次元配列にする →二次元配列では取り扱いきれないので、遠慮なく三次元へ ソートして、出す ''' from collections import defaultdict x = input() n = int(input()) s = [input() for _ in range(n)] new = defaultdict(dict) for i in range(len(x)): new[x[i]] = i ans = [] for i in s: inner = [] for j in i: inner....
burioden/atcoder
submissions/abc219/c.py
c.py
py
566
python
ja
code
4
github-code
36
13989800577
# -*- coding: utf-8 -*- import copy from io import BytesIO from datetime import datetime from xlwt import Workbook, XFStyle, Borders, Pattern class ExcelWT(Workbook): """Excel生成工具 """ def __init__(self, name, encoding=r'utf-8', style_compression=0): super().__init__(encoding, style_compressio...
wsb310/hagworm
hagworm/extend/excel.py
excel.py
py
2,028
python
en
code
13
github-code
36
73903114025
import pandas as pd from datetime import date, timedelta, datetime from meteostat import Point, Daily import statsmodels.api as sm def read_data(): # Set time period start = datetime(2010, 1, 1) end = pd.to_datetime(datetime.now().strftime("%Y-%m-%d")) # Create Point for Vancouver, BC vancouver...
Marcosgrosso/automation_series
predict_model.py
predict_model.py
py
1,724
python
en
code
0
github-code
36
73947800422
from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('',views.ProductList,name='ProductList'), path('productdetails',views.productdetails,name='productdetails'), path('orderslist',views.OrdersList,name='OrdersList'), path('addcolumns',views.AddColumns,n...
Fawazk/VofoxSolutions-test
vofox/purchase/urls.py
urls.py
py
403
python
en
code
1
github-code
36
4193041157
# put your python code here lst = [] while 5: a = input().split() if a == ['end']: break b = [int(i) for i in a] lst.append(b) print(lst) for i in range(len(lst)): for j in range(len(lst[i])): print(lst[i][j - len(lst) + 1] + lst[i][j - 1] + lst[i - 1][j] + lst[i - len(lst) + 1][j], ...
Eduard-z/stepic
spisok.py
spisok.py
py
343
python
en
code
0
github-code
36
4492015736
## Load training SDFs import argparse import colorsys import os import numpy as np import pathlib import tqdm import open3d as o3d import random from CARTO.simnet.lib.datapoint import decompress_datapoint from CARTO.Decoder import utils from CARTO.Decoder.data import dataset from CARTO.Decoder import config from CARTO...
robot-learning-freiburg/CARTO
CARTO/Decoder/visualizing/visualize_sdf_values.py
visualize_sdf_values.py
py
2,511
python
en
code
10
github-code
36
74973903784
#Question 5 def subsequence(st): if len(st) == 1: return list(st) else: subs = subsequence(st[:len(st)-1]) for element in subs: if element[-1] < st[-1]: subs += [element + st[-1]] subs += [st[-1]] return subs def long_com_seq...
SimoneFiorellino/ADM-HW3
q5.py
q5.py
py
780
python
en
code
0
github-code
36
72508017705
''' liguangyao 10/25/2023 guangyaoli@ruc.edu.cn ''' import os import torch from torchvision import transforms, utils from PIL import Image import numpy as np import glob from imagebind import data from imagebind.models import imagebind_model from imagebind.models.imagebind_model import ModalityType device = "cuda:1...
ayameyao/ResearchToolCode
FeatureExtraction/Extract_ImageBind_Features/extract_imagebind_feats.py
extract_imagebind_feats.py
py
7,418
python
en
code
2
github-code
36
11425205526
from edera import Condition from edera import Task from edera.exceptions import StorageOperationError from edera.requisites import shortcut from edera.storages import InMemoryStorage from edera.workflow import WorkflowBuilder from edera.workflow.processors import TargetCacher def test_target_cacher_checks_target_only...
thoughteer/edera
tests/unit/workflow/processors/test_target_cacher.py
test_target_cacher.py
py
2,571
python
en
code
3
github-code
36
19453386854
import requests #Requests é um biblioteca, um pacote de código. Para instalar usar: pip install requests from tkinter import * #Pegando todas as informações da biblioteca tkinter. def pegar_cotacoes(): requisicao = requests.get("https://economia.awesomeapi.com.br/last/USD-BRL,EUR-BRL,BTC-BRL") requisicao_dic...
jessicarios-DevOps/Tkinter-python
janela.py
janela.py
py
1,628
python
pt
code
0
github-code
36
21803177273
""" receives the fieldnames and dimension values for a single species calculates parameters like Volume, Area, and returns them together with sorted Dimensions (min, mid, max) Disclaimer: calculations of A and V are pythonized from the matlab script cellgeom.m by A. Ryabov Tested for: python 3.6 """ # Library imports ...
AlexRyabov/Cell-shape
python/calc_geom_funcs.py
calc_geom_funcs.py
py
28,215
python
en
code
2
github-code
36
19738731229
from vigilo.models.session import DBSession, MigrationDDL from vigilo.models import tables def upgrade(migrate_engine, actions): """ Migre le modèle. @param migrate_engine: Connexion à la base de données, pouvant être utilisée durant la migration. @type migrate_engine: C{Engine} @param act...
vigilo/models
src/vigilo/models/migration/002_Host_mainip_is_really_an_address.py
002_Host_mainip_is_really_an_address.py
py
803
python
fr
code
4
github-code
36
22620837649
class Student: def __init__(self, name, age, gpa, adviser, email): self.name = name self.age = age self.gpa = gpa self.adviser = adviser self.email = email students = [ Student("Dimash", 19, 3.7, "Abdygalym", "dimash@gmail.com"), Student("Ilyas", 19, 3.1, "Abdygalym", "ilyas@gmail.com"), ...
AlikhanIT/func2
main.py
main.py
py
2,255
python
ru
code
0
github-code
36
20655962047
import dataclasses import subprocess from typing import Any, ClassVar, List, Optional from fancy_dataclass.utils import DataclassMixin, issubclass_safe, obj_class_name class SubprocessDataclass(DataclassMixin): """Mixin class providing a method for converting dataclass fields to command-line args that can be use...
jeremander/fancy-dataclass
fancy_dataclass/subprocess.py
subprocess.py
py
5,568
python
en
code
0
github-code
36
2360892821
""" 字符串中字母大小写互换 【问题描述】编写程序,功能是把输入的字符串的大写字母变成小写字母,小写字母变成大写字母,非字母的字符不作变换。输出变换后的结果。 【输入形式】字符串,包含字母和非字母字符。 【输出形式】字符串,字母的大小写已经发生变换。 【样例输入】abcABC 【样例输出】ABCabc """ n = input() m = "" for i in n : if i.isupper(): i = i.lower() m = m + i elif i.lower(): i = i.upper() m = m + i print(m)
xzl995/Python
CourseGrading/5.1.8字符串中字母大小写互换.py
5.1.8字符串中字母大小写互换.py
py
579
python
zh
code
3
github-code
36
4393844283
# 클레어와 물약 # r1 x # https://www.acmicpc.net/problem/20119 # https://welog.tistory.com/256 import sys from collections import deque input = sys.stdin.readline n, m = map(int, input().split()) graph = [set() for _ in range(n + 1)] recipe_dict = {} for _ in range(m): data = list(map(int, input().split())) if d...
sjjam/Algorithm-Python
baekjoon/20119.py
20119.py
py
1,292
python
en
code
0
github-code
36
32296716535
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="trello_client-basics-api-denisshvayko", version="0.0.1", author="denis", author_email="denis.shvayko@phystech.edu", description="Обертка для trello API", long_description=long_description, long_des...
denisshvayko/D1.8
setup.py
setup.py
py
640
python
en
code
0
github-code
36
31757699716
print('Bom dia') count=0 soma =0 for idade in range(10): idade=int(input('Digite sua idade:')) if(idade>=18): count=count+1 soma=idade+soma media=soma/10 print('a quantidade de pessoas é:',count) print('A media:', media)
4ntonio19/PythonExercises
PythonExercises/ListaRevisão6.py
ListaRevisão6.py
py
240
python
pt
code
0
github-code
36
9284740252
a = {'timezone': 'UTC', 'serverTime': 1570802268092, 'rateLimits': [{'rateLimitType': 'REQUEST_WEIGHT', 'interval': 'MINUTE', 'intervalNum': 1, 'limit': 1200}, {'rateLimitType': 'ORDERS', 'interval': 'MINUTE', 'intervalNum': 1, 'limit': 1200}], 'exchangeFilters': [], 'symbols': [...
Sam-0225/Quant_Grid
test.py
test.py
py
2,134
python
en
code
1
github-code
36
30466798237
class Solution: def shortestWordDistance(self, words, word1: str, word2: str) -> int: res = float('inf') res1 = [] res2 = [] for i in range(len(words)): if words[i] == word1: res1.append(i) if words[i] == word2: res2.append(i) ...
dundunmao/LeetCode2019
245. Shortest Word Distance III.py
245. Shortest Word Distance III.py
py
1,097
python
en
code
0
github-code
36
42493212575
""" WRITEME """ from __future__ import absolute_import, print_function, division from copy import copy, deepcopy from sys import getsizeof import sys import traceback import numpy as np import theano from theano.compat import izip from six import reraise from six.moves import StringIO from theano.gof import utils fro...
Theano/Theano
theano/gof/link.py
link.py
py
38,073
python
en
code
9,807
github-code
36
70308798185
import wx class SlideshowFrame(wx.Frame): def __init__(self,**kwargs): wx.Frame.__init__(self, **kwargs) self.SetBackgroundColour(wx.BLACK) self.panel = wx.Panel(self, pos=self.Rect.GetPosition(), size=self.Rect.GetSize()) self.empty_img = wx.EmptyImage(self.Rect.GetWidth()...
jamestunnell/auto-slideshow
slideshow_frame.py
slideshow_frame.py
py
1,851
python
en
code
1
github-code
36
21114082657
from src import app from flask import jsonify, request import requests import json import os slackToken = os.environ['SLACK_TOKEN'] botAccessToken = os.environ['BOT_ACCESS_TOKEN'] hasuraDataUrl = "http://data.hasura/v1/query" chatUrl = "https://slack.com/api/chat.postMessage" ##################### APIs ##############...
Satyabrat35/SlackGitBot
microservices/bot/app/src/server.py
server.py
py
12,668
python
en
code
2
github-code
36
29654762562
import re from io import StringIO from flask import Flask, request, Response, redirect import pandas as pd app = Flask(__name__) def is_valid_query(q): ''' A query is valid if it is strictly consisted of the following three entries: [(A-Z, a-z, 0-9)+ or *] [==, !=, $=, &=] ["..."] Queries can be co...
CandiceD17/Http-Server-Query-Retrieval
my_server.py
my_server.py
py
8,078
python
en
code
0
github-code
36
28891405121
import collections import difflib import logging import os import re from pytype.platform_utils import path_utils from pytype.tools.merge_pyi import merge_pyi import unittest __all__ = ('TestBuilder', 'load_tests') PY, PYI, EXPECTED = 'py', 'pyi', 'pep484.py' OVERWRITE_EXPECTED = 0 # flip to regenerate expected f...
google/pytype
pytype/tools/merge_pyi/merge_pyi_test.py
merge_pyi_test.py
py
2,585
python
en
code
4,405
github-code
36
39265812608
import pandas as pd import plotly.graph_objects as go import prepare_data population = { 'NSW':8089526, 'QLD':5095100, 'VIC':6594804, 'SA':1751693, 'WA':2621680, 'TAS':534281, 'ACT':426709, 'NT':245869, 'Total':25359662, 'DeathsNationally':25359662, } df_aus = prepare_data.aust...
explodingdinosaurs/corona
aus_states_per_capita.py
aus_states_per_capita.py
py
2,043
python
en
code
1
github-code
36
27894940347
class Node(object): def __init__(self, key, val): self.val = val self.key = key self.next = None self.prev = None class List(object): def __init__(self): self.head = Node(None, None) self.tail = None def append(self, node): if self.tail is None: ...
stgleb/algorithms-and-datastructures
hashmaps/lru_cache.py
lru_cache.py
py
2,224
python
en
code
0
github-code
36
12032981505
import itertools import numpy as np import networkx as nx from sklearn.neighbors import kneighbors_graph from sklearn.metrics.pairwise import euclidean_distances from scipy.sparse.csgraph import minimum_spanning_tree from ggc.utils import * def knn_graph(X, k): """Returns k-Nearest Neighbor (MkNN) graph from the...
haczqyf/ggc
ggc/graphs.py
graphs.py
py
4,902
python
en
code
6
github-code
36
19665493360
import re def get_puzzle_input(file: str) -> list[str]: return [line.strip() for line in open(f"{file}.txt", "r").readlines()] def create_list(r1: int, r2: int) -> list: return list(range(r1, r2 + 1)) def parse_input(sections: list) -> list: ranges = [] for section in sections: input = re....
jonnaliesel/Aoc2022
4/solution.py
solution.py
py
1,422
python
en
code
0
github-code
36
34993839592
# Thư viện import pygame, sys import numpy as np import time # Khởi tạo game pygame.init() # --------- # CÁC HẰNG SỐ # --------- WIDTH = 600 HEIGHT = WIDTH LINE_WIDTH = 15 WIN_LINE_WIDTH = 8 BOARD_ROWS = 5 BOARD_COLS = BOARD_ROWS SQUARE_SIZE = WIDTH/BOARD_ROWS CIRCLE_RADIUS = SQUARE_SIZE/3 CIRCLE_WIDTH = 15 CROS...
LeVan102/AI_Caro
Caro5x5.py
Caro5x5.py
py
11,268
python
en
code
0
github-code
36
42154458258
# 1,2,3 더하기 import sys input = sys.stdin.readline case = [] for i in range(int(input())): case.append(int(input())) maxNum = max(case) dp = [0]*(maxNum+1) dp[1] = 1 dp[2] = 2 dp[3] = 4 for i in range(4, maxNum+1): dp[i] = dp[i-3]+dp[i-2]+dp[i-1] for i in case: print(dp[i])
FeelingXD/algorithm
beakjoon/9095.py
9095.py
py
295
python
en
code
2
github-code
36
5663440887
import math def merge_sort(array, left_bound, right_bound): if left_bound < right_bound: middle_bound = math.floor((left_bound + right_bound)/2) merge_sort(array, left_bound, middle_bound) merge_sort(array, middle_bound + 1, right_bound) merge(array, left_bound, middle_bound, right_...
Melkye/Labs
Algorithms/Lab_3_inversions/Lab_3_inversions/fun.py
fun.py
py
4,037
python
en
code
0
github-code
36
28148567000
import datetime import time from gpiozero import LED, Device from gpiozero.pins.pigpio import PiGPIOFactory Device.pin_factory = PiGPIOFactory() # NOTE: Change this to match the GPIO pin you're connecting the LED to led = LED(18) # NOTE: Change these values to set the time you want the light to turn on and off at we...
szh/pi-timedlight
timedlight.py
timedlight.py
py
936
python
en
code
1
github-code
36
39139414792
""" This module contains testcase_32_ephemeral test """ from testcase import Testcase from os.path import basename class testcase_32_ephemeral(Testcase): """ It should be possible to use ephemeral device (if we have one) Note that in rhel6.5 there is no shift letter in dick device name """ stages ...
dparalen/dva
dva/test/testcase_32_ephemeral.py
testcase_32_ephemeral.py
py
3,371
python
en
code
0
github-code
36
70943213544
"""Module to index columns of the paper-summarized CSV file.""" import pandas as pd from loguru import logger from omegaconf import OmegaConf from utils import create_embeddings # Load the configuration cfg = OmegaConf.load("conf/config.yaml") FILE_PATH = cfg.data.path INDEXED_FILE_PATH = cfg.data.indexed_path df =...
naarkhoo/LiteGrave
src/index_csv_columns.py
index_csv_columns.py
py
831
python
en
code
0
github-code
36
36709037388
import rclpy import rclpy.node from airobot_interfaces.srv import StringCommand from gtts import gTTS import speech_recognition as sr import subprocess class SpeechService(rclpy.node.Node): def __init__(self): super().__init__('speech_service') self.get_logger().info('音声サーバーを起動しました') se...
AI-Robot-Book/chapter3
speech_service/speech_service/speech_service_mpg123.py
speech_service_mpg123.py
py
1,728
python
en
code
2
github-code
36
31058374968
import networkx as nx import pandas as pd from matplotlib import pyplot as plt from networkx.generators.ego import ego_graph from pyvis.network import Network from sklearn.decomposition import PCA def plot_network_with_edge_weights(G, figsize=(10, 10)): elarge = [(u, v) for (u, v, d) in G.edges(data=True) if (d["...
ryankarlos/networks_algos
vis/visualize.py
visualize.py
py
3,867
python
en
code
1
github-code
36
3530324591
# from threading import Thread import speech_recognition as sr import keyboard as k import spotipy import os import pyttsx3 import random import credentials from spotipy.oauth2 import SpotifyOAuth from spotipy.oauth2 import SpotifyClientCredentials # from refresh import Refresh # from googleText2Speech import synthe...
nsrehman/Virtual-Assistant
voiceRecognition.py
voiceRecognition.py
py
5,520
python
en
code
0
github-code
36
29730523882
#coding:utf8 #login import logging logging.basicConfig(level=logging.DEBUG) _logger = logging.getLogger(__name__) #flask frame from flask_restplus import Resource #wechat frame import flask_wechat_utils from flask_wechat_utils.user.utils import auth from flask_wechat_utils.config import api #application config impo...
synctrust/flask-wechat-utils
flask_wechat_utils/message_template/routes.py
routes.py
py
1,768
python
en
code
0
github-code
36
14774852874
import streamlit as st from src.plotgraphs import make_radar_graph from src.sentanalysis import hf_analysis from src.sentanalysis import spacy_sentiment if __name__ == "__main__": st.write("Welcome") user_input = st.text_input("Enter a sentence", key="name") result = st.button("Submit") if result: ...
yugant10-commits/sentiment-analysis
main.py
main.py
py
652
python
en
code
0
github-code
36
44034854335
import sys n = int(input()) card = list(map(int, sys.stdin.readline().split())) m = int(input()) d = list(map(int, sys.stdin.readline().split())) card.sort() def binary_search(left, right, t): if left > right: print(0, end = " ") return 0 else: mid = (left + right) // 2 ...
GluteusStrength/Algorithm
백준/Silver/10815. 숫자 카드/숫자 카드.py
숫자 카드.py
py
605
python
en
code
0
github-code
36
17192006071
from typing import List from app.api.validators import ValidatorsClass from app.core.db import get_async_session from app.core.user import current_superuser from app.crud.charity_project import charity_crud from app.models import Donation from app.schemas.charity_project import CharityCreate, CharityDB, CharityUpdate ...
Lexxar91/QRkot_spreadsheets
app/api/endpoints/charity_project.py
charity_project.py
py
4,780
python
ru
code
0
github-code
36
912034710
import cv2 cap = cv2.VideoCapture('vtest.avi') hog = cv2.HOGDescriptor() # 클래스 호출을 통해 객체 생성 # SVM: 머신러닝 기술 이름 hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) while True: ret, frame = cap.read() # 프레임을 읽어서 반환 # ret: true / false, true: 동영상 frame을 정상적으로 읽었을 때, false: 비정상적으로 읽었을 때 if not...
yousung1020/OpenCV
실습자료/chapter 13/hog.py
hog.py
py
782
python
ko
code
0
github-code
36
28923214371
#10815 .숫자카드 import sys input = sys.stdin.readline from bisect import bisect_left, bisect_right N = int(input().rstrip()) nums = list(map(int,input().rstrip().split())) nums.sort() def find(arr, target): if len(arr) == 1: return 1 if arr[0] == target else 0 lo = 0 hi = len(arr)-1 while lo...
GuSangmo/BOJ_practice
BOJ/10815.py
10815.py
py
833
python
en
code
0
github-code
36
37406492523
import logging logging.basicConfig(filename='test_logs.log', encoding='utf-8', level=logging.INFO) logger = logging.getLogger('selenium') logger.setLevel(logging.INFO) disable_loggers = ['urllib3.connectionpool','faker.factory'] def pytest_configure(): for logger_name in disable_loggers: logger_not = log...
AlejandroPadilla99/mentoringPython
conftest.py
conftest.py
py
383
python
en
code
0
github-code
36
35854946253
""" The flask application package. """ # newest 1.4 version of sqlalchemy not working please install 1.3.24 #pip install SQLAlchemy==1.3.24 async_mode = None if async_mode is None: try: import gevent async_mode = 'gevent' except ImportError: pass if async_mode is None: ...
Radkos1976/Hrnest-FLask-enchacment
HrnestBoss/HrnestBoss/__init__.py
__init__.py
py
4,549
python
en
code
0
github-code
36
11370466883
import requests from time import sleep class Ark(object): """This is a python wrapper for the ARK api""" def __init__(self,api_token): self.api_token = api_token self.header = {'api_token' : self.api_token } def check_token(self,full_object=False): """Checks the number of calls your token has left""" bas...
gregimba/Ark
ark.py
ark.py
py
2,070
python
en
code
2
github-code
36
36219148196
import numpy as np from numpy import array from mSimplexFaseII import solve from scipy.optimize import linprog import pprint from math import log, exp from numpy.random import rand, normal from numpy import round, int, abs, array, transpose def main(): #Primer test A = array([[1,0], [0, 2], [3, 2]]) b = ...
SergioArnaud/Linear-programming
Practica1/testFaseII.py
testFaseII.py
py
2,007
python
en
code
0
github-code
36
4861207569
from dataclasses import dataclass from datetime import datetime,date import pytz import dateparser from typing import Union import pandas as pd from sqlalchemy import Column,Integer,DateTime,Text,TIMESTAMP,MetaData,Table from sqlalchemy.engine import create_engine from sqlalchemy.exc import OperationalError fr...
nitesh1489/test
helpers/handlers.py
handlers.py
py
6,204
python
en
code
1
github-code
36
42776999573
"""canaryAPI URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-bas...
toucan-project/TOUCAN
toucan/canary_api/urls.py
urls.py
py
2,670
python
en
code
3
github-code
36
33277423381
# -*- coding: utf-8 -*- """ Created on Fri Jul 28 14:15:31 2017 @author: Simon """ import sleeploader import imp imp.reload(sleeploader) if __name__=='__main__': sleep = sleeploader.SleepDataset('D:/sleep/isruc') channels = {'EEG':['C4-A1','C4-M1'], 'EMG':'X1','EOG':['LOC-A2','E1-M2']} references = {'Re...
skjerns/AutoSleepScorerDev
tmp.py
tmp.py
py
424
python
en
code
8
github-code
36
12639565741
from mainapp.model.Event import Event from datetime import datetime from django.core.cache import cache from mainapp.Common import CacheUtil from django.conf import settings from django.utils import timezone KEY_CACHE_DAO_GET_ALL_EVENT_ACTIVE = 'context-dao-all-event-active' KEY_CACHE_DAO_GET_ALL_EVENT_NOT_ACTIVE = 'c...
trunganhvu/personalweb
mainapp/dao/Event/EventDao.py
EventDao.py
py
2,795
python
en
code
0
github-code
36
25770685168
import numpy as np import seaborn from PIL import Image import matplotlib.pyplot as plt import tensorflow as tf from keras import layers, models from sklearn.metrics import confusion_matrix from sklearn.preprocessing import StandardScaler, Normalizer from sklearn import svm from sklearn.metrics import f1_score...
AndrewSSB/KaggleCompetition
main.py
main.py
py
10,932
python
en
code
0
github-code
36
9228040497
import torch from torch._C import Value import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.loss import PoissonNLLLoss from .MultiHeadAttention import MultiHeadAttention from .Block import Block class Decoder(nn.Module): """ add another attention between encoder's out and decoder a...
chenzhike110/Transformer
Tranformer/Modules/Decoder.py
Decoder.py
py
1,380
python
en
code
0
github-code
36
34444799833
"""Further improved the emphasis - drawing the user's attention when there is only one available seat left """ # initialize loop so that it runs at least once name = "" count = 0 MAX_TICKETS = 5 while name != "Xxx" and count < MAX_TICKETS: if MAX_TICKETS - count > 1: print(f"\nYou have {MAX_TICKETS - coun...
yis1234/Mega_Movie_Fundraiser
02_ticket_loop_v4.py
02_ticket_loop_v4.py
py
822
python
en
code
0
github-code
36
43041308146
from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QApplication,QWidget,QHBoxLayout,QVBoxLayout,QRadioButton,QGroupBox,QPushButton,QLabel,QListWidget,QLineEdit from second_win import * from instr import * class FinalWin(QWidget): def __init__(self,exp): super().__init__(...
AlexanderKudelya/indexruf
index/final_win.py
final_win.py
py
976
python
en
code
0
github-code
36
69801320106
import csv import sys from collections import defaultdict sys.setrecursionlimit(10**9) array_words = [] with open('sgb-words.txt') as csv_file: csv_reader = csv.reader(csv_file) for row in csv_reader: array_words.append(row[0]) def list_incident(word, array_words): array = [] for w in array_w...
Chidt12/discreteMath
Bai3_Searching_on_graph/bai3b_searching_on_graph.py
bai3b_searching_on_graph.py
py
2,846
python
en
code
0
github-code
36
21365527624
import torch import torch.nn as nn import torch.nn.functional as F from torch import Tensor from dptb.nnet.mlp import MLP from dptb.utils.tools import _get_activation_fn from typing import Optional, Any, Union, Callable class ResBlock(nn.Module): def __init__(self, n_in, n_hidden, n_out, activation: Union[str, ...
deepmodeling/DeePTB
dptb/nnet/resnet.py
resnet.py
py
2,761
python
en
code
21
github-code
36
31197803049
""" Cryptocurrency network definitions """ class Network: """ Represents a cryptocurrency network (e.g. Bitcoin Mainnet) """ def __init__(self, description, version_priv, version_pub, pub_key_hash, wif): self.description = description self.version_priv = version_priv ...
henriquetft/pyhdwallet
pyhdwallet/networks.py
networks.py
py
1,814
python
en
code
5
github-code
36
13536557102
''' Prova Pratica di Laboratorio di Sistemi Operativi 19 luglio 2010 Esercizio 3 URL: http://www.cs.unibo.it/~renzo/so/pratiche/2010.09.13.pdf @author: Tommaso Ognibene ''' import os, sys, hashlib, difflib def main(argv): # Check number of parameters if len(argv) != 3: sys.exit("The function needs t...
tomOgn/OS-Python
OS-Python/2004-01-27/showDifferences.py
showDifferences.py
py
3,105
python
en
code
0
github-code
36
73080924903
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 31 04:34:53 2018 @author: can """ import pandas as pd import numpy as np import SimilartyLib as sim # #from sklearn.decomposition import PCA #from sklearn import preprocessing import createGraph as cG import graph_tool.all as gt indElement= ["al2...
cantek41/SpectrumSimilarty
peakSim.py
peakSim.py
py
2,223
python
en
code
0
github-code
36
3494741214
#!/usr/bin/env python3 def make_list(lst): a, b = [], [] lst = sorted(lst) a.append(lst.pop(len(lst)//2)) if len(lst)>0: b.append(lst[:len(lst)//2]) b.append(lst[len(lst)//2:]) while len(a) != len(lst): if b[0] != []: a.append(b[0][len(b[0])//2]) a = b.pop(0) b.append(a[:len(a)//2]) b.appe...
debuitc4/CA268
week5/student_test.py
student_test.py
py
371
python
zh
code
0
github-code
36
7549303047
#### import #### import sys sys.path.append("../") import App from pprint import pprint as pp import time import json class LogiViewSum: """ 予測結果を表示するためのクラス """ #entry_id #a_type #seido #sql_common_cond def __init__(self): #db接続の取得 app = App.AppClass() self.db = app...
Takuya-Nakamura/utility
python/machine_learning_study/logistic/3_logi_view_sum.py
3_logi_view_sum.py
py
6,061
python
en
code
0
github-code
36
72237218663
"""Form definitions.""" from braces.forms import UserKwargModelFormMixin from crispy_forms.helper import FormHelper, Layout from crispy_forms.layout import Fieldset, Submit from django import forms from django.utils.translation import gettext_lazy as _ from .models import Sheet class SheetForm(UserKwargModelFormMi...
FlowFX/unkenmathe.de
src/um/sheets/forms.py
forms.py
py
1,017
python
en
code
1
github-code
36
17484175139
from Modules.Fint import Fint from Modules.PMS import PMS import unittest class TestPMS(unittest.TestCase): def test_set_fint(self): pms = PMS() fint = Fint() pms.set_fint(fint) self.assertEqual(fint, pms.fint) def test_set_data(self): pms = PMS() fint = Fint(...
alexamar0714/TRYBOT
TestModules/TestPMS.py
TestPMS.py
py
1,078
python
en
code
1
github-code
36
12996324236
from Lib.HelpFunction import stop_stopwatch, start_stopwatch from Lib.data.DataCSV import DataCSV from Lib.PreprocessClass import Preprocess """Method manage getting data and preprocessing for both tests.""" def get_and_preprocess_data(arguments, min_items_for_user = 1): preprocess_class = Preprocess(arguments=ar...
recombee/lsh-library
src/DataDbgetParse.py
DataDbgetParse.py
py
1,706
python
en
code
0
github-code
36
15480079320
import io from PIL import Image from django.test import TestCase, Client from django.urls import reverse import numpy as np from unittest.mock import patch from mnist_predictor.views import make_prediction class PredictViewTestCase(TestCase): def setUp(self): self.client = Client() # Create a test ...
MichelWakim/mnist-api
mnist_predictor/tests.py
tests.py
py
1,514
python
en
code
0
github-code
36
2875218070
#!/usr/bin/python3 import requests def number_of_subscribers(subreddit): """ Set a custom User-Agent in headers to prevent API errors""" headers = {'User-Agent': 'MyRedditBot/1.0'} """ Construct the API URL for the given subreddit""" url = f'https://www.reddit.com/r/{subreddit}/about.json' """ Ma...
Ojobumiche/alx-higher_level_programming
0x16-api_advanced/0-subs.py
0-subs.py
py
933
python
en
code
0
github-code
36
13100959928
from __future__ import print_function # import logging import json import sys import uuid from random import randrange # TODO remove this import requests import logging from cakework import exceptions from urllib3.exceptions import NewConnectionError import os # TODO: need to re-enable TLS for the handlers in the fl...
usecakework/async-backend
sdk/python/src/cakework/client.py
client.py
py
6,074
python
en
code
3
github-code
36
44298786313
# -*- coding: utf-8 -*- """ Created on Fri Nov 30 08:29:53 2018 @author: Ahsan """ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import compile, Aer from QGates import gateArity , gateName class QCircuit: def __init__ (self,qBit,cBit,shot=1): '''...
usamaahsan93/AutoQP
myQFn.py
myQFn.py
py
2,868
python
en
code
0
github-code
36
26122545244
# -*- coding: utf-8 -*- """ Created on Thu Jan 14 09:43:42 2016 @author: sampepose """ import csv import numpy as np from sklearn.neighbors import KNeighborsClassifier import matplotlib.pyplot as plt data = [] TestData = [] # Read the training data f = open('data/train.csv') reader = csv.reader(f) next(reader, None...
sampepose/digit-recognizer
kNearestNeighbor/test_increasing_sample_size.py
test_increasing_sample_size.py
py
1,447
python
en
code
0
github-code
36