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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
11878217031 | from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from rest_framework import serializers
from .models import Product
from .serializers import ProductSerializer
@api_view(['GET'])
def ApiOverview(request):
api_urls = {
'A... | Nidhunkumar/Drf_Crud | venv/DrfCrud/api/views.py | views.py | py | 1,460 | python | en | code | 0 | github-code | 1 |
25632415761 | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup ---------------------------------------------... | Substra/substra-documentation | docs/source/conf.py | conf.py | py | 14,762 | python | en | code | 20 | github-code | 1 |
39947038177 | '''CS3A04 Lab 3'''
#PART 1: Lists
'''-----------------Source-------------------------------------------'''
# program that returns dir () on the class 'list'
print (dir(list))
'''-------------------RUN-----------------------------
/Users/scawley/PycharmProjects/CS3A04/venv/bin/python "
/Users/scawley/Library/Prefe... | seancawley35/CS3A04-Coursework | CS3A04_Lab3.py | CS3A04_Lab3.py | py | 3,800 | python | en | code | 0 | github-code | 1 |
35873100334 | class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
# Solution 1 - Two Pointers
if not height: return 0
l, r = 0, len(height) - 1
lmax, rmax = height[l], height[r]
res = 0
while l < r:
... | petermartens98/LeetCode-Algorithms-Roadmap | Python/TwoPointers/TrappingRainWater.py | TrappingRainWater.py | py | 584 | python | en | code | 2 | github-code | 1 |
18788966992 | from cmd_pkg.cmd_helpers import check_for_help_flag
@check_for_help_flag()
def wc(*args, **kwargs):
'''
\n given input, find the number of lines, words or characters.
\n must specify a flag to receive output
\n - \n -
\n wc file.txt -l
\n - \n -
\n
\n Flags:
\n -l: number of... | gramcracker40/Curses-Shell-Implementation | cmd_pkg_use/cmd_pkg/Wc.py | Wc.py | py | 1,553 | python | en | code | 0 | github-code | 1 |
74014407074 | #-*- coding: UTF-8 -*-
import flask, pandas
from flask import render_template, url_for
data = pandas.read_csv('static\data\parsed_EURUSD_y.csv', delimiter=';')
act = data.is_actual.tail(1).to_string(index=False)
cls = data.last_CLOSE.tail(1).to_string(index=False)
app = flask.Flask(__name__)
@app.route('/')
@app.rou... | Bagaviev/BMSTU | Web Stock (Masters)/manage.py | manage.py | py | 868 | python | en | code | 0 | github-code | 1 |
24929389646 | class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy = ListNode(0, head)
curr=slow=dummy
for _ in range(n):
curr = curr.next
while curr and curr.next:
curr = curr.next
... | cha1690/Data-Structures-and-Algoritms | linkedList/RemoveNthNodeFromEndofList.py | RemoveNthNodeFromEndofList.py | py | 426 | python | en | code | 2 | github-code | 1 |
73010306594 | from flask import Flask
from config.settings import config
from api.app1.api import blueprint as bp_app1
from api.app2.api import blueprint as bp_app2
class Application:
def __init__(self):
self.app = Flask(__name__)
self.create()
def __str__(self):
pass
def message(self):
... | joagonzalez/rest-api-seed | src/application.py | application.py | py | 1,541 | python | en | code | 1 | github-code | 1 |
4453184793 | import bs4 as bs
import urllib.request
from time import strptime
from datetime import datetime
import mysql.connector
import arrow
ghtorrentDb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="ghtorrent"
)
project_id = 34674827
cursor = ghtorrentDb.cursor()
cursor.execute("SELECT ur... | pombredanne/ghtorrent_repear | history2.py | history2.py | py | 2,333 | python | en | code | 0 | github-code | 1 |
25949243794 | print("Start running my test Code :-)")
import numpy as np
#set the three parameters (ev. we should use the Niederreiter crypto system)
n=12
k=4
t=8
m=np.random.randint(2, size=(1,k))
print("Bob's message", m)
#-------------------------------------
# Key generation step (done by Alice)
#-----------------------------... | suttedav/McEliece | Test.py | Test.py | py | 2,774 | python | en | code | 0 | github-code | 1 |
44401796444 | from flask import redirect, render_template, request
from app import app
import users
import topics
import threads
import messages
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
topic = request.form["topic"]
if len(topic) < 3 or len(topic) > 50:
retur... | alanenpa/tsoha-message-board-app | routes.py | routes.py | py | 8,047 | python | en | code | 0 | github-code | 1 |
21148876915 | import json
import os
class Landmarks:
def __init__(self, name: str):
self.name = name
json_path = "landmarks/" + name + ".json"
with open(json_path) as json_file:
data = json.load(json_file)
self.emotion, self.version = name.split("_")
self.fps = data["... | jjustin/paintings-animator | src/storage/landmark.py | landmark.py | py | 1,482 | python | en | code | 2 | github-code | 1 |
42662950852 | # Video Capture, Classification and labeling
from keras.models import load_model
import cv2
import numpy as np
# Model from epoch 17 selected as it has the lowest validation loss and highest accuracy in contrast to the other epochs
#Video capture frame activated
model = load_model('model-017.model')
face_clsfr=cv2.... | majedn01/Covid-19-Mask-Dectection | 3.0 detecting Masks.py | 3.0 detecting Masks.py | py | 1,808 | python | en | code | 0 | github-code | 1 |
70813001955 | import cv2
def car_lic_split(img_path):
binary_threshold = 100
segmentation_spacing = 0.9
# 前處理:灰階、二值化
img = cv2.imread(img_path)
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# cv2.imshow('gray', img_gray)
# cv2.waitKey(0)
img_thre = img_gray
cv2.threshold(img_gray, binary_thr... | JamesYeh2017/License-Plate-Recognition-System | car_lic_split.py | car_lic_split.py | py | 2,852 | python | en | code | 1 | github-code | 1 |
27059054576 |
import random
import numpy as np
random.seed(0)
def normalize_matrix_zscore ( matrix, avgs, stds ):
normalized_matrix=[]
for i in range (len(matrix)):
row = []
for j in range (len(matrix[i])):
row.append ( (matrix[i][j] - avgs[j])/stds[j] )
normalized_matrix.append(row)
return normalized_matrix
fin = o... | ellepannitto/Neural-Network | src/MLCUP2017.py | MLCUP2017.py | py | 2,310 | python | en | code | 0 | github-code | 1 |
69814537633 | from pydantic import BaseModel
from typing import List
from config import db
from models.enums.tableType import TableType
class Constraint(BaseModel):
table_name: TableType
attribute_name: str
name: str = "is_unique"
condition: bool
def to_dict(self):
return {
"table_name": se... | DB2Dev/costex | app/models/metadata/attrs_constraints.py | attrs_constraints.py | py | 1,636 | python | en | code | 0 | github-code | 1 |
14466852358 | import docker
import os
import pytest
import subprocess
import sys
SIMPLE_CPP_SOURCE = '''
#include <string>
#include <iostream>
int main()
{
std::cout << "Hello World" << std::endl;
int a = 5;
std::cout << "Five: " << a << " / " << std::to_string(a) << std::endl;
return 0;
}
'''
SIMPLE_C_SOURCE = ... | csm10495/ubuntu_10_04_build | static/tests/test_container.py | test_container.py | py | 4,378 | python | en | code | 1 | github-code | 1 |
69905461153 | """Support for myUplink sensors."""
from __future__ import annotations
import logging
from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from ho... | jaroschek/home-assistant-myuplink | custom_components/myuplink/switch.py | switch.py | py | 1,872 | python | en | code | 11 | github-code | 1 |
38302460948 | """Tests for `ember_mug.mug connections`."""
from __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING
from unittest.mock import AsyncMock, Mock, patch
import pytest
from bleak import BleakError
from bleak.backends.device import BLEDevice
from ember_mug.consts import (
EMB... | sopelj/python-ember-mug | tests/test_connection.py | test_connection.py | py | 21,188 | python | en | code | 18 | github-code | 1 |
7076098975 | import argparse
import sys
import os
def create_arg_parser():
""""Creates and returns the ArgumentParser object."""
parser = argparse.ArgumentParser(description='Description of your app.')
parser.add_argument('inputDirectory',
help='Path to the input directory.')
parser.add_argumen... | a-n-n-a-c-g/Scripts | pythonacceptargs.py | pythonacceptargs.py | py | 633 | python | en | code | 1 | github-code | 1 |
10786181943 | from django import template
register = template.Library()
@register.simple_tag
def bizz_or_fuzz(number):
if number % 3 == 0 and number % 5 == 0:
return 'BizzFuzz'
elif number % 3 == 0:
return 'Bizz'
elif number % 5 == 0:
return 'Fuzz'
else:
return numbe... | lebvlad/milo-django | test_case/templatetags/bizzfuzz.py | bizzfuzz.py | py | 323 | python | en | code | 0 | github-code | 1 |
13434336386 | """
插入排序,又名扑克排序。它的思想很容易理解, 打过扑克的都知道,桌上的牌组是被随机打乱的,但一张一张摸到自己手上的时候,后摸的牌会在手上已排序的牌组中找到对应的位置插入进去
它的实现跟选择排序很像。都是前后分成已排序和未排序的两部分。选择排序是从未排序中依次选择最小或最大的数加到已排序数组后。而插入排序是选择未排序数组中的第一个数,
去和已排序数组中的数比较插入。因为我们要实现线性的内存复杂度,所以需要操作自身,那插入位置后的数得依次后移。所以我们插入的时候需要从已排序数组末尾开始比较,
有点像冒泡一样,依次交换冒到自己的位置。这样在插入到对应位置时,插入位置后的数已经依次后移了
"""
import random
de... | TravelSir/structure_and_algorithm | 排序算法/insertSort.py | insertSort.py | py | 1,248 | python | zh | code | 0 | github-code | 1 |
6205039220 | #!/usr/bin/env python
"""
track.py -- reconnect localizations into trajectories
"""
# Numeric
import numpy as np
# Dataframes
import pandas as pd
# Distance between two sets of 2D points
from scipy.spatial import distance_matrix
# Hungarian algorithm
from munkres import Munkres
hungarian_solver = Munkres()
# C... | alecheckert/quot | quot/track.py | track.py | py | 30,761 | python | en | code | 9 | github-code | 1 |
32161971126 | """Get E3FP default parameters and read parameters from files.
Author: Seth Axen
E-mail: seth.axen@gmail.com
"""
import os
import copy
import ast
from configparser import (
ConfigParser,
NoSectionError,
DuplicateSectionError,
)
CONFIG_DIR = os.path.dirname(os.path.realpath(__file__))
DEF_PARAM_FILE = os.... | keiserlab/e3fp | e3fp/config/params.py | params.py | py | 5,425 | python | en | code | 114 | github-code | 1 |
40419762544 | from pathlib import Path
from collections import deque
import re
import numpy as np
data_folder = Path(".").resolve()
reg_floor = re.compile(r"an? (\w+)(-compatible microchip| generator)")
class Factory:
def __init__(self,data):
locations = dict()
item_index = {"-compatible microchip":0," generato... | eirikhoe/advent-of-code | 2016/11/sol.py | sol.py | py | 3,611 | python | en | code | 0 | github-code | 1 |
2358557106 | # START: OWN CODE
import pandas as pd
import lightgbm as lgbm
from parsing_utility import index_range_parser
import sys
def lightgbm_prediction(model_path, features):
trained_model = lgbm.Booster(model_file=model_path)
return trained_model.predict(features)
if __name__ == '__main__':
input_data = pd.rea... | haochuan-li/Request-Predictor | lgbm_trainer/lightgbm_prediction.py | lightgbm_prediction.py | py | 918 | python | en | code | 0 | github-code | 1 |
30890499502 | # -*- coding: utf-8 -*-
'''
django_chime/forms
------------------
forms for the django-chime app
'''
from django.core.validators import MinValueValidator, MaxValueValidator
from django.forms import ModelForm
from django.forms.fields import FloatField, TextInput
from crispy_forms.bootstrap import FormActions
from cr... | ChrisPappalardo/django-chime | django_chime/forms.py | forms.py | py | 3,022 | python | en | code | 4 | github-code | 1 |
839831529 | import os
import unittest
from advisor.db_log_parser import NO_COL_FAMILY
from advisor.db_options_parser import DatabaseOptions
from advisor.rule_parser import Condition, OptionCondition
class TestDatabaseOptions(unittest.TestCase):
def setUp(self):
self.this_path = os.path.abspath(os.path.dirname(__file... | facebook/rocksdb | tools/advisor/test/test_db_options_parser.py | test_db_options_parser.py | py | 8,454 | python | en | code | 26,384 | github-code | 1 |
34006810606 | import requests
# field to search
# https://www.zoho.com/crm/help/api/v2/#ra-search-records
"""
Only one of the above four parameters would work at one point of time.
Furthermore, if two parameters are given simultaneously, preference will be given in the order criteria,
email, phone and word, and only one of them woul... | czam01/python | request_zohocrm.py | request_zohocrm.py | py | 674 | python | en | code | 0 | github-code | 1 |
72115663074 | import QgsMapTool
class DistanceCalculator(QgsMapTool):
def __init__(self, iface):
QgsMapTool.__init__(self, iface.mapCanvas())
self.iface = iface
def canvasPressEvent(self, event):
transform = self.iface.mapCanvas().getCoordinateTransform()
self._startPt = transform.toMapCoord... | geosconsulting/qgis_vari | calcola distanza.py | calcola distanza.py | py | 1,332 | python | en | code | 1 | github-code | 1 |
9356941908 | from sys import argv
import urllib.request
def meritevFunc(meritev):
list_char = list(meritev)
end_str = ""
for ch in list_char:
if ch.isdigit():
str = ch + "0kV "
else:
str = ch.upper() + " "
end_str = end_str + str
print(end_str)
return end_s... | bertoncelj/LISA_esp32 | getWeb.py | getWeb.py | py | 978 | python | en | code | 0 | github-code | 1 |
40456986935 | # 57. Write a Python program to get the execution time of a Python method.
def calculate_lcm(num1, num2):
for i in range(max(num1, num2), 1+(num1*num2)):
if i % num1 == i % num2 == 0:
lcm = i
break
print("LCM of", num1, "and", num2, "is", lcm)
import time
start_time = time.ti... | emineksknc/Python-Exercises | Python-basic-(Part -I)/57.py | 57.py | py | 403 | python | en | code | 0 | github-code | 1 |
14938210394 | first_cell = input("Укажите первую клетку: ")
second_cell = input("Укажите вторую клетку: ")
color1 = (ord(first_cell[0]) + int(first_cell[1])) % 2
color2 = (ord(second_cell[0]) + int(second_cell[1])) % 2
if color1 == color2:
print("Да")
else:
print("Нет")
# Укажите первую клетку: a3
# Укажите вторую клетку... | TOP-Python321/Moor | 2023.04.16/4.py | 4.py | py | 450 | python | ru | code | 0 | github-code | 1 |
32411269390 | from .models import Leaderboard, Score
import json
class Service():
@staticmethod
def get_all_leaderboard():
leaderboard = Leaderboard.objects()
json_lead = leaderboard.to_json()
dicts = json.loads(json_lead)
return dicts
@staticmethod
def add_new_score(game, score,... | phong1233/website-backend | src/services.py | services.py | py | 1,243 | python | en | code | 1 | github-code | 1 |
39475147519 | from collections import defaultdict
instructions = dict()
bots = defaultdict(list)
outputs = defaultdict(list)
with open("../inputs/10.txt") as f:
for line in f:
line = line.split()
if line[0] == "value":
bot = int(line[5])
microchip = int(line[1])
bots[bot].app... | Lalica/adventofcode | 2016/solutions/day10.py | day10.py | py | 1,388 | python | en | code | 1 | github-code | 1 |
41436539593 | import logging
import string
import uuid
from time import sleep
import pytest
import sqlalchemy
from streamsets.testframework.markers import database
from streamsets.testframework.utils import get_random_string
logger = logging.getLogger(__name__)
@database
def test_query_consumer_network(sdc_builder, sdc_executor,... | streamsets/datacollector-tests | fault/test_jdbc.py | test_jdbc.py | py | 2,975 | python | en | code | 17 | github-code | 1 |
21877799762 | import sys
from collections import deque
rows, columns = map(int, sys.stdin.readline().strip().split())
maze = [[0 for _ in range(columns)] for _ in range(rows)]
dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
def bfs(v, w):
queue = deque()
queue.append((v, w))
while queue:
v, w = queue.popleft()
... | iceprins/study-codingtest | 2178.py | 2178.py | py | 885 | python | en | code | 0 | github-code | 1 |
2071622878 | #!/usr/bin/env python3
import os
def run(*args):
os.execlp(args[0], *args)
rsa_key_size = int(os.getenv('RSA_KEY_SIZE', 4096))
cert_days = int(os.getenv('CERT_DAYS', 365))
run('openssl', 'req', '-new', '-newkey', 'rsa:%d' % rsa_key_size,
'-days', str(cert_days), '-nodes', '-x509', '-keyout',
'server.key... | Inndy/ssaa | ssaa/key/gen-key.py | gen-key.py | py | 376 | python | en | code | 0 | github-code | 1 |
32146339364 | from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView
urlpatterns = [
# path('', include(router.urls)),
# path to djoser... | FirstWind/OZABRU | OZABRU/urls.py | urls.py | py | 1,391 | python | en | code | 0 | github-code | 1 |
72720227234 | import requests as req
# api url
url = "https://animechan.vercel.app/api"
def res_to_str(data):
character = data["character"]
anime = data["anime"]
quote = data["quote"]
res_string = f"\nQuote by: {character}\nFrom: {anime}\nQuote: {quote}\n"
return res_string
def get_data(full_url):
print("G... | imtiaz0307/Python | random_anime_quote_generator.py | random_anime_quote_generator.py | py | 1,363 | python | en | code | 1 | github-code | 1 |
69955543713 | """Handler for vocab data saves and updating."""
import json
import parse_raw
SAVEPATH = "../data/"
OUTPATH = "../output/"
SAVEFILE = "vocab.json"
INFILE = "raw_terms.txt"
DATAFILE = "raw.json"
def fetch_json(filepath=SAVEPATH+SAVEFILE):
"""Fetch data from filepath, if it exists."""
try:
with open(fil... | JDongian/LangGrind | src/vocab.py | vocab.py | py | 2,847 | python | en | code | 0 | github-code | 1 |
24379844080 | from django.shortcuts import get_object_or_404, render
from django.http import JsonResponse
from django.contrib.auth.models import User
from .models import SiteMessage, Payment
from comments.models import Comment
from article.models import ArticlesPost
from album.models import Album
from vlog.models import Vlog
from ... | budaLi/dusainet | extends/views.py | views.py | py | 6,846 | python | en | code | null | github-code | 1 |
20188320963 | import mysql.connector
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())
url_prefix = "https://www.sas.am"
def insert_products(products):
conn = mysql.connector.connect(
host='localhost',
user='root',... | karlosgevorgyan/requests | Requests/selenium_SAS.py | selenium_SAS.py | py | 3,716 | python | en | code | 0 | github-code | 1 |
40898109195 | # 백준 강의 알고리즘 기초 2/2 610-BFS
# 1697번 숨바꼭질
import sys
sys.stdin = open('input.txt')
input = sys.stdin.readline
# 여기부터 제출해야 한다.
# N, K = map(int, input().split())
# list_visit = [[N, K, 0]]
# def next_step(start, goal, depth):
# next_step_1 = start + 1
# next_step_2 = start - 1
# next_step_3 = start *... | boogleboogle/baekjoon | etc/bfs/610/1_1697.py | 1_1697.py | py | 1,415 | python | en | code | 0 | github-code | 1 |
25366643687 | import os
import re
import sys
import time
LIBVERSION = '0.0.3'
# ------------------------------------------
# Return the library version
#
def LibVersion():
return LIBVERSION
# ------------------------------------------
# Read a text file to set up a dictionary for configuration information
# Options supported ar... | openttp/openttp | software/system/src/ottplib.py | ottplib.py | py | 4,946 | python | en | code | 7 | github-code | 1 |
45182407716 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
'''
Simple anti-bot API for Google reCaptcha service.
'''
import logging
import urllib
RECAPTCHA_URL = 'http://www.google.com/recaptcha/api/verify'
TEST_DOMAIN = 'localhost'
TEST_PUB_KEY = '6LeAOr0SAAAAA... | Albertnnn/express-me | src/framework/recaptcha.py | recaptcha.py | py | 1,582 | python | en | code | 0 | github-code | 1 |
74874803553 | import re
import os
import json
import requests
from datetime import datetime
from bs4 import BeautifulSoup
# base_url = 'https://www.kickstarter.com/discover/advanced?category_id=12&woe_id=0&sort=most_funded&seed=2591527'
# base_url = 'https://www.kickstarter.com/discover/advanced?category_id=332&sort=most_funded&s... | yanchenm/dessa-comp | web_scraper.py | web_scraper.py | py | 5,636 | python | en | code | 0 | github-code | 1 |
41934614521 | import re
my_bag = 'shiny gold'
def first(input):
all_bags = {}
regex = re.compile('(\w+ \w+) bags?')
for line in input:
iterator = regex.finditer(line)
first_iteration = True
parent_bag = None
for match in iterator:
bag_color = match.group(1)
if ... | Benbb96/adventofcode | python/2020/day7/day7.py | day7.py | py | 2,251 | python | en | code | 0 | github-code | 1 |
4409582757 | """Module to handle different set operations."""
import itertools
import matplotlib.pyplot as plt
class Set:
"""Class representing a set of different objects."""
def __init__(self, iteratable_data=None):
"""Initialize a set with given data."""
if iteratable_data is not None:
sel... | rkleee/aragonit | set/CustomSet.py | CustomSet.py | py | 9,928 | python | en | code | 0 | github-code | 1 |
34813103313 | import ffmpy3
from multiprocessing import Pool
def main(name, link):
ffmpy3.FFmpeg(inputs={link: None}, outputs={name: None}).run()
if __name__ == '__main__':
name = './test.mp4'
link = 'https://daqqzz.com/20200118/a187bf139b8fe6452130d28921c4b5cf.mp4/index.m3u8?ts=1598258626000&token=1ccf90cce80953842d... | mediew/pynote | spyder/ck资源网/test.py | test.py | py | 421 | python | en | code | 0 | github-code | 1 |
1704459398 | import sys
def palindrome(L):
if len(L) <= 1:
return 1
if L[0] == L[-1]:
return palindrome(L[1:-1])
else:
return 0
N= int(input())
Memo = [[-1] * (N+1) for _ in range(N+1)]
L = list(map(int, sys.stdin.readline().split()))
M = int(input())
for i in range(M):
a,b = map(int, sys.st... | SunghunKim98/Algorithm_Study | sprint06/KMS/SW/BOJ_10942.py | BOJ_10942.py | py | 691 | python | en | code | 0 | github-code | 1 |
9709356118 | from abc import ABC
from typing import List
from visualBase import GameBase
from visualization.conf import *
from graph.graphCreator import createGraphVertex
from graph.graphBase import GraphType
from graph.graphBase import Graph
from graph.graphCreator import createGraphEdge
from algorithm.graphSearch import breadthFi... | chrispaulint3/AStar | visualization/visual.py | visual.py | py | 4,158 | python | en | code | 0 | github-code | 1 |
40310451794 | from .db_handler import DbHandler
from .table_handler import TableHandler
from .enums import DayOfTheWeekDefault, WeekDefault, CourseDefault, LessonTimeDefault
TEACHER_TABLE_DATA = ('teacher', [
('teacher_id', 'INTEGER', 'PRIMARY KEY AUTOINCREMENT'),
('teacher_name', 'TEXT', 'NOT NULL')
])
KBSP_G... | skv0zsneg/kbsched | kb_model/kbsched_model.py | kbsched_model.py | py | 5,861 | python | en | code | 0 | github-code | 1 |
75114058594 | import socket
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind(('localhost',58310))
print('Aguardando conexao')
server.listen(1)
connection, address = server.accept()
print('conectado em: ', address)
namefile=connection.recv(1024).decode()
with open(namefile, 'rb') as file:
for data in fil... | SilenioNeto/UDP | Socket/Servidor/Servidor.py | Servidor.py | py | 398 | python | en | code | 0 | github-code | 1 |
20059123121 | """
AWS temporary credential provider.
"""
from hops import constants, util, hdfs
from hops.exceptions import RestAPIError
import os
def assume_role(role_arn=None, role_session_name=None, duration_seconds=3600):
"""
Assume a role and sets the temporary credential to the spark context hadoop configuration an... | logicalclocks/hops-util-py | hops/credentials_provider.py | credentials_provider.py | py | 5,596 | python | en | code | 26 | github-code | 1 |
26447550240 | from . import populate_one_subcmd
from curtin.block.mkfs import mkfs as run_mkfs
from curtin.block.mkfs import valid_fstypes
import sys
CMD_ARGUMENTS = (
(('devices',
{'help': 'create filesystem on the target volume(s) or storage config \
item(s)',
'metavar': 'DEVICE', 'action': 'stor... | rom1212/maas-guide | deploy/curtin-extract/curtin/commands/mkfs.py | mkfs.py | py | 1,477 | python | en | code | 0 | github-code | 1 |
2276280862 | import random
from flask import Flask, request
from pymessenger.bot import Bot
import process
app = Flask(__name__)
ACCESS_TOKEN = 'EAALxONaYePsBAM5oBExC3ZC9yFGVucIiZB7fxP00AKhZBc9gjPZAqtk7Ed8T8UlD8bhZBsA8pWIcSpPrGpItvUSEk1ZAMPfZBr6B7S5vXRUqzbpxJciSGFZCCWwRei8laoSqmCreAhYgXWva680ftzeZB89S9gbqZBCdPm5Tf0jcxxFQZDZD'
VERI... | vsvipul/ContestBot | messenger.py | messenger.py | py | 2,460 | python | en | code | 4 | github-code | 1 |
71920185634 | # 内記表記
# pra_14_1
ceLeague = ['巨人', 'ヤクルト', 'DeNA', '中日', '阪神', '広島']
BattleCard = [[a, b] for a in ceLeague for b in ceLeague if a != b]
for b in BattleCard:
print(b)
# pra_14_2
ary = [[x+y*3+1 for x in range(3)] for y in range(3)]
print(ary)
for a in ary:
print(a)
# pra_14_3
ary2 = [[x+y*3+1 if x >= y else... | hellomyzn/study | pdf/python/python-intro2/src/section14/main.py | main.py | py | 610 | python | en | code | 0 | github-code | 1 |
34902005124 | from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
import json
from sqlalchemy import desc,and_
import os
from db_manager import db
from models import Event
from datetime import datetime
app = Flask(__name__)
CORS(app)
app.secret_key = os.getenv('SECRET_KEY')
if app.config['ENV'] == '... | MetiKh2/flask-eventsManager | app.py | app.py | py | 3,415 | python | en | code | 0 | github-code | 1 |
43497709134 | import torch
from torchvision import datasets, models, transforms
import torch.nn as nn
import random
from torch.utils.data import Dataset
import glob
from PIL import Image
import cv2
import albumentations as A
from albumentations.pytorch import ToTensorV2
class CustomDataset(Dataset):
def __init__(self, img_dir... | tinhnguyen0110/cars-classification | dataset.py | dataset.py | py | 3,467 | python | en | code | 0 | github-code | 1 |
24040618942 | from dataclasses import dataclass
@dataclass
class Protocols:
arp = "arp"
bootp = "bootp"
icmp = "icmp"
all = "all"
p = Protocols()
print(p.arp)
print("arp" in p)
print(p["arp"])
exit()
protocols = dict(arp="arp", bootp="bootp", icmp="icmp", all="all")
protocols["0"] = "all"
p = lambda: None
p.__d... | atrox3d/pycharm-scratches | data-structures/protocol-dataclass.py | protocol-dataclass.py | py | 373 | python | en | code | 0 | github-code | 1 |
18652820535 | from django.conf.urls import url
from django.urls import path
from .views import CustomerGroupAPIView, CustomerGroupAPIDetailView, SiteAPIDetailView, SiteAPIView
app_name = "api-group"
# app_name will help us do a reverse look-up latter.
urlpatterns = [
url(r'^(?P<id>\d+)/$', CustomerGroupAPIDetailView.as_view(... | KUSH23/bkend | customergroups/api/urls.py | urls.py | py | 539 | python | en | code | 1 | github-code | 1 |
18354714736 | from xml.sax.saxutils import quoteattr
import argparse
import os
import re
import sys
import unittest
# Read at most 100MB of a test log.
# Rarely would this be exceeded, but we don't want to end up
# swapping, etc.
MAX_MEMORY = 100 * 1024 * 1024
START_TESTCASE_RE = re.compile(r'\[ RUN\s+\] (.+)$')
END_TESTCASE_RE = ... | apache/kudu | build-support/parse_test_failure.py | parse_test_failure.py | py | 10,125 | python | en | code | 1,762 | github-code | 1 |
33277651136 | import json
import os
import tempfile
from typing import List, Literal, Optional
from typing_extensions import TypedDict
from loguru import logger
from fastapi import APIRouter, Request, Response
from fastapi.responses import PlainTextResponse
from modeling.animation import build_anim_spec
from service.utils import ran... | AIOT-Learning-Group/uppaal-modeling-smart-home | service/rendering.py | rendering.py | py | 3,913 | python | en | code | 0 | github-code | 1 |
7602478255 | import requests
import pprint
import csv
for page in range(1, 11):
print('======第{}页======'.format(page))
base_url = 'http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.1... | Ricechips/-python- | bilibili/kfc.py | kfc.py | py | 1,156 | python | en | code | 0 | github-code | 1 |
11882940759 | # 需求: 对指定的路由进行访问限制
# 分析: 部分视图需要身份校验,这部分视图每个单独校验仍会出现大量的代码冗余
# 解决办法: 封装 装饰器 完成身份校验逻辑, 对指定视图函数设置装饰器
# 代码示例
from flask import Flask, session, g, abort
from functools import wraps
app = Flask(__name__)
app.secret_key = 'test'
@app.before_request
def prepare():
g.name = session.get('username')
@app.route('/')
def in... | xiaoxiao131111/flask_high_user | 访问限制.py | 访问限制.py | py | 1,769 | python | zh | code | 0 | github-code | 1 |
24759720411 |
poltrona=[1,40]
ocupado=[]
num=1
while num != 0:
num=int(input("Digite o número da poltrona de 1-40. Para finalizar digite 0."))
var = num in poltrona
if var == True:
ocupado.append(num)
del poltrona[num]
if var == False:
print("Esta poltrona já está ocupada.")
print(pol... | GaBenfika/ExPython | 2°SEMESTRE/AU.140921/EX.01.140981.py | EX.01.140981.py | py | 348 | python | pt | code | 0 | github-code | 1 |
5410144311 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import unittest
import deepmind_lab
import random_agent
class RandomAgentsTest(unittest.TestCase):
def test_spring_agent_run(self, length=100):
env = deepmind_lab.Lab(
'tests/demo_ma... | dai-dao/Grounded-Language-Learning-in-Pytorch | python/random_agent_test.py | random_agent_test.py | py | 1,689 | python | en | code | 34 | github-code | 1 |
36787065489 | import os
import platform
import re
from time import time
import cmdstanpy
from cmdstanpy import CmdStanModel, cmdstan_path
import pandas as pd
def get_timing(fit):
"""Extract timing."""
timings = []
for i, path in enumerate(fit.runset.stdout_files):
with open(path) as f:
timing = ""
... | ahartikainen/stan_performance_testing | run_CmdStanPy.py | run_CmdStanPy.py | py | 3,723 | python | en | code | 0 | github-code | 1 |
2032464725 | from rrpam_wds.gui import set_pyqt_api # isort:skip # NOQA
import logging
from rrpam_wds.tests.test_utils import Test_Parent
from rrpam_wds.tests.test_utils import main
class TC(Test_Parent):
logger = logging.getLogger()
def test__initialize_all_components_will_not_close_log_dialog(self):
self.aw.... | asselapathirana/RRPam-WDS | src/rrpam_wds/tests/test_main_window2.py | test_main_window2.py | py | 708 | python | en | code | 3 | github-code | 1 |
2937883579 | import requests
import json
# fs = '1'
import time
count = 1
while True:
try:
r = requests.post("http://ec2-3-84-46-25.compute-1.amazonaws.com", data="getdata")
print("##############")
print(r.text)
print("count: ", count)
break
except:
count += 1
time.sl... | MapleMilk/IoT-smart-road-light | clientForTestAndroid.py | clientForTestAndroid.py | py | 991 | python | en | code | 0 | github-code | 1 |
16988584968 | import scipy.io as sio
import numpy as np
import matplotlib.pyplot as plt
def lsfit(data):
x = data[:,0]
y = data[:,1]
x_bar = np.mean(x)
y_bar = np.mean(y)
xy_bar = np.mean(x*y)
xx_bar = np.mean(x*x)
w1 = (xy_bar - y_bar*x_bar)/(xx_bar - x_bar*x_bar)
w0 = y_bar - w1*x_bar
loss = n... | cartfjord/ASI | Lab1/lab1.py | lab1.py | py | 3,700 | python | en | code | 0 | github-code | 1 |
19294778278 | from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import gensim
import gensim.models
from gensim.models import KeyedVectors
from get_tweets import get_tweets
from wakati import wakati
from tweet_evaluation import evaluation
app = FastAPI()
origins = [
"http://localhost:... | renasami/ts-twitter | backend/main.py | main.py | py | 1,957 | python | en | code | 1 | github-code | 1 |
26024082369 | # type: ignore
# ruff: noqa: F821
import time
import os
from pprint import pprint
import subdir.profiling_test_script2 as script2
@profile
def fact(n):
result = 1
for i in range(2, n // 4):
result *= i
result = 1
# This is a comment
for i in range(2, n // 16):
result *= i
res... | Nodd/lineprofilergui | example/profiling_test_script.py | profiling_test_script.py | py | 1,193 | python | en | code | 9 | github-code | 1 |
4340651422 | from datetime import datetime
from PySide2.QtCore import Qt, QAbstractItemModel, QModelIndex
from PySide2.QtGui import QBrush
from jal.constants import BookAccount, PredefinedAsset, CustomColor
from jal.widgets.helpers import g_tr
from jal.db.helpers import executeSQL
from jal.widgets.delegates import GridLinesDelegate... | iliakan/jal | jal/reports/income_spending_report.py | income_spending_report.py | py | 11,723 | python | en | code | null | github-code | 1 |
20686734920 | import json
import sys
import traceback
from datetime import datetime
from agent.server import Server
if __name__ == "__main__":
info = []
server = Server()
for bench in server.benches.values():
for site in bench.sites.values():
try:
timestamp = str(datetime.utcnow())
... | frappe/agent | agent/analytics.py | analytics.py | py | 775 | python | en | code | 52 | github-code | 1 |
5677957932 | # read the input from console and typecast to string
lineInput = str(input("enter the string"))
# create an empty dictionary
dictionary = {}
# split the words and sort them as well
splitWords = sorted(lineInput.split())
# creating a loop to check for words in split words
for word in splitWords:
# if word is already... | imrc7/CS5590_Python | InClassProgramming/ICP3/Source/dictionaryA.py | dictionaryA.py | py | 510 | python | en | code | 0 | github-code | 1 |
4504389118 | # -*- coding: utf-8 -*-
import sys, os
from time import time
from PyQt5.QtWidgets import QApplication, QMainWindow
from Main_framework import Ui_Form
from Vivo_x23_data import Vivo_x23_data_main
from Vivo_x23_data_analysis import Vivo_x23_data_analysis_main
from Huawei_p20_data import Huawei_p20_data_main
from Huawei_... | WQ1213/Mobile_phone_analysis | Mobile_phone_analysis.py | Mobile_phone_analysis.py | py | 3,248 | python | en | code | 1 | github-code | 1 |
32874716212 | """
Link:
Time complexity: O(N)
Space complexity: O(N)
Created by Hieu Nguyen on 08/02/2022
"""
BASE = 29
INF = 10 * 9 + 7
BASE_FACTOR = [1] * 10 ** 5
for i in range(1, 10 ** 5):
BASE_FACTOR[i] = BASE * BASE_FACTOR[i - 1] % INF
def get_hash_val(text, start, end, hash_val):
if start == 0:
return hash_... | hieuducnguyen/BigOCourse | 30_DB3/kdsk.py | kdsk.py | py | 2,581 | python | en | code | 2 | github-code | 1 |
24918521865 | #!/usr/bin/python
import argparse
import os
import re
import influxdb as idb
import pandas as pd
class Testo():
def __init__(self, saveDirectory):
self.saveDirectory = saveDirectory
def querySelAllFromMeasureResAsDataFrame(client, meas, lborder, rborder):
query = 'SELECT * FROM "{}" where ti... | FutureApp/a-bench | dir_bench/images/influxdb-client/image/rest_server/lib/Testo.py | Testo.py | py | 1,635 | python | en | code | 1 | github-code | 1 |
71250008673 | import tkinter as tk
window=tk.Tk()
window.title("Submit")
window.minsize(500,500)
input=tk.Entry()
input.grid(column=2,row=0, padx=0, pady=0, sticky="NSEW")
def on_click():
txt=input.get()
label.config(text=txt)
#print(text)
button=tk.Button( text="Submit",font="Georgia",command=on_click)
... | nandana-03/PYTHON-Bootcamp | day3/submit_page.py | submit_page.py | py | 502 | python | en | code | 0 | github-code | 1 |
75256440993 | class Solution(object):
def removeOuterParentheses(self, S):
"""
:type S: str
:rtype: str
"""
start, count = 0, 0
result = []
for i, each in enumerate(S):
if each == '(':
count += 1
if each == ')':
count ... | HawkinYap/Leetcode | leetcode1021.py | leetcode1021.py | py | 593 | python | en | code | 0 | github-code | 1 |
17074239864 | from django.db import models
import uuid
class CategoriesOfProducts(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=64)
seq = models.IntegerField(blank=True, unique=True)
class Meta:
verbose_name = 'CategoryOfProducts'
verbose_name_plural = 'C... | masian4eg/livest_test | stock_app/models.py | models.py | py | 1,347 | python | en | code | 0 | github-code | 1 |
2180140168 | """TCP hole punching and peer communication."""
import socket
import threading
from typing import Callable
class Error(Exception):
pass
class Tunnel:
"""High-level packet transmission."""
class Listener:
"""Automatic tunnel creation on port."""
def __init__(self, port: int, backlog: int = None):... | TheDocTrier/pyble | pyble/server/tunnel.py | tunnel.py | py | 1,468 | python | en | code | 0 | github-code | 1 |
42687602182 | import numpy as np
from collections import OrderedDict
import csv
import matplotlib.pyplot as plt
class Adam:
"""Adam (http://arxiv.org/abs/1412.6980v8)"""
def __init__(self, lr=0.001, beta1=0.9, beta2=0.999):
self.lr = lr
self.beta1 = beta1
self.beta2 = beta2
self.iter = 0
... | r07942086/ML2018FALL | hw2/train_best.py | train_best.py | py | 8,694 | python | en | code | 0 | github-code | 1 |
42944510550 | import os, sys
from .TestExec import TestExec
from . import depend
from . import testrunner
class TestExecList:
def __init__(self, usrplugin, tlist):
""
self.plugin = usrplugin
self.tlist = tlist
self.xtlist = {} # np -> list of TestCase objects
self.started = {} # Tes... | rrdrake/vvtools | vvt/libvvtest/execlist.py | execlist.py | py | 6,372 | python | en | code | 4 | github-code | 1 |
28176082453 | import io
import sys
import json
from smoke.io.wrap import demo as io_wrp_dm
from smoke.replay import demo as rply_dm
from smoke.replay.const import Data
class Chat(object):
def __init__(self, player, message):
self.player = player
self.message = message
class Player(object):
def __init__(sel... | qiemem/dotalang | messages.py | messages.py | py | 1,914 | python | en | code | 0 | github-code | 1 |
22374085933 | from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication, QFrame
from PyQt5.QtWidgets import QApplication, QGridLayout, QLabel, QMainWindow, QPushButton, QWidget, QTableWidget, QTableWidgetItem, QMessageBox, QMenuBar, QLineEdit
from PyQt5.QtGui import QBrush, QColor
from PyQt5 import QtCore
from matplot... | celee1/expense-tracker | expense_tracker.py | expense_tracker.py | py | 39,348 | python | en | code | 0 | github-code | 1 |
29007039516 | from django.urls import path
from . import views
from django.shortcuts import render, redirect
urlpatterns = [
path("", views.index ,name="index"),
path("index.html", views.index ,name="index"),
path("robots.txt", views.robots ,name="robots"),
path("ads.txt", (lambda request: render(request, "ads.txt")... | minegishirei/flamevalue | trashbox/django3/app/short_tips/urls.py | urls.py | py | 622 | python | en | code | 0 | github-code | 1 |
10111656279 | from tkinter import*
import tkinter.font as tkfont
from tkinter import messagebox
W=Tk()
W.title('BINARY CONVERSION')
W.geometry("350x300+200+100")
fontstyle = tkfont.Font(family="arial",size=14)
x=IntVar()
y=IntVar()
y.set(0)
h=IntVar
def BTN_click():
if x.get()<=0:
messagebox.showinf... | haviet12/Learning_Python | LAP_TRINH_GIAO_DIEN_PYTHON/GUI_2.py/Bai_Tap_1.py | Bai_Tap_1.py | py | 1,037 | python | en | code | 0 | github-code | 1 |
12513775174 | def binarySearch(arrayInput, key):
leftIndex = 0
rightIndex = len(arrayInput) - 1
while leftIndex <= rightIndex:
middleIndex = leftIndex + (rightIndex - leftIndex) // 2
if arrayInput[middleIndex] == key:
return True
elif key > arrayInput[middleIndex]:
leftIn... | MichaelOgunsanmi/Algorithms-and-Data-Structures | Binary Search Tree/binarySearch.py | binarySearch.py | py | 472 | python | en | code | 0 | github-code | 1 |
36780999631 | import numpy as np
from isoexp.linear.linearbandit import EfficientLinearBandit, LinearBandit, LinPHE
from isoexp.conservative.linearmabs import EfficientConservativeLinearBandit, SafetySetCLUCB
from isoexp.linear.linearmab_models import RandomLinearArms, DiffLinearArms, OtherArms, CircleBaseline, LinPHEModel
from matp... | facebookresearch/ContextualBanditsAttacks | examples/main_linearmab.py | main_linearmab.py | py | 8,137 | python | en | code | 4 | github-code | 1 |
12458772738 | import os, sys
import pygame
import pygame.locals
import grid
import gem
import random
import player
import threading
import time
BLACK = 0, 0, 0
OFFSET = 70
pygame.init()
class Updater(threading.Thread):
'''Handles brick drop speed.'''
def __init__(self, players):
threading.Thread.__init__(self)
... | Ceasar/Puzzle-Fighter | main.py | main.py | py | 5,000 | python | en | code | 4 | github-code | 1 |
11862555936 |
# tea_collection = [
# "Earl Grey",
# "Melbourne Breakfast",
# "Chai",
# "Peppermint",
# "Lemon and Ginger",
# "Strawberry Cream",
# "Chamomile",
# "Green",
# "Dandelion"
# ]
# for tea in tea_collection:
# print(f"I have {tea} flavoured tea.")
# print("ended loop")
# for inde... | roxygia/Python | loops/for_loops.py | for_loops.py | py | 1,009 | python | en | code | 0 | github-code | 1 |
19609459955 | import flask
import threading
import os
import slackeventsapi
import slackweb
import bedroomtv
import youtube
import surveillance
slack_signing_secret=os.environ.get('SLACK_SIGNING_SECRET')
approved_user_id=os.environ.get('APPROVED_USER_ID')
app=flask.Flask(__name__)
slack_events_adapter=slackeventsapi.SlackEventAda... | kriscfoster/my_rpi_personal_assistant | my_rpi_personal_assistant/app.py | app.py | py | 1,456 | python | en | code | 0 | github-code | 1 |
20897754659 | from PyQt4 import QtCore, QtGui
import xml.etree.cElementTree as ET
from log_manager import logger
import csv
SYNC_CONFIG_FILE = "storj_sync_config.xml"
SYNC_DIRECTORIES_FILE = "storj_sync_dirs.csv"
# Configuration backend section
class SyncConfiguration():
def __init__(self, load_config=False):
if loa... | lakewik/EasyStorj | UI/utilities/sync_config.py | sync_config.py | py | 5,871 | python | en | code | 74 | github-code | 1 |
28275954002 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gzip
import os
import shutil
import tempfile
import numpy
from six.moves import urllib
import tensorflow as tf
# CVDF mirror of http://yann.lecun.com/exdb/mnist/
SOURCE_URL = 'http://yann.lecun.com/exd... | Pensarfeo/MNISTFullyConnectedTensorflowExample | dataset.py | dataset.py | py | 3,185 | python | en | code | 1 | github-code | 1 |
22942092792 | import logging
import os
from typing import Dict
from monai.transforms import Invertd, SaveImaged
import monailabel
from monailabel.interfaces.app import MONAILabelApp
from monailabel.interfaces.tasks.infer_v2 import InferTask
from monailabel.interfaces.tasks.scoring import ScoringMethod
from monailabel.interfaces.ta... | Project-MONAI/MONAILabel | sample-apps/monaibundle/main.py | main.py | py | 7,247 | python | en | code | 472 | github-code | 1 |
21675845405 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#Special Pythagorean triplet
#A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a2 + b2 = c2
#For example, 32 + 42 = 9 + 16 = 25 = 52.
#There exists exactly one Pythagorean triplet for which a + b + c = 1000.
#Find the product abc.
# Un ... | Almlett/HOBBY-ProjectEuler | problem_009.py | problem_009.py | py | 882 | python | es | code | 0 | github-code | 1 |
40296920999 | from django.core.mail import send_mail
from fitness.celery import app
from fitness.settings import EMAIL_HOST_USER
from django.utils.translation import gettext_lazy as _
@app.task
def send_code_to_email(code_user, email_user):
"""
Отправка письма с кодом подтверждения
"""
mail_sent = send_mail(
... | SimonaSoloduha/fitness | authentication/tasks.py | tasks.py | py | 605 | python | ru | code | 0 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.