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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
73931882429 | #!python
"""
A natural number, N, that can be written as the sum and product of a given set of at least two natural numbers, {a1, a2, ... , ak} is called a product-sum number: N = a1 + a2 + ... + ak = a1 × a2 × ... × ak.
For example, 6 = 1 + 2 + 3 = 1 × 2 × 3.
For a given set of size, k, we shall call the smallest N ... | DanMayhem/project_euler | 088.py | 088.py | py | 2,498 | python | en | code | 0 | github-code | 6 |
20521018910 | """!
@brief Assert that are used for testing
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
"""
import numpy
class assertion:
@staticmethod
def eq(argument1, argument2):
if isinstance(argument1, numpy.ndarray) or isinstance(argument2, numpy... | annoviko/pyclustering | pyclustering/tests/assertion.py | assertion.py | py | 3,532 | python | en | code | 1,113 | github-code | 6 |
2870616186 | import operator
import struct
from enum import Enum
from collections import defaultdict, namedtuple, deque
import simulatorOps.utils as utils
from simulatorOps.abstractOp import AbstractOp, ExecutionException
class HalfSignedMemOp(AbstractOp):
saveStateKeys = frozenset(("condition",
... | mgard/epater | simulatorOps/halfSignedMemOp.py | halfSignedMemOp.py | py | 9,179 | python | en | code | 35 | github-code | 6 |
28116032092 | import numpy as np
class LinearRegressionDemo:
def __init__(self, learning_rate=1e-3, n_iters=1000):
# init parameters
self.lr = learning_rate
self.n_iters = n_iters
self.weights = None
self.bias = None
def _get_prediction(self, X):
return np.dot(X, self.weights... | Nishaa95/Intro_to_Machine_Learning_Student_Workbooks | linear_reg_demo_grad_desc.py | linear_reg_demo_grad_desc.py | py | 1,736 | python | en | code | 0 | github-code | 6 |
6589861302 | from elasticsearch import Elasticsearch
import pandas as pd
from contexttimer import Timer
es = Elasticsearch(
"http://rgai3.inf.u-szeged.hu:3427/",
basic_auth=("elastic", "V7uek_ey6EdQbGBz_XHX"),
verify_certs=False
)
def get_highlights(csv, es, size):
# adatok kinyerése pd-ből, a már tisztított kérd... | szegedai/SHunQA | scripts/evals/highlights_score_test_w_preprocessed_questions.py | highlights_score_test_w_preprocessed_questions.py | py | 5,241 | python | hu | code | 0 | github-code | 6 |
36060772305 | # #!/usr/bin/env python3
import json
import socket
from utils.save_json import save_json
def initSocket(ip, port, diretorio):
dir = 'src/json/'+diretorio+'.json'
dicionario = ''
try:
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp.bind((ip, port))
tcp.listen(2)
w... | AntonioAldisio/FSE-2022-2-Trabalho-1 | src/servidor/servidor.py | servidor.py | py | 847 | python | pt | code | 0 | github-code | 6 |
6420520466 | import time
import datetime
import math
import logging
class Logger():
def __init__(self):
self. start_time = time.time()
self.logger = logging.getLogger()
self.logger.setLevel(logging.INFO)
print('Starting ' + str(datetime.datetime.now()))
@staticmethod
def printLog(*messa... | Script-2020/autoclusteringFinReports | util/Logger.py | Logger.py | py | 1,437 | python | en | code | 0 | github-code | 6 |
28326166820 | """
OCR Pagination
"""
from past.utils import old_div
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from django.conf import settings
from ocr.permission import get_permissions
# -------------------------------------------------------------------------------
# p... | Srinidhi-SA/temp_spark | SPARK_DOCKER/code/mAdvisor-api/ocr/pagination.py | pagination.py | py | 3,723 | python | en | code | 0 | github-code | 6 |
35603813874 | """
Duncan Rule, Sally Gao, Yi Hao
"""
class MDPState:
"""State class for a given space in gridworld, with directional attributes pointing to other squares.
Each directional attribute is a tuple of coordinates (x, y). """
def __init__(self, up, down, left, right, reward=-1, value=0):
self.up = up
... | sally-gao/mazemdp | mdpstate.py | mdpstate.py | py | 507 | python | en | code | 5 | github-code | 6 |
39222512159 | # %% [markdown]
# 複数ファイルの集計をしていく。
#
# 複数のデータを,1つのDataFrame に要約する方法は,主に2通りあるので,両方紹介する。
#
# 1. 1人分のデータをたくさん用意して,最後に複数の行を1つにまとめる
# - concat メソッドを用いる
# 2. 必要な統計量を人数分まとめた列を必要なだけ用意して,最後に複数の列をまとめる
# - DataFrame を ディクショナリで生成する
# %% [markdown]
# ## 1人分のデータをたくさん用意して,最後に複数の行を1つにまとめる
# %%
# 複数人のデータを順番に読んで,同じ処理をすればよい。
# ... | KeiShimon/lecture | python-kisoc_day_3/05-01a-複数ファイルの集計.py | 05-01a-複数ファイルの集計.py | py | 4,108 | python | ja | code | 0 | github-code | 6 |
34690028943 | from django.contrib import admin
from .models import Service, Category, Feature, FeatureItem
class FeatureItemInline(admin.StackedInline):
model = FeatureItem
@admin.register(Service)
class ServiceAdmin(admin.ModelAdmin):
list_display = ("name", "sub_title")
prepopulated_fields = {"slug": ("name",)}
... | samshultz/techbitsdata | services/admin.py | admin.py | py | 855 | python | en | code | 0 | github-code | 6 |
31543778104 | marks = [[0 for j in range(30)] for i in range(3)]
max_stud = [0,0,0]
for i in range(3):
max_stud[i] = int(input(f"\n\tEnter Maximum students in class {i+1} : "))
print()
if not 0 < max_stud[i] < 31:
print("\tStudents in a class can only be between 1 to 30")
exit(0)
for j in rang... | Shobhit0109/programing | EveryOther/Practical File/python/P8.py | P8.py | py | 554 | python | en | code | 0 | github-code | 6 |
1790565048 | import pdfplumber
import pandas as pd
from babel.numbers import format_currency
def extrair_tabelas(pdf_path):
with pdfplumber.open(pdf_path) as pdf:
# Inicialize uma lista para armazenar todas as tabelas
todas_tabelas = []
# Itera sobre todas as páginas do PDF
for pagina in pdf.pa... | regis-amaral/python-scripts | fatura-pdf/reader-fatura.py | reader-fatura.py | py | 1,927 | python | pt | code | 0 | github-code | 6 |
18797455208 | # -*- coding:utf-8 -*-
import urllib.request
import urllib.parse
# get取网页数据
def geturl(url, data={}, headers={}):
try:
params = urllib.parse.urlencode(data)
req = urllib.request.Request("%s?%s" % (url, params))
# 设置headers
for i in headers:
req.add_header(i, headers[i])... | yunmenzhe/HttpInterfaceAutoTest | utils/httputil.py | httputil.py | py | 906 | python | en | code | 0 | github-code | 6 |
7227006625 | import tqdm
import argparse
import os
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--src-set', '-src-set', type=str, default=r'/home/v-jiaya/RetrieveNMT/data/MD/en-de/iwslt14-en-de/train/train.en',help='source file')
parser.add_argument('--new-src-set', '-new-tgt-set', t... | CSJianYang/RetrieveNMT | RetrieveNMT/SMT/generate_align_data.py | generate_align_data.py | py | 1,178 | python | en | code | 3 | github-code | 6 |
32069589714 | # Задание выполнил, но "обходным путем" - через выпрямление списка в ините
# понимаю, что нужно реализовать задание через рекурсию, но не получается выполнить
# В первой реализации развил логику из задания 1, но из-за return возвращается
# только первый элемент вложенного списка
# Вторая реализация - облегченный, с уп... | sokkos1995/PYDA | module5_adanced_python/hw4/task3.py | task3.py | py | 4,187 | python | ru | code | 0 | github-code | 6 |
17689672862 | import torch
from torch.nn import Module, Conv2d, LeakyReLU, PReLU, BatchNorm2d, Sequential, PixelShuffle, AdaptiveAvgPool2d, Flatten, Linear, Dropout2d, Dropout
class ResidualUnit(Module):
def __init__(self):
super(ResidualUnit, self).__init__()
self.conv1 = Sequential(Conv2d(64, 64, 3, 1, "same")... | abed11326/Training-a-Super-Resolution-GAN-for-4x-image-upscaling | models.py | models.py | py | 2,878 | python | en | code | 0 | github-code | 6 |
35007925134 | from src.main.python.Solution import Solution
# Follow up for "Remove Duplicates":
# What if duplicates are allowed at most twice?
#
# For example,
# Given sorted array nums = [1,1,1,2,2,3],
#
# Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3.
# It doesn't ... | renkeji/leetcode | python/src/main/python/Q080.py | Q080.py | py | 904 | python | en | code | 0 | github-code | 6 |
12100194486 | import unittest
import itertools
from functools import partial
from bst import BST
def _factory(l):
_b = BST(l[0])
for item in l[1:]:
_b.insert(item)
return _b
class TestBST(unittest.TestCase):
def _check_node(self, node, item, left_child, right_child):
self.assertEqual(item, node.i... | Shaywei/MyDevTools | Python/BasicDataStructures/bst_tests.py | bst_tests.py | py | 5,123 | python | en | code | 0 | github-code | 6 |
38949670839 | class Solution:
# @param {string} s A string
# @return {boolean} whether the string is a valid parentheses
def isValidParentheses(self, s):
stack = []
dict = {')':'(', '}':'{', ']':'['}
for ch in s:
if ch in dict.values():
stack.append(ch)
elif... | sublingbling/coding-everyday | 10_26_2016_valid-parentheses/chang.py | chang.py | py | 523 | python | en | code | 1 | github-code | 6 |
36822122944 | import random
from turtle import Turtle, Screen
class Blocks(Turtle):
def __init__(self):
super().__init__()
self.penup()
self.shape("square")
self.turtlesize(stretch_len=3, stretch_wid=1)
self.goto(x=-450, y=0)
self.row_num = {1: 0, 2: 25, 3: 50, 4: 75, 5: 100, 6: ... | guitarkeegan/breakout-game | blocks.py | blocks.py | py | 1,302 | python | en | code | 0 | github-code | 6 |
69895141309 | # -*- encoding: utf-8 -*-
"""
lunaport.domain.line
~~~~~~~~~~~~~~~~~~~~
Line related business logic
"""
import string
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from base import BaseFactory, BaseAdaptor, BaseEntrie
class Line(BaseEntrie):
"""
Line(power line or queue) - district of... | greggyNapalm/lunaport_server | lunaport_server/domain/line.py | line.py | py | 1,844 | python | en | code | 0 | github-code | 6 |
33262623475 | """
1) Создайте текстовое поле.
2) Попросите пользователя ввести в консоли произвольную строку.
3) Выведите эту строку в текстовом поле окна.
Примечание: запрос строки и её вывод в текстовом поле должны происходить до mainloop().
"""
from tkinter import *
def setWindow(root):
root.title("Окно программы") # Зада... | kuzbassghost/Course | BaseRus/GUI/Homework_4.py | Homework_4.py | py | 1,674 | python | ru | code | 0 | github-code | 6 |
20855466611 | import requests
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json
import os
from decouple import config
from prettyprinter import pprint
import GUI
# For the API documentation go to
# https://coinmarketcap.com/api/documentation/v1/#section/Quick-Start-Guide
API_KEY = config("API... | edumarg/cyrpto_currency_portfolio | main.py | main.py | py | 4,492 | python | en | code | 0 | github-code | 6 |
27773506390 | import os
import asyncio
from telepyrobot.setclient import TelePyroBot
from pyrogram import filters
from pyrogram.types import Message, ChatPermissions
from telepyrobot import COMMAND_HAND_LER
from telepyrobot.utils.admin_check import admin_check
__PLUGIN__ = os.path.basename(__file__.replace(".py", ""))
__help__ = f... | Divkix/TelePyroBot | telepyrobot/plugins/chat.py | chat.py | py | 4,652 | python | en | code | 40 | github-code | 6 |
34351667294 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
data = pd.read_csv('CCLhora2.csv')
data1 = pd.read_csv('CCLdia2.csv')
data2 = pd.read_csv('CCLsemana2.csv')
data3 = pd.read_csv('CCLmes2.csv')
data4 = pd.read_csv('CCLaño2.csv')
data["date"] = pd.to_datetime(data["date"], unit='ms')
data1["date"]... | pedrolf8/MastodonTFG | paso.py | paso.py | py | 869 | python | en | code | 0 | github-code | 6 |
74087520829 | # -*- coding: utf-8 -*-
import re
import datetime
import bs4
import scrapy
from scrapy_wssc.Item.BookContentItem import BookContentItem
from scrapy_wssc.Item.BookItem import BookItem
class mobile_spider(scrapy.Spider):
name = 'mobile_spider'
def __init__(self, bid=None):
"""初始化起始页面和游戏bid
""... | chenrunhu/wssc_scrapy | scrapy_wssc/spiders/mobile_spider.py | mobile_spider.py | py | 4,566 | python | en | code | 0 | github-code | 6 |
19412768499 | def get_serialized_rows_by_id(cls, validated_params, rqst_errors):
rqst_staff_id = validated_params['id']
if rqst_staff_id != 'all':
list_of_ids = validated_params['id_list']
else:
list_of_ids = None
navigator_qset = filter_navigator_qset_by_id(cls.objects.all(), rqst_staff_id, list_of_... | bbcawodu/careadvisors-backend | picmodels/models/care_advisors/navigator_models/services/read.py | read.py | py | 11,586 | python | en | code | 0 | github-code | 6 |
44730303411 | import os
import discord
from discord.utils import get
from discord.ext import commands, tasks
from dotenv import load_dotenv
import random
import re
import time
import requests
load_dotenv()
OMDB_KEY = os.getenv('OMDB_KEY')
STREAMING_KEY = os.getenv('STREAMING_KEY')
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.geten... | aburpee/spongebob-text | app.py | app.py | py | 5,748 | python | en | code | 0 | github-code | 6 |
3281849942 | import torch
import wandb
from torch import nn
import torchvision.utils as vutils
def get_time_emb(dim, time):
pos = torch.arange(0, time, dtype=torch.float)
omega = torch.arange(dim // 2, dtype=torch.float)
omega /= dim / 2.0
omega = 1.0 / 10000 ** omega
out = torch.einsum("m,d->md", pos, omega)
... | Shimanogov/bert-slots | model.py | model.py | py | 12,552 | python | en | code | 0 | github-code | 6 |
12864757051 | import streamlit as st
import pandas as pd
import numpy as np
import re
import json
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import math
import warnings
warnings.filterwarnings('ignore')
from PIL import Image
# Page setup
st.set_pag... | smsraj2001/MINI-SEARCH-ENGINE | app.py | app.py | py | 14,858 | python | en | code | 2 | github-code | 6 |
17195304707 | #threading better due to network I/O hinderances
#from threading import Thread
#multiprocessing used for cpu intensive processes (no networking hinderances)
from multiprocessing import Process, Queue
from time import time
def check_value_in_list(x, j, num_of_processes, queue):
max_num_to_check = 10**8
lower_bnd = ... | ganton000/Concurrency | multiprocessing-tutorial/main.py | main.py | py | 1,200 | python | en | code | 0 | github-code | 6 |
43633237973 |
from __future__ import absolute_import
#typing
import numpy
#overrides
import torch
from torch.nn.modules.linear import Linear
import torch.nn.functional as F
from allennlp.common.checks import check_dimensions_match
from allennlp.data import Vocabulary
from allennlp.modules import Seq2SeqEncoder, TimeDistributed, T... | plasticityai/magnitude | pymagnitude/third_party/allennlp/models/simple_tagger.py | simple_tagger.py | py | 6,916 | python | en | code | 1,607 | github-code | 6 |
40201462407 | import cv2
import numpy as np
import pandas as pd
import json
from scipy.spatial.distance import cdist
import os
# Get fps of given video
def getFps(path):
vidObj = cv2.VideoCapture(path)
fps = vidObj.get(cv2.CAP_PROP_FPS)
print("Frames per second using video.get(cv2.CAP_PROP_FPS) : {0}".format(fps))
... | orhungorkem/SIFTDetector | main.py | main.py | py | 11,935 | python | en | code | 0 | github-code | 6 |
17944337782 | import json
from django.views.generic import DetailView, ListView, View, CreateView
from django.core.exceptions import ImproperlyConfigured
from django.http import (
HttpResponse,
HttpResponseBadRequest,
HttpResponseRedirect
)
from django.contrib.auth.decorators import login_required
from django.utils.deco... | rvause/djangodash2013 | suggestions/views.py | views.py | py | 6,614 | python | en | code | 3 | github-code | 6 |
23588347895 | from time import sleep
import psycopg2
import os
import subprocess
from datetime import datetime
from pytz import timezone
import filecmp
db_name = os.environ['POSTGRES_DB']
db_user = os.environ['POSTGRES_USER']
db_pass = os.environ['PGPASSWORD']
db_host = os.environ['POSTGRES_HOST']
db_port = os.environ['POSTGRES_PO... | cjrisua/vinomio-api | docker/vinomioHC/app.py | app.py | py | 2,723 | python | en | code | 0 | github-code | 6 |
6056727556 | #!/usr/bin/env python3
import re
import collections
import vcf
import sys
import argparse
import copy
def parse_my_args():
parser = argparse.ArgumentParser("Combines a VCF of individual calls into one large VCF for population.")
parser.add_argument("vcf", nargs="?", help="Input VCF file; default stdin.")
... | jgbaldwinbrown/vcfstats | combine_single_indivs.py | combine_single_indivs.py | py | 2,138 | python | en | code | 0 | github-code | 6 |
11002868168 | from typing import List
class WordFilter:
def __init__(self, words: List[str]):
self.a ={}
for ind, i in enumerate(words):
for j in range(len(i) + 1):
for k in range(len(i) + 1):
now = i[:j] + '$' + i[k:]
self.a[now] = ind
... | xixihaha1995/CS61B_SP19_SP20 | 745. Prefix and Suffix Search.py | 745. Prefix and Suffix Search.py | py | 702 | python | en | code | 0 | github-code | 6 |
38046454992 | #!/usr/bin/env python3
import os
import sys
import rzpipe
curdir = os.path.dirname(os.path.realpath(__file__))
rz = rzpipe.open(curdir + "/ls", ["-2"])
# print(rzpipe.__file__)
# print(rzpipe.VERSION)
rz.cmd("aa")
sys.stdout.write("/bin/ls ")
pi1 = rz.cmd("pi 1 @e:scr.color=0").strip()
if pi1 == "push rbp":
... | rizinorg/rz-pipe | python/examples/test.py | test.py | py | 407 | python | en | code | 26 | github-code | 6 |
4732908565 | import xml.etree.ElementTree as ET
from datetime import datetime
from bs4 import BeautifulSoup
class XMLParser:
def __init__(self, file: str):
self.file = file
self.parameters = {'INPUT':{},
'DISCRIMINATOR':{},
'QDC':{},
'SPECT... | Chujo58/ReadROOT | XML_Parser.py | XML_Parser.py | py | 11,752 | python | en | code | 0 | github-code | 6 |
9642933289 | import socket
udpsocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
udpsocket.bind(("localhost",7777))
print("UDP server is up and listening")
pair = udpsocket.recvfrom(1024)
res = pair[0]
add = pair[1]
print("Response from client :")
print("Message Received: ", res.decode())
print("Address of clie... | vaibhav477/TCP_chat_app | UDP_Implementation/server.py | server.py | py | 607 | python | en | code | 0 | github-code | 6 |
20602647000 | import sys
sys.path.append('../')
# sys.path.insert(0, '/path/to/application/app/folder')
# from flask import Flask
#from flask_testing import TestCase
import unittest
from unittest import TestCase
import read_ini
# class MyTest(TestCase):
# def create_app(self):
# app = Flask(__name__)
# ... | BhujayKumarBhatta/flask-learning | flaskr/tests/test_read_ini.py | test_read_ini.py | py | 1,580 | python | en | code | 1 | github-code | 6 |
74530690747 | #!/usr/bin/env python3
"""antipatibot, discord server."""
import asyncio
import logging
import os
import secrets
from dataclasses import dataclass
import discord
from discord.ext import commands
import yt_dlp as youtube_dl
youtube_dl.utils.bug_reports_message = lambda: ''
ytdl_format_options = {
'format': 'besta... | antipatico/antipatibot | antipatibot.py | antipatibot.py | py | 14,449 | python | en | code | 0 | github-code | 6 |
39672933944 | import pytest
import common
@pytest.mark.parametrize(
"data,start,end",
[
("0-0", 0, 0),
("11-22", 11, 22),
],
)
def test_parse(data: str, start: int, end: int):
assert common.SectionRange.parse(data) == common.SectionRange(start, end)
@pytest.mark.parametrize(
"range1,range2,res... | cmatsuoka/aoc | 2022 - expedition/04 - camp cleanup/test_common.py | test_common.py | py | 1,252 | python | en | code | 0 | github-code | 6 |
26197481166 | """
Data import
https://github.com/tategallery/collection
"""
import json
import os
import sys
import time
import pandas as pd
csv_file = '/media/joji/DATA/workspace/data/artwork_data.csv'
selected_columns = ['id', 'artist', 'title', 'medium', 'year',
'acquisitionYear', 'height', 'width', 'units']
... | jojimpv/pandasdemo1 | demo3.py | demo3.py | py | 841 | python | en | code | 0 | github-code | 6 |
12691211626 | import os
from twilio.rest import Client
from urllib.request import urlopen
import re
import time
import smtplib
#need twilio credientials to run
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]
twilio_number = os.environ["TWILIO_NUMBER"]
ubc_url = "https://courses.students.... | benkenj/UBCCourseNotifier | UBCCourseNotifierMain.py | UBCCourseNotifierMain.py | py | 3,405 | python | en | code | 0 | github-code | 6 |
71456631549 | import boto3
from operator import itemgetter
ecr_client = boto3.client('ecr')
repositories = ecr_client.describe_repositories()['repositories']
if len(repositories) == 0:
print("Repository is empty!")
for repo in repositories:
print(f"Repository name: {repo['repositoryName']}")
query_repository_name = "java... | ArshaShiri/DevOpsBootcampPythonAutomationAssignment | ecr_in_aws.py | ecr_in_aws.py | py | 728 | python | en | code | 0 | github-code | 6 |
6923620355 | #encoding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import StringIO
import json
import logging
import random
import urllib
import urllib2
# functions
import responseHandler
# standard app engine imports
from google.appengine.api import urlfetch
from google.appengine.ext import ndb
import webapp2
# ... | eglantine-shell/xiaoyiqingbot-2022 | main.py | main.py | py | 3,527 | python | en | code | 0 | github-code | 6 |
16543818867 | from nuitka.nodes.CallNodes import makeExpressionCall
from nuitka.nodes.ConstantRefNodes import makeConstantRefNode
from nuitka.nodes.ContainerMakingNodes import (
makeExpressionMakeTuple,
makeExpressionMakeTupleOrConstant,
)
from nuitka.nodes.DictionaryNodes import makeExpressionMakeDictOrConstant
from nuitka.... | Nuitka/Nuitka | nuitka/tree/ReformulationCallExpressions.py | ReformulationCallExpressions.py | py | 10,742 | python | en | code | 10,019 | github-code | 6 |
10747823823 | '''S3 uploader module'''
import os
import time
import signal
import sys
import boto3
# This module seems to have some issues. pylint ignore them
from setproctitle import setproctitle, getproctitle # pylint: disable=E0611
from kafkatos3.ThreadPool import ThreadPool
def upload_file(self, filename):
'''horrible c... | snowch/kafkatos3 | kafkatos3/S3Uploader.py | S3Uploader.py | py | 2,919 | python | en | code | null | github-code | 6 |
40128810884 | #!/usr/bin/env python3
import itertools
from collections import defaultdict
from heapq import heappush, heappop
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.buffer.readline
INF = 10 ** 9 + 1 # sys.maxsize # float("inf")
def debug(*x):
print(*x, file=sys.stderr)
def blute_solve(N, AS):
"void(... | nishio/atcoder | abc173/d.py | d.py | py | 2,643 | python | en | code | 1 | github-code | 6 |
31574941802 | from PIL import Image
import sys
import argparse
from os.path import exists
import time
import math
import re
import tkinter as tk
from tkinter import filedialog, ttk
import threading
import population
import province
import vicmap
mod_dir_loc = ""
save_file_loc = ""
map_type = ""
glob... | neopythagorean/vic2mapper | src/mapper.py | mapper.py | py | 12,604 | python | en | code | 2 | github-code | 6 |
27214693785 | """
Overview:
Functions to deal with encoding binary data easily.
"""
import sys
from typing import Optional, List
import chardet
from ..collection import unique
_DEFAULT_ENCODING = 'utf-8'
_DEFAULT_PREFERRED_ENCODINGS = ['utf-8', 'gbk', 'gb2312', 'gb18030', 'big5'] # common encodings for chinese
__all__ = [
... | HansBug/hbutils | hbutils/encoding/decode.py | decode.py | py | 2,040 | python | en | code | 7 | github-code | 6 |
15792066200 | import argparse
from os import listdir, makedirs
from os.path import isfile, join, basename, dirname, isdir
from PIL import Image
from tqdm import tqdm
# folder_path = 'photos'
# left, top, right, bottom = 559, 225, 1361, 0
# -d ./photos -s ./photos2 -c -a 559 225 1361 0
def build_argparse():
parser = argparse.... | zsoman/photo_editing | PhotoCropper.py | PhotoCropper.py | py | 4,114 | python | en | code | 0 | github-code | 6 |
38194485687 | # -*- coding: utf-8 -*-
"""
env:python3
author:Jiashuai Liu
to choose from 3 types by 5 characters
"""
import numpy as np
# Random consistency index
RI_dict = {1: 0, 2: 0, 3: 0.58, 4: 0.90, 5: 1.12, 6: 1.24, 7: 1.32, 8: 1.41, 9: 1.45}
# The weight is obtained and calculated by sum method
def get_w(array):... | Liujiashuai/mathematical-modeling | AHP.py | AHP.py | py | 2,504 | python | en | code | 1 | github-code | 6 |
19886899760 | import os
import pytest
from pendulum import datetime
from pathlib import Path
from hypothesis_trio.stateful import (
initialize,
rule,
run_state_machine_as_test,
TrioAsyncioRuleBasedStateMachine,
)
from hypothesis import strategies as st
from guardata.client.types import EntryID, LocalFileManifest, Ch... | bitlogik/guardata | tests/client/fs/workspacefs/test_file_transactions.py | test_file_transactions.py | py | 10,393 | python | en | code | 9 | github-code | 6 |
32371281333 | import cv2
import matplotlib.pyplot as plt
def plotImg(img):
if len(img.shape) == 2:
plt.imshow(img, cmap='gray')
plt.show()
else:
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()
t=0
img = cv2.imread('cv.png')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
binary_... | RisinPhoenix12/Computer-Vision | dots.py | dots.py | py | 818 | python | en | code | 1 | github-code | 6 |
25097367954 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 19 13:24:42 2022
@author: maria
"""
import numpy as np
import pandas as pd
from numpy import zeros, newaxis
import matplotlib.pyplot as plt
import scipy as sp
from scipy.signal import butter,filtfilt,medfilt
import csv
import re
import functions2022_07_15 as fun
import cP... | mariacozan/Analysis_and_Processing | functions/2022-07-19_checking_log_file.py | 2022-07-19_checking_log_file.py | py | 2,748 | python | en | code | 0 | github-code | 6 |
27984730572 | from Circle import Circle
def main():
circle1 = Circle()
print(circle1.radius, " ", format(circle1.get_area(), ".4f"))
circle2 = Circle(5)
print(circle2.radius, " ", format(circle2.get_area(), ".3f"))
circle3 = Circle(25)
print(circle3.radius, " ", format(circle3.get_area(), ".3f"))
cir... | skyclouds2001/Python-Learning | study-7/7-2.py | 7-2.py | py | 413 | python | en | code | 1 | github-code | 6 |
30984637396 | from datetime import datetime
from constants import ProducerTypes
from events.producers import get_producer
from events.utils import get_routing_key
from models import (
Task,
TaskCost,
)
from popug_schema_registry.models.v1.task_cost_added_event_schema import (
TaskCostAddedEventSchema,
)
def send_task... | Drozdetskiy/popug_jira | popug_accounting/src/events/taskcost/send_event.py | send_event.py | py | 857 | python | en | code | 5 | github-code | 6 |
41211788790 | from keras.applications.resnet50 import ResNet50
from keras.preprocessing import image
from keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np
import os
import json
from PIL import Image
import requests
from io import BytesIO
import urllib3
urllib3.disable_warnings(urllib3.exce... | ming19956/PFE | information-retrival-search-engine/informationRetrival/resnet50/resnet50.py | resnet50.py | py | 3,180 | python | en | code | 2 | github-code | 6 |
30779245065 | #Ask user for name
name=input("Enter your name: ")
#Ask user for the age
age=input("Enter your age: ")
#Ask city
city= input("Enter the city name you live in: ")
#Ask what they enjoy
like=input("Enter what you like to do:")
#Create output text
sentence="Your name is {} and you are {} years old. you live in {} and y... | Sruti-Dey/python_mini_projects | 02_hello_you.py | 02_hello_you.py | py | 404 | python | en | code | 0 | github-code | 6 |
33055278390 | import psycopg2 as psy
import pandas as pd
# Class for connect and write Postgresql
class PsycopgPostgresWarehouse:
def __init__(self, host, database, user, pw, port):
self.host = host
self.database = database
self.user = user
self.pw = pw
self.port = port
# Connect D... | Tana8M/data-engineer-assignment | pipeline/function/postgresql_function/psycopg2_postgresql.py | psycopg2_postgresql.py | py | 4,631 | python | en | code | 0 | github-code | 6 |
34111450286 | """helloworld URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-ba... | githubrghd/mydemo | python-demo/helloworld/helloworld/urls.py | urls.py | py | 1,551 | python | en | code | null | github-code | 6 |
74672197946 | #we use flag variables as a signal to the program for systems where multiple conditions may end a while loop
#we set the flag to either True or False
active = True
prompt = "Tell Me Your Name and I Will Give It A Godly Title "
message = ""
while active:
message = input(prompt)
if message == "quit":
active = Fa... | ncortezi/python_education_2023 | chapter_7/intro_flags.py | intro_flags.py | py | 374 | python | en | code | 0 | github-code | 6 |
10241474430 | import scipy
import copy
import numpy as np
def gesd(x, **kwargs):
x_ = np.array(x)
alpha = 0.05 if 'alpha' not in kwargs else kwargs['alpha']
n_out = int(np.ceil(len(x_) * 0.1)) if 'n_out' not in kwargs else kwargs['n_out']
outlier_side = 0 if 'outlier_side' not in kwargs else kwargs['outlier_side']
... | WHThhhh/Seeg_prepro | GESD_wht.py | GESD_wht.py | py | 1,421 | python | en | code | 2 | github-code | 6 |
23007665672 | #!/usr/bin/env python
#
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Top levels scripts to extract castro data from an all-sky analysis
"""
import os
import argparse
import numpy as np
import yaml
from astropy import table
from fermipy import fits_utils
from dmpipe import dmp_roi
from dmpi... | fermiPy/dmpipe | dmpipe/scripts/extract_castro_data.py | extract_castro_data.py | py | 3,510 | python | en | code | 0 | github-code | 6 |
18932829460 | # === Úloha 5===
# Napíšte program, ktorý zistí pomocou funkcie, v ktorom týždni počas roka mal Janko najvyššie výdavky na sladkosti. Jankove výdavky vygeneruje program ako desatinné čísla v rozsahu (0€-2,55€) s presnosťou na dve desatinné miesta.
from random import randint
def najvyssie(vydavky):
i_najvisieho = 0
... | Plasmoxy/MaturitaInformatika2019 | ulohyPL/u05.py | u05.py | py | 775 | python | sk | code | 2 | github-code | 6 |
18464161519 | # Libraries
import pandas as pd
import re, sqlite3
# Reading the data
data = pd.read_csv('Digimon_cards.csv')
# Connecting with the database
con = sqlite3.connect('Digimon_Cards.sqlite')
cur = con.cursor()
# Inserting the data
## Card type's table
insert_card_type = 'INSERT INTO Card_types(name) VALUES'... | davidr9708/Digimon_Card_Game | Code/3_Data_insertion.py | 3_Data_insertion.py | py | 4,306 | python | en | code | 9 | github-code | 6 |
11081518318 | # 'local file' or 'database'
data_source = 'local file'
# if data is loaded from local file, provide file name:
file_name = 'city_rides_2020.pkl'
# columns that the data is grouped by. Should be compatible with file name
# if data is loaded from file.
groupby_cols = ['from_city', 'dep_week']
# color column is scaled ... | relaxingdave/network_visualization | config.py | config.py | py | 678 | python | en | code | 0 | github-code | 6 |
35424778344 | from art import higher_lower,vs
from game_data import data
import random
import os
#Display art
score = 0
game_continue = True
account_b = random.choice(data)
def format_data(account):
"""Takes the account data and return the printable format"""
account_name = account["name"]
account_desc =... | pav537/Python | Higher_Lower Game.py | Higher_Lower Game.py | py | 1,900 | python | en | code | 0 | github-code | 6 |
18677295647 | #!/usr/bin/env python
"""
Unit tests for module `msg`.
"""
from msg import Msg
if __name__ == '__main__':
# for testing only
#import msg
m = Msg()
m.enable_color(True) # only required to force coloured output to file
m.prefix_set('myprog') # make a prefix for following msg's
m.info('Hello World (to stdout... | Open-Technology-Foundation/msg | unittests/msg-test.py | msg-test.py | py | 2,402 | python | en | code | 0 | github-code | 6 |
39940042757 | import numpy as np
import matplotlib.pyplot as plt
import os.path
import Style
import sys
zsims = ['3.61', '4.038','5.017']
simnom = ['SAGE']
cm = plt.get_cmap('tab10') # Colour map to draw colours from
path2sim = 'C:/Users/Olivia/TFG-TUT/'
for iiz, zsim in enumerate(zsims):
for sim in simnom:
ffav = path... | Ovive57/TFG-TUT | Dibujo_Medias_corte_10.py | Dibujo_Medias_corte_10.py | py | 2,682 | python | en | code | 1 | github-code | 6 |
69877253629 | import torch
from torch import nn
import yaml
import cv2
import numpy as np
from vidgear.gears import CamGear
from matplotlib import pyplot as plt
from IPython.display import Image, clear_output
import argparse
import os
import datetime
import sys
from PIL import ImageFont, ImageDraw, Image
import time
from pathlib imp... | yeonsoo98/yolov5_object_count | detect.py | detect.py | py | 5,852 | python | ko | code | 0 | github-code | 6 |
21640069600 | from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from .models import VideoFile
class VideoFileForm(forms.ModelForm):
"""Form for user file uploading."""
def clean(self):
cleaned_data = super().clean()
original... | sergeybe/video-archive | src/video/forms.py | forms.py | py | 813 | python | en | code | 0 | github-code | 6 |
15309466710 | import asyncio
from misc import dp,bot
from .sqlit import reg_user
from aiogram import types
channel1 = -1001804437355
content_id = -1001165606914
print(1)
markup = types.InlineKeyboardMarkup()
bat_a = types.InlineKeyboardButton(text='Access to group 🔑', url = 'https://t.me/share/url?url=https%3A%2F%2Ft.me%2F%2BH4v... | pytera895143242/spec2rep | handlers/commands_start.py | commands_start.py | py | 1,164 | python | en | code | 0 | github-code | 6 |
13111704429 | def update_single(conn, cursor, table, column, file_number, var):
# update a single column in a sql db. Key is file_number.
sql_update = "UPDATE " + table + " SET " + column + "= ? WHERE File_number = '" + file_number + "'"
cursor.execute(sql_update, [var])
conn.commit()
def insert(conn, cursor, table... | dakelkar/Create_BreastCancerDB | new_version/add_update_sql.py | add_update_sql.py | py | 1,264 | python | en | code | 0 | github-code | 6 |
30272112886 | from .views import *
from django.urls import path
urlpatterns = [
path('', home, name='home'),
path('login/', login_user, name='login'),
path('contact/', contact, name='contact'),
path('api/<str:userid>/', api, name='api'),
path('logout/', logout_user, name='logout'),
path('register/', register... | supratim531/hetc-web | scholarship/urls.py | urls.py | py | 693 | python | en | code | 0 | github-code | 6 |
29575131193 | import json
from argo_ams_library import AmsException, AmsMessage, ArgoMessagingService
class PullPublish:
def __init__(self, config):
self.pull_sub = config["pull_sub"]
self.pub_topic = config["pub_topic"]
self.pull_topic = config["pull_topic"]
self.ams = ArgoMessagingService(end... | rciam/rciam-federation-registry-agent | ServiceRegistryAms/PullPublish.py | PullPublish.py | py | 2,400 | python | en | code | 3 | github-code | 6 |
15768547417 | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Type
from django.db.models import JSONField
from django.db.models.lookups import Lookup
from pymilvus.client.types import DataType
from .lookups import get_nearest_n
if TYPE_CHECKING:
from django_milvus.connection import Connection
clas... | kaleido-public/django-milvus | django_milvus/fields.py | fields.py | py | 2,190 | python | en | code | 4 | github-code | 6 |
73925325948 | CUSTOMERS = [
{
"id": 1,
"name": "Ryan Tanay"
},
{
"id": 2,
"name": "Keeley Jones"
},
{
"id": 3,
"name": "Summer Smith"
}
]
def get_all_customers():
return CUSTOMERS
# Function with a single parameter
def get_single_customer(id):
# Varia... | kellyfrancoeur/kennel-server | views/customer_requests.py | customer_requests.py | py | 1,601 | python | en | code | 0 | github-code | 6 |
12731720405 | #/usr/bin/python3.8
"""
This example implements the interaction between Qt Widgets and a 2D
matplotlib plot showing a gaussian curve with scipy.
This app displays a graph inside gui
"""
import sys
import numpy as np
from scipy.stats import norm
from matplotlib import pyplot as plt
from matplotlib.figure import Figure
... | ndlopez/learn_python | learn_qt/qt_graph.py | qt_graph.py | py | 2,123 | python | en | code | 0 | github-code | 6 |
70504080829 | from naman.core.models import VLan
from django.core.exceptions import ImproperlyConfigured
def assign_provisioning_vlan(machine):
print("Entering assign_provisioning_vlan")
prov_vlans = VLan.objects.filter(provisioning_purpose=True)
if prov_vlans.count() == 0:
raise ImproperlyConfigured("Missin... | jpardobl/naman | naman/core/mappings/vlan_actions.py | vlan_actions.py | py | 2,859 | python | en | code | 0 | github-code | 6 |
36385272432 | """
create some fake json book cover records from the book review dataset from kaggle.
it's a very basic implementation for development - too clean for testing.
"""
import pandas as pd
# read the relevant fields into memory
df = pd.read_json('book_list.json') # type:pd.DataFrame
# remove unneeded cols
df = ... | didactapp/didact-fake-json-data-generator | fake_chapters.py | fake_chapters.py | py | 896 | python | en | code | 0 | github-code | 6 |
34045997209 | from faster_rcnn.config import cfg, get_output_dir
import argparse
from utils_py3.timer import Timer
import numpy as np
import cv2
from utils_py3.cython_nms import nms
# from utils_py3.boxes_grid import get_boxes_grid
import pickle
# import heapq
from utils_py3.blob_helper import im_list_to_blob
import os
import math... | hx121071/faster-rcnn-tf-py3 | lib/faster_rcnn/test.py | test.py | py | 8,840 | python | en | code | 1 | github-code | 6 |
16257468366 | import re
import pytest
from morphocut import Pipeline
from morphocut.file import Find, Glob
@pytest.mark.parametrize("sort", [True, False])
@pytest.mark.parametrize("verbose", [True, False])
def test_Find(data_path, sort, verbose, capsys):
d = data_path / "images"
with Pipeline() as pipeline:
filen... | morphocut/morphocut | tests/test_file.py | test_file.py | py | 770 | python | en | code | 7 | github-code | 6 |
71316404667 | import requests
from bs4 import BeautifulSoup
import json
def get_pinned(github_user):
URL = f"https://github.com/{github_user}"
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
pinned_data = soup.find_all("div", {"class": "pinned-item-list-item-content"})
pinned_posts = ... | HectorPulido/HectorPulido | ReadmeGenerator/scraper.py | scraper.py | py | 3,744 | python | en | code | 10 | github-code | 6 |
15306370520 | """ File: eulerCharacteristics.py
Description: calculates the characteristics of the 2D Euler equation.
This includes the flux and the eigenvectors associated with it
Author: Pierre-Yves Taunay
Date: November 2018
"""
import numpy as np
from utils import P_from_Ev
GAM = 1.4
def compute_euler_flux(U,direction):
... | pytaunay/weno-tests | python/euler_2d/eulerCharacteristics.py | eulerCharacteristics.py | py | 4,634 | python | en | code | 1 | github-code | 6 |
42557211122 | import numpy
from PIL import Image
def histogram(img):
image_gray = img.convert('L')
killy = numpy.array(image_gray)
maximum = numpy.max(killy)
minimum = numpy.min(killy)
dim = maximum - minimum + 1
hist, bins = numpy.histogram(killy, bins=dim)
return hist
image1 = Image.open("image1.jpg... | jouhaina-nasri/Project-Indexation | TP Indexation/Histogramme/app.py | app.py | py | 2,290 | python | en | code | 0 | github-code | 6 |
22215955629 | import random
import os
def get_answer() -> bool:
"""
functions gets an answer which decides if
some actions will be done
:return:
"""
x = input(str("press y for yes or n for no:"))
while x != "y" and x != "n":
print("you have entered a wrong answer")
x = input(str("press y... | Ramulica/The-Big-Book-of-Small-Python-Projects-solved-by-ramuica- | Angeilic Powers/main.py | main.py | py | 50,582 | python | en | code | 3 | github-code | 6 |
29457712632 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
'''translate.translate: provides main() entry point.'''
__version__ = '0.1.3'
import logging
import argparse
import requests
from bs4 import BeautifulSoup
from terminaltables import AsciiTable
logging.basicConfig(
filename = '.log',
filemode = 'a+',
... | alvarolopez/translate-term | translate/translate.py | translate.py | py | 5,821 | python | en | code | 1 | github-code | 6 |
26305567938 | #!/usr/bin/python3
from main import Session, engine, User
local_session = Session(bind = engine)
#ascending
users = local_session.query(User).order_by(User.username).all()
for user in users:
print(f"{user.username}")
| AndyMSP/holbertonschool-higher_level_programming | 0x0F-python-object_relational_mapping/Practice_Video/ordering.py | ordering.py | py | 225 | python | en | code | 0 | github-code | 6 |
2810887356 | from odoo import api, fields, models
class Note(models.Model):
_inherit = 'note.note'
@api.multi
def act_back(self):
if self._context.get('save_close'):
return {'type': 'ir.actions.act_window_close'}
return {'name': 'Notes',
'type': 'ir.actions.act_window',
'view_id': self.env.ref('note... | erlaangga/note_quick | note_quick/models/note.py | note.py | py | 984 | python | hi | code | 0 | github-code | 6 |
38907343805 | from sqlalchemy.exc import IntegrityError
from sqlalchemy import select
from sqlalchemy.orm import selectinload
from app.core.repo.base import BaseSqlalchemyRepo
from app.core.exceptions.repo import RepoException
from .models import Review
class ReviewRepo(BaseSqlalchemyRepo):
model = Review
async def create... | rasimatics/excursio-backend | app/apps/review/repo.py | repo.py | py | 1,901 | python | en | code | 1 | github-code | 6 |
28427138730 | from smtplib import SMTP
from email.header import Header
from email.mime.text import MIMEText
def main():
# 请自行修改下面的邮件发送者和接收者
sender = 'sunhui@zhongfu.net'
receivers = ['1161186762@qq.com', 'daersunhui@gmail.com']
message = MIMEText('用Python发送邮件的示例代码.', 'plain', 'utf-8')
message['From'] = Header('... | sunhuimoon/Python100Days | day14/day1403.py | day1403.py | py | 772 | python | en | code | 0 | github-code | 6 |
39348226616 | import os
from rebasehelper.types import Options
from rebasehelper.constants import CONFIG_PATH, CONFIG_FILENAME, CHANGES_PATCH
from rebasehelper.plugins.plugin_manager import plugin_manager
OPTIONS: Options = [
# basic
{
"name": ["--version"],
"default": False,
"switch": True,
... | rebase-helper/rebase-helper | rebasehelper/options.py | options.py | py | 8,712 | python | en | code | 42 | github-code | 6 |
24769179889 | squaredWeight = None
def performCollection(cityLevel, filename):
import os
if cityLevel:
outputDir = 'GoogleTrendsCity/'
if not os.path.exists(outputDir):
os.mkdir(outputDir)
else:
outputDir = 'GoogleTrendsCountry/'
if not os.path.exists(outputDir):
... | apanasyu/GoogleTrends | Main.py | Main.py | py | 20,395 | python | en | code | 0 | github-code | 6 |
41562683103 | # It's a combination of two things: [merging and sorting]!
# Exploits the fact that arrays of 0 or 1 element are always sorted
# Works by decomposing an array into smaller arrays of 0 or 1 elements,
# then building up a newly sorted array
# STEPS
# 1. Divide the array, e.j [1, 2, 4, 3] => [1, 2], [4, 3]
# 2. Divde t... | Wainercrb/data-structures | merge-sort/main.py | main.py | py | 2,396 | python | en | code | 0 | github-code | 6 |
25218471687 | from django.db import models
from article.models import Article
from users.models import User
from ckeditor.fields import RichTextField
from mptt.models import MPTTModel, TreeForeignKey
# Create your models here.
class Comment(MPTTModel):
article = models.ForeignKey(Article, on_delete=models.CASCADE)
user = models.Fo... | MenGG6/personal-blog | comment/models.py | models.py | py | 824 | python | en | code | 0 | github-code | 6 |
12646866981 | from django import forms
from .models import Reservation, Testimonial
class ReservationForm(forms.ModelForm):
name = forms.CharField(label='Your Name', widget=forms.TextInput(
attrs={
'class': 'form-control',
'id': 'name',
'placeholder': 'Your Name'
}
... | Dantes696/restaraunt | res/forms.py | forms.py | py | 4,061 | python | en | code | 0 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.