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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
19034241073 | from boat import Boat
from graph import Graph
from node import CrossingNode
import heapq
from argparse import ArgumentParser
import os
import sys
from time import time
def printSolution(file, currentNode, time, maxStackNodes,maxComputedNodes ):
print("Solution:\n")
currentNode.printPath()
print("Time:",... | LupascuMiruna/IA-first-project | code/index.py | index.py | py | 12,609 | python | en | code | 0 | github-code | 13 |
13834210237 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys, os, shutil, json
from subprocess import call
import distutils.dir_util
import configparser
from distutils.version import LooseVersion
from urllib.request import Request, urlopen
GlobalScriptPath = os.path.dirname(os.path.realpath(__file__)).replace('\\','/')
Glo... | MobileGuru1013/MachinaTrader | BuildRelease.py | BuildRelease.py | py | 6,960 | python | en | code | 16 | github-code | 13 |
24845770878 | """module to capture traffic signal information from parsed opendrive file"""
import iso3166
import numpy as np
import warnings
import enum
from typing import Union
from crdesigner.map_conversion.opendrive.opendrive_parser.elements.road import Road
from crdesigner.map_conversion.common.utils import generate_unique_id
... | CommonRoad/crgeo | commonroad_geometric/external/map_conversion/opendrive/opendrive_conversion/plane_elements/traffic_signals.py | traffic_signals.py | py | 11,367 | python | en | code | 25 | github-code | 13 |
19207869813 | from flask_restful import Resource, reqparse, abort
from flask import request, jsonify
def abort_if_task_id_not_exists(task_id):
if task_id not in tasks:
abort (404, message='The task does not exists.')
dict_func_description = {
'1': 'this is first api description',
'helloworld': 'this is second ... | zhuzhy1214/tam_jobmanager | jobmanager/apis/postmile.py | postmile.py | py | 2,435 | python | en | code | 0 | github-code | 13 |
36387452592 | """ Commerce views. """
import logging
from django.conf import settings
from django.views.decorators.cache import cache_page
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from rest_framework.permissions import IsAuthenticated
from rest_framework.status import HTTP_406_NOT_ACCEPTABL... | escolaglobal/edx-platform | lms/djangoapps/commerce/views.py | views.py | py | 5,899 | python | en | code | 0 | github-code | 13 |
17675379406 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 18 23:38:29 2021
@author: pooja
"""
import numpy as np
import sys
def matrix_to_lst(mat):
# converting to 1D list
flatlist = np.array(mat).reshape(-1)
# replacement dictionary
repl = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G',... | pooja-kabra/15-Puzzle-Problem | helpers.py | helpers.py | py | 1,869 | python | en | code | 0 | github-code | 13 |
19112447343 | import sys
sys.path.append("..")
import torch
import numpy as np
from .inversion_losses import _weighted_CS_SE_loss, _gradient_norm_weighted_CS_SE_loss, _squared_error_loss, \
_cosine_similarity_loss
from torch.nn.functional import conv1d
def _uniform_initialization(x_true, dataset=None, device=None):
"""
... | eth-sri/tableak | attacks/initializations.py | initializations.py | py | 8,675 | python | en | code | 6 | github-code | 13 |
32252693950 | # 1 ############################
import os
os.chdir("DZ_files")
def domains_point_free(filename):
try:
with open(filename, "r") as file:
return [line.strip()[1:] for line in file.readlines()]
except FileNotFoundError as error:
return f"No file {error}"
print(domains_point_free("do... | ssocolov/IntroPython_socolov | DZ_lesson6_SSocolov.py | DZ_lesson6_SSocolov.py | py | 1,217 | python | en | code | 0 | github-code | 13 |
1527780346 | class Disjoint_Set:
def __init__(self,arr):
self.arr=arr
self.parent={i:i for i in self.arr}
def find_path_compress(self,ele):
if ele==self.parent[ele]:
print(ele)
return self.parent[ele]
par=self.find_path_compress(self.parent[ele])
self.parent[... | stuntmartial/DSA | Graphs/Disjoint_Sets/owl_fight.py | owl_fight.py | py | 1,585 | python | en | code | 0 | github-code | 13 |
71304936657 | import pygame as pg
import os
import random
pg.init()
WIDTH = 1280
HEIGHT = 720
screen = pg.display.set_mode((WIDTH,HEIGHT))
clock = pg.time.Clock()
map_image = pg.image.load(os.path.join('assets', 'map.png'))
head_image = pg.image.load(os.path.join('assets', 'head.png'))
body_image = pg.image.load(os.path.jo... | rintarou07/python | python-project1/main.py | main.py | py | 5,791 | python | en | code | 0 | github-code | 13 |
20322570935 | with open("20-input.txt") as f:
lines = f.read().strip().split('\n')
def swap(nums, a, b):
nums[a], nums[b] = nums[b], nums[a]
return nums
def sol(p):
KEY = 811589153
coords = [1000, 2000, 3000]
if p == 1:
nums = list(enumerate(map(int, lines)))
n = len(nums)
og = nums... | TrlRizu/Advent_of_code | Day 20/20-Grove_positioning.py | 20-Grove_positioning.py | py | 1,753 | python | en | code | 0 | github-code | 13 |
15562588946 | from os import getenv
import logging
import time
from dotenv import load_dotenv
from os.path import realpath, dirname
import paho.mqtt.client as mqtt
def on_message(client, userdata, message):
logger.info("message received %s", str(message.payload.decode("utf-8")))
logger.info("message topic=%s", str(messag... | jeremy-share/rabbitmq-simple-mqtt | simple-consumer/src/main.py | main.py | py | 1,357 | python | en | code | 0 | github-code | 13 |
13336479347 |
import os
import io
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r"C:\Users\LENOVO\Documents\hackathon\Unique\ML\ku-hack-6b534f8e99ac.json"
folder_path = r"C:\Users\LENOVO\Documents\hackathon\Unique\ML"
image_path = 'test-KU.png'
path = os.path.join(folder_path, image_path)
def detect_text(path):
"""Detects t... | harshshaw/Unique | ML/app.py | app.py | py | 1,162 | python | en | code | 0 | github-code | 13 |
70766833618 | import itertools
import torch
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
from models import *
import torch.nn.functional as F
from affectnet import get_dataloaders
# class_names = ["Anger", "Disgust", "Fear", "Happy", "Sad", "Surprised", "Neutral... | Accci/OCFER | PreTrain/cm_cbam.py | cm_cbam.py | py | 3,372 | python | en | code | 0 | github-code | 13 |
28183802531 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 7 10:59:08 2017
@author: axel
"""
from nltk.tokenize import sent_tokenize
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
import re
inputfile = open("Document.txt", "r").read()
inputfile = inputfile.replace('”','"').repl... | axelJames/DocumentSummary | doc.py | doc.py | py | 2,263 | python | en | code | 2 | github-code | 13 |
22983798608 | import pytest
from alertmanagermeshtastic.meshtastic import (
create_announcer,
DummyAnnouncer,
MeshtasticAnnouncer,
MeshtasticConfig,
MeshtasticServer,
)
@pytest.mark.parametrize(
'server, expected_type',
[
(MeshtasticServer('meshtastic.server.test'), MeshtasticAnnouncer),
... | Apfelwurm/alertmanagermeshtastic | tests/test_create_announcer.py | test_create_announcer.py | py | 647 | python | en | code | 0 | github-code | 13 |
5971369637 | from rdkit import Chem
from rdkit.Chem.ChemUtils import SDFToCSV
# input file format: *.sdf
# output file format: *.csv
# test
test_out = open('output_file/testset.csv', 'w' )
test_in = Chem.SDMolSupplier('input_file/testset.sdf')
SDFToCSV.Convert(test_in, test_out, keyCol=None, stopAfter=- 1, includeChirality=False,... | ersilia-os/eos30gr | model/framework/train/1_SDFToCSV.py | 1_SDFToCSV.py | py | 843 | python | en | code | 0 | github-code | 13 |
24362211186 | from course import get_course, today
from tkinter import *
window = Tk()
window.title("Банк")
window.geometry("500x500")
window.resizable(width=False, height=False)
img_logo = PhotoImage(file=r"D:\Kod\modul 2\lesson8\logo.png")
logo = Label(window, image=img_logo)
logo.place(x=0, y=0)
title_label = Label(window, tex... | Den4ik20020/modul4 | modul2/lesson8/main.py | main.py | py | 1,625 | python | en | code | 0 | github-code | 13 |
35747940154 | import json
from sqlalchemy.dialects.postgresql import JSONB
from datetime import datetime
from index import db
class Message(db.Model):
__tablename__ = 'messages'
id = db.Column(db.Integer, primary_key=True)
site_id = db.Column(db.ForeignKey('sites.site_id'), index=True)
received = db.Column(db.Date... | cliqz-oss/green-analytics | web/models/message.py | message.py | py | 907 | python | en | code | 8 | github-code | 13 |
35813245090 | import json
import cv2
import torch
import numpy as np
import torch.nn.functional as F
from LSTR.config import system_configs
from LSTR.nnet.py_factory import NetworkFactory
class LSTRPredict:
def __init__(self):
self.load_configs()
# Load model
self.nnet = NetworkFactory()
test_it... | HantsonAlec/Research-Project-CARLA | LstrPredict/lstr.py | lstr.py | py | 3,486 | python | en | code | 1 | github-code | 13 |
29195035592 | import time
import numpy as np
from pylive import liven_plotter
import matplotlib.pyplot as plt
def plot_soc_photon_data(r, key):
var_str = "unit, hm, cTime, dt, sat,sel,mod, Tb, vb, ib, vsat,dv_dyn,voc_stat,voc_ekf, y_ekf, soc_s,soc_ekf,soc,"
count ... | davegutz/myStateOfCharge | SOC_Particle/py/plot_SOC_Photon_data.py | plot_SOC_Photon_data.py | py | 4,871 | python | en | code | 1 | github-code | 13 |
73996338258 | import pandas as pd
from model import *
data=pd.read_csv('seed.txt',sep=' ')
#get X and y
dataset=data.iloc[:].values
print('dataset.....................')
#train the AdaboostClassifier
kmeans=Kmeans(dataset,10,1)
kmeans.clutter()
| hry8310/ai | ml/kmeans/train.py | train.py | py | 235 | python | en | code | 2 | github-code | 13 |
5255681872 | import pytest
import numpy as np
from sklearn import datasets
from sklearn.svm import SVC
from models.svm import SVM
def load_dataset():
X, y = datasets.make_blobs(n_samples=50, n_features=2, centers=2, cluster_std=1.05, random_state=40)
y = np.where(y == 0, -1, 1) # 0이랑 같으면 -1, 아니면 1
return X, y ... | supertigim/ML-DL-Rewind | machine_learning/from_scratch/tests/test_svm.py | test_svm.py | py | 2,285 | python | en | code | 0 | github-code | 13 |
71945806418 | '''
Counter is a subclass of a dictionary where each dictionary key is a hashable
object and the associated value in an integer count of that object.
There are 3 ways to initialize a counter.
'''
from collections import Counter
c1 = Counter('anysequence')
c2 = Counter({'a':1, 'c':1, 'e':3})
c3 = Counter(a=1, c=1, e=3)
... | AniketKul/learning-python3 | counter.py | counter.py | py | 1,450 | python | en | code | 0 | github-code | 13 |
15871535531 | import numpy as np
from tensorflow import keras
from tensorflow.keras import layers
import pathlib
class SupervisedClassifier:
def __init__(self, args, num_classes, save_path, input_shape):
self.args = args
self.num_classes = num_classes
self.save_path = save_path.joinpath("supervised_cla... | Magnuti/IT3030-Deep-Learning | project_3/supervised_classifier.py | supervised_classifier.py | py | 2,624 | python | en | code | 0 | github-code | 13 |
34384271364 | """
Host fwlite jobs in a toolchain. **EXPERIMENTAL!**
"""
import subprocess
import time
from os.path import exists, join
from varial import analysis
from varial import diskio
from varial import monitor
from varial import settings
from varial import toolinterface
from varial import wrappers
class Fwlite(toolinterf... | De-Cristo/MLinHEP | CoTools/Varial/varial/extensions/fwlite.py | fwlite.py | py | 5,522 | python | en | code | 3 | github-code | 13 |
9077953980 | # n = 1일 경우 1개, n = 2일 경우 2개, n = 3일 경우 4개, n = 4일 경우 7개, n = 5일 경우 13개
# n이 3보다 큰 경우부터는 f(n-1) + f(n-2) + f(n-3) = f(n)
t = int(input()) # 테스트 케이스 개수
def sol(n):
if n == 1:
return 1
elif n == 2:
return 2
elif n == 3:
return 4
else:
return sol(n - 1) + sol... | Mins00oo/PythonStudy_CT | BACKJOON/Python/S3/S3_9095_1,2,3 더하기.py | S3_9095_1,2,3 더하기.py | py | 481 | python | ko | code | 0 | github-code | 13 |
37183872910 | import os
import os.path
IMG_EXTENSIONS = [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
]
def is_image_file(filename):
return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
def make_dataset(path_files):
if path_files.find('.txt') != -1:
... | lyndonzheng/Synthetic2Realistic | dataloader/image_folder.py | image_folder.py | py | 1,085 | python | en | code | 177 | github-code | 13 |
26620318039 |
n = int(input())
x_list = []
y_list = []
z_list = []
# x, y, z 값 받기
for i in range(n):
x, y, z = map(int, input().split())
x_list.append(x)
y_list.append(y)
z_list.append(z)
# 정렬
x_list.sort()
y_list.sort()
z_list.sort()
total_list = []
for i in range(n-1):
# x, y, z 각각의 거리를 구해서 삽입 --> 거리, ... | isakchoe/TIL | algorithm /Graph/ex_44.py | ex_44.py | py | 1,086 | python | ko | code | 0 | github-code | 13 |
31939408373 | from django.shortcuts import render, redirect
from .models import *
import bcrypt, time
def index(request):
return render(request, "belt/index.html")
def reg(request):
errors = User.objects.validate_reg(request.POST)
if errors:
for key, val in errors.items():
messages.info(request... | jimisjames/wish_list | apps/belt/views.py | views.py | py | 5,142 | python | en | code | 0 | github-code | 13 |
32276578353 | # exercise 15: Display the Tail of a File
import os.path
import sys
NUM_LINES = 10
# exactly 2 arguments will have to be passed from CLI: file.py file.txt
if len(sys.argv) != 2:
print("you must provide the file name as a command line parameter")
quit()
# showing the two arguments passed from CLI
print(sys.... | sara-kassani/1000_Python_example | books/Python Workbook/files_and_exceptions/ex150.py | ex150.py | py | 722 | python | en | code | 1 | github-code | 13 |
41326774002 | from fastapi import APIRouter, UploadFile,Form, File
from src.core.models import VideoUpload
router = APIRouter(
prefix="/videos", tags=["Videos"]
)
import datetime
import shutil
#!/usr/bin/python
import httplib2
import os
import random
import sys
import time
from apiclient import discovery, http, errors
from ... | ttiagoestevaoo/youtube-video-upload | src/routes.py | routes.py | py | 4,656 | python | en | code | 0 | github-code | 13 |
14230492777 | from django.urls import path
from . import views
urlpatterns = [
# 分级管理员
path(
"grade_managers/",
views.ManagementGradeManagerViewSet.as_view({"get": "list", "post": "create"}),
name="open.management.v1.grade_manager",
),
path(
"grade_managers/<int:id>/",
views.... | TencentBlueKing/bk-iam-saas | saas/backend/api/management/v1/urls.py | urls.py | py | 2,426 | python | en | code | 24 | github-code | 13 |
72298587859 | #Belle Pan
#260839939
import skimage.io as io
import numpy as np
from skimage.color import rgb2gray
from skimage import filters
# This function is provided to you. You will need to call it.
# You should not need to modify it.
def seedfill(im, seed_row, seed_col, fill_color, bckg):
"""
im: The image on whi... | bpan4/COMP204_Fall2019_Computer-Programming-for-Life-Sciences | Assignment 5/cell_counting.py | cell_counting.py | py | 10,730 | python | en | code | 0 | github-code | 13 |
73719195856 | ### Imports
from bs4 import BeautifulSoup
import random as random
import re
import requests
import sys
# Notes:
# base url: https://transcripts.foreverdreaming.org/viewtopic.php?f=292&t={url substrings}
# season 6 url substrings (must include &sid=f24ccd5eea5bfc2086ee09ad73943b29 after "t={}")
## 18278 - 18289
# s... | bjmedina/bachelorette | preproc.py | preproc.py | py | 1,798 | python | en | code | 0 | github-code | 13 |
15123040154 | import random
import copy
is_first=True
def setup(is_first):
lmnop=random.randint(1,3)
#1 is presnt 2 is future 3 is past imperfect
### VERBS INIT ###
hicend1=['aec','uius','uic','anc','āc','ae','ārum','īs','ās','īs']
hicend2=['ic','uius','uic','onc','ōc','ī','ōrum','īs','ōs','īs']
hicend3=['oc... | my-name-here/prgl | prgl2.py | prgl2.py | py | 9,729 | python | en | code | 0 | github-code | 13 |
70765708498 | """Public views tests"""
# run these tests like:
#
# python -m unittest test_user_model.py
import os
from unittest import TestCase
from sqlalchemy import exc
from flask import session
from models import db, User, Phrasebook, Translation, PhrasebookTranslation
from bs4 import BeautifulSoup
os.environ["DATABASE_URL... | adamnyk/capstone-1 | app/tests/test_public_views.py | test_public_views.py | py | 10,118 | python | en | code | 0 | github-code | 13 |
71308410577 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 19 17:32:10 2019
@author: dougpalmer
"""
from __future__ import division
import cv2
import numpy as np
import time
import vision
# Setup classes
cap = cv2.VideoCapture('test_videos/output3.avi')
vis = vision.droidVision()
class droidThresh():
... | krishanrana/droidracer | droidThresh.py | droidThresh.py | py | 2,854 | python | en | code | 0 | github-code | 13 |
42382919306 | import logging
from typing import Callable
from django.conf import settings
from django.core.handlers.wsgi import WSGIRequest
from django.db.models.signals import pre_migrate, post_migrate
from django.dispatch import receiver
from django.http import HttpResponse
from applications.multi_tenant.db import DatabaseAlias
... | CardoAI/django-multi-tenant | multi_tenant/middleware/thread_local.py | thread_local.py | py | 2,640 | python | en | code | 0 | github-code | 13 |
4682776243 | from collections import namedtuple
import sydpy
mapping = namedtuple('Mapping', ['m', 'cs', 'slice'])
class JesdPackerAlgo:
def __init__(self, dtype = None, M=1, N=8, S=1, CS=0, CF=0, L=1, F=1, HD=0):
self.N = N
self.S = S
self.M = M
self.CS = CS
self.CF = CF
... | bogdanvuk/sydpy | tests/packer_coef_calc.py | packer_coef_calc.py | py | 5,566 | python | en | code | 12 | github-code | 13 |
4543934777 | """
Given a string and a non-negative int n, return a larger string that is n copies of the original string.
string_times('Hi', 2) → 'HiHi'
string_times('Hi', 3) → 'HiHiHi'
string_times('Hi', 1) → 'Hi'
"""
def string_times(given_str, times):
print_str = ''
while( times > 0 ):
print_str += given_str
... | avisionx/Must-Know-Programming-Codes | String Functions/string_times.py | string_times.py | py | 458 | python | en | code | 19 | github-code | 13 |
37175509699 | import sqlite3
import logging
class DatabaseHandler():
"""Handles the hearthstone database"""
def __init__(self):
logging.debug("DatabaseHandler trying to connect to database")
try:
self.db = sqlite3.connect('Database/Hearthstone.db')
self.cursor = self.db.cursor()
... | Nieo/HSHelper | Database/dbhandler.py | dbhandler.py | py | 3,391 | python | en | code | 1 | github-code | 13 |
12553493160 | #!/usr/bin/env python3
import curses
from random import randint
def main():
"""Main"""
# set up the window
screen = curses.initscr()
curses.curs_set(0)
n_rows, n_cols = screen.getmaxyx()
win = curses.newwin(n_rows, n_cols, 0, 0)
win.keypad(1)
win.timeout(100)
# draw a game boundar... | keseribp/snake | snake.py | snake.py | py | 2,903 | python | en | code | 0 | github-code | 13 |
10560851369 | #!/usr/bin/env python
# coding: utf-8
# # Week 1 Discussion - Descriptive Statistics
# ### Download the train.csv dataset and run some basic descriptive statistics and graphs for two or more variables of your choosing using Python. Provide your Python code here, perhaps as a Jupyter notebook .html file on GitHub. Em... | brandibeals/NW422-Week1-Titanic | Week 1 Discussion - Descriptive Statistics.py | Week 1 Discussion - Descriptive Statistics.py | py | 1,681 | python | en | code | 0 | github-code | 13 |
4410370705 | from collections import Counter
from msilib import type_short
import time
import numpy as np
from QuickSort2 import FIXED_RANDOM
BASELINE_PIVOT = 0
FIXED_PIVOT = 1
INSERTION_LIMIT = 10
# Function to perform the insertion sort
def insertion_sort(arr):
print("insertion started")
# We start from 1 since... | spyrosgeo13/TheBeg | hybrid_quicksort.py | hybrid_quicksort.py | py | 3,161 | python | en | code | 0 | github-code | 13 |
47006456244 | import sys
import traceback
from telegram import ParseMode
from telegram.utils.helpers import mention_html
from config import ownerId
# error handler sends the message to owner on error
def onError(update, context):
if update.effective_message:
text = "Произошла ошибка. Передам бате."
update.eff... | aa333/Fido | modules/errorHandler.py | errorHandler.py | py | 1,973 | python | en | code | 0 | github-code | 13 |
31084168792 | '''
Desenvolvido por:
- Lucas Azevedo Zortea
- Marcelo Dalvi
- Rhayane Couto Fabres
- Victor Luis Moreira Rosa
'''
from listNode import ListNode
class DoublyLinkedListIterator:
def __init__(self, _firstNode = None):
self.firstNode = _firstNode
self.lastNode = _f... | vlrosa-dev/estrutura-dados-python | 04-struct-data-DoubleLinkedList/doublyLinkedList.py | doublyLinkedList.py | py | 6,377 | python | en | code | 1 | github-code | 13 |
27204096569 | import asyncio
from aiogram import types, Dispatcher
from aiogram.dispatcher import DEFAULT_RATE_LIMIT
from aiogram.dispatcher.handler import CancelHandler, current_handler
from aiogram.dispatcher.middlewares import BaseMiddleware
from aiogram.utils.exceptions import Throttled
from datetime import datetime, timedelta
... | Kyle-krn/TelegramShop | middlewares/throttling.py | throttling.py | py | 1,932 | python | en | code | 0 | github-code | 13 |
71758476177 | def fizzbuzz(number):
for i in range(1, number+1):
string = ''
if i % 3 == 0:
string += 'fizz'
if i % 5 == 0:
string += 'buzz'
print(string or i)
if __name__ == '__main__':
user_input = int(input('Please enter a positive number:\n'))
fizzbuzz(user_in... | jdsmith04/Katas | fizzbuzz.py | fizzbuzz.py | py | 325 | python | en | code | 0 | github-code | 13 |
3634749660 | # Reverse Words in a String
s = 'Python IS awesome'
new_s = ''
words_list = s.split(' ')
for word in words_list:
reversed_word = word[::-1] # ''.join(reversed(word))
swapped_case = reversed_word.swapcase()
new_s += swapped_case + ' '
#print(reversed_word)
#print(swapped_case)
new_s = new_s.rstrip()
... | ashish-kumar-hit/python-qt | python/python-basics-100/String 2.5.py | String 2.5.py | py | 332 | python | en | code | 0 | github-code | 13 |
21381271544 | from django.conf.urls import url, include
from rest_framework_nested import routers
from .views import (
DiagnosisViewSet,
PatientViewSet,
PictureView
)
router = routers.SimpleRouter()
router.register(r'patients', PatientViewSet)
diagnosis_router = routers.NestedSimpleRouter(router, r'patients', lookup='... | wott86/dacardioapp | apps/patients/api_patients/urls.py | urls.py | py | 591 | python | en | code | null | github-code | 13 |
36487921300 | import hashlib
import requests
import sys
import time
# api key and urls
API_KEY = ""
url = "https://api.metadefender.com/v4/"
# constants
BLOCK_SIZE = 8192
# Function calculate hash of a file
def hash_func(filename):
hash_sha256 = hashlib.sha256()
with open(filename, "rb") as f:
block = f.read(BLOCK_S... | youngman-droid/File-Scanner | upload_file.py | upload_file.py | py | 3,294 | python | en | code | 0 | github-code | 13 |
7750379801 | '''
Aim: collect all relevant FITS files from /mnt/astrophysics/muchogalfit-output/ and port them to the all_input_fits located in /mnt/astrophysics/kconger_wisesize/. These files will be necessary when running the build_html_website.py script (in my_mucho_galfit) either locally (will have to scp the folder) or on the ... | Kyssuber/research | my_mucho_galfit/website/move_fits_one_folder.py | move_fits_one_folder.py | py | 5,501 | python | en | code | 1 | github-code | 13 |
37620648212 | #!/usr/bin/env python
"""
List all package names in the repository.
"""
from __future__ import print_function
import pprint
import os
import io
import re
REPO_SRC = os.path.abspath(os.path.join(__file__, "..", "..", "..", ".."))
RGX = re.compile(r"\s*<name>(?P<pkg_name>[_\w]+)</name>")
def _get_xmls():
ret = []
... | wasn-lab/Taillight_Recognition_with_VGG16-WaveNet | src/scripts/ci/list_package_names.py | list_package_names.py | py | 1,102 | python | en | code | 2 | github-code | 13 |
27763611189 | """Represent models for near-Earth objects and their close approaches.
The `NearEarthObject` class represents a near-Earth object. Each has a unique
primary designation, an optional unique name, an optional diameter, and a flag
for whether the object is potentially hazardous.
The `CloseApproach` class represents a cl... | saltamay/Udacity_Intermediate_Python_NEO | models.py | models.py | py | 6,230 | python | en | code | 1 | github-code | 13 |
6368615489 | # !/usr/bin/env python3
# Author: ALP CANER SATI, May 2021
from pathlib import Path
import os
from datetime import datetime as dt
import time
import json
from traceback import format_exc
import requests
import pwd
CONFIG_PATH = "/home/pi/Desktop/config.json"
LOG_FOLDER_PATH = "/home/pi/Desktop/camera_logs/"
def cre... | acsati/motion_detected_with_webcam | scripts/motion_detection.py | motion_detection.py | py | 3,512 | python | en | code | 0 | github-code | 13 |
1146478225 | from dotenv import load_dotenv
import os
import telebot
load_dotenv()
BOT_KEY = os.getenv('BOT_KEY')
bot = telebot.TeleBot(BOT_KEY)
@bot.message_handler(commands=['start'])
def start(m, res=False):
bot.send_message(m.chat.id, 'I am online!')
@bot.message_handler(content_types=['text'])
def handle_text(messag... | DevOps-spb-org/python-telegram-bot-examples | echo-bot/main.py | main.py | py | 446 | python | en | code | 1 | github-code | 13 |
17182124861 | from PyQt5.QtWidgets import*
from PyQt5.QtPrintSupport import *
from PyQt5 import QtCore, QtGui, uic
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import time
import cv2
import os
import sys
from PIL import Image
import threading
import inceptiontest
ui_MainWindow = uic.loadUiType("mainwindow.ui")[0]
class Fr... | zsrabbani/Fruit-Detection | runfile.py | runfile.py | py | 5,288 | python | en | code | 0 | github-code | 13 |
33346415750 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
... | BradleyGenao/LeetCode-Solutions | maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.py | maximum-depth-of-binary-tree.py | py | 834 | python | en | code | 0 | github-code | 13 |
25585964730 | import logging
import rpyc
from utils.strings import genRandomFilename
# exfil data over RPC
def exfilRPC(server, port, data, File=False):
logging.debug("Using RPC exfiltration")
if not File:
if isinstance(data, list):
logging.debug("data is a list, converting to string")
data ... | bcdannyboy/dlpauto | src/dlpautomation/exfil/rpc/exfil.py | exfil.py | py | 1,230 | python | en | code | 0 | github-code | 13 |
16808790624 | import unicodedata
import pytest
from hypothesis.errors import InvalidArgument
from hypothesis.strategies import characters
from tests.common.debug import assert_no_examples, find_any, minimal
from tests.common.utils import fails_with
@fails_with(InvalidArgument)
def test_nonexistent_category_argument():
chara... | HypothesisWorks/hypothesis | hypothesis-python/tests/cover/test_simple_characters.py | test_simple_characters.py | py | 4,132 | python | en | code | 7,035 | github-code | 13 |
19436043687 | def solution(numbers):
answer = [-1] * len(numbers)
stack = [] # 스택에는 인덱스를 넣기
for i in range(len(numbers)):
while stack and numbers[stack[-1]] < numbers[i]:
answer[stack.pop()] = numbers[i]
stack.append(i)
return answer | Youmi-Kim/problem-solved | 프로그래머스/2/154539. 뒤에 있는 큰 수 찾기/뒤에 있는 큰 수 찾기.py | 뒤에 있는 큰 수 찾기.py | py | 294 | python | en | code | 0 | github-code | 13 |
41977764862 |
import heapq
import sys
heap=[]
input=sys.stdin.readline
N=int(input())
for _ in range(N):
a=int(input().strip())
if a>0:
heapq.heappush(heap,(-a,a)) # how to use maxheap using heapq module
else:
if len(heap):
print(heapq.heappop(heap)[1])
else:
print(0)
| honghyeong/python-problem-solving | BOJ/step21_priority_queue/11279.py | 11279.py | py | 317 | python | en | code | 0 | github-code | 13 |
5379494501 | from urllib import request # 引用urllib中的request
from bs4 import BeautifulSoup
import re
import pandas as pd
from pandas import DataFrame
if __name__ == "__main__":
response = request.urlopen("http://58921.com") #获取网址请求返回值
html =str(response.read(), encoding='utf-8') # 返回bytes转为utf8
soup = BeautifulSoup(html,... | luzhonghe999/WebCrawler | 03_爬去结果存储_csv.py | 03_爬去结果存储_csv.py | py | 1,024 | python | en | code | 0 | github-code | 13 |
4882858447 | import os
import logging
from dotenv import load_dotenv
from dune_client.types import QueryParameter
from dune_client.query import QueryBase
from dune_client.api.execution import ExecutionAPI, BaseRouter
from dune_client.models import ExecutionResponse
import time
load_dotenv()
api_key = os.getenv("DUNE_API_KEY_TEAM")... | PaulApivat/data_engineer | practice/celery-worker-etl/etl/client/sample_fact_tokenization_summary_mv_execapi.py | sample_fact_tokenization_summary_mv_execapi.py | py | 3,434 | python | en | code | 0 | github-code | 13 |
39715883832 | import Libnumcomplex as lb
import math
# Experimento de las canicas con coeficientes booleanos, se tomará el 1 como True y el 0 como False.
# m: matriz doblemente estocastica unicamente con valores 1 y 0, v: vector con posiciones iniciales
# c: número de "clicks" que realiza, debe ser un número real
def expcanicas(m,... | JuanMedina-R/CalculadoraNumerosComplejos | DeClasicoACuantico/Capitulo3.py | Capitulo3.py | py | 1,743 | python | es | code | 0 | github-code | 13 |
16929181572 | from flask import Flask, render_template, redirect, url_for, render_template, request, session, flash
from binance.client import Client
from binance.enums import *
app = Flask(__name__)
app.secret_key = "jsad;fk039u2401u90n3k;alkm092uqio234n92837498hwhofiuahsdf"
# client = Client(config.api_key, config.api_secret, tld... | JohnLam916/Wow_Project | app.py | app.py | py | 7,367 | python | en | code | 1 | github-code | 13 |
34247961098 | import urllib.request,json
from .models import NewsArticle
# Getting api key
apikey = None
# Getting the NEWS base url
base_url = None
def configure_request(app):
global apikey,base_url
base_url = app.config['NEWS_API_BASE_URL']
apikey = app.config['NEWS_API_KEY']
def get_news(categories):
'''
F... | AbugaAroni/FlaskIP2 | app/requests.py | requests.py | py | 2,441 | python | en | code | 0 | github-code | 13 |
72755156818 | from selenium import webdriver
def run_scratch_production(productionID, opCode, mess):
production_url = 'http://127.0.0.1:8000/team_match/production/scratch/build/index.html' \
'?id=' + str(productionID) + \
'&opCodeAndMess=' + str(opCode) + str(mess)
chrome_driver = 'C:\\Users\\413knight... | liqiniuniu/- | team_match/run_production.py | run_production.py | py | 743 | python | en | code | 0 | github-code | 13 |
44833280461 | #!/usr/bin/python3
import unittest
from models.base import Base
from models.rectangle import Rectangle
from models.square import Square
from io import StringIO
import sys
import json
class TestBase(unittest.TestCase):
def setUp(self):
"""
function to redirect stdout to check
... | Hanifa-10/alx-higher_level_programming | 0x0C-python-almost_a_circle/tests/test_models/test_base.py | test_base.py | py | 3,751 | python | en | code | 0 | github-code | 13 |
33015682856 | import os
def directory_parser(path):
"""
parses the input the program has got into an array of absolute paths of files to work with
:param path: the input path
:return: a list of absolute paths of files to work with
"""
if os.path.isdir(path):
path_array, valid_paths = os.li... | damebrown/NAND_ex6 | NAND-ex6/file_parser.py | file_parser.py | py | 2,535 | python | en | code | 0 | github-code | 13 |
20448747985 | from flask import redirect, render_template, url_for, Blueprint,flash
from flask_login import login_required
from app.config import UPLOADS_FOLDER, TEMPLATE_FOLDER
from app.views.main.models import AboutPage, File
import os
# Create blueprint
main_blueprint = Blueprint('main_blueprint', __name__, template_folder=TEMPL... | UnilabEdu/Childes | app/views/main/views.py | views.py | py | 4,907 | python | en | code | 0 | github-code | 13 |
37260142483 | from typing import (
cast,
List,
Tuple,
)
import pytest
from galaxyls.services.xml.nodes import XmlElement
from galaxyls.tests.unit.utils import TestUtils
class TestXmlElementClass:
@pytest.mark.parametrize(
"source, expected_offsets",
[
("<test", (5, 5)),
("<... | galaxyproject/galaxy-language-server | server/galaxyls/tests/integration/xml/test_element_node.py | test_element_node.py | py | 1,627 | python | en | code | 22 | github-code | 13 |
9466957384 | # Command Status - SMPP v5.0, section 4.7.6, table 4-45, page 116-122
# The command_status represents the means by which an ESME or MC sends an error code to its peer.
# This field is only relevant in response PDUs.
ESME_ROK = int(0x00000000) # description : No error
ESME_RINVMSGLEN = int(0x00000001) # descri... | kashifpk/smpp5 | smpp5/smpp5/lib/constants/command_status.py | command_status.py | py | 5,845 | python | en | code | 0 | github-code | 13 |
18274821796 | import json
import os
from assemblyline.al.service.base import ServiceBase
from assemblyline.al.common.result import Result, ResultSection, SCORE, TAG_TYPE, TAG_WEIGHT, TEXT_FORMAT
import hashlib
import time
class TorrentSlicer(ServiceBase):
SERVICE_CATEGORY = 'Static Analysis'
SERVICE_ACCEPTS = 'meta/torren... | deeptechlabs/cyberweapons | assemblyline/alsvc_torrentslicer/torrentslicer.py | torrentslicer.py | py | 10,224 | python | en | code | 78 | github-code | 13 |
74282754899 | from flask import Flask, url_for
from flask import request,json
import uuid
app = Flask(__name__)
app.debug = True
@app.route("/",methods=["POST"])
def hello():
if request.method =="POST":
f=request.files["file"]
uid = str(uuid.uuid4())
f.save("D://temp//"+uid+".jpg")
return "ok"
@a... | hello0word/autojs_code | code/微信注册/图片服务器.py | 图片服务器.py | py | 1,134 | python | en | code | 6 | github-code | 13 |
14648841675 | """
Test for the `cdd.emit` module
"""
from os import path
from unittest import TestCase
from cdd.shared.emit import EMITTERS
from cdd.shared.pure_utils import all_dunder_for_module
from cdd.tests.utils_for_tests import unittest_main
class TestEmitters(TestCase):
"""
Tests the `cdd.emit` module magic `__all... | offscale/cdd-python | cdd/tests/test_emit/test_emitters.py | test_emitters.py | py | 747 | python | en | code | 10 | github-code | 13 |
31711726774 | import csv
import os
import time
from gl import *
class Controller():
def __init__(self, count):
self.counter = count
self.cpu_value = ""
self.all_data = [('timestamp', 'cpustatus')]
def testprocess(self):
result = os.popen("adb shell dumpsys cpuinfo | grep %s" % GL_PACKAGE_... | gsy13213009/py_auto | launchTime/cpuinfo.py | cpuinfo.py | py | 1,038 | python | en | code | 0 | github-code | 13 |
35605622925 | import datetime
from typing import List, Tuple
import joblib
from pandas import DataFrame
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
class Model:
def __init__(self, df: DataFrame, target: str, features: List[str]):
X_train, X_test, y_train, y... | BloomTech-Labs/DSLabsCurriculum | machine_learning/model.py | model.py | py | 1,871 | python | en | code | 2 | github-code | 13 |
41810454836 | # Импортируем необходимые компоненты
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from settings import TG_TOKEN, TG_API_URL
from handlers import *
# Создадим (объявляем) функцию main, которая соединяется с платформой Telegram
def main():
# тело функции, описываем функцию
# создад... | Ilgiz-arch/telegram_bot | bot.py | bot.py | py | 1,861 | python | ru | code | 0 | github-code | 13 |
8141492351 | import pprint, sys
from parse.integrations import super_kloudless as kloudlessDrives, super_google as google, confluence, sifter, zoho_bugtracker, gsites, trello
pp = pprint.PrettyPrinter(indent=4)
Services = {
'confluence': {
'title': 'Confluence',
'superService': False,
'module': confluence
},
'gd... | explaain/savvy-nlp | parse/services.py | services.py | py | 2,780 | python | en | code | 0 | github-code | 13 |
20319905140 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
class environment_functions:
u_h = None
u_e = None
u_v = None
f_v = None
v_t = None
k = None
infected_imigration = None
gamma = None
delta = None
def __init__(self, o_multiplier = 1, s_a_multiplier = 1, a_multiplier = 1,
... | Dinidiniz/doutorado_modelo_dia | base_functions.py | base_functions.py | py | 3,560 | python | en | code | 0 | github-code | 13 |
27189557008 | # Jakub Worek 06.03.2023-11.03.2023
#
# Dowód poprawności:
# Jak się okazuje nie bez powodu ulubiony palindrom
# cesarzowej Bajtocji jest nieparzystej długości.
# Idąc po kolei po każdej literze napisu traktujemy ją jako środek
# prawdopodobnego palindromu, ponieważ palindrom ten jest na pewno
# nieparzystej długości.... | JakubWorek/algorithms_and_data_structures_course | 2022-2023/OFFLINE/OFFLINE_1/zad1.py | zad1.py | py | 1,628 | python | pl | code | 0 | github-code | 13 |
29763569779 | # -*- coding: utf-8 -*-
"""
Created on Fri May 20 09:35:05 2022
@author: aceso
"""
import pandas as pd
import numpy as np
import os
import datetime
import matplotlib.pyplot as plt
from sklearn.experimental import enable_iterative_imputer # need this module to use below fx
from sklearn.impute import IterativeImputer
f... | AceSongip/Covid_Cases_Analysis | covid_classes.py | covid_classes.py | py | 3,226 | python | en | code | 0 | github-code | 13 |
11597921772 | from sqlalchemy import Column, Integer, String, DateTime, Float, Boolean, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = "user_table"
uid = Column(Integer, primary_key=True, nullable=False)
nice_total_disk_usage = Column(Stri... | usegalaxy-au/history-mailer | models.py | models.py | py | 2,758 | python | en | code | 0 | github-code | 13 |
38733638402 | """
student URL Configuration
"""
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('register/', views.register, name='register'),
path('info/<int:student_id>/', views.info, name='info'),
] | lianix/feiranSMS | student/urls.py | urls.py | py | 261 | python | en | code | 0 | github-code | 13 |
17484526595 | import itertools
import numpy as np
def print_one_transformation(imgs):
import matplotlib.pyplot as plt
assert len(imgs) == 4, "4 images needed"
fig, axes = plt.subplots(2, 2)
imgs = [ np.squeeze(x) for x in imgs]
axes[0, 0].imshow(imgs[0])
axes[0, 1].imshow(imgs[1], cmap='gray')
axes[... | AdvenamTacet/Steganography-with-Neural-Networks | data/display_data.py | display_data.py | py | 824 | python | en | code | 3 | github-code | 13 |
34467618427 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 18 21:03:40 2021
@author: Anthony
This group of function definitions can be used to apply low-pass Butterworth
filters to experimental data.
"""
import numpy as np
import scipy.signal as sg
import pandas as pd
# %% butterworth trial
def apply_butterworth_filter(trial... | ajanders/cobra-knee | src/filters.py | filters.py | py | 4,748 | python | en | code | 0 | github-code | 13 |
37941148068 |
from AthenaCommon.AlgSequence import AlgSequence
topSeq = AlgSequence()
ServiceMgr.MessageSvc.OutputLevel = DEBUG
from AthenaCommon.DetFlags import DetFlags
DetFlags.bpipe_setOn()
DetFlags.ZDC_setOn()
DetFlags.Truth_setOn()
from AthenaServices.AthenaServicesConf import AtRndmGenSvc
ServiceMgr += AtRndmGenSvc()
fro... | rushioda/PIXELVALID_athena | athena/ForwardDetectors/ZDC/ZDC_SimuDigitization/share/jobOptions.G4Atlas.zdc.pgun.py | jobOptions.G4Atlas.zdc.pgun.py | py | 1,626 | python | en | code | 1 | github-code | 13 |
74907154257 | import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
img = cv.imread("../../resource/chapter6/1.jpg")
def showing(img, isgray=False):
plt.axis("off")
if isgray:
plt.imshow(img, cmap="gray")
else:
plt.imshow(img)
plt.show()
img = cv.imread("../../... | codezzzsleep/records2.1 | robot-and-vision/test/chapter6/demo04.py | demo04.py | py | 647 | python | en | code | 0 | github-code | 13 |
3579935528 | # -*- coding: utf-8 -*-
from io import StringIO
import sys
import unittest
try:
# Python 3
from urllib.parse import urlencode
# Convert bytes to str, if required
def convert_str(s):
return s.decode('utf-8') if isinstance(s, bytes) else s
except:
# Python 2
from urllib import urlencode
... | vecchp/awsgi | test_awsgi.py | test_awsgi.py | py | 2,772 | python | en | code | null | github-code | 13 |
36754330938 | #!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
def to_grayscale(image):
painting2 = image
gray = np.dot(painting2[...,:3], [0.2126, 0.7152, 0.0722])
return gray
def to_red(image):
painting2 = image.copy()
painting2[:,:,1]=0
painting2[:,:,2]=0
return painting2
... | tugee/dap2020 | part03-e11_to_grayscale/src/to_grayscale.py | to_grayscale.py | py | 938 | python | en | code | 0 | github-code | 13 |
25405605608 | def ucs(goal, start):
global graph, cost
ans = []
queue = []
for i in range(len(goal)):
ans.append(9999) # ans = big value
queue.append([0, start])
# dict for visited
visited = {}
count = 0
while (len(queue) > 0): # while not empty
queue = sorted(queue)
... | xBodda/SearchingAlgorithms | In Python/UCS.py | UCS.py | py | 2,083 | python | en | code | 0 | github-code | 13 |
17460418814 | from PyQt5.QtWidgets import (QSizePolicy, QWidget, QSlider, QVBoxLayout, QLabel, QPushButton, QSpacerItem)
from Widget.Slider import Slider
class BallControl(QWidget):
def __init__(self, videoThread):
super().__init__()
self.videoThread = videoThread
colorThreshold = self.videoThread.image... | tanat44/PingpongBallTracker | Widget/BallControl.py | BallControl.py | py | 2,534 | python | en | code | 4 | github-code | 13 |
71995549459 | from urllib.parse import parse_qs, urlparse
import scrapy
from scrapy.loader import ItemLoader
from boatrace_crawler.items import OddsItem, RaceIndexItem, RaceProgramBracketItem, RaceProgramBracketResultsItem, RaceProgramItem, RaceResultPayoffItem, RaceResultStartTimeItem, RaceResultTimeItem, RacerItem
class Boatra... | u6k/boatrace-crawler | boatrace_crawler/spiders/boatrace_spider.py | boatrace_spider.py | py | 27,741 | python | en | code | 0 | github-code | 13 |
16169436802 | import json
from queue import Queue, Empty
event_queues = {}
class Event:
def __init__(self, event_type, data):
self.type = event_type
self.data = data
def __str__(self):
data = json.dumps(self.data) \
if not isinstance(self.data, str)\
else self.data
... | frankli0324/BiliDownload | app/event.py | event.py | py | 802 | python | en | code | 0 | github-code | 13 |
7044496818 | from __future__ import absolute_import
from __future__ import print_function
import os
import re
import time
import argparse
from hid_test import test_hid
from serial_test import test_serial
from msd_test import test_mass_storage
from daplink_board import get_all_attached_daplink_boards
from project_generator.generate... | c1728p9/DAPLink_old | test/test_all.py | test_all.py | py | 14,516 | python | en | code | 0 | github-code | 13 |
23767957714 | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 14 19:41:54 2019
@author: llavi
"""
#general imports
import os
import glob
from os.path import join
import pandas as pd
import numpy as np
import math
import time
import sys
import datetime
#other scripts that are used
#import raw_data_imports
## D... | llavin13/dispatch_RA_model | data_to_csvs.py | data_to_csvs.py | py | 36,725 | python | en | code | 0 | github-code | 13 |
74772490898 | from selenium import webdriver
import os
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from threading import Thread
import thre... | sagarpatel24/Phishing-Detection-ML | Back End/mail.py | mail.py | py | 4,364 | python | en | code | 8 | github-code | 13 |
39681398032 | import os
from pathlib import Path
for path in Path('.').rglob('*'):
if not path.exists():
continue
if path.is_dir() and path.name == 'out':
for child in path.rglob('*'):
os.remove(child)
os.remove( path )
elif not path.is_dir():
if path.name.endswith( ( '.exe', '.pdb', 'output' ) ):
os.remove( pa... | ENDERZOMBI102/AdventOfCode | clean.py | clean.py | py | 325 | python | en | code | 0 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.