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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
1271143615 | from sre_parse import State
import pandas as pd
from pomegranate import *
# Função que realiza o cálculo das probabilidades independetes
def calculaProbIndependente(lista_query, df):
lista_result = []
for query in lista_query:
lista_result.append(len(df.query(query).values) / len(df))
return li... | HudsonJunior/bayesana-network | main.py | main.py | py | 9,801 | python | pt | code | 0 | github-code | 1 |
27843426217 | # this program is to show that a number between 1 to 1000 can be guessed in 10 times or less
low = 1
high = 1000
print("Please think a number between {0} and {1}".format(low, high))
input("Please Enter to start")
guesses = 1
while low != high: # True:
# print("\tGuessing in the range of {} to {}".format(low,... | hkamra/Python | python-masterclass-udemy/ProgramFlow/hiLo.py | hiLo.py | py | 1,254 | python | en | code | 0 | github-code | 1 |
40772316728 | # 1.导包
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
# 2.创建浏览器驱动对象
driver = webdriver.Chrome()
# 3.打开测试网址打开注册A.html页面,完成以下操作
driver.get(
"file:///C:/Users/sandysong/Desktop/pagetest/%E6%B3%A8%E5%86%8CA.html")
# 4.业务操作
# 1).使用CSS定位方式中id选择器定位用户名输入框,并输入:admin
driver.find_elemen... | 1769778682/day03 | test_09_css_前4种.py | test_09_css_前4种.py | py | 1,063 | python | zh | code | 0 | github-code | 1 |
38604120141 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 12 11:47:11 2021
@author: Souparno
"""
import torch
#from transformers import AutoTokenizer, AutoModelWithLMHead
from transformers import T5Tokenizer, T5ForConditionalGeneration
from methodology_bs4 import *
#from correlated_words_0 import *
from summaryg... | Chattopadhyay-Souparno/Medical-Writing-Automation | main_file.py | main_file.py | py | 1,785 | python | en | code | 3 | github-code | 1 |
74532493792 | import random
from art import logo
from art import vs
from game_data import data
import os
# make this as function
# format the account data into printable format
# name = random_data['name']
# follower_count = random_data['follower_count']
# description = random_data['description']
# country = random_data['country']... | yong197578/high-and-low-game | main.py | main.py | py | 1,769 | python | en | code | 0 | github-code | 1 |
18332363530 | import json
from pathlib import Path
# Define the input and output paths
input_filepath = Path('./data/questions.json')
output_directory = Path('./data/qna')
# Expecting the questions.json with an array of { source, question, answer } pair tuples.
with open(input_filepath, 'r') as input_file:
input_json = json.lo... | CsabaConsulting/Vectara | augment_prep.py | augment_prep.py | py | 1,458 | python | en | code | 0 | github-code | 1 |
43649070052 | import matplotlib.pyplot as plt
import numpy as np
from scipy import misc
from math import sqrt
#--------------------------------------------------
# code0.py : Première définitions
#--------------------------------------------------
def u(x): # définition de la fonction u
return x**4
def grad1(f, x... | oungaounga/project21808112.github.io | AllCodesProjet1.py | AllCodesProjet1.py | py | 6,834 | python | fr | code | 0 | github-code | 1 |
30632337598 | import mapclient.splash_rc
from PySide6 import QtCore, QtGui, QtWidgets
class SplashScreen(QtWidgets.QSplashScreen):
def __init__(self):
super(SplashScreen, self).__init__()
pixmap = QtGui.QPixmap(":/mapclient/splash.png")
self.setPixmap(pixmap)
self._font = QtGui.QFont()
... | MusculoskeletalAtlasProject/mapclient | src/mapclient/splashscreen.py | splashscreen.py | py | 1,179 | python | en | code | 19 | github-code | 1 |
22290817065 | from collections import deque
class Solution:
def solve(self, nums):
# Write your code here
def bfs(index, memo):
visited = set([index])
queue = deque([(index, 0)])
best = 2 * len(nums)
while queue:
curr, length = queue.popleft()
... | dhrumilp15/Puzzles | binsearch/parity_jump_memo.py | parity_jump_memo.py | py | 2,701 | python | en | code | 0 | github-code | 1 |
2969017734 | #!/usr/bin/env python
# encoding: utf-8
from waflib.Build import BuildContext
import os,re
APPNAME = 'property.exe'
LIBNAME = 'property'
VERSION = '0.0.1'
top = '.'
out = 'BUILD'
def options(ctx):
ctx.load('compiler_cxx')
ctx.add_option('--clang_uses_ext_stdlib', dest = 'clang_uses_ext_stdlib', help... | o2gy84/libproperty | src/wscript | wscript | 1,889 | python | en | code | 0 | github-code | 1 | |
5432987697 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : segfiles.py
# @Author: wangweimin
# @Date : 17-11-8
# @Desc :
import train.util as util
import train.const as const
"""
输入:src源文件夹,dst目标文件夹,num分成的分数
功能:将给定的源文件夹src中的文件,分成num份,放入dst文件夹中。
备注:dst文件夹中,会出现文件夹1,文件夹2,...,文件夹n。其中,n=num
"""
def run(srcpath, dstpath, nu... | justwangweimin/tr | train/segfiles.py | segfiles.py | py | 1,020 | python | zh | code | 0 | github-code | 1 |
71975299873 | import sys
from PySide6.QtCore import *
from PySide6.QtGui import *
from PySide6.QtWidgets import *
"""
要求:
总共输入5位 左边2(必须是大写字母) - 右边2(必须是数字)
"""
app = QApplication(sys.argv)
window = QWidget()
window.setWindowTitle("QLineEdit-验证器-掩码")
window.resize(500, 500)
window.move(400, 250)
le_a = QLineEdit(window)
le_a.mo... | ESdove/PySide6_Demo | 10-QLineEdit/10-QLineEdit-验证器-掩码.py | 10-QLineEdit-验证器-掩码.py | py | 581 | python | zh | code | 6 | github-code | 1 |
30002086737 | import numpy as np
from torch import nn
from xavier.constants.type import Type
from xavier.core.transformation import get_standard
class Rnn(nn.Module):
NAME_TYPE = Type.rnn
def __init__(self, device=None):
super(Rnn, self).__init__()
self.output_layer = 3
self.device = device
... | fabriciotorquato/pyxaiver-v2 | xavier/net/rnn.py | rnn.py | py | 870 | python | en | code | 1 | github-code | 1 |
27841424849 | from flask import (
Blueprint, flash, g, redirect, render_template, request, url_for, Flask
)
#from werkzeug.exceptions import abort
#from flask_login import current_user, login_user, logout_user, login_required
bp = Blueprint('home', __name__)
@bp.route('/')
@bp.route('/home')
def index():
return ... | snickr42/cookbook | cookr/home.py | home.py | py | 365 | python | en | code | 0 | github-code | 1 |
3216126423 | from app.models.visita_tecnica_model import VisitaTecnicaModel
from app.models.usuario_model import UsuarioModel
from app.models.visita_tecnica_tecnico_model import VisitaTecnicaTecnicoModel
from app.exc import DataNotFound
class VisitaTecnicaTecnicoService:
@staticmethod
def relate_visita_tecnico_list(visit... | lucianofeder/fibraville-backend | app/services/visita_tecnica_tecnico_service.py | visita_tecnica_tecnico_service.py | py | 1,438 | python | it | code | 4 | github-code | 1 |
72499398113 | from sqlalchemy import insert, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.crud.base import CRUDBase, DatabaseModel
from app.models import Question
class CRUDQuesttion(CRUDBase):
"""Класс для работы с моделью Question."""
async def get_previous_object(
self,
sessi... | SergoSolo/quiz_questions | app/crud/question.py | question.py | py | 1,245 | python | en | code | 0 | github-code | 1 |
8556882106 | from .settings import DATABASE, PATH
import glob
import os
import pandas as pd
import sqlalchemy as sqla
import argparse
from argparse import RawDescriptionHelpFormatter
dataset_id = {
'srag': 1,
'sragflu': 2,
'obitoflu': 3,
'sragcovid': 4,
'obitocovid': 5,
'obito': 6
}
# ### 1.2 Scale
scale... | FluVigilanciaBR/seasonality | methods/data_filter/migration.py | migration.py | py | 19,644 | python | en | code | 1 | github-code | 1 |
29845106401 | from fastapi import APIRouter, Form, UploadFile, File
from router.chart.upload_s3 import upload_s3
from database.db import save_chart_info
from PIL import Image
from pydub import AudioSegment
import io
import os
import random, string
import datetime
import hashlib
import json
import requests
with open("... | Kyonkrnk/ymfan | router/chart/upload.py | upload.py | py | 3,799 | python | en | code | 1 | github-code | 1 |
70839184993 | N, d, k, c = map(int, input().split())
sushi = []
for _ in range(N):
sushi.append(int(input()))
maxV = 0
for i in range(N-k+1):
temp = sushi[i:i+k]
temp.append(c)
temp = set(temp)
maxV = max(maxV, len(temp))
for i in range(N-k+1, N):
temp = sushi[i:i+k] + sushi[:i-N+k]
temp.append(c)
... | ckdfh0917/Algorithm | 백준/문제/2531. 회전 초밥.py | 2531. 회전 초밥.py | py | 383 | python | en | code | 0 | github-code | 1 |
74879021154 | import requests
from bs4 import BeautifulSoup
import pandas as pd
import os
base = 'http://mit.spbau.ru'
r = requests.get(base+'/students/se')
html = r.text
soup = BeautifulSoup(html, 'html.parser')
names = []
images = []
hrefs = []
for div in soup.find_all('div', {'class': 'field-content alumni-userpic'}):
for... | Forsenlol/SE_hi | data/scripts_for_parsing/au_alumni.py | au_alumni.py | py | 2,383 | python | en | code | 0 | github-code | 1 |
5441160098 | from socket import *
import threading
port = 10000
server_socket = socket(AF_INET, SOCK_STREAM) ## socket definition
server_socket.bind(('', port)) ## server port = 10000
server_socket.listen(5) ## max client socket = 5
user_list = {} ## chat user dic
... | tlfxk1gkrl/pythonChatServer | main.py | main.py | py | 1,884 | python | en | code | 0 | github-code | 1 |
6420744938 | import math
import gym
from Acrobot_DQN import Acrobot_DQN
from Acrobot_Game import Acrobot_Game
env = gym.make("Acrobot-v1")
min_len4train = 100
max_len4train = 50_000
DISCOUNT = 0.90
min_batch = 64
Batch_Size = 32
SHOW_EVERY = 200
UPDATE_SECONDARY_WEIGHTS = False
UPDATE_SECONDARY_WEIGHTS_NUM = 4
... | Soester10/DRL-Gym-Env | Acrobot/main.py | main.py | py | 810 | python | en | code | 0 | github-code | 1 |
41973668035 | from musikla.parser.printer import CodePrinter
from typing import Any, Optional, Tuple, List
from .statement_node import StatementNode
from ..node import Node
from musikla.core import Value, Context
class MultiVariableDeclarationStatementNode( StatementNode ):
def __init__ ( self, left : List[Node], right : Node, ... | pedromsilvapt/miei-dissertation | code/musikla/musikla/parser/abstract_syntax_tree/statements/multi_var_declaration_node.py | multi_var_declaration_node.py | py | 2,354 | python | en | code | 0 | github-code | 1 |
43707222394 | import re
import nltk.tokenize
from six import text_type
from cakechat.utils.text_processing.config import SPECIAL_TOKENS
_END_CHARS = '.?!'
_tokenizer = nltk.tokenize.RegexpTokenizer(pattern=u'\w+|[^\w\s]')
def get_tokens_sequence(text, lower=True, check_unicode=True):
if check_unicode and not isinstance(tex... | e11co/Astromind | Astrobaby-chat/cakechat/utils/text_processing/str_processor.py | str_processor.py | py | 1,777 | python | en | code | 2 | github-code | 1 |
11111319634 | from apikeys import key_geocoder
import requests
import json
def get_ll_by_name(name, pt=False):
name = ''.join(name.split())
req = f"http://geocode-maps.yandex.ru/1.x/?apikey={key_geocoder}&geocode={name}&size=650,450&format=json"
response = requests.get(req)
# with open('response.json', 'w') as json... | ecol-master/Hackaton_AI | yandex_map/maps/geocoder.py | geocoder.py | py | 3,846 | python | en | code | 0 | github-code | 1 |
38657153583 | import sys
from datetime import datetime
from typing import Collection, Dict, Tuple, List, Optional
if sys.version_info >= (3, 8):
from typing import TypedDict
else:
from typing_extensions import TypedDict
MAX_DATA_ROW_IDS_PER_EXPORT_V2 = 2_000
class SharedExportFilters(TypedDict):
label_created_at: Op... | nicole-kozhuharova/bachelorArbeit | venv/Lib/site-packages/labelbox/schema/export_filters.py | export_filters.py | py | 5,201 | python | en | code | 0 | github-code | 1 |
11747480348 |
from . import blueprint
from .settings import SettingClass
from .forms import SettingsForm
from flask import request, current_app
from .error import FormNotFound
@blueprint.get('/')
def ping():
return 'ping'
@blueprint.post('/s/<setting_key>/set')
def set_value(setting_key):
setting: SettingClass = SettingC... | LordBex/flask-settings | flasky_settings/main.py | main.py | py | 920 | python | en | code | 0 | github-code | 1 |
74071987872 | import numpy.fft as fft
import numpy as np
import math
class Frame:
_start_frequency = 20.
_end_frequency = 20000.
_mel_count = 15
wave = []
start_time = 0
duration = 0
framerate = 0
spectre = None
frequencies = None
phonemes = []
phoneme = None
def __init__(self, wave... | evgenijkatunov/autolipsync | Entities/Frame.py | Frame.py | py | 3,410 | python | en | code | 2 | github-code | 1 |
34694646391 |
import asyncio
import xml.etree.ElementTree as ET
from os import listdir, path
import json
import requests
import pynetbox
import json
from multiprocessing.dummy import Pool
from netaddr import IPAddress
import logging
import os
import filecmp
import re
import sys
import shutil
import time
from netmik... | AlexandrePoix/Projet_Netbox | Script_Netbox.py | Script_Netbox.py | py | 39,789 | python | en | code | 0 | github-code | 1 |
71015523235 | # Title: 진법 변환 2
# Link: https://www.acmicpc.net/problem/11005
import sys
import string
sys.setrecursionlimit(10 ** 6)
read_list_int = lambda: list(map(int, sys.stdin.readline().strip().split(' ')))
nums = [str(i) for i in range(10)] + list(string.ascii_uppercase)
def solution(n: int, b: int):
ans = []
d ... | yskang/AlgorithmPractice | baekjoon/python/change_base_2_11005.py | change_base_2_11005.py | py | 570 | python | en | code | 1 | github-code | 1 |
43732887683 | from collections import deque
import sys
input = sys.stdin.readline
R = []
for _ in range(int(input())):
REV = False
ERR = False
F = input().strip()
N = input()
L = list(input().replace(
"[", "").replace("]", "").strip().split(","))
if L == [""]:
L = []
D = deque(L)
... | pokycookie/BAEKJOON | 5430.py | 5430.py | py | 927 | python | en | code | 0 | github-code | 1 |
19015658590 | from typing import Any
import openai
import os
OPEN_AI_KEY: str | None = os.environ.get("OPENAI_API_KEY")
if not OPEN_AI_KEY:
raise ValueError("Missing OPENAI_API_KEY env variable")
openai.api_key = OPEN_AI_KEY
def get_chat_completion(
user_message: str, model="gpt-3.5-turbo", max_tokens=500, temperature=0... | jakecyr/sms-gpt | sms_gpt/open_ai_client.py | open_ai_client.py | py | 1,084 | python | en | code | 1 | github-code | 1 |
39496901551 | def gcd(a,b):
while b != 0:
a,b = b,a%b
return a
lcm = (1*2)//gcd(1,2)
for n in range(3,21):
lcm = (lcm*n)//gcd(lcm,n)
print(lcm) | yundaehyuck/Python_Algorithm_Note | projecteuler/5.py | 5.py | py | 176 | python | en | code | 0 | github-code | 1 |
44403192728 | import time
import math
import paho.mqtt.client as mqtt
import threading
import ai
# PLAYER VARIABLES
player_x = 13
player_y = 13
target = (6,11)
secondary_target = ()
player_heading = "N"
player_view_radius = 10
a2a = 0
a2g = 0
bombs = 0
countermeasures = 0
fuel = 100
missle_warning = False
#static map data to store... | eolivier8268/cs110-pex | simulation.py | simulation.py | py | 10,595 | python | en | code | 0 | github-code | 1 |
34855295881 | #!/usr/bin/env python3
#y1, y2 = (-10,-5)
#x1, x2 = (20,30)
y1, y2 = (-86,-59)
x1, x2 = (209,238)
bestMaxY = 0
cnt = 0
for vx in range(x2+1):
for vy in range(y1, 500):
start = (0,0)
maxY = 0
tvX, tvY = (vx,vy)
while start[0] <= x2 and start[1] >= y1:
maxY = max(maxY, st... | vanjo9800/AdventOfCode2021 | 17/missle.py | missle.py | py | 755 | python | en | code | 1 | github-code | 1 |
74736843234 | from unittest.mock import Mock
import datetime
import pytest
from pytest_lazyfixture import lazy_fixture
from boxsdk.util import datetime_formatter
@pytest.mark.parametrize(
"valid_datetime_format",
(
"2035-03-04T10:14:24+14:00",
"2035-03-04T10:14:24-04:00",
lazy_fixture("mock_datet... | box/box-python-sdk | test/unit/util/test_datetime_formatter.py | test_datetime_formatter.py | py | 2,309 | python | en | code | 395 | github-code | 1 |
70007701475 | import collections
from collections import Counter, defaultdict
import numpy as np
import jsonlines
import os
import re
from typing import *
import torch
from torch import nn
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
torch.manual_seed(1792507)
from model import Model
# PRE-TRAINED EMBE... | lello5/university-projects | Master degree/Natural Language Processing/HW1/hw1/stud/implementation.py | implementation.py | py | 5,750 | python | en | code | 8 | github-code | 1 |
9348818010 | import unittest
from app import app
class PostTestCase(unittest.TestCase):
# Ensure that ping sends back correct json data
def test_ping_json(self):
tester = app.test_client(self)
response = tester.get('/api/ping')
self.assertEqual(response.get_json(), {'success': True})
# Ensure... | johnlgtmchung/flask_api_practice | test.py | test.py | py | 2,855 | python | en | code | 0 | github-code | 1 |
35847125868 | import ast
import asyncio
import time
import traceback
import rank_calc
from data_base import DataBase
from datetime import datetime
class LeaderboardsCollector:
def __init__(self, main_collector) -> None:
self.main_collector = main_collector
self.vime = main_collector.vime_archive.vime
se... | FalmerF/VimeArchive | collector/leaderboards_collector.py | leaderboards_collector.py | py | 9,211 | python | en | code | 1 | github-code | 1 |
20203802088 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
currNode = r... | Birook2023/A2SV--Group-4A-Progress | Search in a Binary Search Tree.py | Search in a Binary Search Tree.py | py | 586 | python | en | code | 0 | github-code | 1 |
23985904341 | import hashlib
import math
import os
import re
import tkinter
import tkinter as tk
from tkinter import messagebox, filedialog
import threading
import pymysql
import tkinter as tk
from tkinter import ttk
import pandas as pd
from tkinter import filedialog
from openpyxl import Workbook
from tkinter import simpledialog
fro... | yahayaha001/mysql-table | app.py | app.py | py | 42,009 | python | en | code | 0 | github-code | 1 |
20421083972 | from itertools import combinations
st=int(input())
c=int(input())
arr=[]
for x in range(0,c):
arr.append(input().split())
arr2=[]
for y in range(0,len(arr)):
arr[y]=[int(x) for x in arr[y]]
for x in range(0,len(arr)):
cnt=arr[x][0]
for y in range(0,len(arr)):
if arr[y][0]==cnt:
if ar... | goltong1/NYPC | NYPC/2018/NYPC 08.py | NYPC 08.py | py | 1,058 | python | en | code | 1 | github-code | 1 |
18621907063 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: targetstree_service.py
from requests import Session
import xml.etree.ElementTree as ET
import json
import multiprocessing
from joblib import Parallel, delayed
from ..tools import (xmltools, log)
from outpost24hiabclient.clients.hiabclient import HiabCli... | schubergphilis/outpost24hiabclient | outpost24hiabclient/services/target_service.py | target_service.py | py | 10,384 | python | en | code | 2 | github-code | 1 |
31445849910 | import ast
import json
import re
from pathlib import Path
import numpy as np
import pandas as pd
from tqdm import tqdm
from src.constants import DATA_PATH # noqa: I900
def get_hashtags(caption):
if isinstance(caption, str):
return re.findall("#[a-z0-9_]+", caption)
return []
def get_mentions(cap... | Stardust87/VIP | scripts/extract_metadata.py | extract_metadata.py | py | 3,268 | python | en | code | 0 | github-code | 1 |
36044561026 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 19 09:02:24 2020
@author: user
"""
import cv2
import numpy
cap=cv2.VideoCapture(0)
face_cascade=cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
facedata=[]
while True:
ret,frame=cap.read()
if ret==False:
continue
cv2.imshow(... | himanshisehgal19/Face-Detection-OpenCV- | imagecapture.py | imagecapture.py | py | 1,259 | python | en | code | 1 | github-code | 1 |
25009064577 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def initialize_weight(x):
nn.init.xavier_uniform_(x.weight)
if x.bias is not None:
nn.init.constant_(x.bias, 0)
class MultiHeadAttentio... | zxh0916/WeeklyPaper | Week5-Transformer/module.py | module.py | py | 9,868 | python | en | code | 4 | github-code | 1 |
12194813975 | # Import necessary modules
import nextcord # Library for building Discord bots
from nextcord.ext import commands # Additional classes for command handling
from nextcord import SlashOption # Specific class for creating slash command options
import openai # OpenAI's Python library, used to interact with the GPT-3 API... | CryptoAutistic80/Nextcord-Cog-Bot | retired cogs/paint.py | paint.py | py | 9,970 | python | en | code | 1 | github-code | 1 |
24849378108 | import requests
import csv
url = "https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/ja.wikipedia.org/all-access/all-agents/%E9%AC%BC%E6%BB%85%E3%81%AE%E5%88%83/daily/20200601/20200630"
headers = {"User-Agent": "smatsuda@x-hack.jp"}
r = requests.get(url, headers=headers)
data_file = open('data_file.csv... | xhackjp1/python-scraping | 0623/scraping-pageview.py | scraping-pageview.py | py | 453 | python | en | code | null | github-code | 1 |
39674272083 | #!/usr/bin/python
"""
Dirty script which provides some (not well maintained) functions for plotting
data.
"""
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import logging
from matplotlib.patches import Polygon, Circle
def shoot(lon,... | Humpheh/twied | scripts/examples/polyplotter.py | polyplotter.py | py | 7,684 | python | en | code | 11 | github-code | 1 |
14619951113 | import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output
from importlib import reload
from mysql.connector.errors import OperationalError
from app.app import app
from app.datasources import laudos
from app.apps... | IvanBrasilico/laudos_dash | app/apps/app2.py | app2.py | py | 1,945 | python | en | code | 0 | github-code | 1 |
13210926327 | import numpy as np
from math import sqrt
from matplotlib.pyplot import *
from matplotlib import animation
k1 = 0.6
k2 = 0.7
w1 = sqrt(k1 + 1)
w2 = sqrt(k2 + 1)
def wave(x,t):
return np.sin(x*k1 - w1*t) + np.sin(x*k2 - w2*t)
T = 20
dt = 1/60.
t = 0
nt = int(T/dt)
nx = 1001
x = np.linspace(0,100,1001)
all_waves = ... | simehaa/University | fys2140/oblig3_a.py | oblig3_a.py | py | 698 | python | en | code | 0 | github-code | 1 |
28905884657 | import csv
from datetime import datetime, date
from dateutil import parser
import os
import pytz
from app import db
from app.utils.editdiff import EditDiff, ChangedValue, ChangedRow
import logging
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.inspection import inspect
from sqlalchemy.orm import cl... | COVID19Tracking/covid-publishing-api | app/models/data.py | data.py | py | 17,043 | python | en | code | 9 | github-code | 1 |
27652958158 | from sample_page import sample
from bs4 import BeautifulSoup
import urllib.request
import time
import os
import sys
from html_writer import TEMPLATE, ROW_TEMPLATE
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
print(SCRIPT_DIR)
PROJECT_ROOT = os.path.normpath(SCRIPT_DIR + os.sep + os.pardir)
print... | Mailman366/GIT_Repository | Projects/Price_Scraper/python/scratch.py | scratch.py | py | 2,445 | python | en | code | 0 | github-code | 1 |
4851043857 | from __future__ import absolute_import, division
from .transcript import Transcript
from scout.constants import (CONSEQUENCE, FEATURE_TYPES, SO_TERM_KEYS)
gene = dict(
# The hgnc gene id
hgnc_id = int, # required
hgnc_symbol = str,
# A list of Transcript objects
transcripts = list, # list of <tran... | gitter-badger/scout | scout/models/variant/gene.py | gene.py | py | 790 | python | en | code | null | github-code | 1 |
11828029614 | def bfs(node):
if node is None:
return
queue = []
#nodeSet = set()
queue.insert(0,node)
#nodeSet.add(node)
while queue:
cur = queue.pop() # 弹出元素
print(cur.val) # 打印元素值
for next in cur.nexts: # 遍历元素的邻接节点
#if next no... | zhangliukun/data-structure | src/newcode/example.py | example.py | py | 1,494 | python | en | code | 2 | github-code | 1 |
32038833506 | from operator import add
from typing import List, Tuple
FILE_NAME = 'input8.in'
rope = [[0, 0] for _ in range(11)] #0 -> head, 1 -> part1, 9 -> part2
dirs = {"R": [0, 1], "L": [0, -1], "U": [-1, 0], "D": [1, 0]}
def sign_value(value: int) -> int:
return (value > 0) - (value < 0)
def get_diffs(h... | Jozkings/advent-of-code-2022 | 9.py | 9.py | py | 1,311 | python | en | code | 0 | github-code | 1 |
9512999564 | # -*- coding: utf-8 -*-
# Coded By Kuduxaaa
import json, requests
from flask import request
from flask_restful import Resource
from app.service import PriceCalculator
predictor = PriceCalculator()
# This is example API Resource
class PricePrediction(Resource):
def get(self):
"""
Route get method... | Kuduxaaa/fintech | app/api/price.py | price.py | py | 2,667 | python | en | code | 2 | github-code | 1 |
33815489831 | class Hero:
def __init__(self,name,health,attachPower,armor):
#private
self.__name = name
self.__health = health
self.__attachPower = attachPower
self.__armor = armor
#cara untuk mendapatkan variable private, dengan trik membuat methode baru seperti dibawah ini getInfoHe... | irfansantoso/Belajar-Python-Basic | BelajarOOP/encapsulasi.py | encapsulasi.py | py | 718 | python | en | code | 0 | github-code | 1 |
27320167414 | import random as R
class net:
def __init__(self, gs, ikns, okns, skns):
self.gs = gs
self.ikns = ikns
self.okns = okns
self.skns = skns
self.kat = 0.072
self.oks = 0.06
self.bias = 2 * 10**(-2)
self.bir = [[R.random() for a in xrange(self.gs)] for b in xrange(self.ikns)]
self.iki = [[R.random() for ... | MucahitSaratar/3_katmanli_sinir_agi | uc.py | uc.py | py | 1,687 | python | en | code | 0 | github-code | 1 |
11737215383 | """new fields p in project model
Revision ID: dd4e694b3acf
Revises: 966b658403b2
Create Date: 2018-08-09 13:10:41.624416
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'dd4e694b3acf'
down_revision = '966b658403b2'
branch_labels = None
depends_on = None
def u... | johndoe-dev/Ecodroid | migrations/versions/dd4e694b3acf_new_fields_p_in_project_model.py | dd4e694b3acf_new_fields_p_in_project_model.py | py | 675 | python | en | code | 0 | github-code | 1 |
8489624117 | from __future__ import division, print_function, absolute_import
import os
import numpy as np
import pygame
from highway_env.road.graphics import WorldSurface, RoadGraphics
from highway_env.vehicle.graphics import VehicleGraphics
CONTROL = {
"throttle": 0,
"brake": 0.,
"steering": 0
}
ControlledVehicle_... | jasonplato/Highway_SimulationPlatform | highway_env/envs/graphics.py | graphics.py | py | 7,307 | python | en | code | 0 | github-code | 1 |
6445310024 | from PyQt5 import QtWidgets, QtGui, uic
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QFileDialog, QTableWidgetItem
from PyQt5.QtSql import QSqlTableModel
from datetime import datetime
from . import utils
class ImportDialog(QtWidgets.QDialog):
def __init__(self, parent):
super(ImportDialog, self... | willnode/Arsipin | src/importDialog.py | importDialog.py | py | 4,887 | python | en | code | 0 | github-code | 1 |
8761905914 | from Device import Device
from datetime import datetime
#import RPi.GPIO as GPIO
class Led(Device):
status = None
laststatuschange = None
GPIO = None
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
Device.__init__(self)
self... | flipsee/rpicenter | sandbox/internal_recipe/Led.py | Led.py | py | 1,458 | python | en | code | 0 | github-code | 1 |
20448987511 | import json
from random import Random
from config_data import seed, armies_config
from strategy import choose_squad
from army import Army
R = Random(seed)
class Battlefield:
def __init__(self, log_type, file=None):
self.armies = [Army(army["id"], army["chosen_strategy"])
for army ... | QueVege/Task-3 | battlefield.py | battlefield.py | py | 3,225 | python | en | code | 0 | github-code | 1 |
12578117452 | #!/usr/bin/env python3
import math, os.path
import sys
import argparse
from toolbox import *
from toolbox.files import file_groups
def main():
parser = argparse.ArgumentParser(
description="Tidy a folder by moving groups of similar files into separate sub-folders",
)
parser.add_argument(
... | michaelgale/toolbox-py | toolbox/scripts/tidyfolder.py | tidyfolder.py | py | 1,871 | python | en | code | 2 | github-code | 1 |
41978714472 | import struct
from MemoryManager import *
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.Util.Padding import unpad
TOTAL_LEN_WITHOUT_PAYLOAD = 23
FILE_NAME_LEN = 255
FILE_PREFIX_LEN = FILE_NAME_LEN + 4 + ID_SIZE
IV_LEN = 16
BLOCK_SIZE ... | Naveh1/SecuredFileTransfer | Server/RequestProcessor.py | RequestProcessor.py | py | 5,402 | python | en | code | 0 | github-code | 1 |
36999949572 | import numpy as np
import datasets.utils.image_utils as image_utils
image_shape = (36546, 63245, 3)
img = np.zeros(image_shape,dtype=np.uint8)
upsampling_factor = 4
patch_size = (256*2**upsampling_factor,256*2**upsampling_factor,3)
patch = image_utils.compute_patch_indices(image_shape=image_shape, patch_size=patch_si... | vuhoangminh/vqa_medical | tests/test_image_utils.py | test_image_utils.py | py | 529 | python | en | code | 7 | github-code | 1 |
22865648549 | import pytest
from src.app import create_app, DB
from src.app import create_app
from src.app.routes import routes
from flask import json
from sqlalchemy import event
mimetype = 'application/json'
headers = {
'Content-Type': mimetype,
'Accept': mimetype
}
@pytest.fixture(scope="session")
def app():
# Esta... | juliasilvamoura/DEVinHousa-conectaNuvem | Modulo3/Modulo3-Flask/tests/conftest.py | conftest.py | py | 1,713 | python | pt | code | 0 | github-code | 1 |
52681042 | with open(path) as f:
line = f.readline()
while line:
print(line)
line= f.readline()
def deal_txt(path):
file_object= open(path)
file_content =file_object.read()
file_split = file_content.splitlines()
print(file_split[0])
| liuhao940826/python-demo | ReadPython.py | ReadPython.py | py | 267 | python | en | code | 0 | github-code | 1 |
26714078036 | import os
import numpy as np
import keras
from keras.engine.topology import Layer
from keras.models import Model
from keras.layers import Input, Flatten, Dense, Lambda, Reshape, Concatenate
from keras.layers import Activation, LeakyReLU, ELU
from keras.layers import Conv2D, Conv2DTranspose, UpSampling2D, BatchNormaliz... | tatsy/keras-generative | models/cvaegan.py | cvaegan.py | py | 12,613 | python | en | code | 123 | github-code | 1 |
4199959125 | from collections import deque
def solution(n, edge):
answer = 0
# 연결된 노드 정보 그래프
graph =[[] for _ in range(n+1)]
# 각 노드의 최단거리 리스트
distance = [-1] * (n+1)
# 연결된 노드 정보 추가 - 양방향
for e in edge :
graph[e[0]].append(e[1])
graph[e[1]].append(e[0])
q = deque(... | hyeonwook98/Algorithm | Programmers/가장 먼 노드.py | 가장 먼 노드.py | py | 683 | python | ko | code | 0 | github-code | 1 |
40372539590 | from bs4 import BeautifulSoup
with open("indexTwo.html", "r") as f:
document = BeautifulSoup(f, "html.parser")
tags = document.find_all('input', type="text")
for tag in tags:
tag['placeholder'] = "I Love to change things :)"
with open('change.html', 'w') as f:
f.write(str(document))
| Vselenis/Python-Advanced-April-2021 | Web Scraping Project/demo/partTwo.py | partTwo.py | py | 299 | python | en | code | 0 | github-code | 1 |
44386347942 | #
# @lc app=leetcode.cn id=1 lang=python3
#
# [1] 两数之和
#
# @lc code=start
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
target_index = []
for i in range(0, len(nums)):
target_num = target - nums[i]
for j in range(i+1, len(nums)):
... | SmallSky7/PythonTest | leetcode/1.两数之和.py | 1.两数之和.py | py | 486 | python | en | code | 0 | github-code | 1 |
39376438148 | class Human:
name = ''
age = 0
sex = ''
def __str__(self):
return self.name + ' ' + self.sex + ' ' + str(self.age)
if __name__ == '__main__':
h = Human()
h.name = 'Edward'
h.sex = '男'
h.age = 27
print(h.name, h.sex, h.age)
print(h)
| NaiNew/yzu_python1 | lesson07/OO_1.py | OO_1.py | py | 284 | python | en | code | 0 | github-code | 1 |
24218220896 | import requests
from bs4 import BeautifulSoup
from tabulate import tabulate
header = {
"user-agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0'
}
def get_ipl_table():
page = requests.get(
f"https://www.sportskeeda.com/go/ipl/points-table", headers=header)
sou... | Harsh1347/FootBot-DiscordBot | ipl.py | ipl.py | py | 2,388 | python | en | code | 1 | github-code | 1 |
70335835234 | def find_path(pyramid, target):
def dfs(row, col, path, product):
if row == len(pyramid):
if product == target:
return path
return None
left_path = dfs(row + 1, col, path + "L", product * pyramid[row][col])
right_path = dfs(row + 1, co... | jayashankar2357/SampleTest | TestPython.py | TestPython.py | py | 1,012 | python | en | code | 0 | github-code | 1 |
38066104095 | class Solution:
def longestPalindrome(self, s: str) -> str:
# a b a a b b
# a 1 1 3 [0, 3]: check [0+1, 3-1]
# b 0 1 1
# a 0 1 2
# a 0 ... 1 1
# b 0 1 2
# b 0 ... ... 1
cache = {} # substr: palindrome
def find_palindrome(start... | HongyuHe/leetcode-new-round | dp/5_topdown_timeout.py | 5_topdown_timeout.py | py | 1,550 | python | en | code | 6 | github-code | 1 |
12668151670 | import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
image = cv.imread("example.jpg") #change path for your image
for i in range (0, image.shape[0]):
for j in range (0, image.shape[1]):
pixel = 255 - 1 -image[i][j]
image[i][j] = pixel
cv.imwrite('image.png',imag... | rafaelcbpy/ProcessImage-VisionCompute | filters/Negative_Filter.py | Negative_Filter.py | py | 434 | python | en | code | 1 | github-code | 1 |
34885760215 | import os
import imageio
import atexit
import math
from multiprocessing import Process, Queue
from gym.spaces import Box
from gym import utils
from gym.utils import seeding
import numpy as np
import mujoco_py
class PushObjectEnv(utils.EzPickle):
def __init__(self, frame_skip, max_timestep=3000, log_dir='', seed=... | keven425/robot-learn | rl/environment/push_object.py | push_object.py | py | 15,646 | python | en | code | 0 | github-code | 1 |
34999124884 | # -*- coding: UTF-8 -*-
import template.leetcode as leetcode_template
import template.question as question_template
import resource.table as table_template
import resource.datasource as ddl
def fetch_all_problems():
table_template.normal(ddl.QUESTION_DROP)
table_template.normal(ddl.QUESTION_CREATE)
for d... | KochamCie/LeetCodeNote | core/problems.py | problems.py | py | 714 | python | en | code | 7 | github-code | 1 |
43047803864 | # !/usr/bin/env python
# coding: utf-8
import json
import elasticsearch
from elasticsearch.exceptions import NotFoundError
import uuid
from wildzh.utils.config import ConfigLoader
__author__ = 'zhouhenglc'
class ExamEs(object):
def __init__(self, es_conf):
cl = ConfigLoader(es_conf)
host = cl.g... | meisanggou/wildzh | wildzh/classes/exam_es.py | exam_es.py | py | 5,345 | python | en | code | 0 | github-code | 1 |
35096521634 | import os, sys, time
import requests
DEST_DIR = '.\\imgs'
def show(data):
print(data, end=' ')
sys.stdout.flush()
def save_file(img, filename):
path = os.path.join(DEST_DIR, filename)
with open(path, 'wb') as fp:
fp.write(img)
def download(url):
# print(f'downloading {url}')
resp = ... | Kiruen/kiruen_funbox | python_playground/fluent_python/future_demo/downloader_base.py | downloader_base.py | py | 935 | python | en | code | 1 | github-code | 1 |
5432761830 | import docker
import logging
from celery import Celery
from celery.schedules import crontab
app = Celery()
@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
cli = docker.from_env(version="1.28")
for node in cli.nodes.list(filters={"role": "worker"}):
logging.info("Adding reb... | whole-tale/gwvolman | gwvolman/scheduler.py | scheduler.py | py | 603 | python | en | code | 1 | github-code | 1 |
73205800354 | import sys
sys.stdin = open('input.txt')
T = int(input())
for tc in range(1, T+1):
N, M, K = map(int, input().split())
people = sorted(list(map(int, input().split())))
result = 'Possible'
if people[0] < M: # 가장 먼저 도착하는 사람이 M초 전에 오면 impossible
result = 'Impossible'
else:
i... | eunjng5474/Study | week05/S_1860_진기의_최고급_붕어빵/mysol.py | mysol.py | py | 951 | python | ko | code | 2 | github-code | 1 |
1498550659 | #!/usr/bin/env python3
# dpw@plaza.localdomain
# 2023-09-19 19:17:00
import json
import sys
from dataclasses import dataclass
from pathlib import Path
from rich import inspect, print
class TrieNode:
def __init__(self, char):
self.char = char
self.is_end = False
self.children = {}
de... | darrylwest/python-play | algorithms/trie.py | trie.py | py | 2,205 | python | en | code | 0 | github-code | 1 |
14011134082 | import requests
import os
import json
from dotenv import load_dotenv
load_dotenv()
# To set your enviornment variables in your terminal run the following line:
#export 'BEARER_TOKEN'='<your_bearer_token>'
print(os.environ)
def auth():
return os.environ.get('BEARER_TOKEN')
def create_url():
... | samkibe/Text-Mining-ON-Twitter----Sample-codes | Stream.py | Stream.py | py | 1,483 | python | en | code | 1 | github-code | 1 |
1538930426 | import logging
import numpy as np
__author__ = 'frank.ma'
logger = logging.getLogger(__name__)
class RdmBivariate(object):
@staticmethod
def __check_rho(rho: float):
if abs(rho) >= 1.0:
raise ValueError('rho (%.4f) should be smaller than 1' % rho)
@staticmethod
def draw_std(rho... | frankma/Finance | src/Utils/Sequence/RdmBivariate.py | RdmBivariate.py | py | 1,032 | python | en | code | 0 | github-code | 1 |
39087739191 | class Node:
def __init__(self, l):
self.l = l
self.p = -1
self.parents = {}
self.encountered = False
class Solution:
def networkDelayTime(self, times, N: int, K: int) -> int:
"""
First create a hashmap representing the graph node.
Then, iterate over ever... | BastienLaby/leetcodeSolutions | problems/network-delay-time.py | network-delay-time.py | py | 2,806 | python | en | code | 0 | github-code | 1 |
34185397192 | # FastApi einbinden für REST-Services
from fastapi import FastAPI, APIRouter
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
# JSON Serialisierung
import orjson
# Pangas zur Daten-Anaylse
import pandas as pd
# GeoPandas für geometrische Funktionen
import geopandas
# Für geometrisc... | veberle/MCS_Praktikum_Aufgaben | src/challenges/challenge4.py | challenge4.py | py | 2,364 | python | de | code | 0 | github-code | 1 |
15690202492 | from spillbrett import Spillebrett
def hovedprogram():
bredde = int(input("Skriv inn bredde på brettet: "))
hoyde = int(input("Skriv inn høyde på brettet: "))
brett = Spillebrett(bredde, hoyde)
brett.tegn_brett() # Skriv ut Generasjon 0
kommando = hent_kommando()
while kommando != "q":
... | ladysilverberg/IN1000 | Oblig 7/main.py | main.py | py | 747 | python | no | code | 0 | github-code | 1 |
16414347802 | #!/usr/bin/python
from optparse import OptionParser
import logging
from time import sleep
import random
import sys
from formats import formats
from messages import messages
parser = OptionParser()
parser.add_option("-m","--mode", dest="mode")
parser.add_option("-f", "--format", dest="format",
help... | tobinmori/fauxprox | foxprox.py | foxprox.py | py | 2,928 | python | en | code | 1 | github-code | 1 |
15497221889 | from hpp.corbaserver.rbprm.scenarios.demos.hyq_darpa_path import PathPlanner
from hpp.corbaserver.rbprm.scenarios.hyq_contact_generator import HyqContactGenerator
class ContactGenerator(HyqContactGenerator):
def __init__(self):
super().__init__(PathPlanner())
def load_limbs(self):
dict_heuris... | humanoid-path-planner/hpp-rbprm-corba | src/hpp/corbaserver/rbprm/scenarios/demos/hyq_darpa.py | hyq_darpa.py | py | 879 | python | en | code | 3 | github-code | 1 |
23998377870 | from enum import Enum
from singleton import Singleton
from datetime import datetime
Circuitstate = Enum("Circuitstate", ["CLOSED", "OPEN", 'HALFOPEN'])
class CircuitOpenException(Exception):
pass
class Circuitbreaker(Singleton):
"""Circuitbreaker is singleton because if multiple functions are decorated
... | kousiknandy/cktbkr | circuitbreaker.py | circuitbreaker.py | py | 2,676 | python | en | code | 0 | github-code | 1 |
3740386075 | import os
import torch
import torch.nn.functional as F
import glob
import imageio
import numpy as np
from utils.data_utils import get_image_to_tensor, get_mask_to_tensor
class DVRDataset(torch.utils.data.Dataset):
def __init__(self,
args,
mode,
list_... | xingyi-li/SymmNeRF | code/datasets/dvr_dataset.py | dvr_dataset.py | py | 8,219 | python | en | code | 14 | github-code | 1 |
653126704 | from flask import Blueprint
from flask import render_template,request,redirect,url_for
from models import product as pd
from .forms import ProductForm
from app import db
products = Blueprint('products', __name__, template_folder='templates')
@products.route('/', methods=['GET','POST'])
def index():
if request.me... | SVLozovskoy/flask-crm | products/blueprint.py | blueprint.py | py | 1,279 | python | en | code | 1 | github-code | 1 |
15641658927 | import calendar
cal = calendar.month(2020, 4)
print(cal)
import math
result = math.sqrt(100)
print(result)
def ggininder(x, y):
if x < y:
return ("hard")
else:
return ("soft")
result = ggininder(12,700)
print(result) | twyunting/Python-Exercises | for_fun/practice_03.py | practice_03.py | py | 260 | python | en | code | 0 | github-code | 1 |
40478697751 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn.functional as F
from layers.utils import loss_tools
from layers.box_annotation_layer import annotate_proposals
def rcnn_loss_layer(score, delta, label_list, fg_delta_list, index_... | OYMiss/faster-rcnn | layers/rcnn_loss_layer.py | rcnn_loss_layer.py | py | 3,285 | python | en | code | 1 | github-code | 1 |
25735388879 | # 목적지에 도달 가능한가 여부를 판단하면 되므로
# dfs로 문제를 푼다.
import sys
sys.stdin = open('input.txt')
def dfs(here, end):
# here : [r, c]
# 현재 위치 방문 체크
maze[here[0]][here[1]] = 1
# 현재 위치가 목적지라면 return 1 (도달 가능)
if here == end:
return 1
# 델타 방식의 탐색
# 시계방향
# 위, 오, 아래, 왼
dr = [-1, 0, 1, 0]
... | KSoonYo/SW_Expert_Arcademy_problem | 1226_미로1/s1.py | s1.py | py | 1,753 | python | ko | code | 0 | github-code | 1 |
25047222226 | # -*-coding:utf-8 -*-
import os
import test
import functools
from unittest.loader import TestLoader
from baseCase.case import BaseTest
class BaseLoader(TestLoader):
def loadTestsFromTestCase(self, testCaseClass):
def isTestMethod(arr, testClass=testCaseClass):
return arr[:4].lower().startswit... | xiaoyaojushi/appium_auto_test | baseCase/baseSuite.py | baseSuite.py | py | 1,328 | python | en | code | 0 | github-code | 1 |
25846744127 | # -*- coding: utf-8 -*-
from contextlib import contextmanager
try:
from typing import Type
except ImportError: # Python 2.x
pass
import redis
import datetime
from bitmapist4 import events as ev
class Bitmapist(object):
"""
Core bitmapist object
"""
# Should hourly be tracked as default?
... | Doist/bitmapist4 | bitmapist4/core.py | core.py | py | 8,248 | python | en | code | 21 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.