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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
2309854719 | import os
import subprocess
import sys
import tempfile
from contextlib import contextmanager
from os import mkdir, chdir
from pathlib import Path
from subprocess import check_call, PIPE
from tempfile import TemporaryDirectory
from typing import Union, Iterator, Optional, Iterable, Any
@contextmanager
def using_cwd(ne... | kbauer/zgit | zgit/lib/testutil.py | testutil.py | py | 6,397 | python | en | code | 0 | github-code | 13 |
41037588436 | ciphertext = bytes.fromhex('104e137f425954137f74107f525511457f5468134d7f146c4c')
plaintext = None
# Prova tutte le possibili chiavi non stampabili
for key in range(256):
# Esegui l'operazione di XOR tra il testo cifrato e la chiave
candidate = bytes([b ^ key for b in ciphertext])
# Se il risultato decifrat... | EngJohn12/CYBERCHALLENGE-CODE | Crypto05-XOR2.py | Crypto05-XOR2.py | py | 731 | python | it | code | 0 | github-code | 13 |
71675584339 |
from django.contrib.gis.db import models
class Region(models.Model):
idreg = models.FloatField(null=True)
id = models.BigIntegerField(primary_key=True)
province = models.CharField(max_length=254,null=True)
region = models.CharField(max_length=254,null=True)
geom = models.MultiPolygonField(srid=4326... | Oviane16/sig | world/models.py | models.py | py | 544 | python | en | code | 0 | github-code | 13 |
37124717124 | from odoo import fields, models, api, _
from odoo.exceptions import Warning
import random
from odoo.tools import float_is_zero
import json
from odoo.exceptions import UserError, ValidationError
from collections import defaultdict
class pos_config(models.Model):
_inherit = 'pos.config'
def _get_default_locati... | lequipeur/main | bi_pos_stock/models/bi_pos_stock.py | bi_pos_stock.py | py | 8,945 | python | en | code | 1 | github-code | 13 |
34114273374 | from typing import List
ALPHA_LOWER = "abcdefghijklmnopqrstuvwxyz"
ALPHA_CAPITAL = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ALPHA_ALL = ALPHA_LOWER + ALPHA_CAPITAL
NUM = "0123456789"
ALPHA_NUM = ALPHA_ALL + NUM
def group_by_word(line: str, seperator=" ", brackets=None) -> List[str]:
"""Groups a string by words and contents ... | QuTech-Delft/netqasm | netqasm/util/string.py | string.py | py | 2,858 | python | en | code | 17 | github-code | 13 |
4067530302 | import torch
import torch.nn.functional as F
@torch.no_grad()
def evaluate(model, dataset, split_idx, eval_func, criterion, args, result=None):
if result is not None:
out = result
else:
model.eval()
out = model(dataset.graph['node_feat'], dataset.graph['edge_index'])
train_acc = ev... | qitianwu/DIFFormer | image and text/eval.py | eval.py | py | 788 | python | en | code | 248 | github-code | 13 |
32270275683 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 20 11:10:24 2021
@author: sarak
"""
# Change order of keys in dictionary - OrderedDict
def main():
from collections import OrderedDict
d = OrderedDict()
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
print(d)
d.move_to_end... | sara-kassani/1000_Python_example | 07_dictionary/18_ordereddict_change_order_keys.py | 18_ordereddict_change_order_keys.py | py | 765 | python | en | code | 1 | github-code | 13 |
21603468145 |
class SimMIM(nn.Module):
def __init__(self, in_chans, encoder, encoder_stride):
super().__init__()
self.encoder = encoder
self.encoder_stride = encoder_stride
self.decoder = nn.Sequential(
nn.Conv2d(
# in_channels=self.encoder.num_features[-1],
... | bakeryproducts/hmib | src/mim/nn.py | nn.py | py | 1,772 | python | en | code | 0 | github-code | 13 |
44275143122 | import tensorflow as tf
from tf_bodypix.api import download_model, load_model, BodyPixModelPaths
import cv2
from matplotlib import pyplot as plt
import numpy as np
import urllib.request
import sys
import os
import time
import json
# -------------------input url to return image-------------------#
def url_to_image(url)... | Bobowoo2468/SwiftTailorServer | bodyshape.py | bodyshape.py | py | 9,146 | python | en | code | 0 | github-code | 13 |
33175450027 | from crontab import CronTab
from datetime import datetime, timedelta # for the current time and adding time
import pytz # to enale comparison of datetime and astral time, astral is ofset, datetime is naive
from astral import LocationInfo # to get the location info
from astral.sun import s... | llewmihs/sunrise300 | Development/crontabtest.py | crontabtest.py | py | 863 | python | en | code | 1 | github-code | 13 |
11364007352 | import sys
from pprint import pprint
import random
import numpy as np
import tensorflow as tf
import optuna
from optuna.integration.tfkeras import TFKerasPruningCallback
gpus = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(gpus[0], True)
from tensorflow.keras.datasets i... | atobe/intro_to_dl_shared | search_mnist.py | search_mnist.py | py | 2,224 | python | en | code | 0 | github-code | 13 |
17332305061 | """US07"""
from datetime import date
import Error
months = {'JAN': 1, 'FEB': 2, 'MAR': 3, 'APR': 4, 'MAY': 5, 'JUN': 6,
'JUL': 7, 'AUG': 8, 'SEP': 9, 'OCT': 10, 'NOV': 11, 'DEC': 12}
def less_than_150(member, errors):
"""
The age of an individual should less than 150 years
:param member: dict
... | EricLin24/SSW555-DriverlessCar | lessthan_150.py | lessthan_150.py | py | 1,225 | python | en | code | 0 | github-code | 13 |
2752044885 | '''
*********** Curso de programación acelerada en Python ************
Date 04-08-2022
File: sesion2/ejercicio13.py
Autor: Adriana Romero
Action: Permita ingresar un valor del 1 al
10 y nos muestre la tabla de multiplicar del mismo.
'''
numero = int(input("Introduce un valor: "))
for i in range(0, 11):
resultado = i... | Adri2246/Curso-de-programacion-acelerada-en-python | Sesion2/ejercicio17.py | ejercicio17.py | py | 379 | python | es | code | 0 | github-code | 13 |
17585447427 | import os
import csv
import pandas as pd
from datetime import datetime
def is_file_empty(file_name):
"""
Check if file is empty by reading first character in it
"""
# open ile in read mode
with open(file_name, 'r') as read_obj:
# read first character
one_char = read_obj.read(1)
... | hfmandell/air-quality-rover-raspi | process_pm_data.py | process_pm_data.py | py | 3,024 | python | en | code | 1 | github-code | 13 |
39792204322 | import numpy as np
import palantir
import pandas as pd
def compactness(ad, low_dim_embedding="X_pca", SEACells_label="SEACell"):
"""Compute compactness of each metacell.
Compactness is defined is the average variance of diffusion components across cells that constitute a metcell.
:param ad: (Anndata) An... | dpeerlab/SEACells | SEACells/evaluate.py | evaluate.py | py | 5,088 | python | en | code | 115 | github-code | 13 |
21582112323 | """
You've been given a list that states the daily revenue for each day of the week. Unfortunately, the list has been corrupted and contains extraneous characters. Rather than fix the source of the problem, your boss has asked you to create a program that removes any unneccessary characters and return the corrected lis... | Lucky-Dutch/cov-19 | codewars/changeCharInStrings.py | changeCharInStrings.py | py | 837 | python | en | code | 0 | github-code | 13 |
11250446401 | #!/usr/bin/env python
import os
def getTestFile():
retLine=""
with open("testfile.txt", "r") as f2:
for line2 in f2.readlines():
retLine += line2
return retLine
def printFeatureFile():
print ("\n\n ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ")
with open("fe... | allys-99/class3hw | our_csv_parser_file.py | our_csv_parser_file.py | py | 2,484 | python | en | code | 0 | github-code | 13 |
42076966578 | import collections
import sys
sys.setrecursionlimit(10 ** 8)
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(readline())
A = [int(x) for x in readline().split()]
ac = collections.Counter(A)
assert set(ac.keys()).issubset({1, 2, 3})
def solve(c1, c2, c... | keijak/comp-pub | atcoder/dp/J/main.py | main.py | py | 1,216 | python | en | code | 0 | github-code | 13 |
27803194532 | def solution(new_id):
answer = ''
# 1단계
temp = str(new_id).lower()
# 2단계
for word in temp:
if word.islower() or word.isnumeric() \
or word == '-' or word == '_' or word == '.':
answer += word
# 3단계
temp = ''
count = 0
for i in answer:
if i ... | tkdgns8234/DataStructure-Algorithm | Algorithm/프로그래머스/level_1/신규_아이디_추천.py | 신규_아이디_추천.py | py | 945 | python | ko | code | 0 | github-code | 13 |
16464357543 | import sys
import tensorflow as tf
import numpy as np
import six
def DilatedConv_4Mehtods(type, x, k, num_out, factor, name, biased=False):
"""
DilatedConv with 4 method: Basic,Decompose,GI,SSC
Args:
type = Basic,Decompose,GI,SSC
x = input
k = kernal size
num_out output num
factor = dilated factor
Returns:
... | qingbol/ClmsDM | models/dilated.py | dilated.py | py | 3,739 | python | en | code | 0 | github-code | 13 |
26330699380 | from sklearn.svm import LinearSVC
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.feature_selection import SelectFromModel
from sklearn.preprocessing import StandardScaler
import pandas as pd
class FeatureSelector:
def __init__(self) -> None:
... | smriti-joshi/Fairness_training | feature_selector.py | feature_selector.py | py | 3,380 | python | en | code | 0 | github-code | 13 |
46089037124 | from cortex2 import EmotivCortex2Client
import time
url = "wss://localhost:6868"
# Remember to start the Emotiv App before you start!
# Start client with authentication
client = EmotivCortex2Client(url,
client_id='0DyMfKwKuYAG72VKATaJUI51sEHlyGqpsTk19jPP',
clien... | GenerelSchwerz/big-brain-eeg | main.py | main.py | py | 1,771 | python | en | code | 0 | github-code | 13 |
21538308278 | # Native imports
from os.path import exists, join
from shutil import rmtree
from typing import Union
# Local imports
from .utils import _join_paths_mkdir
from ..Args import args
from ..Section import Section
from .nav import generate_nav_as_needed # Import for export
"""Functions to assist in writing docs to disk"""... | Denperidge-Redpencil/divio-docs-gen | src/divio_docs_gen/write_to_disk/__init__.py | __init__.py | py | 1,732 | python | en | code | 0 | github-code | 13 |
18994415623 | import disnake
from disnake.ext import commands
from utils import database, autocompletes, checks
class DeleteSession(commands.Cog):
def __init__(self, bot: disnake.ext.commands.Bot):
self.bot = bot
@commands.slash_command(
guild_only=True,
name="удалить-сессию",
description="... | Komo4ekoI/DiscordCasinoBot | cogs/commands/delete_session.py | delete_session.py | py | 2,474 | python | ru | code | 0 | github-code | 13 |
40380735972 | import re
import numpy as np
def cut_sent(para):
para = re.sub('([。!?\?])([^”’])', r"\1\n\2", para) # 单字符断句符
para = re.sub('(\.{6})([^”’])', r"\1\n\2", para) # 英文省略号
para = re.sub('(\…{2})([^”’])', r"\1\n\2", para) # 中文省略号
para = re.sub('([。!?\?][”’])([^,。!?\?])', r'\1\n\2', para)
# 如果双引号前有终止符,那... | twobagoforange/saier_system | background/split.py | split.py | py | 962 | python | ja | code | 0 | github-code | 13 |
7044548017 | from client_payment_sdk import ClientPaymentSDK, sign
api_secret = 'aa21444f3f71'
params = {
'merchant_id': 15,
'order': '067dbec6-719c-11ec-9e37-0242ac130196'
}
params['signature'] = sign('/withdrawal_request', 'GET', params, api_secret)
client = ClientPaymentSDK()
result = client.withdrawal_status(params)... | spacearound404/client-payment-sdk-python | examples/withdrawal_status.py | withdrawal_status.py | py | 405 | python | en | code | 0 | github-code | 13 |
20868595013 | from functools import partial
import fire
import pandas as pd
from catboost import CatBoostRegressor
from hyperopt import hp, fmin, tpe
from lightgbm import LGBMRegressor
from loguru import logger
from sklearn.pipeline import Pipeline
from vecstack import StackingTransformer
from xgboost import XGBRegressor
from util... | georgiypetrov/citymobil-natural-log | hyperparam_tuning.py | hyperparam_tuning.py | py | 4,096 | python | en | code | 0 | github-code | 13 |
73492625616 | # Solve the Sudoku
def isValid(i,j,val,sudoku):
row=(i//3)*3
col=(j//3)*3
for k in range(9):
if sudoku[k][j]==val:
return False
for k in range(9):
if sudoku[i][k]==val:
return False
for r in range(3):
for c in range(3):
if sudoku[r+ro... | Ayush-Tiwari1/DSA | Days.43/3.Solve-Sudoku.py | 3.Solve-Sudoku.py | py | 1,153 | python | en | code | 0 | github-code | 13 |
404586901 | import os
import json
from shutil import move
categorie = [] # Here all the categories will be saved.
# Check every recipe in the 'ricette' folder for its category then if it's not already in the list: save it.
for path in os.scandir('ricette'):
if path.is_file():
with open(path.path, 'r') as file:
... | TheCaptainCraken/Scraping-Giallo-Zaffferano | find_categories.py | find_categories.py | py | 1,253 | python | en | code | 0 | github-code | 13 |
21051068575 | # 197, 부품찾기
# 내 답, 이진 탐색 이용
def binary_search(arr, target, start, end):
if start > end:
return None
mid = (start + end)//2
if arr[mid] == target:
return mid
elif arr[mid] > target:
return binary_search(arr, target, start, mid - 1)
else:
return binary_search(arr, tar... | jinho9610/py_algo | book/bs_1.py | bs_1.py | py | 1,257 | python | ko | code | 0 | github-code | 13 |
17783409993 | import numpy as np
def day08(inp):
board = np.array([[int(c) for c in line] for line in inp.strip().splitlines()])
visibles = np.zeros_like(board, dtype=bool)
for axis in range(2):
# check rows or columns
for i in range(board.shape[axis]):
# check each row or each column
... | adeak/AoC2022 | day08.py | day08.py | py | 1,798 | python | en | code | 2 | github-code | 13 |
38462273809 | """Test PyDynamic.uncertainty.propagate_convolve"""
from typing import Callable, Optional, Set, Tuple
import numpy as np
import pytest
import scipy.ndimage as sn
from hypothesis import assume, given, settings, strategies as hst
from hypothesis.strategies import composite
from numpy.testing import assert_allclose
from... | Met4FoF/Code | PyDynamic/test/test_propagate_convolution.py | test_propagate_convolution.py | py | 4,280 | python | en | code | 0 | github-code | 13 |
17051990924 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.AudioEvent import AudioEvent
class FenceEvent(object):
def __init__(self):
self._audio_events = None
self._fence_code = None
self._latitude = None
... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/FenceEvent.py | FenceEvent.py | py | 4,060 | python | en | code | 241 | github-code | 13 |
21871588414 | import time
import numpy as np
import matplotlib.pyplot as plt
import imageio
import os
from os import read
import pathlib
def loadData(dir):
files = os.listdir(dir)
print(files)
colors = []
for i in range (len(files)):
colors.append(imageio.imread(dir + files[i]))
return colors
def ... | mershavka/get | 12-spectr/spectrFunctions.py | spectrFunctions.py | py | 4,373 | python | en | code | 0 | github-code | 13 |
27222278170 | from django.core import mail
from django.test import TestCase
from django.shortcuts import resolve_url as r
class SubscribeMailBody(TestCase):
def setUp(self):
"""Tests initialize"""
data = dict(
name="Fabricio Nogueira",
cpf="01234567891",
email="nogsantos@mail... | nogsantos/eventex | eventex/subscriptions/tests/test_mail_subscribe.py | test_mail_subscribe.py | py | 1,317 | python | en | code | 0 | github-code | 13 |
17114748624 | import logging
from os import path
from agr_literature_service.api.models import CrossReferenceModel, ReferenceModel, \
AuthorModel, ModModel, ModCorpusAssociationModel, MeshDetailModel, \
ReferenceCommentAndCorrectionModel, ReferenceModReferencetypeAssociationModel
from agr_literature_service.lit_processing.u... | alliance-genome/agr_literature_service | tests/lit_processing/data_ingest/utils/test_db_write_utils.py | test_db_write_utils.py | py | 10,440 | python | en | code | 1 | github-code | 13 |
505297802 | from django.shortcuts import render
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from django.http.response import JsonResponse
from .models import customer
from customer.Serializer import customerSerializer,customercredSerializer
... | sameerkulkarni2596/Main_project | customer/views.py | views.py | py | 1,733 | python | en | code | 0 | github-code | 13 |
5217142158 |
import configparser
import math
import random
import time
import numpy as np
import torch
#import seaborn as sns
import matplotlib.pyplot as plt
from scipy.ndimage import binary_erosion
def has_cuda():
# is there even cuda available?
has_cuda = torch.cuda.is_available()
if (has_cuda):
# we requ... | SatvikaBharadwaj/Unet_bonehistomorphometry | utils.py | utils.py | py | 4,544 | python | en | code | 0 | github-code | 13 |
43069089692 | # -*- coding: utf-8 -*-
# @Time : 2019-11-10 15:59
# @Author : GCY
# @FileName: sql_save.py
# @Software: PyCharm
# @Blog :https://github.com/GUO-xjtu
import pymysql
import utils.all_config as config
class MySQLCommand(object):
# 初始化类
def __init__(self):
self.host = config.mysql_host
sel... | GUO-xjtu/wyy_spider | utils/sql_save.py | sql_save.py | py | 10,616 | python | en | code | 0 | github-code | 13 |
2200175437 | import numpy as np
def randfunc(p):
f = np.array(p)
f = f / f.sum()
for i in range(1,len(f)):
f[i] = f[i] + f[i-1]
r = np.random.rand()
return np.searchsorted(f,r)
def randfunc2(f):
f = np.array(f)
r = np.random.rand()
return np.searchsorted(f,r)
def zipf_init(num):
f = []... | aaeviru/pythonlib | crand.py | crand.py | py | 485 | python | en | code | 0 | github-code | 13 |
19986619522 | # -*- coding: utf-8 -*-
import os
import sys
sys.path.append(os.getcwd()+"/helpers.py")
from helpers import Helpers
def main():
data = Helpers.get_rate()
df = Helpers.get_dataframe(data)
Helpers.write_data(df)
if __name__ == '__main__':
main()
| farman1855/babbel_project | module/core.py | core.py | py | 266 | python | en | code | 0 | github-code | 13 |
18014774013 | from random import randint, random
from tinydb import Query, TinyDB
from tinydb.table import Document
stock_table = TinyDB('stock.json').table('stock')
def get_stock(product_id: int) -> dict:
stock = stock_table.get(doc_id=product_id)
return stock.copy()
def update_stock(product_id: int, stock: int):
stock_... | Nvillaluenga/villaluenga-unt-microservices | capitulo_2/stock/repository/stockRepository.py | stockRepository.py | py | 643 | python | en | code | 0 | github-code | 13 |
32395172482 |
def update(mean1, var1, mean2, var2):
new_mean = (var2 * mean1 + var1 * mean2) / (var1 + var2)
new_var = 1/(1/var1 + 1/var2)
return [new_mean, new_var]
def predict(mean1, var1, mean2, var2):
new_mean = mean1 + mean2
new_var = var1 + var2
return [new_mean, new_var]
measurements = [5., 6., 7.,... | AymanNasser/Sensor-Fusion-Nanodegree-Udacity | Part4 - Kalman Filters/Lesson-2/1D_KF.py | 1D_KF.py | py | 719 | python | en | code | 0 | github-code | 13 |
27388635845 | import argparse
from classes.datum import Datum
from classes.settings import Settings
parser = argparse.ArgumentParser(description = 'This is filtering outlier data.')
parser.add_argument('-s', '--setting', help = 'Enter path to the setting file.')
parser.add_argument('-d', '--data', help = 'Enter path to the data fi... | alizand1992/chemdata | chemdata.py | chemdata.py | py | 602 | python | en | code | 0 | github-code | 13 |
32932424666 | import cv2
from cvzone.HandTrackingModule import HandDetector
cap = cv2.VideoCapture(0)
detector = HandDetector(maxHands=2, detectionCon=0.8)
while True:
success, img = cap.read()
hands, img = detector.findHands(img)
if hands:
first_hand = hands[0]
first_hand_landmarks = first_hand['lm... | JongBright/Hand-Tracking | multipleHandTracking.py | multipleHandTracking.py | py | 1,304 | python | en | code | 1 | github-code | 13 |
25032279424 | def lesenka(g, a, h):
'''g это тип лесенки: 1 - правый верх, 2- левый верх, 3- правый низ, 4- левый низ'''
'''a это количество строчек'''
'''h это символ, из которого лесенка будет состоять'''
for i in range(1, a + 1):
if g == 1:
print(' ' * (a - i), h * i)
if g == 2:
... | TomasT2/hw-17.04.2021 | 1 lesenka.py | 1 lesenka.py | py | 563 | python | ru | code | 0 | github-code | 13 |
34304660815 | import os
from PyPDF2 import PdfFileMerger
import tkinter
from tkinter import filedialog
# Prevents an empty tkinter window from appearing
tkinter.Tk().withdraw()
#Getting the path of selected files in an array
source_dir = filedialog.askopenfilenames(filetypes=[('PDF files', '*.pdf'),
... | Siraj19/PDF_Merger | main.py | main.py | py | 1,112 | python | en | code | 1 | github-code | 13 |
28117058358 | #!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
# Complete the freqQuery function below.
def freqQuery(queries):
hash = Counter()
count_hash = Counter() # count => count of count
result = []
for q in queries:
op, num = q[0], q[1]
... | piggybox/hackerrank | hash/frequency_queries.py | frequency_queries.py | py | 1,174 | python | en | code | 1 | github-code | 13 |
15339972701 | import time
import logging
import torch
from stud.callbacks import ProgressBar
from stud.training.earlystopping import EarlyStopping
from tqdm.auto import tqdm
from torch.nn.utils import clip_grad_norm_
from torch.optim.lr_scheduler import ReduceLROnPlateau
import pkbar
from sklearn.metrics import f1_score
try:
fr... | elsheikh21/named_entity_recognition | hw1/stud/training/train.py | train.py | py | 11,824 | python | en | code | 0 | github-code | 13 |
37798233944 | import os
from Clarinet.melodyextraction.skyline import skyline,mskyline
from Clarinet.constants import midi_folder
strategies={
"skyline":skyline,
"modified-skyline":mskyline
}
def extractMelody(file, output_dir=midi_folder,strategy="modified-skyline"):
folder_name,filename=file.split('/')[-2],file.split... | rohans0509/Clarinet | Clarinet/melodyextraction/__init__.py | __init__.py | py | 727 | python | en | code | 4 | github-code | 13 |
29876864320 | """Implement quick sort in Python.
Input a list.
Output a sorted list."""
def quicksort(arr):
if len(arr) < 2:
return arr
pivot = arr.pop()
left = list(filter(lambda x: x <= pivot, arr))
right = list(filter(lambda x: x > pivot, arr))
return quicksort(left) + [pivot] + quicksort(right)
tes... | michealkeines/DataStructures | quicksort.py | quicksort.py | py | 383 | python | en | code | 0 | github-code | 13 |
73789045779 | TOKEN = 'Token'
import telebot
from telebot import types
from os import path
#is_content=False
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from PIL import Image
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
import torchvision.models as mo... | marssellio/dls_final_project | bot.py | bot.py | py | 4,162 | python | en | code | 0 | github-code | 13 |
70179200018 | "Iris Model"
# pylint: disable=no-member
from app import db
from sqlalchemy.sql import select
import pandas as pd
# Iris dataset taken from: https://scikit-learn.org/stable/auto_examples/datasets/plot_iris_dataset.html
class Iris(db.Model):
__tablename__ = "iris"
iris_id = db.Column(db.Integer, primary_key=Tr... | davideasaf/modern-flask-boilerplate | app/models/iris.py | iris.py | py | 842 | python | en | code | 0 | github-code | 13 |
7457320257 | #!/bin/env python
import curses
from curses import wrapper
import time
import random
import os
current_text = "texts/classic.txt"
wpm = 0
def start_screen(stdscr):
stdscr.clear()
stdscr.addstr("Welcome to Carter's Typing Test!")
stdscr.addstr("\nPress enter to begin!")
stdscr.addstr("\nMore options:"... | CarterT27/Terminal-Typing-Test | main.py | main.py | py | 6,736 | python | en | code | 3 | github-code | 13 |
9936281877 | import requests
sid = '917503904'
headers = {
'Student-Id': sid,
}
certificate_path = 'C:\\Users\\Jacob\\.mitmproxy\\mitmproxy-ca-cert.pem'
r = requests.get('https://kartik-labeling-cvpr-0ed3099180c2.herokuapp.com/ecs152a_ass1', headers=headers, verify=certificate_path)
print("Status Code:", r.status_code)
print(... | jucobee/152-networks | mitmproxy/proj3.py | proj3.py | py | 330 | python | en | code | 0 | github-code | 13 |
40144911934 | import autode as ade
import numpy as np
from copy import deepcopy
from autode.log import logger
from autode.mol_graphs import make_graph
from autode.path.path import Path
from autode.transition_states.ts_guess import get_ts_guess
from autode.utils import work_in
def get_ts_adaptive_path(reactant, product, method, fbo... | Crossfoot/autodE | autode/path/adaptive.py | adaptive.py | py | 11,617 | python | en | code | null | github-code | 13 |
36548072389 | from army import Army
from army import Squad
from units import Soldier
from random import Random
class Strategy:
@staticmethod
def rand(enemy: Army, rand_=Random()):
squad = rand_.choice(enemy.squads)
return rand_.choice(squad.units)
@staticmethod
def weakest(enemy: Army):
squ... | alpine-cat/battlefield | strategy.py | strategy.py | py | 1,245 | python | en | code | 0 | github-code | 13 |
33792479431 | import cv2
import matplotlib.pyplot as plt
import numpy as np
import skimage.io as io
from skimage.filters import threshold_otsu
from scipy.signal import savgol_filter
# cropped,top,bottom = find_roi(img)
def find_roi(img):
img = img.astype('float32')
# binarize
thresh = threshold_otsu(img)
binary = ... | creamartin/retina | assets/segmentation/segmentation_helper.py | segmentation_helper.py | py | 12,450 | python | en | code | 5 | github-code | 13 |
18445712200 | from .create_input import hexToBinaryZokratesInput
from .create_input import hexToDecimalZokratesInput
def compute_merkle_path(tree, element):
i = tree.index(element)
path = []
direction = []
while i > 0:
if i % 2 == 0:
path.append(tree[i-1])
direction.append(0)
... | informartin/zkRelay | preprocessing/compute_merkle_path.py | compute_merkle_path.py | py | 792 | python | en | code | 24 | github-code | 13 |
8320907199 | """ Contains a City class for modeling epidemic spread through Europe """
from geopy.distance import vincenty
class City(object):
""" City class which contains a dictionary of trade routes,
a dictionary of pilgrimage routes, id, position, name, country,
and whether or not it is infected.
"""
def __init__(self, ... | LucyWilcox/Plague | code/City.py | City.py | py | 2,261 | python | en | code | 0 | github-code | 13 |
3176973614 | from sklearn.neural_network import MLPRegressor
from math import *
import numpy as np
# Method for splitting list of data into smaller lists with roughly even numbers
def split_data(data, num_nets):
for i in range(0, len(data), num_nets):
yield data[i:i + num_nets]
def singleVsMultiple(size, breadth, num... | nvonturk/Experiments | networks/fullinfo_net_sqrt.py | fullinfo_net_sqrt.py | py | 2,400 | python | en | code | 0 | github-code | 13 |
13023906911 | # Encoding: UTF-8
import matplotlib.pyplot as plt
def sum():
# 定义5个数
num1 = 1
num2 = 2
num3 = 3
num4 = 4
num5 = 5
# 计算它们的和
total = num1 + num2 + num3 + num4 + num5
return total
def huatu():
# x =[0,12,9,3,0]
# y=[0,0,4,4,0]
# # 不规则四边形
# x =[0,12,9,3,0]
# y =[7,10,17... | sc1206385466/UAV-Flight-Area-Restrictions | huizhiquyutu.py | huizhiquyutu.py | py | 4,067 | python | en | code | 0 | github-code | 13 |
24991410256 | import sys
l = [list(map(int, s.strip())) for s in sys.stdin]
def step(old):
new = [[i + 1 for i in x] for x in old]
extinct = set()
nxt, fla = doflashes(new, extinct)
print(f'fla {fla} ext {extinct}')
return nxt, fla
def doflashes(world, extinct):
new = [row[:] for row in world]
flashes = 0... | Grissess/aoc2021 | day11.py | day11.py | py | 1,240 | python | en | code | 0 | github-code | 13 |
14739336055 | #Uses python3
import sys
import queue
white = False
black = True
biPartate = True
def bipartite(adj):
#write your code here
#isBipartite = True
colour = [None] * len(adj)
marked = [False] * len(adj)
for v in range(len(adj)):
if not marked[v]:
bfs(adj, colour, marked, v)
... | price-dj/Algorithms_On_Graphs | Week3/workspace/bipartite.py | bipartite.py | py | 1,216 | python | en | code | 0 | github-code | 13 |
7236455306 | import unittest
import requests
import json
from InterfaceTest.common.config import Conf
from InterfaceTest.common.mylogin import mylogin
import time
class GoodsDetail(unittest.TestCase):
def setUp(self):
self.cookie = mylogin()
# 商品详情页
def test_a_goodsDetail(self):
data={
'cli... | renjunpei/Django | text/InterfaceTest/testcase/goodsDetail.py | goodsDetail.py | py | 7,177 | python | en | code | 0 | github-code | 13 |
20654307114 |
class Pedestrian:
def __init__(self, num, prng, current_time):
self.num = num
self.arrival = current_time
self.speed = prng()
self.crossed_street = False
print ("[PED] created with id: {}, speed: {}".format(self.num, self.speed))
def calc_travel_time(self, travel_d... | eric-olson/crosswalkSIM | pedestrian.py | pedestrian.py | py | 1,826 | python | en | code | 0 | github-code | 13 |
7878969678 | '''
집합 자료형
#set.py
Author : sblim
Date : 2018-12-08
이 프로그램은 Set 스터디 프로그램입니다.
'''
#집합(SET)은 파이썬 2.3버전부터 지원하기 시작한 자료형
#s1 = set([1,2,3]) #{1,2,3}
#s2 = set("HELLO") #{'H','E','L','O'}
#특징
#1. 중복을 허용하지 않는다.
#2. 순서가 없다. 인덱싱을 사용할 수 없다.
#인덱싱을 사용하기 위해서
#리스트로 변환
#LIST = list(s1)
#튜플로 변환
#TUPLE = tuple(s2)
#집합 자료형 활용하기
#교... | andylion-repo/python | bak/set.py | set.py | py | 1,075 | python | ko | code | 0 | github-code | 13 |
8208656084 | from ufit import UFitError
from ufit.data import ill, nicos, nicos_old, simple, simple_csv, trisp, \
llb, cascade, taipan, nist
from ufit.data.loader import Loader
from ufit.data.dataset import Dataset, ScanData, ImageData, DatasetList
from ufit.plotting import mapping
from ufit.pycompat import listitems
data_form... | McStasMcXtrace/ufit | ufit/data/__init__.py | __init__.py | py | 5,990 | python | en | code | 1 | github-code | 13 |
4534603079 | #!/usr/bin/env python3
# reTxt.py - searches all .txt files in the current working directory
# for a user supplies regualer expression
import sys, re, os
from pathlib import Path
# Make regex from supplied string
sRegex = re.compile(sys.argv[1])
p = Path.cwd()
fileList = list(p.glob('*.txt'))
# Go trhough... | sbackon/Boring_Stuff | Boring_Stuff_9/Practice_Projects/reTxt.py | reTxt.py | py | 577 | python | en | code | 0 | github-code | 13 |
5104153983 | import numpy as np
import pandas as pd
import datajoint as dj
from ...common.common_nwbfile import AnalysisNwbfile
from ...utils.dj_helper_fn import fetch_nwb
from .position_dlc_pose_estimation import DLCPoseEstimation # noqa: F401
from .position_dlc_position import DLCSmoothInterp
schema = dj.schema("position_v1_dl... | LorenFrankLab/spyglass | src/spyglass/position/v1/position_dlc_cohort.py | position_dlc_cohort.py | py | 4,503 | python | en | code | 49 | github-code | 13 |
18796507031 | import pandas as pd
import os
import pickle
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn import tree
# from catboost import CatBoostClassifier
from sklearn.svm import SVC
# single flexible function to train different model types with different fe... | aMala3/RussianToxic | Train_BinaryClass.py | Train_BinaryClass.py | py | 6,589 | python | en | code | 0 | github-code | 13 |
41612839551 | import pytest
from tsp import Place, Tour
def test_tour_cost(tsp_obj, tour_obj):
assert [tsp_obj.cost(current, next)
for current, next in tour_obj] == [3, 6, 5, 8, 7]
assert tsp_obj.total_cost(tour_obj) == 29
def test_tsp_creation(tsp_obj):
assert Place(0, 0, 0) == tsp_obj.places[0] and \
... | Carlosrlpzi/tsp_ | tests/test_tsp.py | test_tsp.py | py | 746 | python | en | code | 0 | github-code | 13 |
26993679470 | #https://assinaturas.superlogica.com/hc/pt-br/articles/360008275514-Integra%C3%A7%C3%B5es-via-API
import sys
import re
from datetime import date, timedelta, datetime
import threading
from service.clientRestService import ClientRestService
from service.metricasRestService import MetricasRestService
from dao.clientDao... | prgmw/integracao | src/job.py | job.py | py | 5,494 | python | pt | code | 0 | github-code | 13 |
24418424026 | import pandas as pd
import openai
import tiktoken
import re
class AIDataAnalyzer:
'''
AIDA: Artificial Intelligence Data Analyzer
This class contains methods that uses the OpenAI API to analyze data.
The idea is as follows:
- The data are stored in a dataframe, which is passed to the class... | nronaldvdberg/integrify | ronaldlib/ronaldlib/aida.py | aida.py | py | 11,489 | python | en | code | 0 | github-code | 13 |
43581470136 | #!/usr/bin/env python2.7
import kivy
kivy.require('1.7.2')
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from plyer import notification
__version__ = '0.1'
class Playground(BoxLayout):
def _do_notify(self,
title=... | brousch/playground | playground/main.py | main.py | py | 585 | python | en | code | 2 | github-code | 13 |
37005323970 | import torch
import torch.nn as nn
from functools import partial
from timm.models.cait import default_cfgs, checkpoint_filter_fn
from timm.models.registry import register_model
from timm.models.layers import trunc_normal_, Mlp, PatchEmbed
from timm.models.helpers import *
def _create_cait(variant, pretrained=False, ... | tuoli9/GALD | vit_models/re_cait.py | re_cait.py | py | 15,467 | python | en | code | 0 | github-code | 13 |
38462179659 | """Test PyDynamic.uncertainty.propagate_DFT.DFT_deconv"""
from typing import Callable, cast, Dict, Tuple
import numpy as np
import pytest
import scipy.stats as stats
from hypothesis import given, HealthCheck, settings
from hypothesis.strategies import composite, DrawFn, SearchStrategy
from numpy.testing import assert_... | Met4FoF/Code | PyDynamic/test/test_DFT_deconv.py | test_DFT_deconv.py | py | 7,674 | python | en | code | 0 | github-code | 13 |
16846945485 | import pickle
import copy
import pandas as pd
import spacy
nlp = spacy.load('en_core_web_sm')
import string
TAG2INDEX = '../tag2index.pickle'
ADJ_LIST = 'ED_adjacency_list.pickle'
WORDLIST = 'ED_wordlist.pickle'
INDEX2WORD = 'ED_index2word.pickle'
ED_DATA = 'mod_dataset.csv'
data = pd.read_csv(ED_DATA)
data = data... | shandilya1998/CS6251-project | data/ED/data_prep.py | data_prep.py | py | 3,278 | python | en | code | 0 | github-code | 13 |
21021618546 | #!/usr/bin/env python
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('classic')
x = np.linspace(0, 10, 100)
fig = plt.figure()
plt.plot(x, np.sin(x), '-')
plt.plot(x, np.cos(x), '--')
fig.savefig('/home/tmp/0.0.png')
| bismog/leetcode | matplotlib/line000.0.py | line000.0.py | py | 283 | python | en | code | 0 | github-code | 13 |
27910546955 | class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
curr = 0
for i in range(1, len(nums)):
if nums[i] != nums[curr]:
nums[curr+1] = nums[i]
curr += 1
return curr+1 | JinhanM/leetcode-playground | 26. 删除排序数组中的重复项.py | 26. 删除排序数组中的重复项.py | py | 316 | python | en | code | 0 | github-code | 13 |
12343845135 | # Program for computing minimum operations required from moving 0 to N.
# We are allowed to use two operations :
# 1. Add 1 to the number
# 2. Double the number
# ---------------------------------------------------------------------------
# One of the observation is that minimum operations required from 0 -> N will be ... | souravs17031999/100dayscodingchallenge | arrays/min_operations_N.py | min_operations_N.py | py | 950 | python | en | code | 43 | github-code | 13 |
37490231445 | #!/bin/python3
import sys
import csv
import os
import json
from optparse import OptionParser
from collections import OrderedDict
parser = OptionParser()
parser.add_option("-o",dest="output",help="output directory")
(options,args) = parser.parse_args()
outputDir = options.output
if not outputDir.endswith(os.sep):
... | gus3000/Transversal | Cpp/manual_tracking/python/simplifyCsv.py | simplifyCsv.py | py | 1,535 | python | en | code | 0 | github-code | 13 |
13514700106 | import os
import shutil
from copy import deepcopy
import mock
import unittest
from ebcli.operations import scaleops
from .. import mock_responses
class TestScaleOps(unittest.TestCase):
def setUp(self):
self.root_dir = os.getcwd()
if not os.path.exists('testDir'):
os.mkdir('testDir')... | aws/aws-elastic-beanstalk-cli | tests/unit/operations/test_scaleops.py | test_scaleops.py | py | 3,802 | python | en | code | 150 | github-code | 13 |
32039000245 | import os
import re
words = []
file = open('diccionario-hunspell.txt', "r", encoding="utf-8")
for line in file:
words.append(line.rstrip())
len(words)
file = open('../diccionario-rae-completo.txt', "r", encoding="utf-8")
for line in file:
words.append(line.rstrip())
cleanWords = []
for word in words:
if '/'... | fvillena/palabras-diccionario-rae-completo | fuentes/fromHunspell.py | fromHunspell.py | py | 644 | python | en | code | 8 | github-code | 13 |
10031195834 | meses = int(input("Ingrese la cantidad de meses: "))
adultos = 2
recien_nacidas = 0
parejas = 1
for i in range(0, (meses+1)):
parejas = adultos // 2 #Esta division entera para saber cuantas parejas de adultos tenemos y por cada pareja de adultos se genera una nueva recien nacido
adultos ... | matiasnicolassanchez/Guia10LabComp | Ej 6.py | Ej 6.py | py | 595 | python | es | code | 0 | github-code | 13 |
21268936948 | import re
with open("altmir_hit.txt","a") as hit:
hit.write("mirid\tutr_chr\tutr_start-end\tutr_strand\thit_counts\n")
chit=0
with open("s1_miranda_altmir_res_02.txt") as res:
for line in res:
if line:
if line.startswith('Performing Scan:'):
mirid = line.split()[2]
sloc = line.split()[4]
hi... | chunjie-sam-liu/miRNASNP-v3 | scr/target/miranda/s3_gethit.py | s3_gethit.py | py | 592 | python | en | code | 3 | github-code | 13 |
6948084524 | from typing import *
class Solution:
def canPartition(self, nums: List[int]) -> bool:
total_sum = sum(nums)
if total_sum % 2 != 0:
return False
target = total_sum // 2
m = len(nums)
dp = [0] * (total_sum + 1)
for i in range(1, m + 1):
for j i... | Xiaoctw/LeetCode1_python | 动态规划/分割等和数组_416.py | 分割等和数组_416.py | py | 611 | python | en | code | 0 | github-code | 13 |
21021343977 | import torch
import os
import numpy as np
import random
import csv
import pickle
def seed_everything(args):
random.seed(args.seed)
os.environ['PYTHONASSEED'] = str(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
torch.cuda.manual_seed(args.seed)
torch.backends.cudnn.determinist... | qcwthu/Lifelong-Fewshot-Language-Learning | Summarization/utils.py | utils.py | py | 3,958 | python | en | code | 52 | github-code | 13 |
72915473618 | import os.path
import logging
import pytest
import pytest_bdd as bdd
bdd.scenarios('sessions.feature')
@pytest.fixture(autouse=True)
def turn_on_scroll_logging(quteproc):
quteproc.turn_on_scroll_logging()
@bdd.when(bdd.parsers.parse('I have a "{name}" session file:\n{contents}'))
def create_session_file(qutepr... | qutebrowser/qutebrowser | tests/end2end/features/test_sessions_bdd.py | test_sessions_bdd.py | py | 1,800 | python | en | code | 9,084 | github-code | 13 |
26889995924 | import numpy as np
from matplotlib.path import Path
from matplotlib.patches import Ellipse, PathPatch
import validate
class Ring:
"""
The ring class is a simple object that has ring parameters:
inner_radius
outer_radius
transmission
inclination
tilt
With the additio... | dmvandam/beyonce | Ring.py | Ring.py | py | 9,644 | python | en | code | 0 | github-code | 13 |
33049827109 | import os
from flask import Flask
from xgb_api import api_predict
app = Flask(__name__)
@app.route('/')
def hello():
return 'hello, world!'
@app.route('/predict')
def predict():
data = {
'PassengerId': [1],
'Pclass': [3],
'Age': [35],
'Sex': ['male'],
'SibSp': [1],
... | sonhmai/titanic | app.py | app.py | py | 469 | python | en | code | 0 | github-code | 13 |
28326036387 | from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class Exemption(models.Model):
_name = "hr.contribution.exemption"
_description = "Contribution Exemption"
name = fields.Char()
employee_id = fields.Many2one(
comodel_name="hr.employee", string="Employee"
... | odoo-cae/odoo-addons-hr-incubator | hr_cae_contribution/models/hr_exemption.py | hr_exemption.py | py | 1,063 | python | en | code | 0 | github-code | 13 |
72523246737 | from numpy.random import randn
from scipy.linalg import qr
from scipy.linalg import svd
from scipy.sparse import csc_matrix
from numpy import allclose, outer
from sparsesvd import sparsesvd
def mysparsesvd(sparsematrix, m):
Ut, S, Vt = sparsesvd(sparsematrix, m)
return Ut.T, S, Vt.T
extra_dim = 50
power_num =... | karlstratos/cca | src/svd.py | svd.py | py | 1,888 | python | en | code | 10 | github-code | 13 |
74838274256 | from cmath import e
import json
from re import template
from tkinter import E
def main(env, request_handler, method):
"""Simple to do app
Args:
env (Environment): renders environment for our template
request_handler(Request_handler): instance of request handler
method(str): GET or POS... | canjey/pesapal-application | Problem1/sampleapp/__init__.py | __init__.py | py | 1,584 | python | en | code | 0 | github-code | 13 |
42252430005 | import logging
import requests
import json
from time import sleep
from src.webdriver import get_token
def maesk_get_location(cityname:str):
url = "https://api.maersk.com/locations"
querystring = {"cityName": cityname,"type":"city","sort":"cityName"}
response = requests.get(url, params=querystring)
... | mx-jeff/naval_fretes | src/api/maesk.py | maesk.py | py | 3,490 | python | en | code | 0 | github-code | 13 |
37173080443 | # -*- coding: utf-8 -*-
from Tkinter import *
import Tkinter
import Tkinter as tk
import tkMessageBox
import sqlite3 as lite
import sys
con = lite.connect('paliwko.db')
cur = con.cursor()
paliwo = []
fuel = Tk()
fuel.title("Dziennik tankowan")
with con:
cur = con.cursor()
cur.execute("SELECT * FROM tankowa... | kamilpek/python-paliwko | dziennik.py | dziennik.py | py | 2,513 | python | pl | code | 1 | github-code | 13 |
70869657619 | """Tests for unit functionalities."""
import os
import pandas as pd
import pytest
from app.ETL import extract_excel, load_em_um_novo_excel, transforma_em_um_unico
# Sample data for testing
df1 = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})
df2 = pd.DataFrame({"A": [4, 5, 6], "B": ["d", "e", "f"]})
@pytest... | lvgalvao/DataProjectStarterKit | tests/test_unitarios.py | test_unitarios.py | py | 3,049 | python | en | code | 23 | github-code | 13 |
71758469457 | import json
import os
import requests as rq
import datetime as dt
import pandas as pd
import ast
TOKEN_FILE = "token_info.json"
class Spotify():
def __init__(self):
if os.path.exists(TOKEN_FILE):
with open(TOKEN_FILE) as tkfile:
data = json.load(tkfile)
if data['ti... | jdscifi/VinylRec | spotify_tasks.py | spotify_tasks.py | py | 5,857 | python | en | code | 0 | github-code | 13 |
43089321371 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen
from kivy.uix.popup import Popup
# The Label widget is for rendering text.
from kivy.uix.label import Label
from kivy.uix.button import Button
# The GridLayout arranges children in a matrix.
# It take... | ketan-mk/pho-ga | screens/updates.py | updates.py | py | 2,219 | python | en | code | 0 | github-code | 13 |
3914380437 | from aiogram import exceptions as aiogram_exc
from NekoGram import Menu
import asyncio
from const import SEARCH_LIST, ADMIN_IDS, RUN_INTERVAL, NEKO, STORAGE
from loggers import main_logger
import scrappers
import menus
async def send_data(data: Menu, user: int):
while True:
try:
await NEKO.bo... | lyteloli/ProductLookuper | main.py | main.py | py | 2,732 | python | en | code | 0 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.