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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
74453123386 | def solve(n, s, d, m):
combos = 0
i = 0
while i < len(s):
if sum(s[i:(i + m)]) == d:
combos += 1
i += 1
return combos
n = int(input().strip())
s = list(map(int, input().strip().split(' ')))
d, m = input().strip().split(' ')
d, m = [int(d), int(m)]
result = solve(n, ... | em1382/hackerrank | algorithms/implementation/the-birthday-bar.py | the-birthday-bar.py | py | 343 | python | en | code | 0 | github-code | 6 |
8017799306 | import tkinter as tk
from tkinter import ttk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import numpy as np
class GraphPlt():
def __init__(self):
"""インスタンス化。Figureの作成
"""
self.fig = Figure(figsize=(6,6))
def plt(self, title="plot... | komepi/komepiTkinter | komepiTkinter/GraphPlt.py | GraphPlt.py | py | 6,239 | python | en | code | 0 | github-code | 6 |
18801821077 | import requests
requests.packages.urllib3.disable_warnings() # noqa
url = "https://api.github.com/repos/milvus-io/milvus/actions/workflows"
payload = {}
token = "" # your token
headers = {
"Authorization": f"token {token}",
}
response = requests.request("GET", url, headers=headers, data=payload)
def analysis_w... | milvus-io/milvus | tests/python_client/chaos/scripts/workflow_analyse.py | workflow_analyse.py | py | 1,895 | python | en | code | 24,190 | github-code | 6 |
36396180382 | from ast import Lambda
from itertools import groupby
import pandas as pd
import pymysql
from pyecharts.charts import Bar, Line, Pie
from pyecharts import options as opts
conn = pymysql.connect(host="localhost", user="root",
passwd="123456", port=3306, db="591")
cursor = conn.cursor()
sql = 'se... | dichotomania/project | visual.py | visual.py | py | 5,336 | python | en | code | 0 | github-code | 6 |
24847039251 | import pygame
class Character():
"""Create a character - inherits from the Sprite class"""
def __init__(self, screen, game_settings):
self.screen = screen
self.settings = game_settings
# Load the character image and get its rect
self.image = pygame.image.load("images... | YorkshireStu83/Flatpormer | character.py | character.py | py | 2,187 | python | en | code | 0 | github-code | 6 |
29285921224 | from rply import LexerGenerator # type: ignore
# lexer for the "calc" command
lg = LexerGenerator()
lg.add('NUMBER', r'[0-9]+[\.]?[0-9]*') # number token
lg.add('ADDITION', r'\+') # operator tokens
lg.add('SUBTRACTION', r'-')
lg.add('MULTIPLICATION', r'\*')
lg.add('EXPONENT', r'\^')
lg.add('DIVISION', r'\/')
lg.add(... | Chrovo/Productivity | cogs/utils/lexer.py | lexer.py | py | 582 | python | en | code | 0 | github-code | 6 |
20143910497 | import cv2
import argparse
def decode_fourcc(fourcc):
# Decodes the fourcc value to get the 4 chars identifying it
fourcc_int = int(fourcc)
# Print the value of fourcc
print("int value of fourcc: {}".format(fourcc_int))
#return "".join([chr((fourcc_int >> 8 * i) & 0xFF) for i in range(4)])
... | Raylow00/OpenCV-Tutorials | 1_Opencv_basics/6_decode_fourcc.py | 6_decode_fourcc.py | py | 524 | python | en | code | 0 | github-code | 6 |
34622698240 | S = input()
UCPC = "UCPC"
j = 0
for i in range(len(S)):
if S[i] == UCPC[j]:
j += 1
if j == 4:
print("I love UCPC")
quit()
print("I hate UCPC") | ktan9811/BOJ | 10000~/15904.py | 15904.py | py | 187 | python | en | code | 0 | github-code | 6 |
22021920480 | '''
Jessica Dutton
Store Manager (user entity)
'''
from google.cloud import datastore
from flask import Blueprint, Flask, request, make_response
import json
import constants
from google.oauth2 import id_token
from google.auth.transport import requests
client = datastore.Client()
bp = Blueprint('store_manager', __nam... | jdutt25/dvd_store | store_manager.py | store_manager.py | py | 1,310 | python | en | code | 0 | github-code | 6 |
36807817632 | import numpy as np
from scipy import signal
from scipy.signal import butter, lfilter
def createSpec(signals, sr, n_channels=22):
# Reference: https://github.com/MesSem/CNNs-on-CHB-MIT, DataSetToSpectrogram
n_channels = min(n_channels, 22)
for channel in range(n_channels):
y = signals[channel]
... | koike-ya/eeglibrary | eeglibrary/src/chb_mit_cnn_spectrogram.py | chb_mit_cnn_spectrogram.py | py | 1,357 | python | en | code | 1 | github-code | 6 |
4456513686 | from dataclasses import dataclass
from fnmatch import fnmatch
from typing import cast, Optional
from urllib.parse import urljoin
from .config import Config
from .download import DownloaderMixIn, HTTPXDownloaderMixIn
from .exceptions import (
ArbitrarySoftwareAttack,
DownloadNotFoundError,
EndlessDataAttack... | trishankatdatadog/tuf-on-a-plane | src/tuf_on_a_plane/repository.py | repository.py | py | 18,018 | python | en | code | 4 | github-code | 6 |
10795571321 | """
作为初始代码,目标是有的一个固定大小的球,给定一个初识速度,和一个固定阻力,演示球运动的过程。每一个循环的时间与现实时间一致。
从最初代码开始演示如何一步步完善代码最终完成功能的过程。
"""
import sys, pygame
import os.path
import random
import time
import math
#pygame.font.init()
#myfont = pygame.font.SysFont('Comic Sans MS', 30)
def hit_A(x, y):
return y <= 10
def hit_B(x, y):
return x >= 590
... | sillyemperor/pygame-study | rebound-ball-walls.py | rebound-ball-walls.py | py | 1,622 | python | en | code | 0 | github-code | 6 |
19346820391 | from pyparsing import FollowedBy
import tweepy
from app.config import TWITTER_API_KEY,TWITTER_API_KEY_SECRET,get_logger
class TwitterAPI:
def __init__(self,access_token,access_token_secret) -> None:
self.api_key = TWITTER_API_KEY
self.api_key_secret = TWITTER_API_KEY_SECRET
self.access_toke... | Socialet/web-backend | app/services/api/twitterAPI.py | twitterAPI.py | py | 9,191 | python | en | code | 0 | github-code | 6 |
38823318960 | import csv
def write_dev_stock(data):
f = open('output.csv', 'w')
writer = csv.writer(f, lineterminator='\n')
i = 0
while i < len(data.index):
row = data.iloc[i]
writer.writerow(row)
i += 1
f.close()
| shun-chiba/nq52 | python/src/file/write_csv.py | write_csv.py | py | 250 | python | en | code | 0 | github-code | 6 |
24657079519 | from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from . import models
import json
# Register your models here.
class BaseAdmin(admin.ModelAdmin):
list_p... | leafcoder/django-covid19 | django_covid19/admin.py | admin.py | py | 3,276 | python | en | code | 155 | github-code | 6 |
71781182589 | import glob
import os
from datetime import datetime
import cv2
# isResize = False
isResize = True # change this to False, if resize is not required
images = []
image_src_folder = "images"
files = glob.glob(image_src_folder+"/*")
for file in files:
print(f"Processing: {os.path.basename(file)}")
if file.endswi... | yptheangel/opencv-starter-pack | python/examples/image_stitching/stitching.py | stitching.py | py | 1,349 | python | en | code | 8 | github-code | 6 |
24047121946 | import random
from tekleo_common_message_protocol import OdSample
from tekleo_common_utils import UtilsImage, UtilsOpencv
from tekleo_common_utils_ai.dataset_modification.abstract_dataset_modifier import AbstractDatasetModifier
from injectable import injectable, autowired, Autowired
@injectable
class DatasetModifierS... | JPLeoRX/tekleo-common-utils-ai | tekleo_common_utils_ai/dataset_modification/dataset_modifier_saturation.py | dataset_modifier_saturation.py | py | 2,676 | python | en | code | 0 | github-code | 6 |
1698064062 | import pygame
# define constants for the window size and stack element size
ELEMENT_WIDTH = 50
ELEMENT_HEIGHT = 200
# initialize Pygame
pygame.init()
# create a window
window = pygame.display.set_mode((1000, 500))
# define a font to use for displaying the stack elements
font = pygame.font.Font(None, 36)
# define a... | Dhivyno/Programming-projects | All files/test.py | test.py | py | 2,005 | python | en | code | 2 | github-code | 6 |
26922909604 | """
Imports the various compute backends
"""
from typing import Set
from ..exceptions import InputError, ResourceError
from .cfour import CFOURHarness
from .dftd3 import DFTD3Harness
from .entos import EntosHarness
from .gamess import GAMESSHarness
from .molpro import MolproHarness
from .mopac import MopacHarness
fro... | ChemRacer/QCEngine | qcengine/programs/base.py | base.py | py | 2,624 | python | en | code | null | github-code | 6 |
70647215549 | # Procedura REKURENCYJNE-WYSZUKIWANIE-BINARNE(A, p, r, x)
# 1. Jeśli p > r to zwróć NIE-ZNALEZIONO
# 2. W przeciwnym razie (p < r) wykonaj, co następuje:
# A. Nadaj q wartość flor (p + r) / 2
# B. Jeśli A[q] = x to zwróć q
# C. W przeciwnym razie (A[q] not= x), jeśli A[q] > x, to zwróć
# REREKURENCYJN... | koualsky/dev-learning | algorithms/algorithms.py | algorithms.py | py | 16,297 | python | pl | code | 0 | github-code | 6 |
4955963415 | '''
P.S: Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false.
An integer m is a divisor of n if there exists an integer k such that n = k * m.
'''
#Solution:
class Solution:
def isThree(self, n: int) -> bool:
sum=0
for x in range(1,n+1):
if ... | nidhisha-shetty/LeetCode | three-divisors.py | three-divisors.py | py | 400 | python | en | code | 2 | github-code | 6 |
39830489884 | from collections import deque
def solution(n, info):
answer = []
diff = 0
queue = deque()
queue.append((0, [0,0,0,0,0,0,0,0,0,0,0]))
while queue:
idx, arr = queue.popleft()
# 화살을 전부 쐈을경우
if sum(arr) == n:
# 어피치와 라이언 점수 체크
apeach, lion = 0, 0
... | omg7152/CodingTestPractice | kakaoBlindRecruitment2022/Q4.py | Q4.py | py | 2,081 | python | ko | code | 0 | github-code | 6 |
73539848828 | def conta_letras(frase, contar='vogais'):
tam = len(frase)
if contar == 'vogais':
vogais = ['a', 'e', 'i', 'o', 'u']
n_vogais = 0
for i in range(tam):
if frase[i].lower() in vogais:
n_vogais += 1
return n_vogais
if contar == 'consoantes':
... | Icarolmo/Introducao-a-Ciencia-da-Computacao-com-Python-parte-2-IME-USP | Exercícios/contaVogais.py | contaVogais.py | py | 633 | python | pt | code | 1 | github-code | 6 |
39122258660 | from service_info import dp, bot, greeting, download_url, path_to_file_url, PhotoStatesGroup, dict_config, lang_dict
import aiohttp
from visor import tess_visor, easy_visor, keras_visor
from aiogram import types, executor
from keyboards import type_kb, lang_kb
from aiogram.dispatcher import FSMContext
import logging
im... | dfgion/VisorBot | bot.py | bot.py | py | 4,388 | python | en | code | 0 | github-code | 6 |
7506825740 |
# Exercício 1: Crie um algoritmo não recursivo para contar quantos números pares existem em uma sequência numérica (1 a n).
def pairs(n):
count = 0
while n > 0:
if n % 2 == 0:
count += 1
n -= 1
return count
print(pairs(4))
| Gonzagadavid/trybe-exercises-computer-science | exercises/recursividade_35.2/exercise-1.py | exercise-1.py | py | 255 | python | pt | code | 1 | github-code | 6 |
14564990421 | import numpy as np
from IO.Pinocchio.ReadPinocchio import mf
import matplotlib.pyplot as plt
# Box Size
boxsize = 150.0
aux = mf("../TestRuns/pinocchio.1.9775.example.mf.out", "mf")
mf0 = mf("../TestRuns/pinocchio.1.9775.example.catalog.out", "catalog", 64, boxsize)
mf0.dndm_teo = np.interp(mf0.m, aux.m, aux.dndm_t... | TiagoBsCastro/PITILESS-SLICER | Test/test_mf.py | test_mf.py | py | 657 | python | en | code | 1 | github-code | 6 |
24274585662 | # -----------------------------------------------------------
# Creates the views for the database.
# This views are called when user navigates to a certain url.
# They are responsible for either rendering an HTML template or the API data that are requested
# For example: Navigating to the url 'api/operations/' will tr... | KIOS-Research/AIDERS | aidersplatform/django_api/aiders/views.py | views.py | py | 110,716 | python | en | code | 4 | github-code | 6 |
13303759601 | import requests, asyncio
from app import ACCESS_TOKEN, PYONET_API_URL, db
from app.tools.p3log import P3Log
class Poller:
def __init__(self):
self.p3log = P3Log("poller.log")
self.poll_task = None
self.devices = []
async def test_access_token(self):
try:
... | treytose/Pyonet-Poller | pyonet-poller/app/libraries/libpoller.py | libpoller.py | py | 2,336 | python | en | code | 0 | github-code | 6 |
72757283709 | """
Utilities I can't put anywhere else...
"""
import time
from math import copysign, gcd
from copy import copy
import sys
import numpy as np
import datetime
import functools
def true_if_answer_is_yes(prompt=""):
invalid = True
while invalid:
x = input(prompt)
x = x.lower()
if x[0] =... | ahalsall/pysystrade | syscore/genutils.py | genutils.py | py | 11,815 | python | en | code | 4 | github-code | 6 |
32058100772 | lst = []
T = int(input())
for t in range(T):
t = str(input())
cnt = 0
ans = 0
for result in t:
if result == 'O':
cnt += 1
ans += cnt
elif result == 'X':
cnt = 0
print(ans) | doll2gom/Algorithm | 백준/Bronze/8958. OX퀴즈/OX퀴즈.py | OX퀴즈.py | py | 255 | python | en | code | 0 | github-code | 6 |
32467203933 | cnt_double_quote = 0
def solve(s):
global cnt_double_quote
res = ''
for c in s:
if c == '"':
cnt_double_quote += 1
if cnt_double_quote % 2 == 1: # First quote
res += '``'
else: # Second quote
res += "''"
else:
r... | jasonhuh/UVa-Solutions | 272 TEX Quotes/272_TEXT_Quotes.py | 272_TEXT_Quotes.py | py | 834 | python | en | code | 0 | github-code | 6 |
24929832115 | #!/usr/bin/python
from nrf24 import NRF24
import time
from struct import *
class Spinner:
def __init__(self):
# Set up the radio
pipes = ["1Node", "2Node"]
self.radio = NRF24()
self.radio.begin(0,0,25,24) #Set CE and IRQ pins
self.radio.setRetries(15,15)
self.rad... | norn93/honey-spinner-server | spinner.py | spinner.py | py | 2,751 | python | en | code | 0 | github-code | 6 |
7725611508 | import itertools
def det_4x4(matrix):
if len(matrix) != 4 or len(matrix[0]) != 4:
raise ValueError("A matriz não é 4x4")
indices = [0, 1, 2, 3]
permuta = itertools.permutations(indices)
det = 0
for perm in permuta:
sinal = 1
for i in range(4):
for j in range(i + ... | AlexApLima/CalculoDeterminantesLeibniz | CalFormula.py | CalFormula.py | py | 903 | python | pt | code | 0 | github-code | 6 |
27560775803 | data = open('input/day20.txt').read().splitlines()
# data= open('input/day20.txt').read().splitlines()
data = [int(d) for d in data]
id_of_0 = data.index(0)
# %% Build a circular linked list which can move its node to left or right
class Node:
def __init__(self, data, id):
self.data = data
self.nex... | nhannht/aoc2022 | day20.py | day20.py | py | 3,778 | python | en | code | 0 | github-code | 6 |
70740769147 | from __future__ import print_function
import torch
def diff_mse(x, y):
x_vec = x.view(1, -1).squeeze()
y_vec = y.view(1, -1).squeeze()
return torch.mean(torch.pow((x_vec - y_vec), 2)).item()
def ax_plus_b_vector(x, weight, bias):
return weight.mm(x).add(bias)
def ax_plus_b_scalar(x, weight, bias, ... | IvanProdaiko94/UCU-deep-learning-homework | layers/utilities.py | utilities.py | py | 1,222 | python | en | code | 1 | github-code | 6 |
37841455471 | import logging
logger = logging.getLogger()
logger.setLevel(level="DEBUG")
logging.Formatter
# 创建文本处理器
file_handle = logging.FileHandler("./log.txt", mode="a", encoding="utf-8")
file_handle.setLevel(level="ERROR")
logger.addHandler(file_handle)
fmt = "%(name)s--->%(message)s--->%(asctime)s"
logging.basicConfig(level... | amespaces/pythonProject | common/创建文件处理器.py | 创建文件处理器.py | py | 552 | python | en | code | 0 | github-code | 6 |
22906645455 | import xlrd
class XLDateInfo(object):
def __init__(self, path=''):
self.xl = xlrd.open_workbook(path)
self.sheet = None
def get_sheet_info_by_name(self, name):
self.sheet = self.xl.sheet_by_name(name)
return self.get_sheet_info()
def get_sheet_info(self):
infolist... | weijianhui011/uploadfile | public/read_excel.py | read_excel.py | py | 659 | python | en | code | 0 | github-code | 6 |
35007978934 | from src.main.python.Solution import Solution
# Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
#
# For example:
# Given the below binary tree and sum = 22,
# 5
# / \
# 4 8
# / / \
# 11 13 4
# / \ \
# ... | renkeji/leetcode | python/src/main/python/Q113.py | Q113.py | py | 1,099 | python | en | code | 0 | github-code | 6 |
21971690182 | import json
from collections import OrderedDict
from operator import itemgetter
TEAMS = None
MATCHES = {}
def get_other(t, title):
t1, t2 = title.split("-")
if t in t1:
return get_team(t2)
return get_team(t1)
def get_team(t):
for team in TEAMS:
if team in t:
return team
... | mfkaptan/fixture-visualizer | lig.py | lig.py | py | 1,026 | python | en | code | 0 | github-code | 6 |
38364864905 | #!/usr/bin/env python
import eink
import ImageFont
import ImageDraw
import sys
def parse(text):
s = ['', '']
i = 0
for c in text:
if c == '*':
i = 1 - i
else:
s[i] += c
if c.isspace():
s[1-i] += c
else:
s[1-i] ... | need-being/eink | draw_text.py | draw_text.py | py | 940 | python | en | code | 0 | github-code | 6 |
12940606913 | import json
import logging
import avro.schema
from avro.datafile import DataFileWriter
from avro.io import DatumWriter
# Login config
logging.basicConfig(
filename='writer.log',
filemode='w',
format='%(asctime)s - %(levelname)s - %(message)s',
level=logging.INFO
)
# read records from sample_dat... | jocerfranquiz/avro_test | write_avro.py | write_avro.py | py | 1,116 | python | en | code | 0 | github-code | 6 |
74473909946 | from datetime import date
from django.test import Client
from django.test import TestCase
from django.urls import resolve
from .views import index, mhs_name, calculate_age
class Lab1UnitTest(TestCase):
def test_hello_name_is_exist(self):
response = Client().get('/lab-1/')
self.assertEqual(respon... | argaghulamahmad/ppw-lab-arga | lab_1/tests.py | tests.py | py | 1,752 | python | en | code | 0 | github-code | 6 |
5687320564 | from OpenGL.GLUT import *
from OpenGL.GL import *
from OpenGL.GLU import *
import time
import numpy as np
import math
# P(t) = P(0) + V(0)*t + 1/2 * g * t^2
dt = -1
currentTime = 0
lastTime=0
def TimerOn() :
if dt>0 :
return True
else :
return False
def TimerStart():
global currentTime, ... | asd147asd147/High_Quality_OpenGL | OpenGL/lab06/lab06-2-m.py | lab06-2-m.py | py | 2,595 | python | en | code | 0 | github-code | 6 |
28521323695 | """change precision of order amount
Revision ID: fb84527fc0b3
Revises: 5c6f2d25c2f0
Create Date: 2018-04-07 18:51:12.160012+00:00
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = 'fb84527fc0b3'
down_revision = '5c6f2d25c2f0'
... | harveyslash/backend-cleaned | beatest/migrations/versions/20180407185112_fb84527fc0b3_change_type_of_order_amount.py | 20180407185112_fb84527fc0b3_change_type_of_order_amount.py | py | 1,011 | python | en | code | 0 | github-code | 6 |
13194360101 | # -*-coding=utf-8-*-
# @Time : 2019/1/28 14:19
# @File : youtube_downloader.py
import subprocess
import sys
import pymongo
import re
import codecs
def extract_link(filename='web.html'):
with codecs.open(filename, 'r', encoding='utf8') as f:
content = f.read()
try:
result = re.findall('\{"v... | leegb/online_video_download | youtube_downloader.py | youtube_downloader.py | py | 2,952 | python | en | code | 0 | github-code | 6 |
19528069970 | # -*- coding: utf-8 -*-
# 基础公共模块
__author__='zhaicao'
import pymssql
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtCore import Qt
import winreg
import os
import sys
import webbrowser
# SqlServer访问类
class MSSQL:
def __init__(self,**kwargs):
self.dbInfo = kwargs
def __GetConnect(self):
... | zhaicao/pythonWorkspace | DeployTool/eventAction/Utils.py | Utils.py | py | 6,744 | python | en | code | 0 | github-code | 6 |
25875757160 | from numba import jit
import numpy as np
from obspy.taup import TauPyModel
import os
@jit(nopython=True, fastmath=True)
def coords_lonlat_rad_bearing(lat1, lon1, dist_deg, brng):
"""
Returns the latitude and longitude of a new cordinate that is the defined distance away and
at the correct bearing from the ... | eejwa/Array_Seis_Circle | circ_array/geo_sphere_calcs.py | geo_sphere_calcs.py | py | 9,707 | python | en | code | 7 | github-code | 6 |
71804916988 | from __future__ import print_function
import argparse
import torch
from torch import nn, optim
from torch.autograd import Variable
from torch.nn import functional as F
from config import params, data
class VAE(nn.Module):
def __init__(self):
super(VAE, self).__init__()
self.fc1 = nn.Linear(params... | hoxmark/Deep_reinforcement_active_learning | selection_strategies/models/vae.py | vae.py | py | 3,987 | python | en | code | 17 | github-code | 6 |
72313218748 | from flask import Flask, jsonify,request,json
from scrapper import scrap_cards
from config import *
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/scrap', methods = ['POST'])
def generate_json():
req = request.get_json(force=Tr... | mage1711/flask-scrapers-api | app.py | app.py | py | 495 | python | en | code | 0 | github-code | 6 |
9690266532 | """
Xero Linked Transactions API
"""
from .api_base import ApiBase
class LinkedTransactions(ApiBase):
"""
Class for Linked Transactions API
"""
POST_LINKED_TRANSACTION = '/api.xro/2.0/LinkedTransactions'
def post(self, data):
"""
Create new invoice
Parameters:
... | fylein/xero-sdk-py | xerosdk/apis/linked_transactions.py | linked_transactions.py | py | 505 | python | en | code | 0 | github-code | 6 |
20143445172 | """Views for Learning Journal."""
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPFound
from pyramid.httpexceptions import HTTPNotFound
from anna_journal.models import Journals
from pyramid.security import remember, forget
from anna_journal.security import check_credentials
@view_config(ro... | Bonanashelby/pyramid-learning-journal | anna_journal/anna_journal/views/default.py | default.py | py | 2,855 | python | en | code | 0 | github-code | 6 |
19054013888 | """
Scripts to align sequences and transoform them into 1-hot encoding
"""
# Author: Alessio Milanese <milanese.alessio@gmail.com>
import shutil
import time
import subprocess
import shlex
import os
import errno
import sys
import tempfile
import numpy as np
import re
from stag.helpers import is_tool, read_fasta
#===... | zellerlab/stag | stag/align.py | align.py | py | 8,980 | python | en | code | 7 | github-code | 6 |
19672334600 | import pytest
from bfprt.algo import insertion_sort, partition, select, swap
class TestInternal:
def test_swap(self):
items = [4, 1, 2, 5, 9, 8]
swap(items, 2, 3)
assert items == [4, 1, 5, 2, 9, 8]
@pytest.mark.parametrize("items, pivot_index, expected_items, expected_index", [
... | gregorybchris/bfprt | tests/test_internal.py | test_internal.py | py | 1,139 | python | en | code | 0 | github-code | 6 |
13955129653 | import threading
class BuckysMessenger(threading.Thread):
# 'run' is a special thread function
def run(self):
# use the '_' if you just want to loop 10 times and don't care about variable
for _ in range (10):
print(threading.currentThread().getName())
x = BuckysMessenger(name='Sen... | eswartzendruber1/linux_setup | bin/src/sandbox/vid_34.py | vid_34.py | py | 477 | python | en | code | 0 | github-code | 6 |
29259984179 | import os
import sys
from datetime import datetime
from glob import glob
from re import split
from numpy import asarray, savetxt
class iGrav:
# find all the .tsf inside the input directory (even in the sub directory)
def get_all_tfs(self, input_folder):
paths_list = glob(input_folder + "/**/*.tsf", r... | lucamir/iGravToCSV | main.py | main.py | py | 4,775 | python | en | code | 1 | github-code | 6 |
27390800021 | # Find All Approximate Occurrences of a Pattern in a String
# https://rosalind.info/problems/ba1h/
from utilities import get_file, get_answer_file, hamming_distance
def approximate_pattern(pattern, strand, distance):
len_s = len(strand)
len_p = len(pattern)
result = []
for i in range(len_s-len_p+1):
... | Delta-Life/Bioinformatics | Rosalind/Bioinformatics Textbook Track/code/BA1H.py | BA1H.py | py | 704 | python | en | code | 0 | github-code | 6 |
39255470036 | from django.conf import settings
from django.core.cache import cache
from django.utils import timezone
from proco.utils.tasks import update_cached_value
class SoftCacheManager(object):
CACHE_PREFIX = 'SOFT_CACHE'
def get(self, key):
value = cache.get('{0}_{1}'.format(self.CACHE_PREFIX, key), None)
... | unicef/Project-Connect-BE | proco/utils/cache.py | cache.py | py | 1,625 | python | en | code | 2 | github-code | 6 |
74738442108 | import os
import pandas as pd
import sys
from utility_funcs.vid_to_frame import convert_to_annotated_images_cvat
from utility_funcs.stratified_train_test_split import stratified_group_k_fold
irr_conf = 3
if sys.argv[1] == 'split':
trash_vids = [3, 39, 48]
df = pd.read_csv('data/frames.csv').dropna()
df = d... | LHumpe/COINs-CNN-FLOW | src/io/data_generators/data_gen_HpSearch.py | data_gen_HpSearch.py | py | 3,086 | python | en | code | 0 | github-code | 6 |
6919943057 | import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GdkPixbuf
class View(Gtk.Window):
# TODO: Make GUI prettier - low priority
# TODO: Change metric to *C and imperial to *F
def __init__(self):
super().__init__(title='Weather Forecast')
self._box = Gtk.Box(orientati... | lukasz130/WeatherForecast | sources/view.py | view.py | py | 4,949 | python | en | code | 0 | github-code | 6 |
43534065791 | def convert_sample_to_shot_coQA(sample, with_knowledge=None):
prefix = f"{sample['meta']}\n"
for turn in sample["dialogue"]:
prefix += f"Q: {turn[0]}" +"\n"
if turn[1] == "":
prefix += f"A:"
return prefix
else:
prefix += f"A: {turn[1]}" +"\n"
re... | andreamad8/FSB | prompts/coQA.py | coQA.py | py | 334 | python | en | code | 119 | github-code | 6 |
24692323834 | #Import libraries
import sys
import pandas as pd
from sqlalchemy import create_engine
def load_data(messages_filepath, categories_filepath):
'''
Function for loading disaster reponse messages_filepath
Arguments:
messages_filepath: File path to file containing disaster
... | Rmostert/Disaster-response-pipeline | data/process_data.py | process_data.py | py | 3,414 | python | en | code | 0 | github-code | 6 |
37340652783 | from input import Input
from word import Word
from data import Data
from display import Display as dp
from colorama import Fore
import numpy as np
# The Game Object
class LeWord:
# Only gets the mode,
def __init__(self, mode):
self.mode = mode
# The joker of a word is the count of vowels and con... | mburaozkan/LeWord-The-Word-Game | game.py | game.py | py | 14,751 | python | en | code | 2 | github-code | 6 |
39627693477 | # __author__ = "Chang Gao"
# __copyright__ = "Copyright 2018 to the author"
# __license__ = "Private"
# __version__ = "0.1.0"
# __maintainer__ = "Chang Gao"
# __email__ = "chang.gao@uzh.ch"
# __status__ = "Prototype"
import sys
import os
import torch as t
import torch.nn.functional as F
f... | SensorsINI/DeltaGRU-cartpole | modules/util.py | util.py | py | 10,645 | python | en | code | 0 | github-code | 6 |
7926234515 | import pandas as pd
import yfinance as yf
# Read the symbols from a CSV file
symbols_df = pd.read_csv("symbols.csv")
symbols = symbols_df["Symbol"].tolist()
# Specify the years
years = [2021, 2022]
# Create an empty list to store the dataframes for each stock
dfs = []
# Iterate over the symbols
for symbol in symbol... | kmlspktaa/data-analytics | economics/dividends-trading/development/dividend-stocks.py | dividend-stocks.py | py | 2,490 | python | en | code | 0 | github-code | 6 |
14374871985 | # coding=utf-8
"""Unit tests for activitypub.py."""
from base64 import b64encode
import copy
from datetime import datetime, timedelta
from hashlib import sha256
import logging
from unittest import skip
from unittest.mock import patch
from flask import g
from google.cloud import ndb
from granary import as2, microformat... | snarfed/bridgy-fed | tests/test_activitypub.py | test_activitypub.py | py | 76,984 | python | en | code | 219 | github-code | 6 |
16908443054 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import sys
import os
from os import path
import numpy as np
from PIL import Image
import datetime
import matplotlib.pyplot as plt
import time
sys.path.append(os.getcwd() + "/lib/wordcloud")
from wordcloud import WordCloud
text = "初鳩,初花,初... | PL2GroupJ/PyWordCloud | wc.py | wc.py | py | 5,758 | python | en | code | 0 | github-code | 6 |
35941373968 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Filters results from taxonomic classifiers and extracts taxonomic IDs for filtered hits"""
"""To do: Add argparse and logging"""
import os
import sys
import subprocess
import pandas as pd
def main():
# Input
classifier = sys.argv[1]
params = sys.argv[2]
... | Clinical-Genomics/Metoid | bin/extractReferences.py | extractReferences.py | py | 8,493 | python | en | code | 1 | github-code | 6 |
10422627143 | from __future__ import annotations
import asyncio
import dataclasses
import logging
import uuid
from typing import TYPE_CHECKING, Self
from PySide6.QtCore import QObject, Signal
from randovania.bitpacking.json_dataclass import JsonDataclass
from randovania.interface_common.players_configuration import INVALID_UUID
f... | randovania/randovania | randovania/interface_common/world_database.py | world_database.py | py | 4,141 | python | en | code | 165 | github-code | 6 |
5672514853 | def get_config():
import os
from board_game.states.gomoku_state import GomokuState
from .gomoku_dqn import GomokuDqnModel
board_shape = (9, 9)
target = 5
print('board_shape:', board_shape)
print('target:', target)
state = GomokuState(board_shape = board_shape, target = target)
mod... | lbingbing/machine-learning-board-game.old | board_game/players/dqn/gomoku_dqn_train.py | gomoku_dqn_train.py | py | 960 | python | en | code | 0 | github-code | 6 |
20824483233 | import inflect
def main():
p = inflect.engine()
names = []
while True:
try:
name = input("Name: ")
names.append(name)
except(EOFError, KeyboardInterrupt):
names = p.join(names)
print("Adieu, adieu, to " + names)
... | lauriwesterlund/CS50P | Solutions/adieu.py | adieu.py | py | 341 | python | en | code | 0 | github-code | 6 |
38259209826 | import cv2
#Configurable Parameters
inputValue = int(input("Enter the scale value to resize the image: (0 - 100): "))
if inputValue >= 0 and inputValue <= 100:
source = "wx.jpg"
destination = 'newImage.png'
scale_percent = inputValue
src = cv2.imread(source, cv2.IMREAD_UNCHANGED)
#cv2.imshow("tit... | sundaram-sharma/image-resizer-python | main.py | main.py | py | 715 | python | en | code | 0 | github-code | 6 |
22378324072 | from rest_framework.response import Response
from rest_framework.decorators import api_view
from .serializers import PersonSerializer
from .models import Person
from rest_framework import status
from rest_framework.permissions import IsAdminUser
from rest_framework.decorators import api_view, permission_classes
@api_... | sinajamshidi247/django_rest_framework | A/home/views.py | views.py | py | 1,392 | python | en | code | 0 | github-code | 6 |
301052917 | import yaml
import glob
import dropbox
import os
import sys
import time, threading
import RPi.GPIO as GPIO
import time
import pygame
import sentry_sdk
from sentry_sdk import start_transaction
def loadConfig(file):
with open(file, 'r') as stream:
config_dict = yaml.safe_load(stream)
return config_di... | soundtecas/elevator | elevator.py | elevator.py | py | 3,991 | python | en | code | 0 | github-code | 6 |
34338376065 | # -*- coding: utf-8 -*-
import contextlib
import json
import logging
import re
import starlette_werkzeug_debugger
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette.testclient import Te... | mireq/starlette-werkzeug-debugger | tests/test_debugger.py | test_debugger.py | py | 4,009 | python | en | code | 0 | github-code | 6 |
11313840170 | import numpy as np
from sklearn.preprocessing import LabelEncoder
import pandas as pd
import string
import tqdm
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
class preprocessing:
# Dimension adalah dimensi vektor embedding yang digunakan
... | dryantl/product-title-classification | preprocessing_pipeline.py | preprocessing_pipeline.py | py | 10,629 | python | id | code | 0 | github-code | 6 |
11066099241 | import os
import pandas as pd
import glob
root_dir = 'Data/MeasureBoundingBoxAnnotations'
directories = os.listdir(root_dir)
all_csv_files = []
for directory in directories:
file_path = root_dir + '/' + directory + '/'
all_csv_files += [i for i in glob.glob(file_path + '*.csv')]
combined_csv = pd.concat([p... | greyfertich/PDF-Player | merge_csv_files.py | merge_csv_files.py | py | 409 | python | en | code | 0 | github-code | 6 |
38610058452 | import subprocess
import re
import skia
import io
from platform import system
from pathlib import Path
from PIL import Image
from xml.etree import ElementTree as ET
from typing import Any, Tuple, Union, List
class SVG:
"""SVG class to load, edit, render, and export svg files using pillow and inkscape."""
i... | jlwoolf/pillow-svg | PILSVG/SVG.py | SVG.py | py | 20,691 | python | en | code | 0 | github-code | 6 |
29771382768 | import pandas as pd
import re
df = pd.read_csv('C:\\Users\\NAVEEN\\Documents\\school.xls')
for i in range(len(df)):
print(re.sub('[^A-Za-z0-9]+','',str(df.iloc[i,:1])))
print(df)
res= pd.DataFrame() | engineerscodes/PyVisionHUB | DATASET.py | DATASET.py | py | 208 | python | en | code | 4 | github-code | 6 |
24255674964 | from selenium import webdriver
import csv
import config
import time
class instaInfo:
def __init__(self):
"""
init webdriver
"""
self.driver = webdriver.Chrome('chromedriver')
self.profile_url = ''
self.followers_count = 0
self.ask_url()
def ask_url(self... | bfesiuk/InstagramInfo | info.py | info.py | py | 4,293 | python | en | code | 0 | github-code | 6 |
25127087011 | #!/usr/bin/env python
import random
from scapy.all import *
hwKali = "00:00:00:00:00:04"
hwGateway = "00:00:00:00:00:03"
hwVictim = "00:00:00:00:00:05"
broadcast = "ff:ff:ff:ff:ff:ff"
ipGateway = "10.10.111.1"
ipVictim = "10.10.111.101"
pG = Ether(src = hwKali, dst = broadcast)\
/ ARP(hwsrc = hwKali, hwdst = hw... | davidkim827/Network-Security | arpspoof.py | arpspoof.py | py | 574 | python | en | code | 0 | github-code | 6 |
72650165307 | def ID ():
IS = int(input("กรอกรหัสนักเรียน : "))
US = input("กรอกชื่อนักเรียน : ")
PS = float(input("กรอกเกรดเฉลี่ยของนักเรียน : "))
return IS , US , PS
def cal ( PS ):
if PS < 2:
NOPE = "ไม่ผ่าน"
else :
NOPE = "ผ่าน"
return NOPE
def show ( IS , US , PS , NOPE ):
print (... | HowToPlayMeow/WorkshopA | py13.py | py13.py | py | 853 | python | th | code | 0 | github-code | 6 |
36568700730 | # -*- coding: utf-8 -*-
from odoo import models, fields, api
from odoo import exceptions
from odoo.exceptions import ValidationError
import json
import datetime
import string
import requests
from datetime import date
import logging
_logger = logging.getLogger(__name__)
class hr_report(models.Model):
... | AMohamed389/airport4 | hr_extend_minds/models/hr_report.py | hr_report.py | py | 2,381 | python | en | code | 0 | github-code | 6 |
38146173334 | import unittest
import hashlib
from core import *
class StoneTest(unittest.TestCase):
def test_get_stone_report(self):
r = get_stone_report("20171026")
h = hashlib.sha1(r.encode('utf-8'))
hexrhash = h.hexdigest()
defaulth = "1d6ad2ea634514c7ef6225fd15c332cb52ed45fd"
self.as... | tocvieira/StonePagamentos | test_core.py | test_core.py | py | 922 | python | en | code | 0 | github-code | 6 |
74732375868 | import tensorflow as tf
def conv2d(x, kernel_shape, strides=1, relu=True, padding='SAME'):
W = tf.get_variable("weights", kernel_shape, initializer=tf.contrib.layers.xavier_initializer_conv2d(uniform=False))
tf.add_to_collection(tf.GraphKeys.WEIGHTS, W)
b = tf.get_variable("biases", kernel_shape[3], initi... | fabiotosi92/CCNN-Tensorflow | model/ops.py | ops.py | py | 981 | python | en | code | 22 | github-code | 6 |
31533542656 | airline_name = input()
number_tickets_adults = int(input())
number_tickets_kids = int(input())
net_price_ticket_adult = float(input())
tax_service = float(input())
net_price_ticket_kid = net_price_ticket_adult * 0.3
total_price_adult_tickets = (net_price_ticket_adult + tax_service) * number_tickets_adults
total_price_k... | iliyan-pigeon/Soft-uni-Courses | programming_basics_python/exams/exam_2020/agency_profit.py | agency_profit.py | py | 601 | python | en | code | 0 | github-code | 6 |
20968158774 | import math
from flask import Flask, render_template, request, jsonify
import pickle
import pandas as pd
import numpy as np
import mariadb
import jinja2
conn = mariadb.connect(
user="root",
password="root",
host="localhost",
database="pal_taqdeer")
cur = conn.cursor()
app = Flask(__name__)
@app.rout... | sondosaabed/PalTaqdeer | app.py | app.py | py | 2,489 | python | en | code | 5 | github-code | 6 |
25070989865 | import logging
from django.urls import path
from rest_framework import status
from rest_framework.response import Response
from rest_framework.request import Request
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from purplship.server.core.views.api import APIView
from purplship.server.pro... | danh91/purplship | server/modules/proxy/purplship/server/proxy/views/pickup.py | pickup.py | py | 3,927 | python | en | code | null | github-code | 6 |
6114242445 | import argparse
import gym
import numpy as np
from itertools import count
from collections import namedtuple
from functools import reduce
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Categorical
from tensorboardX import SummaryWriter
fr... | ltecot/emergence_properties | hebbian_learning/envs/cartpole.py | cartpole.py | py | 4,095 | python | en | code | 1 | github-code | 6 |
25785453821 | '''
the application of the matrix
'''
import xlrd
import matplotlib.pyplot as plt
from config import *
from model import Dmu
# plt.rcParams['text.usetex']=True
# # Place the command in the text.latex.preamble using rcParams
# plt.rcParams['text.latex.preamble']=r'\makeatletter \newcommand*{\rom}[1]{\bfseries\expandaft... | gaufung/CodeBase | PDA/matrix/app.py | app.py | py | 6,090 | python | en | code | 0 | github-code | 6 |
11437321996 | class student:
def __init__(self,name,age):
self.name=name
self.age=age
def get_age(self):
return self.age
def main():
student1=student("sham",20)
student2=student("andy",15)
print(student1.age)
del student1.age
# print(student.age)
print(student1.n... | sun9085/python | delete_object.py | delete_object.py | py | 387 | python | en | code | 0 | github-code | 6 |
12938444153 | from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from jeopardy.views import (
QuestionList,
QuestionById,
QuestionRandom,
PlayerList,
PlayerByName,
PlayerById,
PlayerQuestionById,
PlayerQuestionByName,
)
from rest_framework.urlpatterns import for... | ryanwholey/jeopardy_bot | trabek_bot/jeopardy/urls.py | urls.py | py | 982 | python | en | code | 1 | github-code | 6 |
26013197336 | from homeassistant.config_entries import ConfigEntry
from .const import (
PLATFORM,
PRESET_MODE_HOLIDAY,
PRESET_MODE_MANUAL,
PRESET_MODE_SCHEDULE_1,
PRESET_MODE_SCHEDULE_2,
PRESET_MODE_SCHEDULE_3,
PRESET_MODE_TEMP_OVERRIDE,
PRESET_MODE_ANTIFROST,
BAXI_PRESET_MANUAL,
BAXI_PRESET_S... | vipial1/BAXI_thermostat | custom_components/baxi_thermostat/helper.py | helper.py | py | 2,194 | python | en | code | 9 | github-code | 6 |
15521328462 | blocks = set()
with open("input", "r") as file:
for line in iter(file.readline, ''):
blocks.add(tuple(map(int, line.rstrip().split(','))))
covered = 0
for block in blocks:
for dir in [1, -1]:
if (block[0] + dir, block[1], block[2]) in blocks:
covered += 1
if (block[0], block[1] + dir, block[2]) in blocks:
... | probablyanasian/advent-of-code | 2022/18/b.py | b.py | py | 1,046 | python | en | code | 0 | github-code | 6 |
37971441649 | '''
Log Optional sensors to CouchDB
Called from /home/pi/MVP/scripts/LogMVP.sh - needs to be uncommented for this to run
Uncomment desired functions in makeEnvObsv
Author: Howard Webb
Date: 5/3/2019
'''
from LogUtil import Logger
from Persistence import Persistence
class LogSensorsExtra(object):
def __init__(sel... | webbhm/NerdFarm | MVP/python/LogSensorsExtra.py | LogSensorsExtra.py | py | 10,776 | python | en | code | 1 | github-code | 6 |
23713666857 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 7 22:16:45 2023
@author: EMILIANO
"""
import openpyxl
import pandas as pd
##Workbook va en mayusculas la primera
from openpyxl import Workbook
Excelworkbook=openpyxl.load_workbook("H:\Documentos\Practica Pyhton Bond Arg\Dataset bonos arg usd.xlsx")
Excelsheet=Excelwor... | emilapuente1/Practica-Pyhton-Bond-Arg | Bondarg.py | Bondarg.py | py | 1,510 | python | es | code | 0 | github-code | 6 |
41849719603 | from Engine import is_area_in_board
class Knight:
def __init__(self, color, pos):
self.pos = pos
self.color = color
self.val = 30 * self.color
self.image_id = self.create_image_id()
def create_image_id(self):
return 13 + self.color
def move(self, boar... | MaciejKrol51/chess | Knight.py | Knight.py | py | 1,692 | python | en | code | 0 | github-code | 6 |
3759720297 | from geometry import *
from ctypes import *
class TriangleMesh(Structure):
_fields_ = [('vNum',c_uint),('v',POINTER(Vector)),
('viNum',c_uint),('vi',POINTER(c_uint)),
('vnNum',c_uint),('vn',POINTER(Vector)),
('vni',POINTER(c_uint))]
def __init_... | millag/Loop-subdivision | SubdivisionSurfaces/shapes.py | shapes.py | py | 1,661 | python | en | code | 6 | github-code | 6 |
16484762613 | import pygame
import time
import random
pygame.init()
screensize = (200,200) # This is a Vector 2 Dimentional Object
screen = pygame.display.set_mode(screensize)
run = True
color = (250, 153, 0)
displacement = 0
x_pos = 200
x_pos_2 = 300
y_pos = 95
pipeno = 0
pipeno2 = 0
gamepipes = 10
loclist = []
for a in ra... | RinUnderscore/LSCC-Pygame-Lesson | main.py | main.py | py | 1,965 | python | en | code | 0 | github-code | 6 |
17646581677 | import boto3
from flask import Flask, request
import json
import os
app = Flask(__name__)
REGION = 'eu-north-1'
TESTING_URL = 'http://localhost:4566' # os.environ['LOCAL_TESTING']
TOPIC_ARN = 'arn:aws:sns:eu-north-1:000000000000:techtalk-sns'
@app.route('/')
def demo_homepage():
return "Welcome to Anusha`s LocalS... | anushacassum/mylocalstack | app.py | app.py | py | 1,458 | python | en | code | 0 | github-code | 6 |
19352162843 | # Enter your code here. Read input from STDIN. Print output to STDOUT
n = list(input().split(' '))
row= int(n[0])
col = int(n[1])
row1=True
spl_chr = '.|.'
spl_chr_num = 1
dash = '-'
num = 1
for r in range(1,(int((row-1)/2)+1)):
dash_num = int(col-(spl_chr_num*3))
print((dash)*int((dash_num)/2),end='')
for... | SomanshuMishra/HackerRank | Designer_Door_Mat.py | Designer_Door_Mat.py | py | 785 | python | en | code | 0 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.