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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
10289153237 | from paprika.core.base_signal import Signal
from paprika.data.fetcher import DataType
from paprika.data.feed_subscriber import FeedSubscriber
from paprika.signals.signal_data import SignalData
from paprika.data.data_channel import DataChannel
from paprika.alpha.base import Alpha
from paprika.data.data_processor import ... | hraoyama/radish | paprika/signals/signals/alpha_unit.py | alpha_unit.py | py | 2,770 | python | en | code | 1 | github-code | 1 |
13649108676 | import json
from rest_framework import status
from api.constans import AutoNotificationConstants, TaskStageConstants
from api.models import *
from api.tests import GigaTurnipTestHelper
class DateTimeSortTest(GigaTurnipTestHelper):
def test_datetime_sort_for_tasks(self):
from datetime import datetime
... | KloopMedia/GigaTurnip | api/tests/test_datetime_sort.py | test_datetime_sort.py | py | 6,128 | python | en | code | 2 | github-code | 1 |
21484583538 | import math
import numpy as np
import scipy.constants as sc
import units as unit
def db_to_abs(db_value):
"""
:param db_value: list or float
:return: Convert dB to absolute value
"""
absolute_value = 10**(db_value/float(10))
return absolute_value
def abs_to_db(absolute_value):
"""
:p... | adiazmont/optical-network-simulator | transmission_system.py | transmission_system.py | py | 23,048 | python | en | code | 4 | github-code | 1 |
33141010072 | import time
from tkinter import *
canvas = Tk()
canvas.title("Reconnext&Teleplan")
canvas.geometry("1366x768")
canvas.resizable(1,1)
bg = PhotoImage(file="images\mb.png")
canvas.attributes ('-transparentcolor','')
mycan = Canvas( width=1366, height=768)
label = Label(font=("Arial", 140, "bold"), fg="green")
l... | khonmv/Bobo | Main Folder/nf/TeleplanZegarek.py | TeleplanZegarek.py | py | 812 | python | en | code | 0 | github-code | 1 |
10327628407 | import numpy as np
import os
from PIL import Image
import cv2
import matplotlib.pyplot as plt
from tqdm import tqdm
import pandas as pd
from config import *
import dlib
def convert_csv_to_jpg(csv_path):
# 加载opencv的人脸识别文件
# 'haarcascade_frontalface_alt' higher accuracy, but slower
# 'haarcascade_frontalfac... | ryangawei/CNN-Facial-Expression-Recognition | src/preprocess.py | preprocess.py | py | 5,897 | python | en | code | 16 | github-code | 1 |
13457456760 | from spacy.lang.en import English
import numpy as np
import srsly
from flask import Flask, render_template
patterns = srsly.read_jsonl("Backend/skill_patterns.jsonl")
nlp = English()
ruler = nlp.add_pipe("entity_ruler")
ruler.add_patterns(patterns)
def extract_keywords(txt):
doc = nlp(txt)
keywords = lis... | MAlshaik/Joblify | Backend/analyzer.py | analyzer.py | py | 1,008 | python | en | code | 0 | github-code | 1 |
44293486284 | import pygame
import os
pygame.font.init()
WIDTH, HEIGHT = 1100, 800
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Cowboy shooter")
class Draw_Controller:
def __init__(self, covers, P1, P2, Bullet_Controller):
self._DESERT = pygame.transform.scale(pygame.image.load(os.path.j... | Ivailo2707/Pygame_Project_Cowboy | Draw_Controller.py | Draw_Controller.py | py | 1,641 | python | en | code | 1 | github-code | 1 |
8478882949 | from bs4 import BeautifulSoup
from selenium import webdriver
import requests
import csv
browser = webdriver.Chrome()
URL = "https://search.shopping.naver.com/search/all?query=%EB%B0%80%ED%82%A4%ED%8A%B8%20%EB%96%A1%EB%B3%B6%EC%9D%B4&pagingIndex=1"
URLTEST = "https://search.shopping.naver.com/search/all?query=%EC%83%9D... | setda1494/MyCode | Python/1-1/home/data crawling/MultipleProduct.py | MultipleProduct.py | py | 954 | python | en | code | 0 | github-code | 1 |
19152762512 | from django.test import TestCase
from django.core.urlresolvers import reverse
from committee.models import Committee, Meeting
class ResponseStatus(TestCase):
def test_committees(self):
response = self.client.get(reverse('committee-hub'))
self.assertEqual(response.status_code, 200)
def test_c... | imagreenplant/beacon-food-forest | committee/tests.py | tests.py | py | 1,001 | python | en | code | 2 | github-code | 1 |
71112237794 | from AIPUBuilder.Optimizer.utils import *
from AIPUBuilder.Optimizer.framework import *
from AIPUBuilder.Optimizer.ops.activation import apply_with_activation, with_activation_out_is_signed, apply_with_activation_quantize, with_activation_allow_merge_out_zerop_to_bias
from AIPUBuilder.Optimizer.logger import *
from AI... | Arm-China/Compass_Optimizer | AIPUBuilder/Optimizer/ops/conv.py | conv.py | py | 14,605 | python | en | code | 18 | github-code | 1 |
12191064034 | import numpy as np; #NumPy package for arrays, random number generation, etc
import matplotlib.pyplot as plt #for plotting
import pandas as pd
#Simulation window parameters
startpoint = [[-100,-1000],[-100,0],[-100,1000],[0,-100],[0,100],[100,-100],[100,0],[100,100]]
xx = np.array([])
yy = np.array([])
hz = np.array([... | BongSangKim/colab_test | InterferenceBSppp.py | InterferenceBSppp.py | py | 966 | python | en | code | 0 | github-code | 1 |
28069348557 | from telegram import Bot
from telegram.ext import Dispatcher, PicklePersistence
from handlers import handlers
def setup_bot(token, persistence_filename='persistence'):
# Create bot, update queue and dispatcher instances
bot = Bot(token)
bot_persistence = PicklePersistence(filename=persistence_filename)
... | The0nix/pythonanywhere-tg-bot | bot.py | bot.py | py | 610 | python | en | code | 1 | github-code | 1 |
71114520353 | from plot import *
from bokeh.plotting import output_file, show
from bokeh.models import Div
# example values
layout = column(
Div(text="<h1>Cruise control (PI regulator)</h1>", align="center"),
make_plot(start_velocity=0, end_velocity=50),
make_plots(start_velocity=0, end_velocity=50)
)
output_file("crui... | gg-mike/PUT-3-PA-project | Main.py | Main.py | py | 376 | python | en | code | 0 | github-code | 1 |
72794581795 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from rknn.api import RKNN
#import _init_paths
import cv2
import numpy as np
import math
import threading
from time import sleep
imreadLock = threading.Lock()
#from python_wrapper import *
#import os
import sys
PNET_PYRAMID= np.array([[270,207],[192,147],[136,10... | chenshiqin/mtcnn | demo_camera_spilt.py | demo_camera_spilt.py | py | 26,819 | python | en | code | 5 | github-code | 1 |
4157922495 | from django.urls import path
from .views import (
SignupAPIView,
SigninAPIView,
DeleteUserView,
ProjectMixins,
ProjectDetailMixins
)
urlpatterns = [
path("users/signup/", SignupAPIView.as_view(), name='signup'),
path("users/signin/", SigninAPIView.as_view(), name='signin'),
path("user... | HyeonWooJo/tts-input-service | backend/apis/urls.py | urls.py | py | 531 | python | en | code | 0 | github-code | 1 |
26191591366 | import numpy as np
import matplotlib.pyplot as plt
import torch
from torchvision.io import read_image
from torchvision.ops import masks_to_boxes
def show_mask(mask, ax, random_color=False):
if random_color:
color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
else:
color = np... | anushkumarv/AITestKitchen | SAM/utils/helper.py | helper.py | py | 1,807 | python | en | code | 0 | github-code | 1 |
9324774880 | import csv, re, os
from typing import List, Dict, Tuple
from cProfile import Profile
from pstats import Stats
from vacancy import InputConnect
from statistic import Report, get_statistic, get_salary_level, get_count_vacancies, print_statistic
from Task322 import get_stat_by_year
prof = Profile()
prof.disable()
class... | Elenaz441/Zasypkina | main.py | main.py | py | 13,812 | python | ru | code | 0 | github-code | 1 |
37614366922 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
plt.style.use('fivethirtyeight')
def fit_model(x_train, y_train):
# Fits a linear regression to find the actual b and w that minimize the loss
regression = LinearRegression()
regression.fit(x_train, y_train... | dvgodoy/PyTorchStepByStep | plots/chapter1.py | chapter1.py | py | 1,612 | python | en | code | 622 | github-code | 1 |
10602325825 |
def check(data):
s = [] # 호출할 떄마다 초기화해야되니까
for i in data:
if i == '(' or i == '{':
s.append(i)
elif i == ')' or i == '}':
if data[-1] == i:
s.pop()
else:
return 0
if s:
return 0
else:
return 1
import sy... | nopasanadamindy/Algorithms | 0214/괄호체크_new.py | 괄호체크_new.py | py | 456 | python | en | code | 0 | github-code | 1 |
41559504876 | #!/usr/bin/env python
def fit_lambda(root='j100025+021706', newfunc=True, bucket_name='aws-grivam'):
import time
import os
import numpy as np
import boto3
import json
from grizli_aws.fit_redshift_single import run_grizli_fit
beams, files = get_needed_paths(root, bucket_name=bucket... | grizli-project/grizli-aws | scripts/fit_redshift_local.py | fit_redshift_local.py | py | 2,656 | python | en | code | 0 | github-code | 1 |
14450494565 | import socket
# host = "172.16.98.38"
class Client:
def __init__(self, host = "172.16.98.38", port = 8080) -> None:
self.s = socket.socket()
self.s.connect((host, port))
print("connected")
def make_req(self, com):
self.s.send(com.encode('utf8'))
def read_sock(self, filen... | aleksejvalenkov/hakaton_baumanka | data_transfer/client.py | client.py | py | 749 | python | en | code | 0 | github-code | 1 |
35486364587 | import csv
import os
budget_data_csv = "budget_data.csv"
# declare my variables
months = 0
money = 0
profit = 0
changes = []
greatest_increase = ['', 0]
greatest_decrease = ['', 0]
#open csv
with open(budget_data_csv, "r") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=",")
#skip fir... | Gator1013/python_challenge | PyBank/main.py | main.py | py | 1,904 | python | en | code | 0 | github-code | 1 |
38420624656 | import configparser
import csv
from src.web_monitor import web_monitor
def read_config():
config = configparser.ConfigParser()
config.read('config.ini')
with open("websites.txt", "r") as web_config:
tsv_reader = csv.DictReader(web_config, delimiter='\t')
web_dict = {}
for row in t... | Cy83rr/web_monitor | run_script.py | run_script.py | py | 556 | python | en | code | 0 | github-code | 1 |
41436655263 | import logging
from string import ascii_letters
import pytest
# Import TestListener with a leading underscore to prevent pytest from
# thinking that it's a test class.
from stomp.listener import TestListener as _TestListener
from streamsets.testframework.markers import jms, sdc_min_version
from streamsets.testframewor... | streamsets/datacollector-tests | pipeline/test_jms_stages.py | test_jms_stages.py | py | 5,338 | python | en | code | 17 | github-code | 1 |
70547442913 | import logging
import ask_sdk_core.utils as ask_utils
import openai
from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.dispatch_components import AbstractRequestHandler
from ask_sdk_core.dispatch_components import AbstractExceptionHandler
from ask_sdk_core.handler_input import HandlerInput
from ask_s... | cainfoxy/Alexa-GPT4-CFX | Lambda/lambda_function.py | lambda_function.py | py | 4,046 | python | en | code | 1 | github-code | 1 |
44221249022 | import torch
def tile_features_and_labels(x, y):
"""
Tile the features and lables along the sequence dimension.
Example: the sequence [(x_1,y_1), (x_2, y_2), (x_3, y_3)] encodes 3 different testing paradigms.
We can use [(x_1, y_1), (x_2, y_2), x_3] to predict y_3, [(x_2,y_2), (x_3,y_3), x_1] to predict y_1... | cfifty/CAMP | models/context_model_utils.py | context_model_utils.py | py | 830 | python | en | code | 0 | github-code | 1 |
11178768615 | import pandas
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
data = pandas.read_csv("database.csv")
crop = pandas.read_csv("crop.csv")
city = data['city'].to_list()
max_temp = list(map(int, data['max temperature'].to_list()))
min_temp = li... | dr1810/Agrolect | main.py | main.py | py | 2,546 | python | en | code | 1 | github-code | 1 |
40881700274 | def isPerfect(start, n):
if(n < 1):
return False
total = isPerfect(start, n-1)
if(start % n == 0):
total = total + n
if(start == n):
if(total == (start * 2)):
return True
else:
return False
return total
def isPerfect2(n):
if((2 * n... | malyala/Programming-Paradigms | Haskell/a1/test.py | test.py | py | 1,451 | python | en | code | 0 | github-code | 1 |
22985181208 | from core.performing import Behaviour, Performing
from core.blackboard import Blackboard
from random import gauss
from core.measures import Recorder
class RobotProgram(Behaviour):
def __init__(self, nname, commChannel, movetime, pprecision):
super().__init__(nname)
self.movementTime = movetime
... | stefanomarrone/smcsim | robot/robots.py | robots.py | py | 2,103 | python | en | code | 0 | github-code | 1 |
5737840117 | class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
ans = ""
if len(strs)==0:
return ans
minlen = len(strs[0])
for i in range(1,len(strs)):
minlen = min(minlen, len(strs[i]))
for i in range(0,minlen):
curr = strs[0][i]
... | EthanCLEMENT/Leetcode | 14.py | 14.py | py | 535 | python | en | code | 2 | github-code | 1 |
4295634182 | import streamlit as st
import requests
import streamlit.components.v1 as components
import streamlit.components.v1 as stc
from PIL import Image, UnidentifiedImageError
import PIL.Image
import os
import csv
import pandas as pd
import pymongo
from pymongo import MongoClient
from io import BytesIO
import base... | fl0rch/Pet_Enhacement_Transition | pagina.py | pagina.py | py | 18,889 | python | es | code | 1 | github-code | 1 |
19752680843 | import json
import os
from datetime import datetime
from flask import Flask
from flask import request
from flask import Response
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from kaner.context import GlobalContext as gctx
from kaner.adapter.tokeniz... | knowledgeresearch/kaner | kaner/service.py | service.py | py | 5,904 | python | en | code | 4 | github-code | 1 |
41405496993 | from http import HTTPStatus
from typing import Any
from fastapi import APIRouter, Depends, Request
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi_restful.cbv import cbv
from pydantic.schema import UUID
from src.api.response_models.error import generate_error_responses
from... | Studio-Yandex-Practicum/lomaya_baryery_backend | src/api/routers/report.py | report.py | py | 4,802 | python | ru | code | 26 | github-code | 1 |
32060238017 | from django.shortcuts import render
from core.forms import NameForm
def form_manual(request):
data = {}
if request.method == 'POST':
data['name'] = request.POST.get('name', 'name not found')
data['active'] = request.POST.get('active', 'off')
data['week'] = request.POST.get('week', 'week not fou... | djangomoc/formularios | core/views.py | views.py | py | 927 | python | en | code | 1 | github-code | 1 |
33682119543 | """
28.06.23
@tcnicholas
Utility functions.
"""
import re
from typing import Tuple, List
import numpy as np
from numba import njit
def round_maxr(max_r: float, bin_width: float) -> float:
"""
Round the max_r value by flooring to a multiple of the bin_width.
:param max_r: maximum value of r.
:param ... | tcnicholas/amorphous-calcium-carbonate | ljg_simulator/utils.py | utils.py | py | 3,772 | python | en | code | 4 | github-code | 1 |
19828479754 | from tkinter import *
from tkinter import messagebox
from tkinter import ttk
import mysql.connector
def run(stats):
b_fg=stats[0]; b_bg=stats[1]
background=stats[2]
f=list(stats[3])
f[1]=18
f=tuple(f)
entry_bg=stats[4]; label_fg=stats[5]
entry_select_bg=stats[6]
sql_u=stats... | keertan-balaji/Employee-Database-Management-System | option2.py | option2.py | py | 4,224 | python | en | code | 0 | github-code | 1 |
34251105743 | # -*- coding: utf-8 -*-
import os
import sys
basedir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
# SQLite URI compatible
WIN = sys.platform.startswith('win')
if WIN:
prefix = 'sqlite:///'
else:
prefix = 'sqlite:////'
class Operations:
CONFIRM = 'confirm'
RESET_PASSWORD = 'reset-pa... | tongowen/bkl | app/settings.py | settings.py | py | 2,368 | python | en | code | null | github-code | 1 |
36937439358 | import pprint
import sys
from os import path
import yaml
def to_upper(oldList):
newList = []
for element in oldList:
newList.append(element.upper())
return newList
def find_key(input_dict, target):
solutions = []
for key, value in input_dict.items():
for i in to_upper(value):
... | richardphi1618/personal_finances | test/match_key.py | match_key.py | py | 999 | python | en | code | 0 | github-code | 1 |
34641424745 | import re
import uuid
from django import template
from django.utils.safestring import mark_safe
from django.template.loader import get_template
from django.utils.translation import gettext as _
from dal_select2.widgets import Select2WidgetMixin
register = template.Library()
@register.inclusion_tag('selia/components... | CONABIO-audio/irekua | irekua/selia/templatetags/selia_components.py | selia_components.py | py | 9,880 | python | en | code | 0 | github-code | 1 |
438838700 | from functools import reduce
import numpy as np
from scipy import optimize, linalg
from utils import *
import itertools
# === Configure ===
np.set_printoptions(precision=3, linewidth=120, suppress=True)
# === Constants ===
ineq_coeff = None
# === Memory Locations ===
mem_loc = [2, 2, 2, 2, 7]
ps_A1, ps... | tcfraser/quantum_tools | archive/chsh_violation.py | chsh_violation.py | py | 3,101 | python | en | code | 1 | github-code | 1 |
74395034273 | from mlfromscratch.supervised.random_forest import Random_forest
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
def test():
iris = load_iris()
X = iris['data']
y = iris['target']
X_train... | harjotsodhi/ML-from-scratch | mlfromscratch/testing/test_random_forest.py | test_random_forest.py | py | 965 | python | en | code | 0 | github-code | 1 |
10328266017 | import os
import re
import shutil
import sys
# 遍历当前文件夹及其子文件夹
root_folder = "."
target_folder_name = "images"
# 遍历文件夹及子文件夹
for root, dirs, files in os.walk(root_folder):
# 如果当前目录已经存在 images 子目录,则跳过操作
if target_folder_name in dirs:
dirs.remove(target_folder_name)
continue
for filename in fi... | DawnT0wn/Learning-History | imageHandler.py | imageHandler.py | py | 3,166 | python | en | code | 3 | github-code | 1 |
8244780315 | from sorting.merge_sort import merge_sort
def bucket_sort(lst, f, k):
"""
Sorts the given list with bucket sort algorithm.
:param lst: The unsorted list
:param f: A function f: element e -> [0, 1[ with f(e) <= f(e') if e <= e'
:param k: number of buckets
:return: the sorted list
"""
bu... | MoritzM00/AlgorithmsAndDataStructures | sorting/bucket_sort.py | bucket_sort.py | py | 519 | python | en | code | 0 | github-code | 1 |
18481811861 | # -*- coding: utf-8 -*-
"""
Functions to analyze the distances between given number inside a sudoku.
"""
# STD
from collections import defaultdict
import math
import functools
# EXT
import numpy
import matplotlib.pyplot as plt
from scipy.linalg import eigh
# PROJECT
from general import Sudoku, SudokuCollection, read... | Kaleidophon/shiny-robot | experiments/distances.py | distances.py | py | 9,676 | python | en | code | 1 | github-code | 1 |
42716172674 | from tkinter import *
from turtle import width
window = Tk()
window.geometry("700x500")
window.title("Formularios en Tkinter | DokkenLee")
# Texto Encabezado
header = Label(window, text="Formularios con Tkinter - Milton Ponce")
header.config(
fg = "white",
bg = "darkgray",
font = ("Open Sans", 18),
p... | MiltonPonceRodriguez1/master-python | 21-tkinter/06-formularios.py | 06-formularios.py | py | 1,593 | python | es | code | 0 | github-code | 1 |
9196596468 | from collections import namedtuple
import altair as alt
import math
import pandas as pd
import streamlit as st
"""
# Welcome to Streamlit!
Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:
If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
fo... | kathleenmariekelly/streamlit-example | streamlit_app.py | streamlit_app.py | py | 7,031 | python | en | code | null | github-code | 1 |
30992767830 | from fastapi import HTTPException
from fastapi.param_functions import Depends
from fastapi_users.fastapi_users import FastAPIUsers
from sqlalchemy.sql import select, delete
from sqlalchemy.ext.asyncio.session import AsyncSession
from sqlalchemy.sql.expression import desc
from starlette.responses import Response
from fa... | HakierGrzonzo/PBL-polsl-2022 | backend/backend/measurements.py | measurements.py | py | 13,022 | python | en | code | 3 | github-code | 1 |
37402669477 | from numpy import finfo, log
eps = finfo(float).eps
def compute_kullback_leibler_divergence(pdf_0, pdf_1):
pdf_0[pdf_0 < eps] = eps
pdf_1[pdf_1 < eps] = eps
return pdf_0 * log(pdf_0 / pdf_1)
| UCSD-CCAL/ccal | ccal/compute_kullback_leibler_divergence.py | compute_kullback_leibler_divergence.py | py | 209 | python | en | code | 0 | github-code | 1 |
6609929946 | import pytest
from unittest.mock import MagicMock, patch
from cura.PrinterOutput.Models.ExtruderConfigurationModel import ExtruderConfigurationModel
from cura.PrinterOutput.Models.MaterialOutputModel import MaterialOutputModel
from cura.PrinterOutput.Models.PrinterConfigurationModel import PrinterConfigurationModel
fr... | Ultimaker/Cura | tests/PrinterOutput/TestPrinterOutputDevice.py | TestPrinterOutputDevice.py | py | 3,837 | python | en | code | 5,387 | github-code | 1 |
35057815224 | class Solution:
def uniquePaths(self, m: int, n: int) -> int:
return self.solvePath(m,n)
def solvePath(self, m, n, memo = {}):
key = str(m) + "," + str(n)
if(key in memo.keys()):
return memo[key]
if(m == 0 or n == 0):
return 0
... | lazyCodes7/DSA | 30-Days-Of-DSA/Day3/gridtraveler.py | gridtraveler.py | py | 539 | python | en | code | 2 | github-code | 1 |
36038820473 | def twoSum(numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
num2idx = {}
for i in range(len(numbers)):
if numbers[i] in num2idx:
num2idx[numbers[i]].append(i+1)
else:
num2idx[numbers[i]] = [i+1]
for n in numb... | zhaoxy92/leetcode | 167_2sum.py | 167_2sum.py | py | 854 | python | en | code | 0 | github-code | 1 |
29448425552 | from PIL import Image
from flask import Flask, request, render_template
from glob import glob
import os
from imageTransfer import Transfer
import numpy as np
class PathInfo(object):
def __init__(self):
style_img_paths = glob('static/style/*.jpg') + glob('static/style/*.jpeg') + glob('static/style/*.png')
... | Jieqianyu/styleTransfer | server.py | server.py | py | 2,650 | python | en | code | 4 | github-code | 1 |
22292869539 | # Serach in the file
fname = input('Enter the file name: ')
try:
fhand = open(fname)
count = 0
# count the number of the lines which start with "From"
#for line in fhand:
# line = line.strip('\n') #Strip the newline symbol
# if not line.startswith('From'):
# continue
# print(line)
#print(fhand)
... | ChanghaoWang/py4e | Chapter7_Files/search.py | search.py | py | 804 | python | en | code | 1 | github-code | 1 |
25092121024 | from __future__ import print_function
import os.path
from time import sleep
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from vidconvert import getframes
f... | ray1i/googledocs-bad-apple | main.py | main.py | py | 3,375 | python | en | code | 1 | github-code | 1 |
45394487316 | #!python
#!/usr/bin/python3
import threading
import _thread
from time import ctime
from atexit import register
def atexit_1():
print("All Done")
@register
def atexit_2():
print("All finished", end="")
register(atexit_1)
lock = _thread.allocate_lock()
lock.acquire()
print(lock.locked())
lock.release()... | cl900522/feature-view | python3-feature-view/basic/fun_self_plan.py | fun_self_plan.py | py | 359 | python | en | code | 0 | github-code | 1 |
25098499183 |
# this will beeeeeee eeeeee
# from ConfigParser import RawConfigParser
import os
PROJECT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
project_path = lambda a: os.path.join(PROJECT_PATH, a)
here = lambda a: os.path.join(os.path.abspath(os.path.dirname(__file__)), a)
# config = RawConfigParser(... | rajmohanperiyasamy/iservice | iservice/settings.py | settings.py | py | 3,282 | python | en | code | 0 | github-code | 1 |
71681471074 | # -*- coding: utf-8 -*-
import logging
import werkzeug
from odoo import SUPERUSER_ID, api, http, _
from odoo import registry as registry_get
from odoo.addons.web.controllers.main import (login_and_redirect, ensure_db, set_cookie_and_redirect)
from odoo.exceptions import AccessDenied
_logger = logging.getLogger(__name_... | chenrongxu/login_sso | controllers/controllers.py | controllers.py | py | 1,975 | python | en | code | 0 | github-code | 1 |
4474723624 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 27 19:24:35 2020
@author: Scott T. Small
This module demonstrates documentation as specified by the `NumPy
Documentation HOWTO`_. Docstrings may extend over multiple lines. Sections
are created with a section header followed by an underline of equal... | stsmall/abc_scripts2 | project/stat_modules/sumstats.py | sumstats.py | py | 12,274 | python | en | code | 3 | github-code | 1 |
19309406675 | from tkinter import ttk
from window import Window
from game import Game
from leaderboard import Leaderboard
from dimensions import mainFrame
class Menu(Window):
def __init__(self):
Window.menu = self
self.frame = ttk.Frame(self.window)
Leaderboard()
self.frame.grid(rowspan=2,colu... | wjld/MineMineMine | menu.py | menu.py | py | 2,125 | python | en | code | 0 | github-code | 1 |
11612600962 | import random
from game.enums import *
class AI:
def __init__(self, board):
self.board = board
def make_random_move(self):
x = random.randint(0, self.board.size - 1)
y = random.randint(0, self.board.size - 1)
return x, y
class EasyAI(AI):
def __init__(self, board):
... | theoilside/go_game | game/ai.py | ai.py | py | 3,280 | python | en | code | 0 | github-code | 1 |
29434652675 | """
Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0).
"""
max_val = int(input("Please give a maximum value of n: "))
def calc(n:int):
i = 1
sum = 0
while i <= n:
out = i/(i+1)
sum += out
i +=1
print(f'Output: {sum:.2f}')
calc(max_val... | devaksu/100_Python_Exercises | 60-70/60.py | 60.py | py | 321 | python | en | code | 0 | github-code | 1 |
35881891250 | from selenium import webdriver
class ImageMonkeyChromeWebDriver(webdriver.Chrome):
def __init__(self, headless=True, delete_all_cookies=True):
options = webdriver.ChromeOptions()
if headless:
options.add_argument('--headless')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--no-s... | ImageMonkey/imagemonkey-core | tests/ui/webdriver.py | webdriver.py | py | 451 | python | en | code | 46 | github-code | 1 |
16069403722 | import json
from qwikidata.sparql import (get_subclasses_of_item,
return_sparql_query_results)
import logging
queries_log = logging.getLogger('QUERIES')
class Queries:
@staticmethod
def query(query=None, json_path=None, log="", already_asked=False, limit=None):
if limit ... | lucastorrealba/CC7220 | app/cc7220/extra/queries.py | queries.py | py | 7,412 | python | en | code | 0 | github-code | 1 |
36427186703 | """
199. Binary Tree Right Side View
Medium
1076
46
Favorite
Share
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 ... | fengyang95/OJ | LeetCode/python3/199_BinaryTreeRightSideView.py | 199_BinaryTreeRightSideView.py | py | 1,718 | python | en | code | 2 | github-code | 1 |
36976850467 | # -*- coding: utf-8 -*-
###########################################################
# Send data from a simple device (raspberry, gpu, watch) to another device
# version 0.5
# syntaxe:
# python this_script_name remote_ip dataname [value] or python this_script_name start_server
# eg: python this_script_name 1... | alexandre-mazel/electronoos | scripts/versatile/versatile.py | versatile.py | py | 54,037 | python | en | code | 2 | github-code | 1 |
13223905757 | # -*- coding: utf-8 -*-
"""Concentration layer
This module contains code for calculating PSD concentration based on dilution and volume
"""
# Importing dependencies
import tensorflow as tf
from tensorflow.keras.layers import Input, Lambda
from tensorflow.keras.models import Model
class ConcentrationModel:
"""
... | rfjoni/ParticleModel | hybrid_model/layers/ConcentrationModel.py | ConcentrationModel.py | py | 2,274 | python | en | code | 7 | github-code | 1 |
30675767566 | from .values import *
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
def setParagraphType(paragraph):
if paragraph[:7].upper() == CHAPTER_TEXT:
type = CHAPTER_TEXT
elif paragraph[:10].upper() == DEDICATION_TEXT:
type = EXTRA_SECTION
elif paragraph[:14].upper()... | Cristian-G-P/Writer-Apps | Flask-Web-App-Tutorial-main/website/callistoAuxFunctions.py | callistoAuxFunctions.py | py | 7,872 | python | en | code | 0 | github-code | 1 |
18187098239 | import re
import sqlite3
import os
import glob
import datetime as dt
import bokeh.models
import xarray
import numpy as np
from functools import lru_cache
from forest.exceptions import FileNotFound, IndexNotFound
from forest.old_state import old_state, unique
import forest.util
import forest.map_view
from forest import ... | MetOffice/forest | forest/drivers/eida50.py | eida50.py | py | 11,480 | python | en | code | 38 | github-code | 1 |
69890553314 | import agent.potil_lstm as agent
from expert_dataloader import ExpertLoader, ExpertLoader_each_step
import agent.utils as utils
import sys
sys.path.append('/catkin_workspace/src/ros_kortex/kortex_examples/src/move_it')
import torch
torch.backends.cudnn.benchmark = True
from mpl_toolkits import mplot3d
import numpy as n... | ZDDWLIG/KinovaArm_PegInsert_DRL | BC_train.py | BC_train.py | py | 4,776 | python | en | code | 3 | github-code | 1 |
7074320791 | #!/usr/bin/env python
# coding: utf-8
# # Image_Segmentation
# ## 1. Contours
# ### Contours are continuous lines or curves that bound or cover the full-boundary of an object in an image
# In[1]:
import cv2 #importing necessary libraries
import numpy as np
# In[2]:
image=... | Prasad3617/IMAGE-MANIPULATIONS | Image_Segmentation.py | Image_Segmentation.py | py | 1,228 | python | en | code | 1 | github-code | 1 |
9641595094 | import numpy as np
import dezero.functions as F
import dezero.layers as L
from dezero import Variable
np.random.seed(0)
x = np.random.rand(100, 1)
y = np.sin(2 * np.pi * x) + np.random.rand(100, 1)
x = Variable(x) # type:ignore
y = Variable(y)
I, H, O_ = 1, 10, 1
l1 = L.Linear(I, H)
l2 = L.Linear(H, O_)
def predi... | copipe/dezero | steps/step44.py | step44.py | py | 740 | python | en | code | 0 | github-code | 1 |
16965004254 | # Задание-1:
# Написать программу, выполняющую операции (сложение и вычитание) с простыми дробями.
# Дроби вводятся и выводятся в формате:
# n x/y ,где n - целая часть, x - числитель, у - знаменатель.
# Дроби могут быть отрицательные и не иметь целой части, или иметь только целую часть.
# Примеры:
# Ввод: 5/6 + 4/7 (вс... | DaniilKrk/HW | L03/L03_Hard.py | L03_Hard.py | py | 8,686 | python | ru | code | 0 | github-code | 1 |
29499148195 | from flask import render_template, url_for, flash, redirect, request, abort, jsonify, make_response
from app import app, db, bcrypt, mail
from forms import *
from models import *
from flask_login import login_user, current_user, logout_user, login_required
from routes.commonRoutes import commonTempRoute
@app.route("... | alankhoangfr/NilStock_Inventory | routes/supplierRoutes.py | supplierRoutes.py | py | 5,120 | python | en | code | 0 | github-code | 1 |
74418296034 | from movielog import api as movielog_api
from movielog.cli import confirm, radio_list
def prompt() -> None:
options = [
(None, "Go back"),
(update_titles_and_people, "<cyan>Update titles and people</cyan>"),
(
update_watchlist_person_credits,
"<cyan>Update watchlist... | fshowalter/movielog | movielog/cli/imdb.py | imdb.py | py | 930 | python | en | code | 1 | github-code | 1 |
15405786193 | #!/usr/bin/env python3
"""
https://adventofcode.com/2022/day/9
"""
from collections import namedtuple
from operator import add, sub
import aoc
PUZZLE = aoc.Puzzle(day=9, year=2022)
class Point(namedtuple('Point', ('x', 'y'))):
"""A point class with overridden operators"""
def __abs__(self):
return ... | trosine/advent-of-code | 2022/day09.py | day09.py | py | 1,929 | python | en | code | 0 | github-code | 1 |
73587061154 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 26 2017
Description:
Input: symbols of chosen stocks
Randomly assign weights to given stocks.
Calculate portfolio return, volatility, and Sharp Ratio.
Output: portfolio with maximum SR or minimum volatility
@author: chenkai
"""
import nump... | chenkai0208/Quantitative_Finance_in_Python | portfolio_optimization.py | portfolio_optimization.py | py | 3,072 | python | en | code | 3 | github-code | 1 |
23015193717 | from dataclasses import field
from rest_framework import serializers
from django.contrib.auth import get_user_model
import requests
import json
from apps.core.models import UserRole
from apps.core.serializers import MyAccountSerializer, UserAppointment, UserSerializer
from apps.profiles.serializers import CounsellorPr... | rupendra-p/ekurakani | apps/appointment/serializers.py | serializers.py | py | 4,487 | python | en | code | 0 | github-code | 1 |
23033727735 | # gets grupy data and runs a plotting function
import matplotlib.pyplot as plt
def GruPlot( prefix, q_labels, gru_data):
fig, axes = plt.subplots(nrows=1, ncols=1)
x = []
lab = []
for i in xrange( len(q_labels) ):
lab.append( q_labels[i][1] )
x.append( q_labels[i][0] )
plt.setp(axes, xticks=x, xticklabel... | alex-miller-0/grupy | Versions/1.0/grupy/GruPlot.py | GruPlot.py | py | 561 | python | en | code | 5 | github-code | 1 |
35942244086 | import heapq
from collections import defaultdict
from typing import List
start_and_end_times = [[4, 7], [2, 5], [1, 3], [5, 8]]
# test_tuples = [(1, 5), (3, 4), (3, 3), (2, 1), (2, 7), (1, 1)]
# heapq.heapify(test_tuples)
def max_concurrency_best(s):
"""Naive method to solve max_concurrency. Passes all tests!"... | eforgacs/schoolSandbox | fundamental_algorithms/Midterm/max_concurrency.py | max_concurrency.py | py | 7,345 | python | en | code | 0 | github-code | 1 |
24412532866 | from appFile import request, app, ma, cross_origin
from models.index import db, Events, Timeline
from flask import jsonify
from controllers.auth import JWTcheck
class EventSchema(ma.Schema):
class Meta:
fields = ('id', 'name', 'info', 'timeline_id', 'day', 'month', 'year', 'time', 'date_created')
event_schema =... | Snugles/onTimeline | server/controllers/events.py | events.py | py | 2,173 | python | en | code | 0 | github-code | 1 |
35270222913 |
def function_names(open_file_handler):
'''
This function takes in an open_file_handler (python file) and will scan
though it to find function names within the file.
:param open_file_handler: io.TextIOWrapper, a file handler in the read mode
:return: list of strings
'''
# Two lists, one of f... | dmf444/CSCA08-Python | CSCA08/Exercise5/ex5.py | ex5.py | py | 1,599 | python | en | code | 0 | github-code | 1 |
37749262526 | import os
import requests
import shutil
import boto3
from PIL import Image
import urllib.request
access_key_src = os.environ.get("AWS_ACCESS_KEY_ID")
secret_key_src = os.environ.get("AWS_SECRET_ACCESS_KEY")
region_name = os.environ.get("AWS_REGION_NAME")
bucket_name = os.environ.get("AWS_MEDIA_BUCKET_NAME")
bucket_fol... | trungannl/globallink-upload-media-master | uploadwebp/cron.py | cron.py | py | 2,536 | python | en | code | 0 | github-code | 1 |
23670216784 | import pandas as pd, numpy as np
import re
import pickle
dataset = pd.read_csv("Restaurant_Reviews.csv")
dataset['Review']
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
corpus = []
for i in range(0, 1000):
review = re.sub('[^a-zA... | MM1026-DS/Ml-web-nlp-app | app_1.py | app_1.py | py | 1,549 | python | en | code | 1 | github-code | 1 |
22549796737 | from PIL import Image
import PIL.ImageOps
from shutil import move
def alpha_channel_upscale(inpath, outpath, workingImage, settings):
"""Opens the current working image as well as the original image, resizes (BICUBIC) the original image and copies the alpha channel"""
originalImage = Image.open(workingImage.or... | RainbowRedux/TextureUpscalingPipeline | TextureUpscaler/AlphaChannelUpscale.py | AlphaChannelUpscale.py | py | 833 | python | en | code | 5 | github-code | 1 |
21097072993 | def primeNumb():
testNum = int(input("Enter an integer to test for prime: "))
if testNum > 1:
for i in range(2,testNum):
#print(i)
if (testNum % i) == 0:
print(testNum, "is not a prime number")
print(i,"times",testNum//i,"is",testNum)
... | NetworkAsCode/getMerakiLicensingStatus | test.py | test.py | py | 546 | python | en | code | 0 | github-code | 1 |
70953465635 | 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:TreeNode, val: int) -> TreeNode:
while root:
if root.val == val:
return root
elif... | steventejeda/DSA-Solutions | search_in_a_binary_tree.py | search_in_a_binary_tree.py | py | 875 | python | en | code | 0 | github-code | 1 |
74129330593 | """Test the A-priori, position-based and hybrid method in freqsubseq.py. """
import unittest
from freqsubseq import initialized_tree, candidates, run_apriori
from freqsubseq import assign_pattern_index, initialized_queue
from freqsubseq import candidate_mappings, run_position
from freqsubseq import number_of_freq_sub... | chiahungyang/FreqSeqPatternMining | Scripts/test_algorithms.py | test_algorithms.py | py | 7,450 | python | en | code | 0 | github-code | 1 |
11343329447 | import re
from utils import logger
BIO_PATTERN = re.compile(r'\[(.+?)\](_[A-Z]{3}_)')
BIO_BEGIN = re.compile(r'_[A-Z]{3}_\[')
BIO_END = re.compile(r'\]_[A-Z]{3}_')
def pre_process(text):
text = BIO_PATTERN.sub(r'\2[\1]\2', text)
i = 0
res = []
label = ''
is_begin = False
is_inner = False
... | henryhyn/caesar-next | ner/ner_utils.py | ner_utils.py | py | 2,017 | python | en | code | 1 | github-code | 1 |
186882541 | import json
import pandas as pd
import numpy as np
def processing_title(title):
return title.upper()
def processing_author(author):
return author.title()
def processing_discount(discount):
try:
discount = discount.replace('%dcto', '')
return int(discount)
except ValueError:
... | avilanac/book_tracker_buddy | processing.py | processing.py | py | 2,114 | python | en | code | 0 | github-code | 1 |
37850912162 | # Fails: 251.py
# Autors: Dmitrijs Doronins
import Tkinter as tk
root= tk.Tk()
root.title("Mana Bilde")
w = tk.Canvas(root, width=600, height=400, bg="#abc")
w.pack()
linija = w.create_line(50,100,400,300,width='5',fill='#FF0')
root.mainloop()
| dmitriydoronin/Dmitrij141REB169 | darbi2/LD25/251.py | 251.py | py | 251 | python | en | code | 0 | github-code | 1 |
23205933467 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import dgl
from dgl.base import DGLError
from dgl.ops import edge_softmax
import dgl.function as fn
class Identity(nn.Module):
"""A placeholder identity operator that is argument-insensitive.
(Identity has already been supp... | taotianli/gin_model.py | examples/pytorch/tgn/modules.py | modules.py | py | 18,905 | python | en | code | 5 | github-code | 1 |
31342061733 | import unittest
from datetime import date
from sqlalchemy import inspect, func, Numeric
from src.modelo.actividad import Actividad
from src.modelo.gasto import Gasto
from src.modelo.viajero import Viajero, ActividadViajero
from src.modelo.declarative_base import Session, engine, Base
from src.logica.Logica_mock import... | ManuelMasferrer/MISW4101-202111-Grupo57-sandbox | tests/ivan_gastos_actividad_testcase.py | ivan_gastos_actividad_testcase.py | py | 4,990 | python | es | code | 0 | github-code | 1 |
29599272508 | import argparse
import cv2
import logging as log
import sys
import time
import socket
import paho.mqtt.client as mqtt
import json
import math
import os
from inference import Network
# Set the MQTT server environment variables
HOSTNAME = socket.gethostname()
IPADDRESS = socket.gethostbyname(HOSTNAME)
MQTT_HOST = IPAD... | jonathanyeh0723/OpenVINO_People_Counter_App | main.py | main.py | py | 7,735 | python | en | code | 2 | github-code | 1 |
71773999394 | """EJERCICIO 3
El día juliano correspondiente a una fecha es un número entero que indica los días que han
transcurrido desde el 1 de enero del año indicado. Queremos crear un programa principal que
al introducir una fecha nos diga el día juliano que corresponde. Para ello podemos hacer las
siguientes subrutinas:
Leer... | dvidals/python | ejercicios_clase_interfaces/ejer_funciones3.py | ejer_funciones3.py | py | 2,974 | python | es | code | 0 | github-code | 1 |
16516618905 | from __future__ import absolute_import, division, print_function,\
with_statement
import collections
import errno
import socket
import logging
import ssl
import sys
from tornado import ioloop
from tornado.log import gen_log
from tornado.netutil import ssl_wrap_socket, ssl_match_hostname, \
SSLCertificateError... | zinic/pyrox | pyrox/tstream/iostream.py | iostream.py | py | 20,656 | python | en | code | 37 | github-code | 1 |
16926588360 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
---------------------------------------------------------------------------------------------------
calc_razao_curva
DOCUMENT ME!
revision 0.2 2015/nov mlabru
pep8 style conventions
revision 0.1 2014/nov mlabru
initial version (Linux/Python)
---------------------... | contemmcm/pytracks | ptracks/model/emula/cine/calc_razao_curva.py | calc_razao_curva.py | py | 3,431 | python | pt | code | 0 | github-code | 1 |
70205998754 | from typing import List
from .. import DeviceModel, _template_env
from . import signed_weight
class IntegratorModel(DeviceModel):
ng_spice_model_name = 'int'
def __init__(
self,
model_name: str,
in_offset: float = 0.0,
gain: float = 1.0,
out_lower_limit: float = -10.0,... | hammal/cbadc | src/cbadc/circuit/models/integrator.py | integrator.py | py | 2,546 | python | en | code | 8 | github-code | 1 |
33820929017 | from werkzeug.utils import secure_filename
import sqlite3
import json
import os
class DatabaseHelper:
"""
This help to manage databases.
"""
def __init__(self) -> None:
pass
def save_image(self, main_dir: str, user_token: str, images: dict) -> bool:
"""
save_image() will ... | s3h4n/CVIS | packages/db_helper/db_helper.py | db_helper.py | py | 1,171 | python | en | code | 0 | github-code | 1 |
70888279075 | # 서로 다른 N개의 자연수의 합이 S라고 한다. S를 알 때, 자연수 N의 최댓값은 얼마일까?
s = int(input())
l = 1
r = s
answer = 0
while l <= r:
mid = (l+r)//2
add = mid*(mid+1)//2
if add <= s:
l = mid + 1
answer = mid
elif add > s:
r = mid - 1
print(answer) | rhkddud3917/Algorithm-Practice | BOJ/1789-수들의합.py | 1789-수들의합.py | py | 331 | python | ko | code | 0 | github-code | 1 |
26481678278 | import torch
import gym
from model import Model
from collections import deque
import numpy as np
from env_wrapper import FlappyBirdEnv
env = FlappyBirdEnv(render_mode = "human")
policy = Model(4, 2)
def reinforce(policy, n_training_episodes, max_t, gamma, print_every):
is_pick = True
scores_deque = deque(maxl... | qvd808/flappy-bird-policy-gradient | flappy_bird_env.py | flappy_bird_env.py | py | 2,299 | python | en | 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.