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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
11396190634 |
def even_or_average():
list_new = []
list_two = []
print("Please enter 5 numbers - \n")
count = 0
while len(list_new) < 5:
user_input = input(f'Please input number {count + 1} - ')
list_new.append(int(user_input))
count += 1
continue
print(list_new)
for i... | nick-github-sa/python50days | python21/python2.py | python2.py | py | 502 | python | en | code | 0 | github-code | 1 |
13795425768 | from menu import MENU, resources
def prompt_user():
"""Prompts user for input and returns user's choice"""
choice = input("What would you like? (espresso/latte/cappuccino): ")
return choice
def print_report(resources):
"""Takes resources dictionary as parameter and prints a report detailing the amount... | kamiwis/coffee-machine | helpers.py | helpers.py | py | 1,664 | python | en | code | 0 | github-code | 1 |
10581123244 | import requests
import time
with open('NEWURL.txt','r') as f:
url = f.readlines()
for i in range(len(url)):
url[i] = url[i].strip()
try:
t1 = time.time()
r = requests.get(url[i])
t2 = time.time()
Time = t2 - t1
print(Time)
print(len(r.content))
Throughput = (len(r.content)/ (Time))
... | MieMieWangWang/SNS | throughput.py | throughput.py | py | 466 | python | en | code | 0 | github-code | 1 |
7958211750 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^register', views.register),
url(r'^login', views.login),
url(r'^show', views.show),
url(r'^add', views.add),
url(r'^createtrip', views.createtrip),
url(r'^logout', views.logout),
... | jbacos7/C- | secondDojo answers1/Python/Django/pexam2/pexam2 2/apps/pexam2/urls.py | urls.py | py | 519 | python | en | code | 0 | github-code | 1 |
25088785509 | from flask import Flask, request, jsonify
import sys
from elasticsearch_dsl import Search, A, Q
from elasticsearch import Elasticsearch
app = Flask(__name__)
from flask import render_template
import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(... | chaopli/movielib-incomplete | movielib.py | movielib.py | py | 2,280 | python | en | code | 0 | github-code | 1 |
43134615624 | # -*- coding: utf-8 -*-
from __future__ import print_function
import sys, os, warnings
gpu = sys.argv[ sys.argv.index('-gpu') + 1 ] if '-gpu' in sys.argv else '0'
os.environ['PYTHONHASHSEED'] = '0'
#os.environ['CUDA_VISIBLE_DEVICES']=gpu
#os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Disable Tensorflow CUDA load stateme... | fjcastellanos/FewShotLayoutAnalysisMusic | main.py | main.py | py | 8,374 | python | en | code | 0 | github-code | 1 |
37312132142 | from flask import render_template,redirect
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask import Blueprint, current_app, jsonify, make_response, request
# 将model添加成视图,并控制在前端的显示
from myapp.models.model_serving import Service,KfService
from myapp.models.model_team import Project,Project_User
... | wujiapei/alldata | dataAI/mlops/myapp/views/view_kfserving.py | view_kfserving.py | py | 16,210 | python | en | code | 3 | github-code | 1 |
41035495644 | import typing
from sqlalchemy import Integer
from sqlalchemy import Text
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import declared_attr
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
class Base(DeclarativeBase):
pass
class HasRelatedDataMixin:
@declared_attr... | sqlalchemy/sqlalchemy | test/typing/plain_files/orm/declared_attr_two.py | declared_attr_two.py | py | 1,104 | python | en | code | 8,024 | github-code | 1 |
17958676898 | # 2차원 배열 채우기 3(달팽이 배열)
# filling 2D array(snail pattern array)
# n이 입력되면 크기가 n인 다음과 같은 2차원 배열을 출력하시오.
n = int(input())
a = [[0] * n for i in range(n)]
k, c = 0, 1
f = n
i = 0
j = -1
while True:
# 행 고정, 열 증가 또는 감소
for b in range(1, f+1):
if k >= n*n:
break
k += 1
j += c
... | junes7/python_algorithm | CodeUp/2D_array/1505.py | 1505.py | py | 722 | python | ko | code | 1 | github-code | 1 |
29995601060 | "Command line driver for changing from files chunking by baseline to files chunking by time."
from hera_cal import vis_clean
from hera_cal._cli_tools import parse_args, run_with_profiling
parser = vis_clean.time_chunk_from_baseline_chunks_argparser()
a = parse_args(parser)
run_with_profiling(
vis_clean.time_chun... | HERA-Team/hera_cal | scripts/time_chunk_from_baseline_chunks_run.py | time_chunk_from_baseline_chunks_run.py | py | 521 | python | en | code | 9 | github-code | 1 |
6781398623 | def factorial(a,n):
flag=0
global fac
global i
if a==n:
flag=1
if flag ==1:
print(fac)
else:
fac *= i
i=i+1
factorial(a+1,n)
if flag==1:
return
t=int(input())
fac=1
i=1
factorial(0,t) | Hyunjong1461/python | 200222/팩토리얼.py | 팩토리얼.py | py | 277 | python | en | code | 0 | github-code | 1 |
72389012194 | # coding: utf-8
"""Download and file clips."""
import logging
import hashlib
import os
import datetime
import ffmpy
import requests
from tinydb import Query
from config import db, SUPPORTED_TYPES, DATA_DIR
logger = logging.getLogger('oxo')
def download_clip(url, bot, update, content_type, fname=None):
"""Down... | cafca/displaybot | displaybot/conversion.py | conversion.py | py | 2,395 | python | en | code | 0 | github-code | 1 |
31904172202 | import flanders
# as a first step we build the search tree
# we can later reuse the search tree many times
points = [
(60.4, 51.3),
(173.9, 143.8),
(132.9, 124.9),
(19.5, 108.9),
(196.5, 9.9),
(143.3, 53.3),
]
tree = flanders.build_search_tree(points)
# now we will search the indices of ne... | bast/flanders | example/example.py | example.py | py | 1,073 | python | en | code | 7 | github-code | 1 |
35847150078 | import ast
import asyncio
import threading
import time
from datetime import datetime, timedelta
from collector.main_collector import MainCollector
from data_base import DataBase
from keys import VIME_TEST_TOKEN
from keys import VIME_TOKEN, VIME_TEST_TOKEN
from utils import cls
from vime_api.vime import Vime
TEST_MODE... | FalmerF/VimeArchive | run.py | run.py | py | 4,035 | python | en | code | 1 | github-code | 1 |
27826917586 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 15 12:19:30 2023
@author: sharrm
"""
import fiona
import geopandas as gpd
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import pickle
import rasterio
from rasterio.mask import mask
from scipy import spatial
from scipy import ndimage
f... | sharrm/RSD | zero_shoreline_old.py | zero_shoreline_old.py | py | 24,259 | python | en | code | 0 | github-code | 1 |
22885261332 | from __future__ import print_function
import datetime
from tzlocal import get_localzone
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.p... | vwlau/eink-cal | g_cal.py | g_cal.py | py | 3,214 | python | en | code | 38 | github-code | 1 |
36900648139 | from pico2d import *
import time
image = None
end_result = False
closing = False
change_state = None
final_score = None
strings = []
index = 0
last_time = 0
last_blink = 0
score_font = None
blink = False
def init():
global image, end_result, closing, change_state, score_font, final_score, strings, index, last_ti... | petere333/2DGP_restart | final_projects/bin/after_play.py | after_play.py | py | 1,937 | python | en | code | 0 | github-code | 1 |
39726595273 | """Delete disabled column
Revision ID: de3bdf5a9ff8
Revises: 2b7fcebfede1
Create Date: 2021-06-20 09:35:40.600021
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = 'de3bdf5a9ff8'
down_revision = '2b7fcebfede1'
branch_labels = ... | shin-hama/JunkNoteAPI | app/db/migrations/versions/de3bdf5a9ff8_delete_disabled_column.py | de3bdf5a9ff8_delete_disabled_column.py | py | 1,169 | python | en | code | 1 | github-code | 1 |
7807856985 | from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from .models import UserInfo
from .models import battledata
from .forms import UserForm,dataForm
# ユーザ情報を辞書に格納して、users.htmlに返す
def showUsers(request):
usefinfo = UserInfo.objects.all()
context... | pyTakuya/djongoform | form/views.py | views.py | py | 3,361 | python | en | code | 0 | github-code | 1 |
20604431851 | """djangodemo03 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cla... | demo112/1809 | PythonWeb/Django/1809/djangoproject/djangodemo03/index/urls.py | urls.py | py | 1,823 | python | en | code | 0 | github-code | 1 |
30322056770 | '''
实现从一个文件夹下随机抽取一定数量的图片并移动到另一个文件夹
'''
import os
import random
import shutil
def moveFile(fileDir):
pathDir = os.listdir(fileDir) # 取图片的原始路径
filenumber = len(pathDir)
rate = 0.2 # 自定义抽取图片的比例,比方说100张抽10张,那就是0.1
picknumber = int(filenumber * rate) # 按照rate比例从文件夹中取一定数量图片
sample = random.sample(pa... | huilizhou/Deeplearning_Python_DEMO | move_pic_to_another_file.py | move_pic_to_another_file.py | py | 856 | python | zh | code | 0 | github-code | 1 |
3164290218 | #!/usr/bin/env python3
from time import sleep
from datetime import datetime
from tasks import primeira_task, segunda_task
q1 = 'filarq30_1'
q2 = 'filarq30_2'
s = 'INFORMACAO '
if __name__ == '__main__':
while True:
try:
print(f'*** {datetime.now()}')
_1 = primeira_task.apply_asy... | htbrandao/tutorial-rabbit-and-celery | demo/app.py | app.py | py | 505 | python | en | code | 0 | github-code | 1 |
314948147 | """
Creates TSV/CSV data based on predictions
"""
from pred.webserver.predictionsearch import get_all_values
from pred.webserver.dnasequence import DNALookup
class RowGenerator(object):
"""
yields CSV/TSV data using row_format for a list of predictions
"""
def __init__(self, separator, row_format):
... | Duke-GCB/iMADS | pred/webserver/csvgenerator.py | csvgenerator.py | py | 7,660 | python | en | code | 0 | github-code | 1 |
17384052453 | """
Create a Blockchain
"""
import hashlib
import datetime
class Block:
def __init__(self, timestamp, data, previous_hash):
self.timestamp = timestamp
self.data = data
self.previous_hash = previous_hash
self.hash = self.calc_hash()
#Define a function to create... | DomingoCast/DS-and-algorithms | Blockchain.py | Blockchain.py | py | 1,551 | python | en | code | 0 | github-code | 1 |
14386615131 | '''
73. UTF-8 검증
입력값이 UTF-8 문자열이 맞는지 검증하라.
Example 1:
data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 00000001.
Return true.
It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.
'''
class Solution:
def validUtf8(self, data: List[int]) -> bool:
... | hyo-eun-kim/algorithm-study | ch19/taeuk/ch19_4_taeuk.py | ch19_4_taeuk.py | py | 1,026 | python | en | code | 0 | github-code | 1 |
25167180092 | import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from app import app
from apps import database, measurement, home, posttest, config
import pandas
import glob
app.layout = html.Div([
dcc.Location(id='url', refresh=False),
html.Div(id='page-conte... | donovan97/IAP_Measurement | src/index.py | index.py | py | 977 | python | en | code | 0 | github-code | 1 |
36656638244 | #!/usr/bin/env python
import sys
import math
class Monkey(object):
def __init__(self):
self._items = []
self._operation = None
self._test_div = 1
self._true_throw = None
self._false_throw = None
self._inspections = 0
def __str__(self):
ret = ''
... | gerrowadat/adventofcode | 2022/11/11-1.py | 11-1.py | py | 2,758 | python | en | code | 1 | github-code | 1 |
21514961807 | import unittest
from entities.trip import Trip
from services.trip_service import TripService
from errors.errors_handling import EmptyInputError, NotIntegerError
from tests.testing_env.test_repository import test_trip_repository
class TestTripService(unittest.TestCase):
def setUp(self):
self.trip_serivce =... | gabikakol/software-dev-exercises | travel-budget-app/src/tests/services/trip_service_test.py | trip_service_test.py | py | 1,198 | python | en | code | 0 | github-code | 1 |
70436483553 | import torch
from torch.utils.data import DataLoader, Subset
import torch.optim as optim
class AssignmentModel:
def __init__(self, dataloader=None, latent=None, generator=None, critic=None, cost=None, device='cpu', A_couples=None, A_cost=None):
## Variables ##
self.device = device
self.cos... | devbflow/optimal-transport-gan | src/models/AssignmentModel.py | AssignmentModel.py | py | 7,497 | python | en | code | 0 | github-code | 1 |
27493427622 | import pygame
import random
import tkinter as tk
# Set up the game window
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500
pygame.init()
WINDOW = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("Snake Game")
# Set up the colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255... | EsmailTaghizadehResume/mini_games | Snake_Game.py | Snake_Game.py | py | 5,558 | python | en | code | 0 | github-code | 1 |
42618756934 | import cirq
import sympy
import numpy as np
import tensorflow as tf
import tensorflow_quantum as tfq
from tensorflow.keras import layers
from tensorflow.keras import models
from tensorflow.keras.metrics import Precision, Recall, AUC
from tensorflow.keras.optimizers import Adam
class QConv(tf.keras.layers.Layer):
... | Djack1010/tami | code_models/sota_code_models/QCNN_QConv.py | QCNN_QConv.py | py | 7,873 | python | en | code | 8 | github-code | 1 |
12984958358 | #!/usr/bin/env python
from threading import Thread
from queue import Queue
from channel_operators import (
init_url_q,
put_text_q,
put_url_q,
)
def call_in_thread(f, *args, **kwargs):
t = Thread(target=f, args=args, kwargs=kwargs)
t.start()
return t
if __name__ == '__main__':
import ... | moskytw/elegant-concurrency-lab | graph_initializer.py | graph_initializer.py | py | 815 | python | en | code | 43 | github-code | 1 |
36363288443 | import os
import sys
import argparse
import datetime
import pandas as pd
import dxchange.reader as dxreader
from pathlib import Path
from tomolog import log
def show_tomolog(args):
fname = args.h5_name
if os.path.isfile(fname):
all_tomolog = dxreader.read_dx_meta(fname)
log.info('All tomo... | decarlof/tomolog | tomolog/tomolog.py | tomolog.py | py | 6,637 | python | en | code | 0 | github-code | 1 |
24710060493 | def get_desk_side(width: int, height: int, diploma_count: int) -> int:
"""
Функция вычисления минимального размера стороны квадратной доски.
:param width: ширина диплома
:type width: int
:param height: высота диплома
:type height: int
:param diploma_count: количество дипломов
:type dipl... | OkhotnikovFN/Yandex-Algorithms | trainings_1.0/hw_6/task_c/c.py | c.py | py | 1,149 | python | ru | code | 1 | github-code | 1 |
2744513023 | from setuptools import setup, find_packages
from pathlib import Path
this_directory = Path(__file__).parent
long_description = (this_directory / "README.md").read_text()
def get_version(rel_path):
for line in (this_directory / rel_path).read_text().splitlines():
if line.startswith('__VERSION__'):
... | iisaka51/scrapinghelper | setup.py | setup.py | py | 1,519 | python | en | code | 1 | github-code | 1 |
4652979163 | from typing import Dict, List
from datamodel import OrderDepth, TradingState, Order
import numpy as np
class Trader:
period = 15
def __init__(self) -> None:
self.price_log = np.zeros(Trader.period)
self.past_day = {}
def run(self, state: TradingState) -> Dict[str, List[Order]]:
... | Samukat/IMC_Trading_game | Sam/momentum.py | momentum.py | py | 3,833 | python | en | code | 0 | github-code | 1 |
26426288387 | from collections import defaultdict,deque
def solution(n, arr1, arr2):
ans = []
for y in range(n):
st = ""
total = (1<<n)-1
bit = arr1[y] | arr2[y]
for i in range(n):
if (1<<i)&bit: st+="#"
else: st+=" "
ans.append(st[::-1])
return ans | dohui-son/Python-Algorithms | programmers/k비밀지도_bitmask.py | k비밀지도_bitmask.py | py | 313 | python | en | code | 0 | github-code | 1 |
27037063648 | from rest_framework import serializers
class RegisterDnaSerializer(serializers.Serializer):
dna = serializers.ListField(
child=serializers.CharField()
)
class AllRegisterDnaSerializer(serializers.Serializer):
id = serializers.IntegerField()
dna = serializers.CharField()
isMutant = serial... | felipehoyos1110/Mutant-magneto | xMen/mutant/serializers.py | serializers.py | py | 771 | python | en | code | 0 | github-code | 1 |
35705255261 | import numpy as np
# function for damped pseudo-inverse
def damped_pseudoinverse(jac, l = 0.01):
m, n = jac.shape
if n >= m:
return jac.T @ np.linalg.inv(jac @ jac.T + l*l*np.eye(m))
return np.linalg.inv(jac.T @ jac + l*l*np.eye(n)) @ jac.T
# function for skew symmetric
def skew_symmetric(v):
... | nikosmar/franka-emika-hanoi-controller | src/utils.py | utils.py | py | 1,236 | python | en | code | 1 | github-code | 1 |
33827589363 | import redis
import json
import threading
import rospy
from movebase import MoveBase as AdmMove
r = redis.Redis()
p = r.pubsub()
p.subscribe('ros-panel')
map_metadata = None
map_filename = None
current_pos = None
def setupdone(minfo,mapfilename):
global map_metadata, map_filename
map_metadata = minfo
... | adm-sglm/ros-project | src/worker.py | worker.py | py | 1,913 | python | en | code | 0 | github-code | 1 |
14740379632 | # -*- coding: utf-8 -*-
# @Time : 2022/3/5 12:14
# @Author: Shelly Tang
# @File: data.py
# @Function: data.py, deal with the dataset
import glob
import pandas as pd
import random
import csv
import os
import numpy as np
from sklearn.metrics import confusion_matrix
KeyContentLen = 512
SplitDataN = 2
PAR... | SleepingMonster/Chinese-text-classification-pytorch-bert | data.py | data.py | py | 22,136 | python | en | code | 1 | github-code | 1 |
31496879213 | import serial
import time
ser = serial.Serial('/dev/ttyACM0', baudrate = 9600, timeout = 1)
time.sleep(3)
numPoints = 17 #no.of values coming
dataList = [0]*numPoints
def getValues():
arduinoOutput = ser.readline().decode().split(':')
#print(arduinoOutput)
#print(len(arduinoOutput))
if(numPoints ... | Niyas-A/auto | src/imu/src/imu_pub.py | imu_pub.py | py | 901 | python | en | code | 0 | github-code | 1 |
21753957627 | from config_data import config
import requests
import json
import re
from loader import logger
endpoint_search = 'locations/v2/search'
endpoint_hotels = 'properties/list'
endpoint_photo = 'properties/get-hotel-photos'
def json_mod(text, file_name):
data = json.loads(text)
with open(file_name, 'w', encoding=... | russe19/telegram-bot-project | api_requests.py | api_requests.py | py | 3,060 | python | en | code | 0 | github-code | 1 |
70427984994 | import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import linregress
# Data
voltage = np.array([710, 730, 750, 770, 790, 810, 830, 850, 870, 890, 910, 930, 950, 970, 990])
count = np.array([91, 102, 90, 137, 142, 149, 154, 126, 160, 160, 156, 150, 181, 143, 168])
coefficients = np.polyfit(voltage, co... | NolanTrem/phys1494 | experiment10/background.py | background.py | py | 845 | python | en | code | 1 | github-code | 1 |
38204015096 | import os,json
from .exceptions import NsValueIsNotDict, NsUuidDoesNotExist
from .nbiapi.identity import bearer_token
from .nbiapi.ns import Ns
from .nbiapi.vim import Vim
from .nbiapi.vnf import Vnf
def getToken():
creds = os.environ.get('OSM_ADMIN_CREDENTIALS')
token = None
if creds:
creds = j... | sonata-nfv/son-monitor | vnv_manager/app/api/management/commands/osm/utils.py | utils.py | py | 5,464 | python | en | code | 5 | github-code | 1 |
44068529651 | # Grocery Billing System
from datetime import datetime
print('------WELCOME TO OUR SUPER-MARKET-----------')
name=(input('Enter your Name: '))
#LISTS of items
lists= '''
Rice Rs 20/kg
Sugar Rs 40/kg
Salt Rs 35/kg
Oil Rs 70/kg
Panner Rs 80/kg
Maggi Rs 50/kg
Boost Rs 90/kg
Colgate Rs 20/... | sreenivas782/Grocery-Billing-System | Hi.py/hello.py | hello.py | py | 2,187 | python | en | code | 0 | github-code | 1 |
22575763387 | import sys
sys.setrecursionlimit(1000000000)
def input():
return sys.stdin.readline().rstrip()
def dp(v):
con = 0
for nei in tree[v]:
dp(nei)
dp_mat[v][1] += max(dp_mat[nei][0], dp_mat[nei][1])
con = max(con, stat[v-1]*stat[nei-1] - max(dp_mat[nei][0]-dp_mat[nei][1], 0))
dp_mat[... | dydwkd486/coding_test | baekjoon/python/baekjoon17831.py | baekjoon17831.py | py | 603 | python | en | code | 0 | github-code | 1 |
41572392565 | ################################################################################
# CSVtest..py
#
# PURPOSE: Learing how to read CSV files
#
# Written by: Bailey Brookes
# Supervisor: Dr Paul Robertson
################################################################################
import csv
parsed_data = []
with op... | BaileyBrookes/Part_IIB_Project | Code/CSVtest.py | CSVtest.py | py | 1,138 | python | en | code | 0 | github-code | 1 |
5862193517 | # -*- coding: utf-8 -*-
"""
Created on Sat May 06 17:48:26 2017
@author: 821647
"""
import csv
IN_FILE = "SAN_flight_history2.csv"
OUT_FILE = "SAN_flight_history_parsed2.csv"
def main():
out_rows = []
with open(IN_FILE, 'rb') as csvfile:
reader = csv.reader(csvfile)
next(reader)
... | thegreatwarlo/UdacityDataVisualization | data_transform.py | data_transform.py | py | 1,318 | python | en | code | 0 | github-code | 1 |
74868111712 | import shodan
import json
import sys
from time import sleep
from parser import process_parser
def portCheck(info):
ports = info['ports']
if 515 in ports:
content = str(info['ip_str']) + ":port 515 printer find"
writeToFile('log/port.log',content)
print(content)
if 9100 in ports:
... | IotScanner2021/IotScanner2021 | backup/shod.py | shod.py | py | 2,592 | python | en | code | 1 | github-code | 1 |
74112945952 | from dyn2sel.apply_dcs import DCSApplier
from dyn2sel.ensemble import DDCSEnsemble
import numpy as np
class DDCSMethod(DCSApplier):
"""
DDCSMethod
The Double Dynamic Selection (DDCS) is a method that applies traditional offline techniques of Dynamic
Selection in online Machine Learning environments. ... | luccaportes/Scikit-DYN2SEL | dyn2sel/apply_dcs/DDCSMethod.py | DDCSMethod.py | py | 3,618 | python | en | code | 8 | github-code | 1 |
20791741761 | #-*- coding:utf-8 -*-
#记录话题信息
import threading
import time
import os
class MyThread(threading.Thread):
def __init__(self,topic_name):
threading.Thread.__init__(self)
self.topic_name = topic_name
def run(self):
os.system('rostopic hz '+self.topic_name+'> ... | gitgaoqian/Python | CloudVerify/hz_topic/hz_compute.py | hz_compute.py | py | 600 | python | en | code | 0 | github-code | 1 |
69861434594 | import aws_infrastructure.tasks.library.instance_helmfile
import scope.config
from invoke import Collection
from pathlib import Path
import tasks.terraform.ecr
CONFIG_KEY = "helmfile"
STAGING_LOCAL_HELMFILE_DIR = "./.staging/helmfile"
STAGING_REMOTE_HELM_DIR = "./.staging/helm"
STAGING_REMOTE_HELMFILE_DIR = "./.stagi... | uwscope/scope-aws-infrastructure | tasks/helmfile.py | helmfile.py | py | 6,863 | python | en | code | 0 | github-code | 1 |
30896401362 | from data import get_data
from experiments import INVASETrainer
from config import get_decode_args
import torch
from models.decoder import LinearDecoder
import os
from tqdm import tqdm
from robustness.tools.helpers import AverageMeter
from argparse import Namespace
from torch import optim
import torch.nn as nn
import m... | choheeee22/invase-pytorch | decode_analysis.py | decode_analysis.py | py | 4,778 | python | en | code | 0 | github-code | 1 |
21468516172 | import logging
import os
from motor.motor_asyncio import AsyncIOMotorClient
log = logging.getLogger(__file__)
class Database:
def __init__(self, connection_url: str | None = None):
connection_url = connection_url or os.getenv('DB_CONNECTION_URL')
assert connection_url, 'Connection URL to DB not... | kozlowskimaciej/microblog | backend/api/database/db.py | db.py | py | 758 | python | en | code | 2 | github-code | 1 |
40891984064 | # In Python, a dictionary is a {key: value} pair - like maps in Java
programming_dictionary = {
"Bug": "An error in a program that prevents the program from running as expected.",
"Function": "A piece of code that you can easily call over and over again.",
}
# Access dictionary elements by the key - key must be... | hornet33/myPythonLearnings | 01Beginner/Day 09/dictionaries.py | dictionaries.py | py | 3,473 | python | en | code | 0 | github-code | 1 |
8312912464 | import random
import time
def displayIntro():
HP = 100
attack = 10
defence = 5
day = 1
print("You are an Immortal Adventurer. Every day you Explore from a choise of 4 areas.")
time.sleep(1.5)
print("You know tha two of these areas, Will require you to fight with monster's")
time.sleep(1.... | icancode20/my-codes | Teach/Day 7/Teach6.py | Teach6.py | py | 8,319 | python | en | code | 0 | github-code | 1 |
72856098274 | from boto.ec2.ec2object import TaggedEC2Object
from boto.resultset import ResultSet
from boto.ec2.group import Group
class Attachment(object):
"""
:ivar id: The ID of the attachment.
:ivar instance_id: The ID of the instance.
:ivar device_index: The index of this device.
:ivar status: The status o... | heathkh/iwct | snap/boto/ec2/networkinterface.py | networkinterface.py | py | 8,639 | python | en | code | 5 | github-code | 1 |
74576595552 | import pandas as pd
from datetime import datetime, timedelta
def add_english_time_column(dataframe):
# Convertissez la colonne de date en datetime si elle n'est pas déjà au format datetime
# if not pd.api.types.is_datetime64_ns_dtype(dataframe['Date']):
# dataframe['Date'] = pd.to_datetime(dataframe['D... | kermia-ai/pythonProject | prepar_data.py | prepar_data.py | py | 1,400 | python | fr | code | 0 | github-code | 1 |
72046529635 | import smtplib
from email.mime.text import MIMEText
from email.utils import COMMASPACE # This is a just a fancy way of doing: COMMASPACE = ", "
def sendEmail():
recipient = ['email@gmail.com','email2@gmail.com']
pwd = 'your password'
sender = 'pyfeeds@gmail.com'
subject = '**** ALERT ****'
messag... | pybokeh/python | email/SendingEmail.py | SendingEmail.py | py | 1,057 | python | en | code | 0 | github-code | 1 |
28517427312 | #coding=utf-8
from pyrogram import Client, filters
from pyrogram.errors import FloodWait
from pyrogram.types import ChatPermissions
import time
from time import sleep
import random
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
app = Client("my_account", api_id=config['pyrogra... | Slay-of/dtx_userbot | main.py | main.py | py | 1,384 | python | en | code | 0 | github-code | 1 |
26157049157 | from fastapi import APIRouter, Response, status, Depends, HTTPException
from psycopg.errors import UniqueViolation
from datetime import datetime
from pydantic import BaseModel
from fastapi.security import OAuth2PasswordBearer
import os
from jose import jwt
from user_db import pool
from .users import User
from profile_d... | MichaelEChristian/ProjectGamma | backend/accounts/api/routers/profile.py | profile.py | py | 3,353 | python | en | code | 0 | github-code | 1 |
34436411858 | #!/usr/bin/env python3
import sys
import os
from threading import Thread
from queue import Queue, LifoQueue
from functools import cache
from operator import itemgetter
from collections import Counter
from rectangle import Rectangle
# Keep a count of each area a rectangle might have
rect_areas = Counter()
rect_queue = ... | atlantistechnology/thinking-about-debugging | queues/summarize.py | summarize.py | py | 2,262 | python | en | code | 0 | github-code | 1 |
11451090672 | '''
Created on 6 mars 2017
@author: Rickard
'''
from nearestneighbor import *
def cross_validation(data, labels, neighbors, n=3):
n=3
#n-fold cross validation. Not really, since it's hard coded to 3 folds
fold_size = len(data)/n
folds_data = []
folds_labels = []
for i in range(n-1):
... | Riwzi/D7041EProject | cross_validation.py | cross_validation.py | py | 2,562 | python | en | code | 0 | github-code | 1 |
74935568354 | import numpy as np
from pdb import set_trace
# load text data
set_trace()
txt_data = "abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz " # input data
# txt_data = open('input.txt', 'r').read() # test external files
chars = list(set(txt_data)) # split and remove duplicate characters. ... | gov-ind/char-rnn | p.py | p.py | py | 6,284 | python | en | code | 0 | github-code | 1 |
73564417634 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from main.models import *
from main.forms import *
from django.conf import settings
from django.core import serializers
from django.http import HttpResponse
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
fro... | gruizmir/valporanking | main/views.py | views.py | py | 4,771 | python | en | code | 0 | github-code | 1 |
35745723621 | import re
import abc
import inspect
from pysnooper.third_party.six.moves import zip_longest
from python_toolbox import caching
import pysnooper.pycompat
def get_function_arguments(function, exclude=()):
try:
getfullargspec = inspect.getfullargspec
except AttributeError:
result = inspect.geta... | SpyderKong/PySnooper | tests/utils.py | utils.py | py | 7,369 | python | en | code | 0 | github-code | 1 |
29890631794 | import requests
import random
import string
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
url="http://127.0.0.1:5166"
routes=["/code","/linq","/rawsql"]
tries=50
sum = []
queries=[]
print("------------Starting Benchmark------------")
## generate random search query
for i in range(... | amineamri3/SocialBrothersCase | benchmark.py | benchmark.py | py | 1,407 | python | en | code | 0 | github-code | 1 |
10965322490 | import numpy as np
import pandas as pd
from curation.remodeling.operations.base_op import BaseOp
PARAMS = {
"command": "split_events",
"required_parameters": {
"anchor_column": str,
"event_numbers_column": str,
"new_events": dict,
"remove_parent_event": bool
},
... | VisLab/hed-curation | curation/remodeling/operations/split_event_op.py | split_event_op.py | py | 3,657 | python | en | code | 0 | github-code | 1 |
35058154164 | from Graph import Graph
def detectBridge(graph):
time_visited = {}
least_time = {}
visited = {}
time_count = 1
print(graph.edges)
for edges in graph.edges:
visited[edges] = False
for edges in graph.edges:
if(visited[edges]==False):
visited[edges] = True
time_visited[edges] = time_count
least_time... | lazyCodes7/DSA | graphs/detect-bridge-dfs.py | detect-bridge-dfs.py | py | 1,281 | python | en | code | 2 | github-code | 1 |
12889468637 | import numpy as np
import torch
from torch.utils.data.dataloader import DataLoader
from torchvision import transforms
from functions import*
import os
'''
abbvi without any extension
'''
num_epochs=1
batchSize=500
num_S=5#训练的采样数量
dim=1000000+1
num_St=100#测试的采样数量
#eta=0.05#eta、k、w、c这四个参数是和论文对应的
k=1
w=5e13
c=1.3e9
M=10
... | allenzhangzju/Black_Box_Variational_Inference | bbvi_criteo4000000/abbvi_basic.py | abbvi_basic.py | py | 3,145 | python | en | code | 1 | github-code | 1 |
11743119938 | import eval7
# https://pypi.org/project/eval7/
from pprint import pprint
import sys
import datetime
sys.path.insert(0, ".")
sys.path.insert(0, ".libs")
from pokereval import PokerEval
pokereval = PokerEval()
from tqdm import tqdm
hr1 = eval7.HandRange("TT+, AQ+, KQ+") # 78 combo
hr2 = eval7.HandRange("77+, A9+, KT+, ... | jinyiabc/holdem_board_analyzer | test_constant_board.py | test_constant_board.py | py | 4,552 | python | en | code | 0 | github-code | 1 |
25694035511 | import os
from flask import Flask, request, jsonify, render_template
from keras.preprocessing import image
from bs4 import BeautifulSoup
from keras import backend as K
import keras
import requests
import re
app = Flask(__name__,template_folder='/Users/iqbalsandhu/Desktop/finalproject-2')
app.config['UPLOAD_FOLDER'] = '... | thusneem/CNN | finalproject-2/app.py | app.py | py | 3,736 | python | en | code | 0 | github-code | 1 |
15575848076 | # Based on data show cities with positive temperature. Additionally - calculate average temperature for all cities.
# Use map(), filter() and reduce() function for that
from functools import reduce
data_from_api = [
{'city': 'Kraków', 'province_id': 8, 'current_temp': 3.5},
{'city': 'Warszawa', 'province_id'... | deinoo/python | other/filter_map_reduce_for_temperature.py | filter_map_reduce_for_temperature.py | py | 1,113 | python | en | code | 1 | github-code | 1 |
70320340513 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 9 17:05:27 2021
Author: James Dixon
Date: Summer 2021
Convex Optimisation program
's' is signal estimate
"""
import numpy as np
from scipy.optimize import minimize
def Opt(MeasMtx,y,Errorbars,MaxPhtnNum):
# Generate error bound
epsilo... | jmsdixon/Photon-Stats-ConVxOpt | ConvexOpt1.py | ConvexOpt1.py | py | 2,316 | python | en | code | 1 | github-code | 1 |
20004381625 | import cv2
from os import listdir
from os.path import isfile, join
import os
import shutil
def rearrange(files):
if "ordered" in files[0]:
return False
if len(files) % 4 != 0:
return False
new = []
for i in range(0, len(files), 4):
for j in range(2):
new.append(files... | dartmouth-review/reorganizer | rearrange.py | rearrange.py | py | 1,875 | python | en | code | 0 | github-code | 1 |
9527606346 | from pytest import fixture
from core.db.models import db
from core.db.models.domain_attribute import DomainAttribute
@fixture
def domain_attribute(domain_category):
node = DomainAttribute(
name='domain attribute',
category_id=domain_category.id,
has_taxonomy=False,
taxonomy_is_sco... | NLPDev/Wine_Project | tests/fixtures/domain_attribute.py | domain_attribute.py | py | 632 | python | en | code | 0 | github-code | 1 |
35678508596 | # Write a Python program to sort (ascending and descending) a dictionary by value.
import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
print("Original list: ", d)
sorted_d = sorted(d.items(), key=operator.itemgetter(1))
print('Dictionary in ascending order by value : ', sorted_d)
sorted_d = dict(sorted(d.items(), key=op... | harshalwarkar2020/Practice_assignment | Dict_2.py | Dict_2.py | py | 1,471 | python | en | code | 0 | github-code | 1 |
4258636095 | from __future__ import division
import os
import numpy as np
from scipy import stats
from osgeo import gdal,ogr
import configparser
import inspect
import sys
import pandas as pd
from GeoFlood_Filename_Finder import cfg_finder
from time import perf_counter
from scipy.stats import gmean,theilslopes
def r... | passaH2O/GeoFlood | GeoFlood/River_Attribute_Estimation.py | River_Attribute_Estimation.py | py | 9,320 | python | en | code | 29 | github-code | 1 |
24919761960 | import requests
import json
import re
from xml.dom.minidom import parse
import xmltodict
from fontTools.ttLib import TTFont
from bs4 import BeautifulSoup
heard={
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36',
}
def mapping... | smilemilk1992/myPspider | autoHome/main.py | main.py | py | 4,894 | python | en | code | 2 | github-code | 1 |
18272016245 | # -*- coding: utf-8 -*-
import os
import time
import logging
import numpy as np
import jieba
from gensim.models import KeyedVectors
import sys
file_root = os.path.dirname(__file__)
sys.path.append(file_root)
from get_file import get_file
pwd_path = os.path.abspath(os.path.dirname(__file__))
USER_DATA_DIR = pwd_path
... | Hanscal/unlp | unlp/unsupervised/Word2Vec/word2vec.py | word2vec.py | py | 6,268 | python | en | code | 9 | github-code | 1 |
73199008034 | #!/usr/bin/env python
# importing the required library
from confluent_kafka import Producer
from confluent_kafka.serialization import StringSerializer
import confluent_kafka
import requests
import os, sys, time
import argparse
import json
import socket
import datetime
import random
def gen_custom_data(namespace, us... | yanshanlangren/python-test | src/cloudsat/kafka_sender.py | kafka_sender.py | py | 2,841 | python | en | code | 0 | github-code | 1 |
74454066272 | # Write a Python program to count the number of characters (character frequency) in a string.
from collections import Counter
m = 'google.com'
count = Counter(m)
print(count)
#Prgram to reverse words the string
def reverse_string_words(text):
for line in text.split('\n'):
return(' '.join(line.split()[::-1]... | IswaryaJ/Practice | String/Prog1.py | Prog1.py | py | 447 | python | en | code | 0 | github-code | 1 |
16371574110 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
import os
import versioneer
HERE = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(HERE, "README.md"), "r", encoding="utf8") as fh:
README = fh.read()
with open(os.path.join(HERE, ... | opsdroid/opsdroid-homeassistant | setup.py | setup.py | py | 1,467 | python | en | code | 2 | github-code | 1 |
34547350066 | #library imports
import re
import json
#my script imports
import website_parser
import textual_feature_extracter
import information_retrieval_feature_extractor
import textual_feature_transformer
import link_feature_transformer
def main(url):
#Check if the inputted Url is valid using Regex
i... | colm-brandon-ul/IVS_Code | scripts/pipeline.py | pipeline.py | py | 2,103 | python | en | code | 0 | github-code | 1 |
35497926119 | import numpy as np
def hyperbolic_departure(mu_sun, mu, R1, R2, rp):
term1 = np.sqrt(mu_sun/R1)
term2 = np.sqrt(2*R2/(R1+R2))-1
v_infinity = term1 * term2
eh = 1+rp*v_infinity**2/mu
h = rp*np.sqrt(v_infinity**2+2*mu/rp)
v1 = np.sqrt(mu/rp)
v2 = h/rp
delta_v = v2-v1
beta... | gwak2349/hi | hyperbolic_departure.py | hyperbolic_departure.py | py | 842 | python | en | code | 0 | github-code | 1 |
24280152763 | import requests
import bs4 as bs
import pandas as pd
import pickle
import sys
from datetime import datetime
import math
# # Puxa o nome dos 1965 ativos que vieram do site da uol e estao no arquivo chamado ativos
# with open('ativos', 'rb') as f:
# ativos = pickle.load(f)
# ########
# Lista de acoes que o program... | pedrocampeloa/UnB-LMF-Data-Science | algoritimo1.py | algoritimo1.py | py | 5,095 | python | pt | code | 0 | github-code | 1 |
34471177330 | import sys
si = sys.stdin.readline
n, m, k = map(int, si().split())
diag = [[False for i in range(m+1)] for _ in range(n+1)]
MOD = 1000000007
for _ in range(k):
r, c = map(int, si().split())
diag[r-1][c-1] = True
dy = [[0 for _ in range(m+1)] for _ in range(n+1)] # dy[r][c] := r행 c열인 직사각형을 최단거리로 이동하는 경우의 수
dy... | yeafla530/algorithms | 해몽/0609_wootaecam/2.py | 2.py | py | 1,225 | python | ko | code | 0 | github-code | 1 |
69860095714 | #!/usr/bin/python3
import json
import os
class FileStorage:
__file_path = '../../file.json'
__objects = {}
def all(self):
return FileStorage.__objects
def new(self, obj):
key = "{}.{}".format(type(obj).__name__, obj.id)
FileStorage.__objects[key] = obj
'''
... | Tboy54321/trials | hbnb/models/engine/file_storage.py | file_storage.py | py | 1,754 | python | en | code | 0 | github-code | 1 |
7730906922 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
def plot_tree(tree):
ax = plt.gca()
ax.set_axis_off()
build_tree(tree, 0.25, 0.25)
ax.set_xlim(-1, 2)
ax.set_ylim(-2, 1)
plt.show()
def build_tree(tree, left, bottom, depth=0, ax=plt.gca()):
hei... | nas-w/Techniques-Avancees-IA-ift7025-tp4 | utils/graphics.py | graphics.py | py | 4,032 | python | en | code | 0 | github-code | 1 |
30468013567 | #!/usr/bin/env python
# coding: utf-8
# %%
# %%
import os
import pickle
import sys
import pandas as pd
from RASLPhysio import Features
from datetime import datetime, timedelta, date
# %%
# %%
def nearest(items, pivot):
return min(items, key=lambda x: abs(x - pivot))
# %%
subjects = [ "S" + str(i) for i... | nibraaska/CHIL2022 | ExtractFeatures.py | ExtractFeatures.py | py | 1,972 | python | en | code | 0 | github-code | 1 |
82002215 | import time
from urlparse import urlparse
import boto
from scrapy.exceptions import NotConfigured
from twisted.internet.threads import deferToThread
class S3Pipeline(object):
@classmethod
def from_crawler(cls, crawler):
return cls(crawler.settings)
def __init__(self, settings):
self.tim... | TeamHG-Memex/scrash-pageuploader | pageuploader/__init__.py | __init__.py | py | 1,341 | python | en | code | 1 | github-code | 1 |
18653183685 | from django.db.models import Sum
import math
from rest_framework import serializers
from rest_framework.reverse import reverse as api_reverse
from tickets.models import Ticket, Visit
from customerorders.api.serializers import CustomerOrderSerializer
from customerprojects.api.serializers import CustomerProjectSerializ... | KUSH23/bkend | tickets/api/serializers.py | serializers.py | py | 2,495 | python | en | code | 1 | github-code | 1 |
27611690782 | import rclpy
import rclpy.node
import rclpy.qos
from geometry_msgs.msg import Point
class ROS2Sub(rclpy.node.Node):
def __init__(self, *args):
super(ROS2Sub, self).__init__("ROS2Sub")
self.create_subscription(
Point, "points", self.points_callback, rclpy.qos.qos_profile_sensor_data)
... | NMBURobotics/ros2_python_demos | ros2_demo_python_nodes/ros2_demo_python_nodes/topic_sub.py | topic_sub.py | py | 561 | python | en | code | 5 | github-code | 1 |
31920134745 | #!/home/knielbo/virtenvs/ndhl/bin/python
"""
Build signal(s) from information dynamics in model
@author: kln@cas.au.dk
"""
import os
import numpy as np
from numpy.matlib import repmat
import scipy as sp
from util import load_pcl
# vis and test
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams.upda... | centre-for-humanities-computing/NDHL-AHM20 | src/build_signal.py | build_signal.py | py | 5,392 | python | en | code | 0 | github-code | 1 |
29732233926 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from math import pi
from math import sqrt
from math import radians
from math import cos
from weblib.pubsub import Publisher
class ACSSessionCreator(Publisher):
def perform(self, push_adapter):
"""Log into the Appcelerator Cloud services and return the create... | iamFIREcracker/strappon | strappon/pubsub/__init__.py | __init__.py | py | 2,675 | python | en | code | 0 | github-code | 1 |
138298365 | from django.db import models
from datetime import datetime
class ShowManager(models.Manager):
def basic_validator(self, postData):
errors = {}
if len(postData['title']) < 3:
errors['title'] = 'Title should be at least 2 characters.'
if Show.objects.filter(title=postData['title']... | yuzuha48/Bootcamp-Public | back-end/django/tv_shows/tv_shows_app/models.py | models.py | py | 1,253 | python | en | code | 0 | github-code | 1 |
32674362326 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('fantaapp', '0015_auto_20150807_1532'),
]
operations = [
migrations.RemoveField(
model_name='incontrocalendario',... | abenassen/holyfootball | fanta/fantaapp/migrations/0016_auto_20150807_1908.py | 0016_auto_20150807_1908.py | py | 1,365 | python | en | code | 0 | github-code | 1 |
70577593634 | import os
import time
import base64
from PIL import Image
from io import BytesIO
import torch
from torch.autograd import Variable
from torchvision.utils import save_image
from models import TransformerNet
from utils import *
from flask import *
from flask_cors import CORS
app = Flask(__name__, )
# r'/*' 是通配符,让本服务器所... | bugstop/fast-neural-style-transfer | docs/source/server/server.py | server.py | py | 2,655 | python | en | code | 5 | github-code | 1 |
22092281530 | p = [["E", "C", "A", "F"]]
b = 0
for i in range(int(input())):
s = input().split()
if s == p[-1]:
b += 1
p.pop()
else:
p.append(s[::-1])
if not p:
p.append(["E", "C", "A", "F"])
print(b)
| JoaoAssalim/Beecrowd-Solution | Python/1944.py | 1944.py | py | 241 | python | ko | code | 5 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.