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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
74769733793 | '''
You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit.
Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit.
(Her tekne aynı anda en fazla ... | bulentsiyah/data-preprocessing_cv-skills | leetcode/b/boats-to-save-people.py | boats-to-save-people.py | py | 1,624 | python | en | code | 2 | github-code | 1 |
15531056887 | """
Created on Thu Dec 1 06:33:09 2016
@author: sushma
"""
import pickle
from collections import Counter
def main():
finalfile=open("summary.txt","w")
clusterinput = open("clusterinput.pkl","rb")
users=pickle.load(clusterinput)
classifyinput = open("classifyinput.pkl","rb")
messagedata=pickle.load(classify... | smahade4/Online-Social-Network-Analysis | Gender classification and community prediction using twitter/summarize.py | summarize.py | py | 1,984 | python | en | code | 1 | github-code | 1 |
3243282065 | import pickle as pkl
import numpy as np
import torch.utils.data as data
from data import common
class SatData(data.Dataset):
def __init__(self, args, train=True):
self.args = args
self.train = train
self.scale = args.scale if train else args.scale_test
with open('./dataset/info.... | miracleyoo/Meta-SSSR-Pytorch-Publish | data/sat_data.py | sat_data.py | py | 2,624 | python | en | code | 4 | github-code | 1 |
21055488185 | from __future__ import absolute_import
import atexit
import contextlib
import sys
import requests
import requests.packages.urllib3 as urllib3
from requests.adapters import DEFAULT_POOLBLOCK, HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
from requests.packages.urllib3.util.retry import Retr... | franzinc/agraph-python | src/franz/miniclient/backends/requests.py | requests.py | py | 8,252 | python | en | code | 34 | github-code | 1 |
70041056675 | from time import sleep
n1 = int(input('Primeiro valor: '))
n2 = int(input('Segundo valor: '))
opcao = 0
while opcao != 5:
opcao = int(input('''
[1] somar
[2] multiplicar
[3] maior
[4] novos números
[5] sair do programa
Qual é sua opção? '''))
if opcao == 1:
print('A soma é {}'.fo... | luizaacampos/exerciciosCursoEmVideoPython | ex059.py | ex059.py | py | 881 | python | pt | code | 0 | github-code | 1 |
34063507829 | import os
import time
import numpy as np
import pymysql
import cv2
if __name__ == '__main__':
host = 'localhost'
user = 'root'
password = '880510'
db = 'fx'
sql_select = "SELECT * FROM fileTmpTest2 where file_name like '%\\_3\\_%'"
sql_delete = "DELETE FROM fileTmpTest2 WHERE file_n... | 314257smcag2/okteto | sanan/分选图像判定/detect3.py | detect3.py | py | 4,561 | python | en | code | 0 | github-code | 1 |
10242742848 | def fact(n):
prod = 1
for i in range(1, n + 1):
prod *= i
return prod
s = input().strip()
while s != "0":
chars = set()
for c in s:
chars.add(c)
print(fact(len(s)) // fact(len(s) - len(chars)))
s = input().strip() | lvirgili/programming_challenges | uri/uri1980.py | uri1980.py | py | 248 | python | en | code | 5 | github-code | 1 |
5235426120 | from PIL import Image
from io import BytesIO
from all_data import all_data
def open_image(filename):
return Image.open(filename)
def convert_bytes(bytes_stream):
return Image.open(BytesIO(bytes_stream)).convert("RGBA")
def combine(image_name, file_id, other_image):
image_data = all_data["images"][imag... | TurboGoose/turbo_bot | image_module.py | image_module.py | py | 1,148 | python | en | code | 0 | github-code | 1 |
3630655417 | """
This module contains all the paths for the wiredrive app.
Name: Michael Feigen
Date Completed: 7/31/2018
"""
from django.urls import path
from . import views
urlpatterns = [
path('', views.IndexView.as_view(), name='wiredrive'),
path('form/', views.getName, name='get_name'),
path('list/', ... | michaelfeigen/portal | wiredrive/urls.py | urls.py | py | 466 | python | en | code | 2 | github-code | 1 |
3178025434 | import mxnet as mx
import numpy as np
import cv2
from test_utils.predict import predict
def pred(image, net, step, ctx):#step为样本选取间隔
h, w, channel = image.shape
image = image.astype('float32')
size = int(step *0.75) #取样本中size尺寸为最终预测尺寸
margin = int((step - size) / 2)
inhang = int(np.ceil(h/size))
... | scrssys/semantic_segment_RSImage | temp/predict_from_xuhuimin.py | predict_from_xuhuimin.py | py | 1,308 | python | en | code | 49 | github-code | 1 |
3480209277 | from . import models
from django.conf.urls import url
from stark.service import v1
import json
from django.db.models import Q
from utils import message
from xxxxxx import XXX
from django.utils.safestring import mark_safe
from django.shortcuts import HttpResponse, redirect, render
from django.utils.safestring import ma... | frank12a/Gemma- | crm/stark.py | stark.py | py | 24,228 | python | en | code | 0 | github-code | 1 |
245936115 | #!/usr/bin/python
import threading
import numpy as np
import cv2
import rospy
from viman_utility.msg import CamZ
"""
Common class where calibrated CV image matrix is stored and accessed
"""
class Output:
# dummy image
img = np.zeros((640,480,3), np.uint8)
lock = threading.Condition()
def __init__(self):
p... | ProjectViman/viman | viman_control/scripts/slam_Z/process_vision.py | process_vision.py | py | 4,123 | python | en | code | 3 | github-code | 1 |
24452600516 | # -*- coding:utf-8 -*-
import random
import requests
from scrapy.selector import Selector
class GetIP(object):
def __init__(self):
self.IP_list = []
self._crawl_ip()
def _crawl_ip(self):
useragent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36' \
... | Linsublime/scrapyspider | scrapy_spider/utils/crawlxiciIP.py | crawlxiciIP.py | py | 1,566 | python | en | code | 0 | github-code | 1 |
26730078254 | import sys
class Node:
id = ""
children = {}
def __init__(self, id_val):
self.id = id_val
self.children = {}
def Trie(patterns):
tree = []
root = Node(0)
tree.append(root)
counter = 1
for string in patterns:
location = root
for lett... | wolffj97/code_check | codeChallenges/Trie.py | Trie.py | py | 1,258 | python | en | code | 0 | github-code | 1 |
35436389590 | #! /usr/bin/env python3
import re
import math
from copy import copy, deepcopy
# ==== INPUT ====
data = ""
with open('11.txt', 'r') as file:
data = file.read().strip()
rows = [list(row.strip()) for row in data.split('\n')]
# ==== SOLUTION ====
WIDTH = len(rows[0])
HEIGHT = len(rows)
NEIGHBOUR_OFFSETS = [(x,y) f... | finwarman/advent-of-code-2020 | 11/02.py | 02.py | py | 1,576 | python | en | code | 1 | github-code | 1 |
43788011167 | import requests
import json
word = ' Busca-cep '
print(f'{word:=^30}')
usercep = str(input('Informe seu CEP: '))
api = requests.get(f'https://viacep.com.br/ws/{usercep}/json/')
#cepdata = json.loads(api.text)
print(api.text) | Guribeiro/python | api/busca-cep.py | busca-cep.py | py | 229 | python | en | code | 0 | github-code | 1 |
74945420193 | #!/usr/bin/env python
Import('env')
if env.get('WITH_RADAU5'):
srcs = Split("radau5 decsol.f dc_decsol.f")
radau5obj = env.SharedObject(srcs)
lib = env.SharedLibrary("radau5",["asc_radau5.c",radau5obj]
,LIBS = ['ascend']
,LIBPATH = ['#']
,SHLIBSUFFIX = env['EXTLIB_SUFFIX']
,SHLIBPREFIX = env['EXTLIB_PREF... | georgyberdyshev/ascend | solvers/radau5/SConscript | SConscript | 530 | python | en | code | 5 | github-code | 1 | |
34549216828 | import numpy as np
import neuralnet as nl
import load_mnist as lm
np.random.seed(21)
dataset = lm.load_mnist()
x_train = dataset['x_train']
y_train = dataset['y_train']
x_test = dataset['x_test']
y_test = dataset['y_test']
img = np.zeros(28 * 28 * 10).reshape(10, 784)
img_test = np.zeros(28 * 28 * 10).res... | xyw0025/AI2020f | HW3/learn.py | learn.py | py | 1,782 | python | en | code | 0 | github-code | 1 |
20567742774 | ''' kth largest / smallest element
Solution: selection rank algorithm (if you can modify the original array)
Solution: Red Black trees with rank in each node specified
'''
import os
import random
from binary_tree import *
# based on quicksort method O(N) but array need to have distinct elements
def randomNum(lower... | gayathrimahalingam/interview_code | kt_largest_element.py | kt_largest_element.py | py | 2,503 | python | en | code | 0 | github-code | 1 |
43439871442 | import tests_suite
import unittest
from cpu import CPU
from ram import RAM
from rom import ROM
class tests_ld_a_bc(unittest.TestCase):
def test_ld_a_bc_loads_corect_value(self):
ram = RAM()
ram[0x4747] = 0x12
cpu = CPU(ROM(b'\x0a'), ram)
cpu.BC = 0x4747
cpu.readOp()
... | pawlos/Timex.Emu | tests/tests_ld_a_bc.py | tests_ld_a_bc.py | py | 787 | python | en | code | 5 | github-code | 1 |
33712330932 |
class ColorCard(qWidget):
def __init__(self,
color: str,
uid: str = None,
signals: fSignalVar = None,
*args, **kwargs):
qWidget.__init__(self, uid, signals, *args, **kwargs)
f = QFrame(self)
f.setStyleSheet(f"backgro... | omamkaz/flapy | examples/color_card.py | color_card.py | py | 892 | python | en | code | 1 | github-code | 1 |
29061052103 | import threading
import time
import dothat.backlight as backlight
from standing_desk.settings import MAX_HEIGHT, MIN_HEIGHT
class Lightbar(threading.Thread):
def __init__(self, desk):
self.desk = desk
threading.Thread.__init__(self)
self.update()
def run(self):
while True:
... | timmyomahony/standing-desk | src/standing_desk/lightbar.py | lightbar.py | py | 649 | python | en | code | 3 | github-code | 1 |
163369334 | #! /usr/bin/env python
"""Toolbox for imbalanced dataset in machine learning."""
import codecs
import os
from setuptools import find_packages, setup
# get __version__ from _version.py
ver_file = os.path.join('imblearn', '_version.py')
with open(ver_file) as f:
exec(f.read())
DISTNAME = 'imbalanced-learn'
DESCRI... | jem0101/BigSwag-SQA2022-AUBURN | TestOrchestrator4ML-main/resources/Data/supervised/GITHUB_REPOS/scikit-learn-contrib@imbalanced-learn/setup.py | setup.py | py | 2,284 | python | en | code | 2 | github-code | 1 |
11687840437 | #!/usr/bin/python
# This file is used for extracting images from one or more bag files.
# Before run this file, remember to create a folder to store the images and 2 txt files which will store the
# image name with its corresponding omega.
# Then change the folder name to the one you created in line 52 & 53.
# In thi... | OpenPPAT/ai-course-2019 | 08-imitation-learning/bag2txt.py | bag2txt.py | py | 3,216 | python | en | code | 4 | github-code | 1 |
1777805113 | #! /usr/bin/env python
# compare dijet and Z+jets responses in various eta bins
# A.Karavdina 14.07.2017
from ROOT import *
import sys
import numpy
import os
pathGL = "/afs/desy.de/user/k/karavdia/xxl/af-cms/GlobalFit_2016_dijet_Zjets_data/"
filelist = {'Dijet_BCD':'/Dijets_20170712/RunBCD/output/JEC_L2_Dijet_AK4PF... | miquork/jecsys | overlay_Dijet_Zjet.py | overlay_Dijet_Zjet.py | py | 5,326 | python | en | code | 3 | github-code | 1 |
6659057511 | import models
import math
import numpy as np
import helper_methods.dictionary_methods as dictionary_methods
# 从左边查最大的单词匹配
def fmm_greedy_check(term, word_dictionary):
word_to_check_in_dictionary = term
is_dictionary_match = False
while not is_dictionary_match and word_to_check_in_dictionary:
is_dictionary_m... | robert1ridley/chinese-segmentation-tool | helper_methods/segmenting_methods.py | segmenting_methods.py | py | 3,670 | python | en | code | 0 | github-code | 1 |
14476654720 | import datetime
from django.core.management.base import NoArgsCommand
from django.template import Context, loader
from localtv import models
from localtv import util
class Command(NoArgsCommand):
def handle_noargs(self, **kwargs):
self.send_email(datetime.timedelta(hours=24),
'to... | natea/Miro-Community | localtv/submit_video/management/commands/review_status_email.py | review_status_email.py | py | 1,589 | python | en | code | 2 | github-code | 1 |
39560590081 |
import os
import glob
import fnmatch
# Set working directory
wkdir = os.path.dirname('')
# Set image name, e.g. 'RT_516_02'
img = ''
# Path to input directory
indir = os.path.join(wkdir, 'data', 'tracking', img, 'results', 'tracks')
for file in os.listdir(indir):
# Check if the file format is 'TRACK_0001.txt'... | anyastep/rp-chromatin | csvConvert.py | csvConvert.py | py | 580 | python | en | code | 0 | github-code | 1 |
24893217036 | # -*- coding:utf-8 -*-
# @Author: james
# @Date: 2019/1/7
# @File: base.py
# @Software: PyCharm
import json
import scrapy
from scrapy import Request, FormRequest
from lxml import etree
from WaiBaoSpider.utils.csvWriter import CSVDumper
from WaiBaoSpider.utils.base import unicode_body, deal_ntr
import os
class BeiJin... | jamesfyp/WaiBaoSpider | WaiBaoSpider/spiders/beijing.py | beijing.py | py | 4,102 | python | en | code | 1 | github-code | 1 |
29359771140 | from pathlib import Path
from typing import List
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
DATASET = 'dataset_7_classes_v3.xlsx'
TEST_SIZE = 0.15
VALIDATION_SIZE = 0.2
FAILURE_MECHANISMS = ['NF', 'RM', 'DPF', 'NPF', 'DWF', 'NWF']
BINARY_LABELS = ['No_Failure', 'Failu... | cristian-castro-a/slope-stability-surrogate-model | 04_multiclass_multilabel_classification_model/04_01_data_split/run_multiclass_data_split.py | run_multiclass_data_split.py | py | 7,464 | python | en | code | 0 | github-code | 1 |
17959209518 | # 거품 정렬(Bubble Sort)
# 버블 정렬이란 이웃하는 숫자들끼리 크기를 비교하여 자리를 바꾸는 정렬
# 기법이다. 버블 정렬은 구현이 쉬운 반면 속도가 빠른 편은 아니다. 가장
# 큰 단점은 정렬이 이미 다 끝났는데도, 끝까지 대소비교를 하는 문제점이
# 있다. 예를 들어 10 50 30 20 40이 있고 오름차순으로 정렬한다면 총
# 4단계를 거치게되는데, 1단계: 10 30 20 40 50, 2단계: 10 20 30 40 50
# (정렬 완료), 3단계: 10 20 30 40 50, 4단계: 10 20 30 40 50 | 4단계중
# 이미 2단계에서 정... | junes7/python_algorithm | CodeUp/Sort/3011.py | 3011.py | py | 1,162 | python | ko | code | 1 | github-code | 1 |
29281040301 |
def check_inputs(func):
def wrapper(value):
if value <= 1:
raise Exception("The input value must be greater than 1")
return func(value)
return wrapper
def isPrime(number):
"""Check if a number is prime.
Args:
number (int or float): a number to test.
Returns:... | jhags/the-perfect-prime | theperfectprime/prime.py | prime.py | py | 1,114 | python | en | code | 0 | github-code | 1 |
23495538946 | from youtube_transcript_api import YouTubeTranscriptApi
from yt_concate.pipeline.steps.step import Step
class DownloadCaptions(Step):
def process(self, data, inputs, utils):
for yt in data:
url = yt.url
video_id = yt.id
captions_dir = yt.captions_dir
if uti... | NoelTW/yt-concate | yt_concate/pipeline/steps/download_caption.py | download_caption.py | py | 819 | python | en | code | 4 | github-code | 1 |
24640717596 | year = int(input())
month = int(input())
day = int(input())
daylist = [31,28,31,
30,31,30,
31,31,30,
31,30,31]
tatalDays = 0;
isRun = year % 4 ==0 and year % 400 != 0 or year % 400 == 0
for i in range(month-1):
tatalDays += daylist[i]
tatalDays += day
if isRun:
tatalDays +... | smakerm/list | Pybase/idea/perday.py | perday.py | py | 341 | python | en | code | 0 | github-code | 1 |
43679816578 | class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def info(self):
print(f'Работника зовут {self.name}\n'
f'Его зарплата {self.salary}')
worker_1 = Employee('Tom', 10000)
worker_2 = Employee('Bob', 12000)
worker_1.info()
worker_2.inf... | Dober616/work | 24/24.4/work.py | work.py | py | 348 | python | en | code | 0 | github-code | 1 |
27909309696 | import limmy
import time
# How to use limmy, by Adrian Ornelas
# First, create motor objects. This will automatically start the heartbeat thread that keeps the motor alive.
serial_port_1 = 'COM15' # Change this to the serial port of your VESC, on Linux (Raspberry Pi) it will be something like '/dev/ttyUSB0'
... | UCI-HyperXite/limmy | lim.py | lim.py | py | 1,664 | python | en | code | 1 | github-code | 1 |
35655245303 | from win32com.client import Dispatch
import requests
import json
def speak(str):
talk = Dispatch("SAPI.SpVoice")
talk.Speak(str)
if __name__ == '__main__':
speak("Hello, welcome to newstoday.com. I am your news anchor")
speak(" top news for today from are ")
print("Hello, welcome to ... | Kaushal-Dhungel/newsreader | newsreader.py | newsreader.py | py | 2,081 | python | en | code | 0 | github-code | 1 |
23930974543 | import os
import streamlit as st
import requests
from dotenv import load_dotenv
st.set_page_config(
page_title="advotis – Strafbarkeit prüfen",
page_icon="assets/advotis_icon.png",
layout="centered",
)
st.sidebar.image("assets/advotis_logo.png")
def category_to_result_text(category: str) -> str | None:... | matzewolf/LegalLovesTechHackathon | pages/1_⚖️_Strafbarkeit_prüfen.py | 1_⚖️_Strafbarkeit_prüfen.py | py | 7,720 | python | de | code | 0 | github-code | 1 |
24348949436 | import numpy as np
from os import getcwd
from os.path import dirname
def load_npy(crop_size=240, test_phase=False, filename=None):
"""Load .npy preprocessed in Matlab"""
# dir_A = r'%s\ProstateX\data' % dirname(dirname(getcwd()))
# A = np.expand_dims(np.load('%s/T2_combined_%d_preproc.npy' % (dir_A, crop_... | minhto2802/T2_ADC | CycleGAN/util/load_npy.py | load_npy.py | py | 1,355 | python | en | code | 0 | github-code | 1 |
14821631079 | import pygame
import sys
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load("music.mp3")
pygame.mixer.music.play(-1)
Width = 1280
Height = 720
screen = pygame.display.set_mode((Width, Height))
pygame.display.set_caption("Pong V2")
white = (255, 255, 255)
black = (0, 0, 0)
clock = pygame.time.Clock()
paddl... | Pigiotyreal/Pong-V2 | src/main.py | main.py | py | 3,014 | python | en | code | 0 | github-code | 1 |
13043081088 | import pytest
from iotile.core.hw.debug import SparseMemory
from iotile.core.exceptions import ArgumentError
@pytest.fixture(scope='function')
def single_segment():
mem = SparseMemory()
mem.add_segment(0, bytearray(range(0, 256)))
return mem
@pytest.fixture
def multi_segment(scope='function'):
mem =... | iotile/coretools | iotilecore/test/test_debug/test_sparsememory.py | test_sparsememory.py | py | 1,673 | python | en | code | 14 | github-code | 1 |
26447542170 | import os
import pty
import sys
from curtin import util
from . import populate_one_subcmd
CMD_ARGUMENTS = (
((('-a', '--allow-daemons'),
{'help': 'do not disable daemons via invoke-rc.d',
'action': 'store_true', 'default': False, }),
(('-i', '--interactive'),
{'help': 'use command invoked... | rom1212/maas-guide | deploy/curtin-extract/curtin/commands/in_target.py | in_target.py | py | 1,979 | python | en | code | 0 | github-code | 1 |
15204506942 | import os
os.system('cls||clear')
soma = 0
contador = 0
num = 1
resp=input("Quer fazer a média s/n?")
while resp=='s' and num!=0:
num = int(input("\033[1;94mDigite um número inteiro ou zero para sair: \033[0;0ms"))
soma = soma + num
if num!=0:
contador= contador + 1
media = soma/contador
print(f"A média é {... | msanches/PyCode | SystemOS/clear.py | clear.py | py | 336 | python | pt | code | 0 | github-code | 1 |
11572385557 | import sys
input = sys.stdin.readline
def get_pi(pattern): #Pi배열, LPS
length = len(pattern) # 패턴의 길이
lps = [0] * length # Pi 배열을 저장할 공간
p_idx = 0 # 패턴의 인덱스
for idx in range(1, length): #파이 배열의 첫 값은 0임
#p_idx가 0이 되거나, idx와 p_idx의 접근 값이 같아질 때 까지
while p_idx > 0 and pattern[idx] !... | hyojeong00/BOJ | boj1786.py | boj1786.py | py | 1,335 | python | ko | code | 0 | github-code | 1 |
41753289786 |
def yes_no(question):
Vaild = False
while not Vaild:
response = input(question).lower()
if response == "yes" or response == "y":
response = "yes"
return response
elif response == "no" or response == "n":
respo... | evansj2573/lucky-unicorn | yes_no_V3.py | yes_no_V3.py | py | 535 | python | en | code | 0 | github-code | 1 |
38463610858 | import base64
import cv2
import numpy as np
input_name = 'temp.bin'
output_name = 'temp.jpg'
with open(input_name, 'rb') as f:
f = f.read()
img = base64.standard_b64decode(f)
img = cv2.imdecode(np.frombuffer(img, dtype=np.uint8), -1)
cv2.imwrite(output_name, img)
| ZombaSY/util-collection | file converter/blob_to_img_writer.py | blob_to_img_writer.py | py | 282 | python | en | code | 0 | github-code | 1 |
33703956955 | from typing import List
import pytest
import networkx as nx
from networkx.exception import NetworkXNoPath
from src.domain.wordchainservice import WordChainService
@pytest.mark.parametrize(
"start_word,end_word,expected_chain",
[
("spin", "spot", ["spin", "spit", "spot"]),
("hide", "sort", ["h... | gileslloyd/word-chain | tests/unit/domain/test_wordchainservice.py | test_wordchainservice.py | py | 860 | python | en | code | 0 | github-code | 1 |
257427796 | import datetime
import django_filters
from django import forms
from .choices import EXPERIENCIES, HIERARCHIES, MODALITIES, PERIOD_CHOICES
from .models import Job
class JobFilter(django_filters.FilterSet):
q = django_filters.CharFilter(field_name='title', lookup_expr='icontains')
modality = django_filters.Mu... | Ricardo-Jackson-Ferrari/jobfinder | apps/job/filters.py | filters.py | py | 1,761 | python | en | code | 5 | github-code | 1 |
17052614858 |
import sys
from car import Car
from board import Board
from helper import load_json
class Game:
"""
The class represent the Game object, each game initializes with
his Board object that the game will be played on him.
The class handles A full session of the RUSH HOUR game by getting user
input e... | OmerFerster/Introduction-to-CS | Exercise 8/game.py | game.py | py | 3,460 | python | en | code | 1 | github-code | 1 |
32656021823 | """Differentiate between type of service token
Revision ID: ddd3db82f370
Revises: 0e6ac85397af
Create Date: 2023-03-21 13:50:34.046658
"""
from alembic import op
from sqlalchemy import text
# revision identifiers, used by Alembic.
revision = 'ddd3db82f370'
down_revision = '0e6ac85397af'
branch_labels = None
depends_... | SURFscz/SBS | server/migrations/versions/ddd3db82f370_differentiate_between_type_of_service_.py | ddd3db82f370_differentiate_between_type_of_service_.py | py | 2,331 | python | en | code | 4 | github-code | 1 |
7414818396 | from __future__ import unicode_literals, print_function, division
__author__ = "mozman <mozman@gmx.at>"
import copy
from .tableutils import new_empty_cell, get_table_rows, is_table
from .tableutils import get_min_max_cell_count, count_cells_in_row
from .tableutils import RepetitionAttribute
from . import const
class... | T0ha/ezodf | ezodf/tablenormalizer.py | tablenormalizer.py | py | 5,081 | python | en | code | 61 | github-code | 1 |
36812771219 | import argparse
import os
import re
import shutil
parser = argparse.ArgumentParser(
description="Converts a VHDL circuit that uses the default UsbPort implementation (via JTAG) into one that can use the VPI+GHDL one."
)
# TODO: generate a new Makefile / update the old one with the new files
# python3 usb_port_vp... | roby2014/virtual-board-vhdl | UsbPort/script/usb_port_vpi_ghdl.py | usb_port_vpi_ghdl.py | py | 5,151 | python | en | code | 2 | github-code | 1 |
39492874795 | """Inferrer"""
from PIL import Image
import torch
import numpy as np
import matplotlib.pyplot as plt
import cv2
from utils.load import load_yaml
from model import get_model
from dataloader.transform import DataTransform
class Inferrer():
"""SSDでの予測と画像の表示をまとめて行うクラス"""
def __init__(self, configfile):
... | noji0101/object-detection-app | executor/inferrer.py | inferrer.py | py | 7,262 | python | ja | code | 0 | github-code | 1 |
70410826594 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 27 18:13:13 2019
@author: nwu
"""
import requests
import copy
from secret import headers
from datetime import datetime, timedelta
from time import sleep
from math import exp
class ZoomAPIException(Exception):
def __init__(self, response):
... | 50wu/Project | zoomQOS/zoomQos.py | zoomQos.py | py | 5,737 | python | en | code | 0 | github-code | 1 |
28022620563 | """
Local Search 2 : Simulated simulatedAnnealing
"""
import time
import sys
import math
import numpy
import random
class SimulatedAnnealing:
def __init__(self, instance, seed, limit):
self.city = instance
self.seed = seed
self.time_limit = limit
self.edges = []
self.gra... | glorianachen/project-of-algorithm-analysis | code/SimulatedAnnealing.py | SimulatedAnnealing.py | py | 4,530 | python | en | code | 0 | github-code | 1 |
73866795874 | _base_ = [
'./datasets/pipelines/rcrop_hflip_resize.py'
]
__train_pipeline = {{_base_.train_pipeline}}
__test_pipeline = {{_base_.test_pipeline}}
__dataset_type = 'TVDatasetSplit'
__dataset_base = 'CIFAR10'
data = dict(
samples_per_gpu=16,
workers_per_gpu=2,
num_classes=10,
pipeline_options=dict(... | openvinotoolkit/model_preparation_algorithm | recipes/stages/_base_/data/cifar10_cls_selfsl.py | cifar10_cls_selfsl.py | py | 1,423 | python | en | code | 20 | github-code | 1 |
28462922536 | # Create a function in Python that accepts two parameters.
# The first should be the full price of an item as an integer.
# The second should be the discount percentage as an integer.
#
# The function should return the price of the item after the discount has been applied.
# For example, if the price is 100 and the dis... | B-SAHIL/learn_python | discounted_bill.py | discounted_bill.py | py | 838 | python | en | code | 0 | github-code | 1 |
14386709281 | """
## 21-2. 키에 따른 대기열 재구성
여러 명의 사람들이 줄을 서 있다.
각각의 사람은 (h, k)의 두 정수 쌍을 갖는데,
h는 그 사람의 키, k는 앞에 줄 서 있는 사람들 중 자신으 키 이상인 사람들의 수를 뜻한다.
이 값이 올바르도록 줄을 재정렬하는 알고리즘을 작성하라.
"""
from typing import *
import heapq
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
# 96ms
pe... | hyo-eun-kim/algorithm-study | ch21/saeyoon/ch21_2_saeyoon.py | ch21_2_saeyoon.py | py | 1,259 | python | ko | code | 0 | github-code | 1 |
31716326895 | """
游戏主程序
1. 封装 主游戏类
2. 创建 游戏对象
3. 启动游戏
"""
import sys
import pygame
import background
from plane_sprites import SCREEN_RECT, FRAME_PER_SEC
from enemy import *
from plane_sprites import *
from hero import *
class PlaneGame:
"""用于配置及初始化游戏内容"""
def __init__(self):
"""初始化"""
print("游戏... | NekoSilverFox/EasyQQ | plane_main.py | plane_main.py | py | 3,988 | python | zh | code | 1 | github-code | 1 |
20667383231 | #프로그래머스 lv1
# 구현
# int로 함수가 3진수, 16진수 그냥 써줄수있는거
def solution(n):
answer = 0
lst=[]
tmp=0
while 1:
if n<3:
lst.append(n)
break
tmp=n%3
lst.append(tmp)
n=n//3
for i in range(len(lst)):
tmp=lst.pop()
if i==0:
... | jeongkwangkyun/algorithm | Programmers/3진법 뒤집기.py | 3진법 뒤집기.py | py | 682 | python | en | code | 0 | github-code | 1 |
7043095448 | import heap
def _maximum(l, n):
max_index = 0
for x in range(1, n+1):
if (l[x] > l[max_index]):
max_index = x
return max_index
def _swap(l, n1, n2):
l[n1], l[n2] = l[n2], l[n1]
def selection_sort(l):
n = len(l) - 1
while n > 0:
max_index = _maximum(l, n)
_swap(l, n, max_index)
n -= 1
def insertio... | eze210/tda1 | tp1/sorting/sorting.py | sorting.py | py | 1,480 | python | en | code | 0 | github-code | 1 |
8760507118 | def quicksort(seq):
if not seq:
return []
pivot = seq.pop(0)
left = []
right = []
for i in range(len(seq)):
if seq[i] < pivot:
left.append(seq[i])
else:
right.append(seq[i])
left = quicksort(left)
right = quicksort(right)
return left + [pi... | 310mo/array_kadai | quicksort.py | quicksort.py | py | 391 | python | en | code | 0 | github-code | 1 |
15752024246 | def find_consecutives(tup):#taking tuple as parameter, defining function.
elements = iter(tup)#"iter ()" function returns an iterator in tuple(with this iterator ,can access the elements in the tuple sequentially.)and assigned elements.
x,y=None,next(elements,None)#declaring x and y with None in elements.
... | talhaasan/python-Assignment1 | problem3.py | problem3.py | py | 833 | python | en | code | 0 | github-code | 1 |
34036384470 | from twilio.rest import Client
class TwilioService:
client = None
def __init__(self):
account_sid = 'AC1db0e8cfbae1e3b9b5834772c0ef8d6c'
auth_token = '7f70419841a1632045d657089acd65c1'
self.client = Client(account_sid, auth_token)
def send_message(self, message,e_recepient_phone_n... | mutuaMkennedy/homey | contact/services/twilio_service.py | twilio_service.py | py | 598 | python | en | code | 0 | github-code | 1 |
70040530274 | import numpy as np
import cv2
lineThickness = 3
url = "http:/localhost:8082/?action=stream"
# initialize USB webcam video capture.
# unable to capture directly from /dev/video0, but by using mjpg-streamer in another terminal,
# capture here works from URL instead.
cap = cv2.VideoCapture(url)
# limiting this to '1' m... | elicorrales/Fort.Laud.Robotics.Meetup.Group | Meetup.5/loopFaceEyeDetect.py | loopFaceEyeDetect.py | py | 1,847 | python | en | code | 0 | github-code | 1 |
4199270485 | import sys
import heapq
input = sys.stdin.readline
v, e = map(int, input().split())
edge = [[] for _ in range(v+1)]
chk = [False] * (v+1)
rs = 0
for i in range(e):
a,b,c = map(int,input().split())
edge[a].append([c,b])
edge[b].append([c,a])
heap = [[0,1]]
while heap:
w, each_node = heapq.heappop(heap)
if ... | hyeonwook98/Algorithm | Baekjoon/1197.py | 1197.py | py | 516 | python | en | code | 0 | github-code | 1 |
1567266808 | from SPARQLTransformer import post_process
def strip_empties_from_list(data):
new_data = []
for v in data:
if isinstance(v, dict):
v = strip_empties_from_dict(v)
elif isinstance(v, list):
v = strip_empties_from_list(v)
if v not in (None, str(), list(), dict(),):... | InTaVia/InTaVia-Backend | intavia_backend/conversion.py | conversion.py | py | 2,326 | python | en | code | 1 | github-code | 1 |
42936198452 | from primitives.base_market_agent import BaseMarketAgent
from high_frequency_trading.hft.trader import ELOInvestor
from utility import MockWSMessage
from discrete_event_emitter import RandomOrderEmitter
import draw
from db import db
import logging
log = logging.getLogger(__name__)
# this is a passive agent
# given a ... | hademircii/financial_market_simulator | agents/pacemaker_agent.py | pacemaker_agent.py | py | 2,013 | python | en | code | 4 | github-code | 1 |
34707631023 | from pathlib import Path
from util.util import get_data_path
from .base_loader import BaseLoader
class JSONLoader(BaseLoader):
def __init__(self, path: str, params: dict, index=None):
super().__init__(
name="JSONLoader",
path=path,
params=params,
data_load... | SherifNeamatalla/jarvis | src/loaders/json_loader.py | json_loader.py | py | 663 | python | en | code | 0 | github-code | 1 |
25140299013 | import inspect
import logging
import ssl
import signal
from pathlib import Path
from queue import Queue
from threading import Event, Lock, Thread, current_thread
from time import sleep
from typing import (
Any,
Callable,
List,
Optional,
Tuple,
Union,
no_type_check,
Generic,
TypeVar,
... | nishidage/-1 | telegram/ext/_updater.py | _updater.py | py | 24,967 | python | en | code | 0 | github-code | 1 |
35805629848 | #!/usr/bin/env python
import networkx as nx
import matplotlib.pyplot as plt
#create empty grapgh
G = nx.Graph()
print(G.nodes())
print(G.edges())
print(type(G.nodes()))
print(type(G.edges()))
#adding just one node:
G.add_node("a")
# a list of nodes:
G.add_nodes_from(["b","c"])
#add edges
G.add_edge(1,2)
edge = ("... | StoneNLD/python-projects | graph/graph_from_links.py | graph_from_links.py | py | 683 | python | en | code | 0 | github-code | 1 |
10612744193 | import sys
# INF = 4000010
read = sys.stdin.readline
n = int(read())
if n == 1:
print(0)
sys.exit()
decimal = []
decimalCheck = [False] * (n+1)
def decimalFun():
for i in range(2, n+1):
if not decimalCheck[i]:
decimal.append(i)
for j in range(i + i, n+1, i):
... | lkc263/Algorithm_Study_Python | RTplzrunBlog(baekjoon)/BruteForce/1644.py | 1644.py | py | 703 | python | en | code | 0 | github-code | 1 |
8511838057 | from typing import List, Tuple, Dict
from math import sqrt
import torch
from torch import Tensor
import torch.nn as nn
from torch_geometric.nn import MessagePassing
from graph.detectors.models.common_model import GNNPool
import numpy as np
EPS = 1e-15
class ExplainerBase(nn.Module):
def __init__(self, model:... | for-just-we/VulDetectArtifact | graph/explainers/approaches/common.py | common.py | py | 10,334 | python | en | code | 0 | github-code | 1 |
2359487852 | """NATS implementation of messenger."""
from dataclasses import asdict
import json
from typing import Callable, Dict, Optional
from logzero import logger
from pynats import NATSClient, NATSMessage
from blackcap.configs.base import BaseConfig
from blackcap.messenger.base import BaseMessenger
from blackcap.schemas.mes... | EBI-Metagenomics/orchestra | blackcap/src/blackcap/messenger/nats_messenger.py | nats_messenger.py | py | 2,908 | python | en | code | 4 | github-code | 1 |
71918011235 | import datetime
import re
def regex_replace(s, find, replace):
"""Find and replace using regular expressions
Args:
s (string): The string containing the text whose be replaced
find (string): The regex pattern
replace (string): The string whose replace the pattern
Returns:
... | GrindLabs/lsmakeupstudio | lsmakeupstudio/utils/template.py | template.py | py | 1,679 | python | en | code | 0 | github-code | 1 |
42470067186 | import torch
import numpy as np
import math
import random
from skimage.metrics import structural_similarity as SSIM
from skimage.metrics import peak_signal_noise_ratio as PSNR
def proto_with_quality(output, target, output_proto, target_proto, criterion, acc_proto, images, num_cluster):
# InfoNCE loss
loss = cri... | leafliber/myPCL | scripts/loss.py | loss.py | py | 2,230 | python | en | code | 0 | github-code | 1 |
31119335020 | from contextlib import contextmanager
from ducktape.cluster.remoteaccount import LogMonitor
@contextmanager
def monitor_log(node, log, from_the_beginning=False):
"""
Context manager that returns an object that helps you wait for events to
occur in a log. This checks the size of the log at the beginning o... | apache/ignite | modules/ducktests/tests/ignitetest/services/utils/log_utils.py | log_utils.py | py | 850 | python | en | code | 4,585 | github-code | 1 |
23719298346 | import databaseConnectivity as db
import os
import shutil
import datetime
import re
import sys
# Should be uncommented with Python 2.7
reload(sys)
sys.setdefaultencoding('utf8')
from botocore.errorfactory import ClientError
# Empty list to store S3obectKeys, documentIds, customerIds and source paths
documentIds = []
S... | viratY/doc-management-utilities | document-extraction/src/utilityMethods.py | utilityMethods.py | py | 5,701 | python | en | code | 0 | github-code | 1 |
2807615123 | score = []
x = int(input("students number:"))
a = 0
b = 0
print(x)
for i in range(x):
y = int(input("students score:"))
score.append(y)
b = b+y
print(score)
print("average score", b/x)
for i in score:
print(i)
for i in score:
if i > a:
a = i
print("highest score",... | aaronpengfc/day5-hw | day5hw3.py | day5hw3.py | py | 334 | python | en | code | 0 | github-code | 1 |
23525174675 | from selenium.webdriver.common.by import By
from lib import Lib
from time import sleep
import pyautogui
class TestsPage(Lib):
'Coloquem os localizadores dos elementos aqui, vai facilitar!'
URL = 'https://undbclassroom.undb.edu.br'
__LOGIN_DIRETO_URL = 'https://undbclassroom.undb.edu.br/login/index.php#'
... | soniaelisabeth/classroom_automation | tests_page.py | tests_page.py | py | 17,791 | python | pt | code | 0 | github-code | 1 |
43467567605 | from bs4 import BeautifulSoup
excluidos = ['Adamo',
'Todos',
'Agrale',
'Ariel',
'Asia',
'Avallone',
'Bianco',
'BRM',
'Caterham',
'CBT',
'Chamonix',
'Chana',
'Changan',
'Cross Lander',
'Daewoo',
'Daihatsu',
'DeLorean',
'Effa',
'Engesa',
'Enseada',
'Envemo',
'Farus',
'Geely',
'Gurgel',
'Hafei',
'Hennessey',
'Hofstetter'... | Sankhay/Estudos | Python/selenium/getFabri.py | getFabri.py | py | 1,005 | python | en | code | 0 | github-code | 1 |
9175181375 | from datetime import datetime
import json
import logging
from bs4 import BeautifulSoup
from db.models import Victim
from net.proxy import Proxy
from .sitecrawler import SiteCrawler
class Ragnar(SiteCrawler):
actor = "Ragnar"
def scrape_victims(self):
with Proxy() as p:
r = p.get(f"{self... | captainGeech42/ransomwatch | src/sites/ragnar.py | ragnar.py | py | 2,485 | python | en | code | 294 | github-code | 1 |
21055679175 | # Get, change, or verify the version number stored in src/franz/_init__.py
# Usage: python version.py <command> [<args...>]
# Commands:
# get: print the version number to stdout
# set V: set the version number to V
# next: Increment the fifth version segment,
# make sure 'dev0' is at the end.
# undev: S... | franzinc/agraph-python | version.py | version.py | py | 2,705 | python | en | code | 34 | github-code | 1 |
13037432263 | import stripe
import json
from django.conf import settings
from django.shortcuts import redirect
from rest_framework.decorators import api_view,permission_classes
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from .m... | DevDhira/tubemize | backend/payment/views.py | views.py | py | 3,955 | python | en | code | 0 | github-code | 1 |
20489512283 | # this is the launcher of the batch all series script
# to be executed on a cluster login node
import os
alldatasetsNameFile = "../Results/UCR/workableDatasets.txt"
alldatasetsSizeFile = "../Results/UCR/workableDatasets_size.txt"
with open(alldatasetsNameFile,'r') as f:
datasets = f.read().strip().split('\n')
wit... | BrilliantMustache/MultivariteDTW | Experiments/batchLauncher.py | batchLauncher.py | py | 773 | python | en | code | 0 | github-code | 1 |
30896395982 | from torchvision import transforms
from torchvision.datasets import MNIST
import torch
from PIL import Image
import numpy as np
from tqdm import tqdm
class MNISTInvase(MNIST):
def __init__(self, *args, **kwargs):
super(MNISTInvase, self).__init__(*args, **kwargs)
def __getitem__(self, index):
... | choheeee22/invase-pytorch | data/mnist.py | mnist.py | py | 2,173 | python | en | code | 0 | github-code | 1 |
33288174422 | import store
import os
import FTP_Cryptography
import bson
from bson.binary import Binary
import mongodb
from cryptography.fernet import Fernet
files = mongodb.db.files
FILE_DATA = store.FILE_DATA
INFO_FILE = store.INFO_FILE
def check_file_name(file_name):
return os.path.exists(file_name)
def send_file(socket... | boom-chill/Chat-app-MMT-DA | file.py | file.py | py | 3,796 | python | en | code | 0 | github-code | 1 |
73898604835 | """
Dataloader building logic.
Author: JiaWei Jiang
This file contains the basic logic of building dataloaders for training
and evaluation processes.
"""
from typing import Any, Union
import numpy as np
import pandas as pd
from omegaconf.dictconfig import DictConfig
from torch.utils.data import DataLoader
from .data... | JiangJiaWei1103/Competitive-DS-Made-Easy | data/build.py | build.py | py | 1,217 | python | en | code | 0 | github-code | 1 |
17871789895 | from optparse import OptionParser
from bigdl.dataset import mnist
from bigdl.dataset.transformer import *
from bigdl.nn.layer import *
from bigdl.nn.criterion import *
from bigdl.optim.optimizer import *
from bigdl.util.common import *
def build_model(class_num):
model = Sequential()
model.add(Reshape([1, 28,... | PacktPublishing/Learning-Generative-Adversarial-Networks | Chapter05/Code/BigDL/BigDL-MNIST.py | BigDL-MNIST.py | py | 3,403 | python | en | code | 33 | github-code | 1 |
31324875227 | ##read the markers from file and search in Graingenes.Each one seek for five times.
#If one makrer hasn't been found even by five times,it will be recorded in the file.
import re
import requests
def get_marker(url):
r = requests.get(url, timeout=20)
t = r.text
seq_compiles = re.compile("PCR primers.+?\n")
... | Jiny000/BIOinformatics | python/requests.py | requests.py | py | 2,124 | python | en | code | 0 | github-code | 1 |
35416090944 | import numpy as np
import random
import re
from rasa_core.policies.policy import Policy
from rasa_core.actions.action import ACTION_LISTEN_NAME
#----------------------------------------------------------------------
# gReflections, a translation table used to convert things you say
# into things the computer says ... | rohitjain-dev/chatbot | rasa/policies/ElizaPolicy.py | ElizaPolicy.py | py | 4,204 | python | en | code | 0 | github-code | 1 |
31637033591 | import os
import json
import time
from S3utility.s3_notification_info import parse_activity_data
from provider import digest_provider, download_helper, email_provider, utils
from activity.objects import Activity
class activity_ValidateDigestInput(Activity):
"ValidateDigestInput activity"
def __init__(self, s... | elifesciences/elife-bot | activity/activity_ValidateDigestInput.py | activity_ValidateDigestInput.py | py | 4,401 | python | en | code | 19 | github-code | 1 |
33499385148 | import os
import subprocess
import sys
import uuid
import dmake.common as common
from dmake.common import DMakeException, SharedVolumeNotFoundException, append_command
from dmake.deepobuild import DMakeFile
tag_push_error_msg = "Unauthorized to push the current state of deployment to git server. If the repository bel... | Deepomatic/dmake | dmake/core.py | core.py | py | 58,937 | python | en | code | 37 | github-code | 1 |
6611942066 |
import numpy as np
from mtuq.grid_search import DataArray, DataFrame, MTUQDataArray, MTUQDataFrame
from mtuq.util import dataarray_idxmin, dataarray_idxmax, product, warn
def _nothing_to_plot(values):
""" Sanity check - are all values identical in 2-D array?
"""
mask = np.isnan(values)
if np.all(mas... | uafgeotools/mtuq | mtuq/graphics/uq/__init__.py | __init__.py | py | 1,778 | python | en | code | 57 | github-code | 1 |
25136656838 | import time
from bs4 import BeautifulSoup
import requests
from requests import Session
from Extractor.extractor import EbayKleinanzeigenExtractor
import json
from print_dict import pd
class Cookies:
def __init__(self, filename: str = "default.json", log: bool = True,
cookies: dict = None, save=F... | zakir0101/ebay-kleineanzeigen-api | Cookies/cookies.py | cookies.py | py | 6,574 | python | en | code | 0 | github-code | 1 |
21748179330 | import sys
sys.path.append('..')
from utils import *
import argparse
from keras.models import *
from keras.layers import *
from keras.optimizers import *
class MctsNNet():
def __init__(self, game, args):
# game params
self.board_dim = game.getBoardSize()
self.action_size = game.getActionSi... | rubenrtorrado/NLP | alpha-zero-word-level/models/mcts/textgen/keras/MctsNNet.py | MctsNNet.py | py | 3,339 | python | en | code | 2 | github-code | 1 |
12782226500 | ####################################################################################################################################
#Given a binary tree, find its minimum depth.
#The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
#Note: A leaf is a node w... | tranphibaochau/LeetCodeProgramming | Easy/min_depth_binary_tree.py | min_depth_binary_tree.py | py | 1,408 | python | en | code | 0 | github-code | 1 |
11212420595 | def convert(number):
sounds = {
3: 'Pling',
5: 'Plang',
7: 'Plong'
}
sound = ''
for keys in sounds:
if not number % keys:
sound += sounds.get(keys, '')
return sound if sound else str(number)
| stimpie007/exercism | python/raindrops/raindrops.py | raindrops.py | py | 257 | python | en | code | 0 | github-code | 1 |
14346415777 | from random import randint
import math
from PIL import Image, ImageDraw, ImageFont
# Did you know that calculating the correct font size
# is NP-Hard? This function is for when they will solve
# P = NP?
def calculate_font_size(string, image_width):
global FONT_SIZE
return FONT_SIZE
def pad_string(text, how_m... | mrkct/cool-experiments | inrainbows-album-art/generate.py | generate.py | py | 2,495 | python | en | code | 0 | github-code | 1 |
8556892866 | # coding:utf8
__author__ = 'Marcelo Ferreira da Costa Gomes'
# Apply filters of interest in a dataframe containing SINAN-SRAG data
import pandas as pd
import numpy as np
import argparse
import logging
import re
from argparse import RawDescriptionHelpFormatter
from .insert_epiweek import insert_epiweek
from .delay_tabl... | FluVigilanciaBR/seasonality | methods/data_filter/sinan_filter_of_interest.py | sinan_filter_of_interest.py | py | 47,482 | python | en | code | 1 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.