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
3198044243
class Solution(object): def subarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ dt = collections.defaultdict(int) dt[0] = 1 ss, res = 0, 0 for n in nums: ss += n res += dt[ss - k] ...
niufenjujuexianhua/Leetcode
subarray-sum-equals-k/subarray-sum-equals-k.py
subarray-sum-equals-k.py
py
353
python
en
code
0
github-code
1
39960784073
import argparse import pandas as pd import os import subprocess parser = argparse.ArgumentParser() parser.add_argument('-csv_path', '--csv_path', default='download_list.csv', help='path of download_list.csv') parser.add_argument('-save_path', '--save_path', default='video/data/', help='dir for saving videos') parser.a...
deepbrainai-research/koeba
download_video.py
download_video.py
py
2,794
python
en
code
30
github-code
1
73428982753
import os import PIL import math import numpy as np import pandas as pd import cv2 as cv from PIL import ImageFont from PIL import Image from PIL import ImageDraw if __name__ == '__main__': # 图片文件夹目录 path = "image" files = os.listdir(path) for img_file in files: print(img_file)...
leemengwei/dead_pig_insurance
src/DeadPigImage.py
DeadPigImage.py
py
2,937
python
en
code
0
github-code
1
44568571061
# Дана строка. Найдите в этой строке второе # вхождение буквы f, и выведите индекс этого вхождения. # Если буква f в данной строке встречается только # один раз, выведите число -1, а если не встречается # ни разу, выведите число -2.При решении # этой задачи нельзя использовать метод count. s = input() f1 = s.find('f')...
dbychkar/python_lessons
python_coursera/3_week/46_Второе вхождение.py
46_Второе вхождение.py
py
638
python
ru
code
4
github-code
1
2573579566
""" overriden methods of general classes, specific for English """ from verb_record import Verb_record from frame_extractor import Frame_extractor class En_verb_record( Verb_record): def __init__( self, lemma): super().__init__( lemma) #self.frame_type_class = En_frame_type class En_frame_extrac...
Jankus1994/ud-valency
udapi-python/udapi/block/valency/backups/b_1_10_2022/en_module.py
en_module.py
py
2,487
python
en
code
0
github-code
1
34506238695
import cocotb from cocotb.triggers import Timer, RisingEdge, FallingEdge, ClockCycles from cocotb.result import TestFailure from cocotb.clock import Clock from cocotb.binary import BinaryValue from cocotb.scoreboard import Scoreboard from cocotb.monitors import Monitor from cocotb.regression import TestFactory from coc...
Alberto12MC/Modules
tb/Zybo_Example/cocotb/Zybo_Example_tb.py
Zybo_Example_tb.py
py
6,898
python
en
code
3
github-code
1
72615318755
import functools from keras.layers import * from keras.models import Model from keras.wrappers.scikit_learn import KerasClassifier from keras.regularizers import l2 from keras.optimizers import SGD import numpy as np import pandas as pd import tensorflow as tf import os import pickle import plac from rectified_adam i...
csvance/uthealth-ri
run.py
run.py
py
8,731
python
en
code
0
github-code
1
10436178052
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Use text editor to edit the script and type in valid Instagram username/password from InstagramAPI import InstagramAPI import json api = InstagramAPI("instamike59.officiel", "091h1scd") if (api.login()): api.getSelfUserFeed() # get self user feed data = api.LastJs...
michaeldupont/my_instagram_bot
insta.py
insta.py
py
516
python
en
code
0
github-code
1
20962586522
from pyspark import SparkContext sc = SparkContext("local[*]", "week9Assignment") sc.setLogLevel("WARN") def check_age(line): fields = line.split(",") if int(fields[1]) > 18: return fields[0], fields[1], fields[2], "Y" else: return fields[0], fields[1], fields[2], "N" base_rdd = sc.text...
Nishant-001/BigData_PySpark
week9assignment.py
week9assignment.py
py
502
python
en
code
0
github-code
1
33803503278
''' @author: Dmitry ''' import unittest import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', reshape=False, one_hot=True, validation_size = 5000) from SimpleCapsNet import * from Trainer import * class CapsTests(unittest...
dshelukh/CapsuleLearner
tests/CapsTests.py
CapsTests.py
py
2,897
python
en
code
1
github-code
1
2628304929
import os from datetime import datetime import re import logging from os.path import join def validate_date_prefix(date_prefix, formats, present): '''Returns True if the string date_prefix is a valid date, given the list of formats and if the date is smaller than the given present date. ''' for forma...
tamiryspino/orderPhotos
src/rename_file.py
rename_file.py
py
6,354
python
en
code
1
github-code
1
33159038452
# -*- coding: utf-8 -*- import csv import json import re # Make utility functions available exec(compile(open("util.py", "r").read(), "util.py", 'exec')) #open needed files and copy their content into lists with open('../data/mp/stats/templates.txt', 'r') as file: reader = csv.reader(file, delimiter=',') templates...
kreuvf/fkmod
csv2json/templates.py
templates.py
py
2,156
python
en
code
0
github-code
1
41056211155
import sys class Node: def __init__(self, mult): self.parent = None self.child_2 = None self.child_4 = None self.mult = mult self.cur_value = None def function(width): return_list = [] root = Node(1) root.cur_value = 1 list = [root] l...
vassilas/High-Speed-Recursive-Ling-Adder
CodeGen/Jackson_functions/Tree.py
Tree.py
py
2,526
python
en
code
2
github-code
1
15778184315
import functools from math import inf _DEBUG = True class Processor: """Processor that can schedule jobs""" def __init__(self, schedule_cost=0, dispatch_cost=0, preemption_cost=0, cache_warmup_time=None, warm_cache_rate=1): """ :param schedule_cost: overhead to schedule a jo...
ragibson/real-time-simulator
task_scheduling.py
task_scheduling.py
py
15,723
python
en
code
1
github-code
1
26854894161
#! /usr/bin/env python """ Optimizer performance comparison """ import os import sys import subprocess from multiprocessing import Pool problems = { 'xray': '../doc/examples/xray/model.py', 'pemu': '../doc/examples/superlattice/PEMU-web.py', } # Aim for evals; assume problem size is 10 root = 'out' nrepe...
reflectometry/refl1d
compareopt/compare.py
compare.py
py
2,024
python
en
code
16
github-code
1
29878128846
from __future__ import print_function, division import pandas as pd import numpy as np # import matplotlib # matplotlib.use('qt4agg') import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler, minmax_scale def mae(y, prediction): return np.mean(np.abs(y - prediction)) # Read in full data set X...
moosmann/bl
bike.py
bike.py
py
2,710
python
en
code
0
github-code
1
13282483117
""" # ================================================================== # Python module # # This module provides methods to compute the lifetime and # branching ratio of HNLs given its mass and couplings as # input parameters. # # Created: 30/11/2014 Elena Graverini (elena.graverini@cern.ch) # # Updated: 0...
ShipSoft/FairShip
python/hnl.py
hnl.py
py
27,059
python
en
code
21
github-code
1
38018666023
import torch import torch.nn as nn from networks.layers import ( RecurrentConvolutionalLayer, ConvLayer, Dense ) class SharkRCNN(nn.Module): def __init__(self, num_steps): super(SharkRCNN, self).__init__() self.conv = ConvLayer(1, 32, (7,3), (2,1), (3,1)) self.pool1 = ...
buchholzmd/SharkBehaviorClassification
networks/rcnn.py
rcnn.py
py
1,499
python
en
code
3
github-code
1
31440311203
import pyspark from pyspark.sql import SparkSession from pyspark.sql.functions import col, asc,desc spark = SparkSession.builder.appName('SparkByExamples.com').getOrCreate() simpleData = [("James","Sales","NY",90000,34,10000), \ ("Michael","Sales","NY",86000,56,20000), \ ("Robert","Sales","CA",81000,30,23000)...
sahil20101993/spark_examples
pivot_df.py
pivot_df.py
py
889
python
en
code
0
github-code
1
41287163895
from django.urls import path, re_path, register_converter from .views import * from core.routers import PetuniRouter from .converters import CRMIdConverter app_name = 'crm' register_converter(CRMIdConverter, 'crmid') router = PetuniRouter() urlpatterns = [ path('contact/<crmid:crm_id>/pull/', CRMContactView.as_v...
sdmitrievlolx/code_samples
crm/urls.py
urls.py
py
1,400
python
en
code
0
github-code
1
5118771666
def calc_gain(dataset, attr, target_attr): """ Calculate Information Gain @param dataset: Dataset @param attr: super attribute @param target_attr: tarrget attribute """ #super information entropy and sub-class entropy mclass_entropy = calc_entroy(dataset, attr) sclass_...
yingzk/MyML
A-Decision Tree/ppt/Calculate Information Gain.py
Calculate Information Gain.py
py
645
python
en
code
65
github-code
1
31365626043
import db class FormattedData(): database = db.MyDatabase(db.SQLITE, dbname='taxi.db') def get_drivers(self,lname=None, fine=None, commendation=None): try: if lname: query = f"SELECT * FROM driver WHERE last_name = '{lname}';" elif fine: query = ...
veschin/taxi_db_app
fd.py
fd.py
py
3,057
python
en
code
0
github-code
1
31506165264
import warnings from itertools import islice from math import log2, pow, sqrt from copy import copy from PIL import Image, ImageChops from numpy import array, zeros, append from scipy.fftpack import dct, idct from qtar.core.imageqt import ImageQT, ImageQTPM from qtar.core.curvefitting import fit_cfregions, CFRegions,...
Raykeen/qtar-stego
qtar/core/qtar.py
qtar.py
py
17,375
python
en
code
0
github-code
1
1058802908
import socket import select import mtbot.protocol as p from mtbot.botpackage import * class MTServer: """Some kind of proxy.""" psock = {} saddr = {} pdst = {} def __init__(self, adr, dst): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(adr) sel...
Lejo1/mtmodule
readout.py
readout.py
py
3,112
python
en
code
1
github-code
1
70839187233
N = int(input()) days = [[-1, -1]] + [[] for _ in range(N)] for i in range(1, N+1): days[i] = list(map(int, input().split())) maxV = 0 def dfs(x, res): global maxV for i in range(x+1, N+1): if i + days[i][0] - 1 < N+1: dfs(i+days[i][0]-1, res+days[i][1]) maxV = max(res, maxV) r...
ckdfh0917/Algorithm
백준/삼성SW역량테스트기출문제/14501. 퇴사.py
14501. 퇴사.py
py
433
python
en
code
0
github-code
1
12981297349
#!/usr/bin/env python # Import PyGame library import pygame import adapter import MD3Buttons import RetroflagSnes import ArduinoMicro from actions import * import logger controllers = { MD3Buttons, RetroflagSnes, ArduinoMicro, } pad = {} joysticks = {} currentGuid = "" currentAdapter = -1 def pressButton(btn): ...
Pilou44/UsbToConsole
code/gamepad.py
gamepad.py
py
4,184
python
en
code
0
github-code
1
26856048171
from setuptools import setup, find_packages from os.path import join import sys version = '2.2.dev0' readme = open("README.rst").read() history = open(join('docs', 'HISTORY.txt')).read() install_requires = ['setuptools', 'gocept.munin', 'Products.ZServerViews>=0.2'] if sys.version_info < (2, 5): install_requires....
RedTurtle/munin.zope
setup.py
setup.py
py
1,759
python
en
code
6
github-code
1
25422528336
import urllib.request import json import dml import prov.model import datetime import uuid class trans_school(dml.Algorithm): contributor = 'kobesay' reads = ['kobesay.publicschool', 'kobesay.nonpublicschool'] writes = ['kobesay.regionschool', 'kobesay.regionpublicschool', 'kobesay.regionnonpublicschool'] ...
data-mechanics/course-2017-spr-proj
kobesay/trans_school.py
trans_school.py
py
6,680
python
en
code
0
github-code
1
21369768960
import argparse import sys from ft_config import load_config # check python version >= 3.6 assert sys.version_info >= (3, 6) # read config.json config = load_config() # parse arguments parser = argparse.ArgumentParser() parser.add_argument('--action', required=True, help="...
mikkorautiainen/fasttext-decrapifier
decrapper.py
decrapper.py
py
2,218
python
en
code
2
github-code
1
15053848115
from django.contrib import admin from django.urls import path, include from .views import register_view, login_view, index, profile_view, oikawakuroo urlpatterns = [ path('home/', index, name='home'), path('register/', register_view, name='register'), path('login/', login_view, name='login'), path('pro...
KamiliyaOikawa/Lending
user/urls.py
urls.py
py
421
python
en
code
0
github-code
1
28558005881
from django import forms from django.forms import ValidationError from pgweb.core.models import Organisation from .models import Event class EventForm(forms.ModelForm): form_intro = 'Before submitting an event, please read the <a href="/about/policies/news-and-events/">current policy</a> for News and Events' ...
postgres/pgweb
pgweb/events/forms.py
forms.py
py
2,439
python
en
code
66
github-code
1
70018798433
import math from random import random import pytest import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier from starter.ml import model @pytest.fixture def dummy_data(): data_df = pd.DataFrame({ "id": list(range(100)), "numerical_feat": [random()*10...
ympaik87/heroku_fastapi_deployment
starter/starter/test_model.py
test_model.py
py
1,460
python
en
code
0
github-code
1
20113302418
from llmstudio.llm import LLM name = "version" __version__ = "0.2.27" __requirements__ = [ "pydantic", "requests", "numpy", "torch", "sentence-transformers", "fastapi", "uvicorn", "PyYaml", "openai>=1.0", "tiktoken", "google-auth", "google-cloud-aiplatform", "langch...
TensorOpsAI/LLMstudio
llmstudio/__init__.py
__init__.py
py
404
python
en
code
60
github-code
1
622186416
import torch.nn as nn import torch resl_to_ch = { 4 : (512, 512), 8 : (512, 512), 16 : (512, 512), 32 : (512, 512), 64 : (512, 256), 128 : (256, 128), 256 : (128, 64), 512 : (64, 32), 1024 : (32, 16), } resl_to_batch = { 4 : 512, 8 : 512, 16 : 512...
blacknwhite5/privacy-preserving-v2
models/pg_network.py
pg_network.py
py
4,274
python
en
code
0
github-code
1
40357222820
import ssl from telnetlib import * from telnetlib.option import TelnetOption class TelnetOptionAuthentication( TelnetOption ): """ RFC 2941, Telnet Authentication Option """ AUTH_TYPE_NULL = chr( 0 ) AUTH_TYPE_KERBEROS_V4 = chr( 1 ) AUTH_TYPE_KERBEROS_V5 = chr( 2 ) AUTH_TYP...
pe2mbs/pytelnet
telnetlib/option/authentication.py
authentication.py
py
3,701
python
en
code
0
github-code
1
7674180202
import math import random list=[] for i in range(0,100): z = random.uniform(-14.5,14.5) t = random.uniform(-14.5,14.5) d = z+t*1j list.append(d) for i in range(0,100): u=list[i].real z=list[i].imag print(i,u,z) def modul(z): return math.sqrt((z.real)**2+(z.imag)**2) ...
grzesiaaa/IntroductionToPython
List6/6.5_1.py
6.5_1.py
py
949
python
en
code
0
github-code
1
17288175559
""" Handling mouse events in pygame Drag and drop an image """ import pygame BLACK = 0, 0, 0 WHITE = 255, 255, 255 RED = 255, 0, 0 GREEN = 0, 255, 0 BLUE = 0, 0, 255 pygame.init() canvas = pygame.display.set_mode((500, 600)) people = pygame.image.load('assets/people.png') # Start with image at 0, 0 people_rect...
Apress/game-development-with-pygame
p45b_mouse_events.py
p45b_mouse_events.py
py
1,361
python
en
code
2
github-code
1
875275062
import pandas as pd import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages from matplotlib import ticker PATH = "statistics/results" df = pd.read_csv(PATH+'.csv', index_col=0).round(2) timings = [10**i for i in range(2, 6)] fig, ax =plt.subplots(figsize=(4,3)) ax.axis('tight') ax.axis('...
matrs01/Advanced_Cpp_course_4_sem
homework_3/vector_with_sort_vs_set/plot_maker_hw_3.py
plot_maker_hw_3.py
py
996
python
en
code
0
github-code
1
39586354908
# fixtures are functions that are run by the pytest before the actual test functions # eg= setup database connection, initialize webdriver import pytest # define fixtures function (parent method) @pytest.fixture() def setup_list(): print("\n in fixtures..\n") # city2 = ["new york", "london", "mumbai"] city...
kasthuridinesh/pythonprojects
pytest/parallel_test/udemy/test_fixtures01.py
test_fixtures01.py
py
606
python
en
code
0
github-code
1
23007266288
""" Created on 7 Apr 2018 @author: john.dwan ELEVATION PROFILE APP GENERATOR ideagora geomatics-2018 http://geodose.com """ import json from math import asin, cos, radians, sin, sqrt import urllib.request import matplotlib.pyplot as plt from shapely.geometry import LineString from siteline import config def have...
John-Dwan/siteline
siteline/open_elevation_profile.py
open_elevation_profile.py
py
4,101
python
en
code
0
github-code
1
72585234275
# Створіть програму для отримання курсу валют за певний період. # - отримати від користувача дату (це може бути як один день так і інтервал - початкова і кінцева дати, # продумайте механізм реалізації) і назву валюти # - вивести курс по відношенню до гривні на момент вказаної дати (або за кожен день у вказаному інтерва...
Poprop/GeekHubHomework
HT_14/task_2/task_2.py
task_2.py
py
3,999
python
uk
code
0
github-code
1
12348014771
import abc from typing import TYPE_CHECKING from ml_deeco.estimators import Estimate if TYPE_CHECKING: from ml_deeco.simulation import Experiment class ComponentMeta(abc.ABCMeta): """ Metaclass for Component. Uses a counter to automatically generate the component ID. """ def __new__(mcs, name, ...
smartarch/ML-DEECo
ml_deeco/simulation/components.py
components.py
py
2,001
python
en
code
0
github-code
1
8197675549
""" Problem Set 3 """ def pretty_print_fwd(fwd_struct): """ Arma cuadro para visualizar una estructura forward. Parámetros: fwd_struct : Estructura de tasas forward """ for t, fwds in fwd_struct.items(): fwds_txt = ', '.join(f'{tt:3}: {r:6.2%}' for tt, r in fwds.items()) pr...
FedericoMenendez22/pythonFinanzas
clases/ps3.py
ps3.py
py
530
python
en
code
0
github-code
1
525556312
# -*- coding: utf-8 -*- # __author__ = 'Administrator' import time from core import get_info start = 0 end = 0 def main(s, e): """ 起始学号s,结束学号e,遍历。 模拟登录教务系统获取学生信息, 写入到ninfo.txt文件中。 """ for i in range(s, e, 1): counts = 0 mdic = get_info.get_info(i) print(i) whi...
q673230559/get_stu_info
main.py
main.py
py
737
python
en
code
0
github-code
1
12497368956
"""Common methods and classes used for mesh client""" from collections import namedtuple import os import json import boto3 REGION_NAME = os.environ.get("AWS_REGION", "eu-west-2") class SingletonCheckFailure(Exception): """Singleton check failed""" def __init__(self, msg=None): super().__init__() ...
NHSDigital/spine-core-aws-common
mesh_aws_client/mesh_common.py
mesh_common.py
py
4,776
python
en
code
11
github-code
1
32072889087
from factsumm import FactSumm import jsonlines factsumm = FactSumm() with jsonlines.open('/home/tiezheng/workspace/FidSum/data/qmsum/processed_data_no_sent_split/test.jsonl') as F: article = [] target = [] for item in F: article.append(item['src']) target.append(item['tgt']) with open('sr...
TysonYu/KA-QFMS
src/utls/hallucination.py
hallucination.py
py
1,434
python
en
code
0
github-code
1
26699915281
from card import Card suits = ('Spades', 'Clubs', 'Hearts', 'Diamonds') values = ('A', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K') class Deck: def __init__(self): self.deck = [] for x in suits: for y in values: self.deck.append(Card(x, y))
dpotts1616/dccCapstone
deck.py
deck.py
py
314
python
en
code
0
github-code
1
70199033954
from odoo import models, api from odoo.exceptions import UserError class ReportTrainingList(models.AbstractModel): _name = 'report.training.report_training_list' def _get_training(self, data): trainer = data['form'].get('trainer_id')[0] date_from = data['form'].get('date_from') or None ...
obukaodoo10/obuka10
addons/training/report/training_list_report_parser.py
training_list_report_parser.py
py
2,383
python
en
code
0
github-code
1
70960372193
import sys sys.stdin = open("swap.in", "r") sys.stdout = open("swap.out", "w") n,m,k = map(int, input().split()) order = [tuple(map(int, input().split())) for _ in range(m)] cows = list(range(1,n+1)) record = [tuple(cows)] for i in range(k): for a,b in order: cows[a-1:b] = cows[a-1:b][::-1] cur_cows =...
cola0405/usaco
silver_pythonxxxxxxx/20-2/1.py
1.py
py
526
python
en
code
0
github-code
1
35915432951
""" Validating Credit Card Numbers https://www.hackerrank.com/challenges/validating-credit-card-number/problem """ import re for _ in range(int(input())): num = input() ok1 = bool(re.match(r"^[456]\d{15}$", num)) ok2 = bool(re.match(r"^[456]\d{3}\-\d{4}\-\d{4}\-\d{4}$", num)) num = num.replace("-",...
rene-d/hackerrank
python/py-regex/validating-credit-card-number.py
validating-credit-card-number.py
py
466
python
en
code
72
github-code
1
1704714948
def solution(n, m, x, y, r, c, k): answer = '' graph = [[0 for _ in range(m+1)] for _ in range(n+1)] route = [] def DFS(x, y, troute, cnt): if cnt == k and x == r and y == c: route.append(troute) if cnt >= k: return remain = k - cnt + 1 short = ab...
SunghunKim98/Algorithm_Study
sprint10/KMS/실시간/미로 탈출 명령어.py
미로 탈출 명령어.py
py
863
python
en
code
0
github-code
1
73026228835
class Node(): def __init__(self, value): self.value = value self.next = None class LinkedList(): def __init__(self): self.head = None self.tail = None self.index = 0 def print_list(self): current = self.head linked_list = "" while(current is n...
zalogarciam/data-structures-and-algorithms
HashTables/HashTable.py
HashTable.py
py
11,256
python
en
code
0
github-code
1
3517549162
import heapq def solution(time, works): answer = 0 for i in range(len(works)): works[i]=-works[i] heapq.heapify(works) while time>0 and works: a=heapq.heappop(works) if a==0: continue a+=1 time-=1 heapq.heappush(works,a) for i ...
leezzangmin/pythonBOJ
프로그래머스/야근 지수.py
야근 지수.py
py
396
python
en
code
0
github-code
1
31008119657
from math import inf from collections import deque from tracemalloc import start def dijkstra(wmat, start, end=-1): n = len(wmat) dist = [inf] * n dist[start] = wmat[start][start] # 0 spVertex = [False] * n parent = [-1] * n path = [{}] * n for count in range(n - 1): minix = i...
kmlutkmtll/discreteMath
graph2.py
graph2.py
py
4,325
python
en
code
0
github-code
1
7419480168
""" HSC Datasets """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from . import hsc_utils from . import astroimage_utils from tensor2tensor.data_generators import generator_utils from tensor2tensor.data_generators import image_utils from tensor2tensor.d...
ml4astro/galaxy2galaxy
galaxy2galaxy/data_generators/hsc.py
hsc.py
py
8,144
python
en
code
27
github-code
1
39999778314
import numpy as np import cv2 import time from framecounter import FrameCounter fcount = FrameCounter() cv2.startWindowThread() # cap = cv2.VideoCapture('walking.mp4') cap = cv2.VideoCapture(0) i = 0 while(True): i+=1 ret, frame = cap.read() fcount.start() frame = cv2.resize(frame,(640,360)) #fr...
cbernet/maldives
opencv/video_in.py
video_in.py
py
817
python
en
code
3
github-code
1
16083859777
def run(model): import pandas as pd n_rows = None print("____ Loading Data") x_train = pd.read_csv('csv/traffic/x_train.csv', nrows=n_rows) x_test = pd.read_csv('csv/traffic/x_test.csv', nrows=n_rows) y_train = pd.read_csv('csv/traffic/y_train.csv', nrows=n_rows) y_test = pd.read_csv('csv/traffic/y_test.csv',...
arthurpiazzi/Traffic-Flow
teste.py
teste.py
py
2,827
python
en
code
1
github-code
1
31635301404
def factorial(number): if number == 1 or number == 0: return 1 handle_odd = False goal = number if number % 2 == 1: goal -= 1 handle_odd = True next_sum = goal next_multi = goal factorial = 1 while next_sum >= 2: factorial *= next_multi next_s...
bentondavidl/ProjectEuler
Python/(20)Factorial digit sum.py
(20)Factorial digit sum.py
py
481
python
en
code
0
github-code
1
72486000035
from django.conf.urls.defaults import * from django.contrib.auth.views import login, logout_then_login from dpro.bilet.views import * #index, doldur, listele, csvdeneme, degistir, urlpatterns = patterns( '', (r'^bilet/admin/', include('django.contrib.admin.urls')), (r'^bilet/login/$', login, {'template...
zekzekus/dpro
urls.py
urls.py
py
695
python
en
code
1
github-code
1
72495913955
import pickle import shutil import torch import numpy as np import unittest from openfold.data.data_pipeline import DataPipeline from openfold.data.templates import TemplateHitFeaturizer from openfold.model.embedders import ( InputEmbedder, RecyclingEmbedder, TemplateAngleEmbedder, TemplatePairEmbedde...
aqlaboratory/openfold
tests/test_data_pipeline.py
test_data_pipeline.py
py
3,124
python
en
code
2,165
github-code
1
42231125149
import random import pytz import json from django.dispatch import receiver from django.db.models.signals import pre_save from django_celery_beat.models import CrontabSchedule, PeriodicTask from .models import Agent days = { "sun": 0, "mon": 1, "tue": 2, "wed": 3, "thu": 4, "fri": 5, "sat...
wh1te909/backup-offsite
offsite/core/signals.py
signals.py
py
2,265
python
en
code
11
github-code
1
41407261632
# 100. Same Tree # https://leetcode.com/problems/same-tree/discuss/ # https://discuss.leetcode.com/topic/14561/shortest-simplest-python # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Sol...
aszx4510/LeetCode
python/0100-same_tree.py
0100-same_tree.py
py
867
python
en
code
0
github-code
1
23396022396
import random allCiphers = [] class cryptoErr(BaseException): #This is the error class that will be raised if there is a problem def __init__(): self.errName = '' self.errValue = None self.errHandler = None self.errMetaData = '' self.errUsrMsg = '' return def handle(self): if self.errHandler != None: ...
Michael-Naguib/Simple-Cryptography
crypto.py
crypto.py
py
15,131
python
en
code
0
github-code
1
11207901318
""" End to end test of video timelines. """ import datetime import logging from edx.analytics.tasks.tests.acceptance import AcceptanceTestCase log = logging.getLogger(__name__) class VideoAcceptanceTest(AcceptanceTestCase): """End to end test of video timelines.""" INPUT_FILE = 'video_timeline.log' d...
openedx/edx-analytics-pipeline
edx/analytics/tasks/tests/acceptance/test_video.py
test_video.py
py
3,956
python
en
code
90
github-code
1
17553648881
import os import argparse import json from pypdf import PdfReader import openai API_KYE = os.environ['OPENAI_API_KEY'] openai.api_key = API_KYE def summarize_file(path): reader = PdfReader(path) number_of_pages = len(reader.pages) page = reader.pages[0] text = page.extract_text() messages=[ ...
xzymustbexzy/summarizer
src/main.py
main.py
py
857
python
en
code
1
github-code
1
41003672865
import vapoursynth as vs import muvsfunc def LimitedSharpen2(clp, ss_x=1.0, ss_y=1.0, dest_x=None, dest_y=None, Smode=4, strength=None, radius=2, Lmode=1, wide=False, overshoot=1, soft=False, edgemode=0, special=False, aSharpS=0.5, aWThresh=0.75, exborder=0): core = vs.get_core() # Avisynth's Round func...
dubhater/vapoursynth-limitedsharpen2
LimitedSharpen2.py
LimitedSharpen2.py
py
6,821
python
en
code
1
github-code
1
33603031027
import pandas as pd import matplotlib.pyplot as plt import base64 from io import BytesIO from time import strptime from pandas.core import base import plotly.express as px class Myclass: def __init__(self,path1,path2): self.path1=path1 self.path2=path2 def matrix_multiplication(self): ...
AshishPhadtare1999/Assets-Portfolio-data-project
myproject/myapp/Port_Assets.py
Port_Assets.py
py
4,808
python
en
code
0
github-code
1
28940574898
import PyPDF2 #translate the pdf file to txt file def pdf_to_text(pdf_file_path, txt_file_path): try: # Open the PDF file with open(pdf_file_path, 'rb') as pdf_file: pdf_reader = PyPDF2.PdfReader(pdf_file) # Initialize an empty text string text = "" ...
evanJensengit/finance_helper
pdf_to_txt.py
pdf_to_txt.py
py
1,096
python
en
code
0
github-code
1
9512617669
""" The PyRankine: the hybrid steady-state simulator of Rankine Cycle class Split_One2Two ↓ iPort ┌────┴────┐ oPort0 oPort1 json object example: { "name": "inpur name", "devtype": "SPLIT_ONE2TWO", "iPort": {}, "oPort0...
thermalogic/PyRankine
SimRankine/components/split_one2two.py
split_one2two.py
py
3,851
python
en
code
4
github-code
1
14458236466
def solve(s): l = s.split(" ") a = [i.capitalize() for i in l] return " ".join(a) s = input() print(solve(s)) ''' m = input().split(' ') didn't work properly. Every letter seperated n = '' for i in m: n += i.capitalize() print(' '.join(n)) def solve(s): #16 point get by submit this. one test case ...
maruf1847/problem-solving-python
HackerRank/capitalize.py
capitalize.py
py
556
python
en
code
0
github-code
1
38834117829
# Invert a binary tree. # Example: # Input: # 4 # / \ # 2 7 # / \ / \ # 1 3 6 9 # Output: # 4 # / \ # 7 2 # / \ / \ # 9 6 3 1 # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # ...
VJ-P/30-Days-Of-LeetCode-June-2020
1-invertTree.py
1-invertTree.py
py
740
python
en
code
0
github-code
1
34333936223
# 1st Approach: class Solution: def lengthOfLongestSubstring(self, s: str) -> int: winS = winE = 0 hashMap = {} maxL = 0 while winE < len(s): hashMap[s[winE]] = hashMap.get(s[winE], 0)+1 if len(hashMap) == winE-winS+1: maxL = max(maxL,...
siddiqui-sana/Leetcode-Challenge
Leetcode Challenge/Extra/Longest_Substring_Without_Repeating_Characters.py
Longest_Substring_Without_Repeating_Characters.py
py
1,075
python
en
code
1
github-code
1
42482303901
import graphene from graphene import Field from graphene_django.types import ErrorType from graphene.types.base import BaseOptions from django.core.exceptions import ObjectDoesNotExist class DeleteMutationOptions(BaseOptions): model = None arguments = None output = None resolver = None interface...
JiaWeiXie/django-project-template
project-name/src/app/utils/graphql/mutation.py
mutation.py
py
2,807
python
en
code
0
github-code
1
36789311814
# Q1: #Kullanıcının boy ve ağırlık değerlerinin girilmesi boy = float(input("Lütfen boyunuzu (santimetre cinsinde) yazınız: ")) agirlik = float(input("Lütfen ağırlığınızı (kilogram cinsinde) yazınız: ")) #Vücut Kitle İndeksinin (VKİ) hesaplanması VKİ = agirlik / (boy * boy) #Sonuç print("Vücut Kitle İndeksiniz:", V...
caglaakyol/BA-Assignments
BA-Q1.py
BA-Q1.py
py
352
python
tr
code
0
github-code
1
28822048293
import os import math import pandas as pd from scipy.stats import gmean from tabulate import tabulate from eval import * ''' usage: python .\result.py > .\result.log input: all log files output: csv file that contains the evaluation results ''' def format_integer(number): if math.isnan(number): return nu...
CactiLab/Sherloc-Cortex-M-CFVD
host_tools/evaluation/result.py
result.py
py
28,369
python
en
code
4
github-code
1
6972824573
#!usr/bin/python def longestCommonSubstringOf(strings): lcsm = '' if len(strings) > 1 and len(strings[0]) > 0: for i in range(len(strings[0])): for j in range(len(strings[0])-i-1): if j > len(lcsm) and isSubstring(strings[0][i:i+j], strings): lcsm = strings[0][i:i+j] else: lcsm = strings[0] return ...
oryoruk/Rosalind
Bioinformatics Stronghold/LCSM.py
LCSM.py
py
935
python
en
code
1
github-code
1
2768505134
# Mauricio Carmelo (2019) import csv import numpy as np def loadCSV(filepath): """ method which loads the information from a .csv file INPUT filepath - relative path to the .csv file OUTPUT sheet - dictionary structure referencing an attribute to all values in a single column attributes - names of colu...
MauricioCarmelo/machine-learning
loadCSV.py
loadCSV.py
py
1,225
python
en
code
0
github-code
1
35072935714
from kivy.uix.screenmanager import Screen from kivy.lang import Builder from kivy.uix.boxlayout import BoxLayout from kivy.properties import StringProperty from kivy.utils import platform from kivymd.uix.dialog import MDDialog from kivymd.uix.button import MDFlatButton from kivymd.uix.filemanager import MDFileManager ...
wasimafser/DataShare
screens/send.py
send.py
py
3,650
python
en
code
2
github-code
1
31932909558
from flask import Flask, render_template , Response import cv2 , os import argparse app = Flask(__name__) app.config['SECRET_KEY'] = '1234' @app.route('/') #html 보여준다. def index(): return render_template('index.html') @app.route('/video_show') def video_show(): return Response(yield_video(), mimetype= "multi...
amo33/taskprojects
yieldvideo/videoyield.py
videoyield.py
py
1,512
python
en
code
0
github-code
1
40586297846
# -*- coding: utf-8 -*- """ Created on Fri Oct 29 18:16:02 2021 @author: Park Ihn """ import json from collections import OrderedDict import csv from datetime import datetime import re from turtle import Turtle #input file open inputCsv = open("KIKmix.20220401(말소코드포함).csv","r",encoding="cp949") rd = csv.reader(inputCs...
YangHong-bin/visual_code
py_요기요 코드/test.py
test.py
py
3,713
python
ko
code
0
github-code
1
19951049514
""" Python Exception Handling Using try, except and finally statement""" def entering(age): if age < 18: raise ValueError else: print('You can enter to the club') try: entering(10) except: print('Your age is less than 18,and you can not enter')
elguneminov/Python-2021-Complete-Python-Bootcamp-Zero-Hero-Programming
Entering.py
Entering.py
py
295
python
en
code
0
github-code
1
74345205154
# # @lc app=leetcode.cn id=198 lang=python3 # # [198] 打家劫舍 # # https://leetcode-cn.com/problems/house-robber/description/ # # algorithms # Medium (48.38%) # Likes: 1379 # Dislikes: 0 # Total Accepted: 272.8K # Total Submissions: 561.4K # Testcase Example: '[1,2,3,1]' # # # 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃...
Zigars/Leetcode
动态规划/198.打家劫舍.py
198.打家劫舍.py
py
2,487
python
zh
code
0
github-code
1
7955220563
import unittest from core.Sendhttp import SendHttp class skulist(unittest.TestCase): def setUp(self): self.url="/common/skuList" def test_skulist(self): result=SendHttp().sent_get(self.url) print(result) # goodsId为Int类型 def test_skulistById(self): skul...
King-BAT/RanZhi
Requests/QingGuo/SingleAPI/skulist_test.py
skulist_test.py
py
1,575
python
en
code
0
github-code
1
10899288283
import threading import time import copy import cafeteria as cf def fixed_input(): """ This function will create a cafeteria object and give the hardcoded values to the attributes parametes : None returns : Cafeteria object """ number_of_restaurants = 4 number_of_items = 4 list_of_dict_...
AyushRaghuwanshi/System-for-cafeteria
main.py
main.py
py
3,504
python
en
code
0
github-code
1
25594134201
import pytest import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'books_api.settings') django.setup() from books.models import Book @pytest.fixture def basic_book_data(): return { "googleapis_id": "iY4yZEkphNgC", "title": "basic_book", "authors": "['basic author']", ...
bartoszbad/googleapis-books
tests/conftest.py
conftest.py
py
2,319
python
en
code
0
github-code
1
36690158335
# dynamic programing explore card class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ if n <= 2: return n dp_prev1 = 1 dp_prev2 = 2 for i in range(3, n+1): dp_curr = dp_prev1 + dp_prev2 ...
lingerxu/leetcode-solutions
dynamic_programming.py
dynamic_programming.py
py
471
python
en
code
0
github-code
1
38487802023
import os import json import sys def pr(matrix): for r in matrix: print(r) path = os.path.dirname(os.path.abspath(__file__)) inputname = sys.argv[1] if len(sys.argv) > 1 else os.path.join(path, "input.txt") with open(os.environ.get("AOC_INPUT", inputname), "r") as f: INPUT = f.read().split("\n") ...
pting/aoc2022
day08/day08.py
day08.py
py
2,153
python
en
code
0
github-code
1
15978928257
import math import numpy as np import torch from PIL import Image class BackDoorAttack(): @staticmethod def make_attack(train_x, train_y, args): """ Makes a backdoored dataset, following Gu et al. https://arxiv.org/abs/1708.06733 train_x: clean training features - must be shape (n_sa...
andrewyguo/auditing
attacks/backdoor.py
backdoor.py
py
2,198
python
en
code
1
github-code
1
25461318315
import unittest from collections import namedtuple from telemetry.internal.results import page_test_results from telemetry.page import page from telemetry.web_perf.metrics import single_event from telemetry.web_perf import timeline_interaction_record TRACE_EVENT_NAME = 'FrameView::performLayout' METRIC_NAME = 'layout...
hanpfei/chromium-net
third_party/catapult/telemetry/telemetry/web_perf/metrics/single_event_unittest.py
single_event_unittest.py
py
2,972
python
en
code
289
github-code
1
70511358435
from nio import Block from nio.util.discovery import not_discoverable from nio.testing.block_test_case import NIOBlockTestCase from ...multiple import MultipleSignals from ...generators.counter import CounterGenerator @not_discoverable class SampleCounterBlock(CounterGenerator, Block): pass @not_discoverable c...
nio-blocks/simulator
tests/generators/test_counter.py
test_counter.py
py
3,075
python
en
code
1
github-code
1
31904462804
# sc_logger.py import logging class XBLogger: def __init__(self): log = logging.getLogger('log') log.setLevel(logging.DEBUG) # setup file handler & formatter ch = logging.FileHandler(filename='log/scorpius.log', mode='w') # setup output string # format_s = '%(lev...
xavibenavent/scorpius
src/sc_logger.py
sc_logger.py
py
702
python
en
code
0
github-code
1
23160211530
#! /usr/bin/env python3 import re from collections import deque from typing import List def initialize_stacks(initial_state: List[str]) -> List[deque]: """Initialize stacks. Example stack initialization: [D] [N] [C] [Z] [M] [P] 1 2 3 """ # read position of boxes in each stac...
donovan-h-parks/advent-of-code
2022/python/day-05/day-05.py
day-05.py
py
3,798
python
en
code
0
github-code
1
7572097224
class Solution(object): def anagramMappings(self, A, B): """ :type A: List[int] :type B: List[int] :rtype: List[int] """ idx_list = [] for ele in A: idx_list.append(B.index(ele)) return idx_list if __name__ == '__main__': s = Solution(...
Ray-Zhang/leetcode
easy/anagramMappings.py
anagramMappings.py
py
415
python
en
code
0
github-code
1
11724373152
from app import app from flask import render_template, request from bs4 import BeautifulSoup from app.forms import GetPageForm import requests import string def get_page_controller(): form = GetPageForm() page_url = form.url.data page = requests.get(page_url) soup = BeautifulSoup(page.text, 'html.parser') ...
kellybarber/python-scraper
app/controllers/get_page_controller.py
get_page_controller.py
py
789
python
en
code
0
github-code
1
17792588129
import RPi.GPIO as GPIO # Configura modo de definicao de pinos como BOARD, ou seja, contagem de pinos da placa GPIO.setmode(GPIO.BOARD) #Desativa warnings GPIO.setwarnings(False) pinVermelho = 8 pinVerde = 11 #Configura pino 7 e 11 da placa (GPIO24) como saida GPIO.setup(pinVermelho,GPIO.OUT) GPIO.setup(pinVerde,GP...
wagnermarques/rfid-arduino-raspberry
ledCommands.py
ledCommands.py
py
1,132
python
pt
code
0
github-code
1
23624669701
import tkinter as tk import Pendu as p root = tk.Tk() frm_start = tk.Frame(root) frm_start.grid() frm_jeu = tk.Frame(root) frm_gagner = tk.Frame(root) frm_perdu = tk.Frame(root) jeu = p.Pendu(frm_start, frm_jeu, frm_gagner, frm_perdu) tk.Label(frm_start, text="Entre le mot mystere : ").grid(column=0, row=0) start...
12dorian12/Cours_Python
Pendu_Tkinter/main.py
main.py
py
1,521
python
fr
code
0
github-code
1
21205910301
import pandas as pd from UTILS import Cache from UTILSD import Defaults as djn_def from UTILSD import main as djn_utils def objects(request: djn_utils.CustomRequest, info: djn_utils.ApiInfo): """ UpdatedAt: --- About: ----- return home objects Input: ----- | Link: Home/objects | methods: post | token req...
aPerfectPolygon/polygon-backend-Rpi
API/v1/Views/Home/main.py
main.py
py
1,281
python
en
code
0
github-code
1
3081179883
#Trabalho realizado pelo aluno: # Nome: Vítor Augusto Cecílio e Silva | RA:104409 from Instruction_Memory import Instruction_Memory from cpu import CPU import sys def main(): args = sys.argv[1:] if len(args) > 1: print("Mais argumentos recebidos do que o devido!") return False elif len...
VtrCecilio/Simulador_CPU_Paralelo
main.py
main.py
py
605
python
pt
code
0
github-code
1
33618000873
from django.shortcuts import render # Create your views here. from rating.models import Rating def add(request): if request.method=="POST": obj=Rating() obj.rating=request.POST.get('rating') obj.u_id="1" obj.save() return render(request,'rating/add_rating.html') def view(request...
abhinavtp/gadget
shop/e_gadget/rating/views.py
views.py
py
973
python
en
code
0
github-code
1
27069940928
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019/10/23 11:16 # @Author: yanmiexingkong # @email : yanmiexingkong@gmail.com # @File : main.py import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webd...
Annihilater/blast.ncbi.nlm.nih.gov
main.py
main.py
py
3,127
python
en
code
0
github-code
1