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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
3168618507 | from collections import OrderedDict
from typing import Tuple, Union
from fvcore.common.registry import Registry
import copy
import json
import threading
import numpy as np
import torch
import torch.nn.functional as F
import torch.distributed as dist
from torch import nn
from collections import defaultdict
from clip i... | zhaoyanpeng/vipant | cvap/module/decoder/loss_head.py | loss_head.py | py | 25,849 | python | en | code | 19 | github-code | 1 |
74539033312 | """Execution and managing kernels."""
import os
import warnings
from logging import Logger
from pathlib import Path
import nbconvert
from docutils.parsers.rst import Directive, directives
from nbconvert.preprocessors import ExtractOutputPreprocessor
from nbconvert.writers import FilesWriter
from sphinx.errors import ... | jupyter/jupyter-sphinx | jupyter_sphinx/execute.py | execute.py | py | 11,919 | python | en | code | 173 | github-code | 1 |
22593834724 | from logicToMath import logicToMath
#import evaluate
def check_tautology(formula="(~(P->~P)&&~(Q->~Q))->~(P->~Q)", verbose=True, debugMode=False):
if (formula.find("P") < 0) and (formula.find("Q") < 0):
return False
mathFormula = logicToMath(formula, verbose, debugMode)
#Replace P's and Q's with 0's and ... | jaredjay91/logicTree | formulaTester.py | formulaTester.py | py | 1,953 | python | en | code | 0 | github-code | 1 |
5254686523 | import cirq
def balanced(qubits):
circuit = cirq.Circuit()
for i in range(3):
circuit.append(cirq.CNOT(qubits[i], qubits[3]))
return circuit
def constant(qubits):
circuit = cirq.Circuit()
circuit.append(cirq.X(qubits[3]))
return circuit
def run(gate):
circuit = cirq.Circuit... | robertGGA/qubit | home2.py | home2.py | py | 789 | python | en | code | 0 | github-code | 1 |
40454861663 | import os
from datetime import datetime
from typing import Any, Dict, List, Tuple, Union
from uuid import uuid4
import sqlalchemy as sa
from sqlalchemy.orm import Session, aliased
from sqlalchemy.sql import label
from umeta import config, core, generators, models, sources
def get_buckets(db: Session, s: config.Sour... | subdavis/umeta | umeta/crud.py | crud.py | py | 10,616 | python | en | code | 0 | github-code | 1 |
71546384995 | import numpy as np
lista_nif = []
lista_nombre = []
lista_edad = []
lista_pertenece = []
lista_conyugal = []
i = 0
poto = 0
def grabar(nif,nombre,edad,pertenece,conyugal):
lista_nif.append(nif)
lista_nombre.append(nombre)
lista_edad.append(edad)
lista_pertenece.append(pertenece)
lista_c... | Sshavii/VicenteTramon_PGY1121_009D | VicenteTramon_PGY1121_009D/VicenteTramon_PGY1121_009D.py | VicenteTramon_PGY1121_009D.py | py | 4,022 | python | es | code | 0 | github-code | 1 |
28228601843 | from flask import Flask
from flask import render_template
from os import environ
import Function
import requests
app = Flask(__name__)
# key=43a462f629d817bf91ca4bb95f9cd7b3
@app.route('/')
def hello_world():
return render_template(
'Search.html'
)
#192.168.191.1:8080
if __name__ == '__ma... | hetianle/AmapApplication | AMapApplication/Main.py | Main.py | py | 536 | python | en | code | 0 | github-code | 1 |
32593904247 | import os, shutil
'''Simple script that imports .java an .py files from the Download folder into a Python or Java folder.
The remaining files that are not the two are moved into the Extra_Files folder
By Patrick Zapata (PatZap) Updated Jan 18 2020
'''
def download_path(path):
os.chdir(path)
download_list = os.l... | patzap/File_Transfer | File_Transfer.py | File_Transfer.py | py | 1,241 | python | en | code | 0 | github-code | 1 |
70737253154 | ## 18111. 마인크래프트 (01.05)
n, w, b = map(int, input().split())
space = []
for _ in range(n):
space.append(list(map(int, input().split())))
min_value = min(map(min, space))
max_value = max(map(max, space))
leastTime = 1e9
for i in range(min_value, max_value+1):
pluscount = 0
minuscount = 0
for j in rang... | ChanWhanPark/Algorithm | BaekJoon/Brute_Force/18111_minecraft.py | 18111_minecraft.py | py | 704 | python | en | code | 0 | github-code | 1 |
24859917703 | from starlette.datastructures import FormData
from starlette.requests import Request
from fcg.viewmodels import parse
from fcg.viewmodels.base_viewmodel import BaseViewModel
class FormBaseViewModel(BaseViewModel):
def __init__(self, request: Request):
super().__init__(request)
self.proposal_code ... | saltastroops/finder-chart-generator | fcg/viewmodels/form_base_viewmodel.py | form_base_viewmodel.py | py | 772 | python | en | code | 0 | github-code | 1 |
23707946723 | import random
import sys
import numpy as np
from tqdm import tqdm
import cv2
import os
from skimage.util import random_noise
from skimage import img_as_ubyte
def __augment(img):
options = [
'gaussian',
'poisson',
's&p',
]
option = random.choice(options)
noise_img = (random_no... | nielsRocholl/pr-assignment-2 | task_1/big_cats/pipeline_modules/feature_extraction.py | feature_extraction.py | py | 2,555 | python | en | code | 0 | github-code | 1 |
2100341497 | def check1(list1,list2):
result=False
for i in list1:
for j in list2:
if(i==j):
result=True
return result
break
list1=[]
list2=[]
size=int(input('enter the size of the list\n'))
print('enter the elements of first list\n')
for i in r... | naikharshada/Python-Code | WAP that takes 2 list and returns true if they have at least one common element.py | WAP that takes 2 list and returns true if they have at least one common element.py | py | 626 | python | en | code | 2 | github-code | 1 |
46251647661 | from ...utils.exceptions import ArgumentException, AuthenticationException
class SendUserRecoveryService:
def __init__(self, user_repository, email_factory, email_sender, token_generator):
self.user_repository = user_repository
self.email_factory = email_factory
self.email_sender = email_... | agarciavallejo/buitre | app/services/user/sendUserRecoveryService.py | sendUserRecoveryService.py | py | 885 | python | en | code | 1 | github-code | 1 |
9194086611 | import pygame
import numpy as np
from astar_point_rigid import *
import time
def triangleCoordinates(start, end, triangleSize = 5):
rotation = (math.atan2(start[1] - end[1], end[0] - start[0])) + math.pi/2
# print(math.atan2(start[1] - end[1], end[0] - start[0]))
rad = math.pi/180
coordinateList... | mesneym/Astar-Path-Planning | main.py | main.py | py | 6,588 | python | en | code | 0 | github-code | 1 |
23863331799 | # coding=utf-8
from __future__ import absolute_import
### (Don't forget to remove me)
# This is a basic skeleton for your plugin's __init__.py. You probably want to adjust the class name of your plugin
# as well as the plugin mixins it's subclassing from. This is really just a basic skeleton to get you started,
# defi... | amsbr/OctoPrint-EEPROM-Marlin | octoprint_eeprom_marlin/__init__.py | __init__.py | py | 1,781 | python | en | code | 15 | github-code | 1 |
11711488050 | # 교통사고 주/야, 요일 -> 예상 속도
# 6시 ~ 18시 : 주 / 1 ~ 5시, 19시 ~ 24시
import tensorflow as tf
from keras.models import *
from keras.layers import *
from keras.callbacks import *
import numpy as np
import pandas as pd
import csv, random
class Dataset:
def __init__(self):
self.week_names = ['월', '화', '수', '목', '금', '토'... | Jyeo-Archive/Samsung-Data-Challenge | 02. Vehicle-Speed-Prediction/model.py | model.py | py | 5,550 | python | en | code | 0 | github-code | 1 |
19955541989 | # © 2021 Solvos Consultoría Informática (<http://www.solvos.es>)
# License LGPL-3.0 (http://www.gnu.org/licenses/lgpl-3.0.html)
from odoo import api, models, fields
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
website_warehouse_ids = fields.Many2many(
"stock.w... | solvosci/slv-e-commerce | website_sale_stock_warehouses/models/res_config_settings.py | res_config_settings.py | py | 880 | python | en | code | 0 | github-code | 1 |
26062127123 | import numpy as np
import pandas as pd
from scipy.sparse.linalg import svds
from scipy.sparse import csc_matrix
users=pd.read_json("data/customers.json")
users.columns = ["user_id",'username']
products=pd.read_json("data/products.json")
products.columns = ["product_id","product_name","price"]
ratings=pd.read_json("d... | TranHap/SheCodes-Recommendation-System | mf.py | mf.py | py | 2,005 | python | en | code | 0 | github-code | 1 |
22526657259 | import logging
import os
DEFAULT_LOGGING_LEVEL = os.environ.get("LOGGING_LEVEL", "INFO")
class Logging:
"""
Singleton for logging.
This eases the retrieval of loggers with a uniform format for all the library.
"""
def __init__(self, level=DEFAULT_LOGGING_LEVEL):
self._level = level
... | cryptonglab/poktbot | poktbot/log/poktbot_logging.py | poktbot_logging.py | py | 1,565 | python | en | code | 11 | github-code | 1 |
15969978807 | import sys
import math
pi = math.pi
e = math.e
def main():
_input = sys.stdin.readlines()
for line in _input:
arr = line.split(' ')
a = int(arr[0])
op = arr[1]
b = int(arr[2])
if op == '+':
ans = (a+b)%10000
if op == '*':
ans = (a%10000*... | andrewome/kattis-problems | checkingforcorrectness.py | checkingforcorrectness.py | py | 418 | python | en | code | 0 | github-code | 1 |
41559924516 | #!/usr/bin/python
#################
# Imports
import os
import time
import datetime
import time
from datetime import datetime as dt
from time import strftime
import pDBIconnect
import decimal
import pandas as pd
def nowTime():
nowstrt = datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S")
return nowstrt
pd.s... | grizli-beep/resume | Monitoring scripts/check_PositionsAttributes.py | check_PositionsAttributes.py | py | 1,552 | python | en | code | 0 | github-code | 1 |
33008344480 | import time
import random
from ctypes import windll, wintypes, byref
from functools import reduce
def r():
return random.random()
def r_g():
return random.gammavariate(1,2)
'''
リビルドを開始しました...
1>------ すべてのリビルド開始: プロジェクト:FugaClass, 構成: Debug Any CPU ------
1>D:\PG\新しいフォルダー\FugaClass\Class1.cs(20,13,20,16): ... | Yotty0404/Cafe_Coding | Cafe_Coding_Build.py | Cafe_Coding_Build.py | py | 5,098 | python | ja | code | 2 | github-code | 1 |
33880837913 |
from collections import defaultdict
def solve(program):
painted_hull = {}
x, y = 0, 0
dx, dy = 0, 1
painting = True
def input_func():
print(f"get_color({x}, {y}) : {get_color(x, y)}")
return get_color(x, y)
def output_func(value):
nonlocal x, y, dx, dy, painting
... | bdaene/advent-of-code | 2019/day11/part 1.py | part 1.py | py | 5,225 | python | en | code | 1 | github-code | 1 |
25053880076 | # https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
from typing import List
"""
Time O(n)
Space O(1)
"""
class Solution:
def maxProfit(self, prices: List[int]) -> int:
prices_length= len(prices)
max_profit=0
for i in range(1, prices_length):
if prices[i] > pric... | snk95/Sarvesh-Code | Leetcode/Arrays/Best_Time_to_Buy_Sell_Stock_II.py | Best_Time_to_Buy_Sell_Stock_II.py | py | 422 | python | en | code | 0 | github-code | 1 |
11561996852 | # 20151105 Runtime: 104 ms
# Non-recursive inorder traversal
# Definition for a binary tree node
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BSTIterator(object):
def __init__(self, root):
"""
:type roo... | chaor/LeetCode_Python_Accepted | 173_Binary_Search_Tree_Iterator.py | 173_Binary_Search_Tree_Iterator.py | py | 878 | python | en | code | 49 | github-code | 1 |
42891539155 | from django.urls import path
from .views import DashboardView, ProfileView, SettingView, ReportHistoryView
app_name = "doctor"
urlpatterns = [
path('doctor/dashboard/', DashboardView, name="dashboard"),
path('doctor/report/history/', ReportHistoryView, name="report-history"),
path('doctor/profile/', Pr... | Zarar-Anwar/glucoma_detect | doctor/urls.py | urls.py | py | 429 | python | en | code | 0 | github-code | 1 |
26206633753 | from tempfile import TemporaryDirectory
import popxl
import numpy as np
from popxl_addons.layers import Linear
from popxl_addons.module import Module
from popxl_addons.task_session import TaskSession
import os
import glob
class MockModel(Module):
def __init__(self):
super().__init__()
self.l1 = Li... | graphcore/popxl-addons | tests/integration/test_task_session.py | test_task_session.py | py | 2,609 | python | en | code | 1 | github-code | 1 |
1074569179 | import os
import shutil
import sys
import datetime
import json
dateconvert = {
1: "Jan",
2: "Feb",
3: "Marc",
4: "Apr",
5: "Maj",
6: "Jun",
7: "Jul",
8: "Aug",
9: "Szept",
10: "Okt",
11: "Nov",
12: "Dec"
}
def prepare():
root = ""
if l... | Je-RICO-h/Python-picsorter | Picsorter/main.py | main.py | py | 3,237 | python | en | code | 0 | github-code | 1 |
28522304283 | import atexit
import sqlite3
import sys
import os
import traceback
sys.path.append('./server')
from helper import *
from content import *
settings_dict = load_yaml_dict(read_file("../Settings.yaml"))
content = Content(settings_dict)
version = read_file("../VERSION").rstrip()
# This tells us whether the migration ha... | srp33/CodeBuddy | front_end/migration_scripts/15_to_16.py | 15_to_16.py | py | 1,336 | python | en | code | 8 | github-code | 1 |
39073393325 | import numpy as np
from word2vec import Word2Vec
#from random import shuffle
'''
DataFeed
- (list_of_datapoints)
- [ datapoints ] -> batch_i
- [ datapoints ] -> next_batch
'''
class DataFeed(object):
def __init__(self, batchop, batch_size=1,
datapoints = [], w2v=None):... | ai-guild/SQuADQA | framework/datafeed.py | datafeed.py | py | 2,114 | python | en | code | 1 | github-code | 1 |
74965858274 | class Solution:
def climbStairs(self, n: int) -> int:
if n==1:
return 1
if n==2:
return 2
first=1
second=2
for i in range(2,n):
step=first+second
first=second
second=step
return second | GreatTwang/lccc_solution | Python/dp/Climbing Stairs.py | Climbing Stairs.py | py | 296 | python | en | code | 2 | github-code | 1 |
31658308898 | import sklearn.svm
import ProtModel
import numpy as np
import sys
class SVM(ProtModel.Model): #classe per modello SVM, estende classe astratta modello generico e utilizza la classe SVC di SkLearn
def __init__(self, C, G):
self.C=C
self.G=G
def train(self,datat): #train the model gi... | Rambaldelli/SVM-GOR-Secondary-Structure-Prediction-Comparison | MySVM.py | MySVM.py | py | 2,653 | python | en | code | 0 | github-code | 1 |
74258977312 | import sys, os, time, traceback
import ctypes
from optparse import OptionParser
import pygame.midi
import winreg
# Constants
# Axis mapping
axis = {'X': 0x30, 'Y': 0x31, 'Z': 0x32, 'RX': 0x33, 'RY': 0x34, 'RZ': 0x35,
'SL0': 0x36, 'SL1': 0x37, 'WHL': 0x38, 'POV': 0x39}
# Slider or Pitchbend keys(m_types)
sliders = ... | c0redumb/midi2vjoy | midi2vjoy/midi2vjoy.py | midi2vjoy.py | py | 4,958 | python | en | code | 73 | github-code | 1 |
71039294435 | import json, os
coder = "utf8"
numlist = {
"一" : 1,
"二" : 2,
"三" : 3,
"四" : 4,
"五" : 5,
"六" : 6,
"七" : 7,
"八" : 8,
"九" : 9,
"十" : 10
}
class StringTool :
def bins(BinsStrings : str) :
re = []
for i in BinsStrings :
i = b... | Donseking/dsksystem | pymodle/dskmod.py | dskmod.py | py | 6,240 | python | en | code | 1 | github-code | 1 |
42603986144 | from django.shortcuts import render
from portfolio.models import MyApp
# Create your views here.
def home(request):
# name = "John"
all_apps = MyApp.objects.all()
context = {
'my_apps': all_apps
}
return render(request, 'website/index.html', context)
| SergeiVorobev/MyPortfolio | portfolio/views.py | views.py | py | 281 | python | en | code | 0 | github-code | 1 |
15930150666 | import numpy as np
import pandas as pd
import seaborn as sns
df = pd.read_excel('./data/hot/唐山打人事件.xlsx')
df_parent = pd.read_excel('./data/hot/clear_data_#唐山打人事件#.xlsx')
xi = {}
for name in df["comment_user_name_x"]:
ci = df[df.comment_user_name_x==name]['sentiment_score']
ai = len(ci)
xi[name] = sum(ci)... | comddy/shenzhenbei | 问题一/爬虫/hot/PageRank-SIR-RUCM.py | PageRank-SIR-RUCM.py | py | 2,506 | python | en | code | 0 | github-code | 1 |
5853173865 | def inputs():
"""
:return: a list of commands (tuples): (direction, distance)
"""
fl = open('input.txt')
return [ln.strip().split(' ') for ln in fl]
def part1():
"""
:return: product of horizontal and vertical coordinates
"""
for command in commands:
if command[0] == 'for... | mcostigan/2021-Advent-Of-Code | adventOfCode/day2/day2.py | day2.py | py | 1,170 | python | en | code | 0 | github-code | 1 |
44646236744 | class Employee:
company_name = "tcs"
raise_amount = 1.05
all = []
def __init__(self, first: str, last: str, salary: float):
# Run validation for the received attributes.
assert salary >= 0, f"Salary '{salary}' should be greater then zero"
# Assign to self objects
self.f... | TarakaKoda/Object-Oriented-Programming | practice_example.py | practice_example.py | py | 1,830 | python | en | code | 0 | github-code | 1 |
34139026795 | import torch
import onnx
from torchvision import models
from torch import nn
import onnxruntime
import numpy as np
import onnxsim
class NaiveModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.net = models.mobilenet_v2(pretrained=True)
self.out2 = nn.Linear(1000,2)
def f... | qiaofengsheng/ai_deploy | TensorRT/python/export_onnx.py | export_onnx.py | py | 3,222 | python | en | code | 16 | github-code | 1 |
21721104652 |
#김성우 BTE2703-01 금요일 실습 분반
#2016163055, n까지의 emrip를 세는 프로그램
#2017년 9월 27일 작성 python 3.6.2버젼
print(''' ********** EMIRP NUMBERS ***********
emirp is a nonpalindromic prime number
whose reversal is also a prime
''')
#변수들 미리 설정
count=n=p=0
#n과 p를 입력하는 loop로 잘못 입력하면 다시 문구가 나오도록 설정
while (n<=1 or 10000... | blackll15/Yonsei | Biotechnology Information Processing/2016163055_실습과제_1_1679938363.py | 2016163055_실습과제_1_1679938363.py | py | 1,774 | python | ko | code | 0 | github-code | 1 |
34765804871 | #Faça um algoritmo que leia uma variável e some 5 caso seja par
#ou some 8 caso seja ímpar, imprimir o resultado desta operação.
numero = int(input('Digite um valor: '))
if (numero%2) == 0:
resul = numero + 5
print('O número digitado é par, e seu valor somado com 5 é: ' + str(resul))
else:
resul = numero ... | gustavoborgesguimaraes/python-projects | identificar par ou impar.py | identificar par ou impar.py | py | 417 | python | pt | code | 0 | github-code | 1 |
70319724513 | # -*- coding: utf-8 -*-
from five import grok
from jowent.bannerviewlet import MessageFactory as _
from jowent.bannerviewlet.behaviors.bannerimage import IBannerImage
from jowent.bannerviewlet.interfaces import IBannerViewletSettings
from plone.namedfile.interfaces import INamedBlobImageField
from plone.registry.interf... | jowent/jowent.bannerviewlet | jowent/bannerviewlet/validators.py | validators.py | py | 2,198 | python | en | code | 0 | github-code | 1 |
33846406001 | from pages.spitogatos import SpitogatosUtilities
def test_basic_spitogatos_submit():
# Given the Spitogatos home page is displayed
b1 = SpitogatosUtilities()
# When the user submits valid inputs in all fields of submission form
b1.completeform("Dimitris", "Metaxakis", "+30 432564325", "Jim@spitogatos... | DimitrisMetaxakis/Python_Selenium_Test_Projects | tests/spitogatos_test.py | spitogatos_test.py | py | 2,414 | python | en | code | 0 | github-code | 1 |
38906726308 | from typing import Optional
from .AircraftData import AircraftData
from src.pyLiveKML.KML.GeoCoordinates import GeoCoordinates
from src.pyLiveKML.KML.KML import AltitudeMode
from src.pyLiveKML.KML.KMLObjects.IconStyle import IconStyle
from src.pyLiveKML.KML.KMLObjects.Placemark import Placemark
from src.pyLiveKML.KML.... | smoke-you/pyLiveKML | evals/apps/aircraft_trail/AircraftPosition.py | AircraftPosition.py | py | 1,270 | python | en | code | 1 | github-code | 1 |
72781393635 |
"""
This program lists all the active courses as well
as courses with an assignment group containing "Ungraded"
This is useful for configuring the Redis db (See README.md)
"""
import os
import dotenv
from canvasapi import Canvas
dotenv.load_dotenv()
canvas_url = 'https://moravian.instructure.com/'
canvas_token = ... | bjcoleman/trello-todo-canvas | list_ids.py | list_ids.py | py | 819 | python | en | code | 0 | github-code | 1 |
17217415192 |
from random import random, randint, choice
import numpy
from ..ops import multiType
from p4p.wrapper import Value
def rand_str():
N = randint(0, 10) # inclusive
return ''.join([choice('abcdefghijklmnopqrstufwxyz') for n in range(N)])
def rand_int():
return randint(-10, 10)
def rand_flt():
return r... | epics-base/masarService | python/minimasar/gather/sim.py | sim.py | py | 2,591 | python | en | code | 6 | github-code | 1 |
35235621538 | from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import FormView, View, ListView
from django.views.generic.base import TemplateView, TemplateResponseMixin
from ... | NeelRoshania/MarPersonnel | home/views.py | views.py | py | 16,642 | python | en | code | 0 | github-code | 1 |
2769032283 | from sklearn.svm import SVC
import pandas as pd
from sklearn.metrics import accuracy_score
import pickle
train = pd.read_csv("./mnist/train.csv")
valid = pd.read_csv("./mnist/t10k.csv")
train_label = train.iloc[:, 0] #모든행에 1번쨰 열
train_data = train.iloc[:, 1:] #모든 행에 2번째 ㅇ열부터 끝까지
valid_label = train.iloc[:... | Aki-hwang/Python_lvl_1 | 66_손글씨_숫자_학습.py | 66_손글씨_숫자_학습.py | py | 738 | python | ko | code | 0 | github-code | 1 |
18271903265 | # -*- coding: utf-8 -*-
"""
@Time : 2022/1/14 3:34 下午
@Author : hcai
@Email : hua.cai@unidt.com
"""
import os
import time
file_root = os.path.dirname(__file__)
import sys
sys.path.append(file_root)
from classification.run import Service
class Classification(object):
def __init__(self, model_name, mode='pred... | Hanscal/unlp | unlp/supervised/text_classify.py | text_classify.py | py | 1,890 | python | en | code | 9 | github-code | 1 |
30719544704 | from poloniex import Poloniex
class PoloniexInterface:
pairs = {
'LTC_BTC': 'BTC_LTC',
'BCH_BTC': 'BTC_BCH',
'ETH_BTC': 'BTC_ETH',
'ETC_BTC': 'BTC_ETC'
}
def __init__(self):
self.polo = Poloniex()
def get_data(self):
res = self.polo.returnTicker()
... | alzkun/crypto-data | poloniex_interface.py | poloniex_interface.py | py | 514 | python | en | code | 0 | github-code | 1 |
73871196835 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Steps to fix up datasets:
1. Gene IDs, detailed elsewhere, but should put it here
2. EPA requires bifurcating trees. See bifurcating_trees.py
3. IQTREE: must eliminate sequences that are all gaps.
"""
import glob
import os
import sys
import random
import subprocess
i... | davidemms/SHOOT | shoot/create_shoot_db.py | create_shoot_db.py | py | 9,970 | python | en | code | 22 | github-code | 1 |
9789033915 | from mongo import engine
from mongo.course import *
from datetime import datetime
from .user import *
from .utils import *
__all__ = ['Post']
class Post():
@classmethod
def found_thread(cls, target_thread):
reply_thread = []
if target_thread.reply:
for reply in target_thread.repl... | Normal-OJ/Back-End | mongo/post.py | post.py | py | 4,387 | python | en | code | 2 | github-code | 1 |
2889154407 | from pprint import pprint as pp
from collections import defaultdict
import sys
sys.setrecursionlimit(10 ** 7)
readlines = sys.stdin.buffer.readlines
map_readlines = lambda: map(int, readlines())
readline = sys.stdin.buffer.readline
map_readline = lambda: map(int, readline().split())
sreadline = lambda: readline().decod... | Kumamoto-Hamachi/atcoder_pr | others/abs/10.py | 10.py | py | 1,049 | python | en | code | 1 | github-code | 1 |
13361493796 | import pickle
import sys
from DataLoader import DataLoader
if __name__ == '__main__':
if len(sys.argv) == 1:
filename = 'trained_model.sav'
testcsv = "test.csv"
else:
filename=sys.argv[1]
testcsv = sys.argv[2]
dataloader =DataLoader()
xTest = dataloader.loa... | Yuval938/convolution-network-from-scratch | trained.py | trained.py | py | 424 | python | en | code | 0 | github-code | 1 |
72269310114 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import re
regex = re.compile(r'([A-Za-zĘÓŁŚĄŻŹĆŃęółśążźćń0-9–])[A-Za-zĘÓŁŚĄŻŹĆŃęółśążźćń0-9–]*')
#znak jest za znakiem
regex_bad_interpuction_1 = re.compile(r'([A-Za-zĘÓŁŚĄŻŹĆŃęółśążźćń0-9–\?\!\.,;])([\(\‘\“\"])')
#po znaku jest spacja
regex_bad_interpuction_2 = re... | Deinonzch/Visual_Novel_Translator | Script/correct_output.py | correct_output.py | py | 2,121 | python | en | code | 0 | github-code | 1 |
25142555924 | #1
import pygame
from pygame.locals import *
#2
pygame.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
keys = [False, False, False, False]
playerpos = [100,100]
acc = [0,0]
boomerangs = []
#3
player = pygame.image.load("dude.png")
player = pygame.transform.scale(player, (1... | thomakj/tools | hobby/games/Hello Bunny/game.py | game.py | py | 1,362 | python | en | code | 0 | github-code | 1 |
26237514951 | from uuid import uuid4
import pytest
from synthetic.conf import EngagementConfig, PopulationConfig, ProfileConfig, global_conf
from synthetic.event.constants import EventType
from synthetic.utils.current_time_utils import get_current_time
from synthetic.database.schemas import SyntheticUserSchema
from synthetic.user.... | benshi-ai/open-synthetic-data-generator | tests/test_synthetic_user/test_db.py | test_db.py | py | 1,953 | python | en | code | 0 | github-code | 1 |
41403385342 |
class Node:
def __init__(self, item, rank=0):
"""
initializer of <class 'Node'>
:param item: denotation of a node.
:param rank: rank of a node.
"""
self.item = item
self.rank = rank
def __str__(self):
"""
overload of build-in function '... | aszx826477/Distributed-MST-pyspark | DisjointSet.py | DisjointSet.py | py | 2,987 | python | en | code | 4 | github-code | 1 |
30340835666 | from PyQt5 import uic
from PyQt5 import QtGui, QtCore
from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication, QTextEdit, QApplication, QDialog
def p(x):
print (x)
class callScript(QDialog):
#def __init__(self):
# super().__init__()
def setupCB(self, akvoData, kernelParams, SaveStr... | LemmaSoftware/akvo | akvo/gui/callScript.py | callScript.py | py | 2,344 | python | en | code | 2 | github-code | 1 |
9492227464 | import os
import cv2
import numpy as np
from PyQt5 import QtCore, QtGui, QtWidgets # uic
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton, QWidget,
QLabel, QVBoxLayout) # +++
from ui import Ui_Form # +++
... | selim1763/python_record_video | record_video.py | record_video.py | py | 3,051 | python | en | code | 0 | github-code | 1 |
2832233832 | import math
#Request imput from user
choose=input("Choose either 'investment' or 'bond' from the menu below to proceed:\n \ninvestment - to calculate the amount of interest you'll learn on your investment\nbond - the amount you'll have to pay on a home loan \n").lower()
#If user choose investment,ask us... | Gaetanolopez/finance_calculator.py | finance_calculators.py | finance_calculators.py | py | 1,687 | python | en | code | 0 | github-code | 1 |
70755614754 | import unittest2
import os
import top
class TestStopParser(unittest2.TestCase):
@classmethod
def setUpClass(cls):
cls._sp = top.StopParser()
test_dir = os.path.join('top', 'tests', 'files')
test_file = 'TCD_Deliveries_20140207111019.DAT'
cls._test_file = os.path.join(test_dir... | loum/top | top/tests/test_stopparser.py | test_stopparser.py | py | 3,059 | python | en | code | 0 | github-code | 1 |
9509034408 | from flask import request, make_response, jsonify
import hashlib
from bson import json_util
from bson.objectid import ObjectId
import os
from werkzeug.utils import secure_filename
import base64
from utils.config import app, userCollection, postCollection,imgCounterCollection
from utils.response import make_response, ... | DoniyorI/FILO | utils/post.py | post.py | py | 3,159 | python | en | code | 0 | github-code | 1 |
41403616679 | #========================================================
# SiteDescription.py
#========================================================
# PublicPermissions: True
#========================================================
# SiteDescription class to parse standard format XML
# file and create a matching Python representa... | jodysankey/pythonpath | src/sitemgt/sitedescription.py | sitedescription.py | py | 5,890 | python | en | code | 0 | github-code | 1 |
12762645895 | import math
import pygame
from debug import debug
from svg.path import parse_path
from settings import TILE_SIZE
from supports import import_folder
from audio import audio_manager
class Player(pygame.sprite.Sprite):
def __init__(self, pos, groups, obstacle_sprites, camera) -> None:
super().__init__(group... | Instelce/FastRoute | player.py | player.py | py | 9,344 | python | en | code | 0 | github-code | 1 |
17398366029 | #
def city_country(city='minsk', country='belarus'):
city_name = city + ', ' + country
return city_name.title()
c_name = city_country()
city_countrys = city_country('moscow', 'russia')
fist_city = city_country('warsaw', 'poland')
print(c_name + "\n" + city_countrys + "\n" + fist_city)
def city_0country(city... | pavel-malin/python_work | city_country.py | city_country.py | py | 789 | python | en | code | 1 | github-code | 1 |
7080163471 | from airflow import DAG
from databox import Client
from google.cloud import storage
from gcsfs import GCSFileSystem
import pandas as pd
import logging as log
import pendulum
import requests
from airflow.operators.python import PythonOperator
from airflow.operators.dummy import DummyOperator
from airflow.models import V... | adriennejohnson719/CS_280_Data_Workflow_Project | ETL.py | ETL.py | py | 9,938 | python | en | code | 0 | github-code | 1 |
29779728564 | n=input("input language")
file=open("text.txt",encoding="utf-8")
s=file.readlines()
if n=="hy":
print(s[0])
elif n=="ru":
print(s[1])
elif n=="en":
print(s[2])
else :
print("please input correct language") | narekfrnjyan/homework | homework.py | homework.py | py | 221 | python | en | code | 0 | github-code | 1 |
23655343690 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# History analizer
#
# This is the main file for this module, where the test cases should be
# developed and where the functions called by the API must be located.
# It depends on several other files, mainly:
#
# fetcher.py - Uses the browser_history library to actual... | Shit-bucket/Morpheos | backend/modules/history/__init__.py | __init__.py | py | 1,031 | python | en | code | 1 | github-code | 1 |
16794116797 | """
ndi_sensor.py
This module contains the NDIsensor class, which provides a simple API for interacting with NDI sensors.
Author: Jaspor Jiang
Email: sjiang44@jh.edu
Date: 2023-05-05
"""
import crtk
class NDIsensor(object):
"""Simple sensor API wrapping around ROS messages
"""
# initialize the sensor
... | heyunwang1/dvrk-continuum | dvrk_rcm_estimation/ndi_sensor.py | ndi_sensor.py | py | 1,240 | python | en | code | 0 | github-code | 1 |
25459941035 | import logging
import subprocess
from telemetry.core import exceptions
from telemetry.internal.platform import android_platform_backend as \
android_platform_backend_module
from telemetry.core import util
from telemetry.internal.backends import android_command_line_backend
from telemetry.internal.backends import bro... | hanpfei/chromium-net | third_party/catapult/telemetry/telemetry/internal/backends/chrome/android_browser_backend.py | android_browser_backend.py | py | 8,590 | python | en | code | 289 | github-code | 1 |
38151484604 | # Strings Problem
# https://www.hackerrank.com/challenges/alternating-characters/problem
def alternatingCharacters(s):
s = list(s)
i = 0
count = 0
while i < len(s) - 1:
if s[i] == s[i + 1]:
del (s[i])
count += 1
else:
i += 1
return count
q = int... | JShilpa/HackerRank-PySolutions | Algorithms/Alternating Characters/solution.py | solution.py | py | 438 | python | en | code | 7 | github-code | 1 |
28027131695 | '''
Implementing queue using linked list
Operations on Queue:
Mainly the following four basic operations are performed on queue:
Enqueue(): Adds an item to the queue. If the queue is full, then it is said to be an Overflow condition.
Dequeue(): Removes an item from the queue. The items are popped in the same order in... | Aman0Analyst/data_structures_python | Queue/Queue..py | Queue..py | py | 2,808 | python | en | code | 0 | github-code | 1 |
26219588881 | import torch.nn as nn
import torch
import math
import argparse
from tqdm import tqdm
# This enables the inbuilt cudnn auto-tuner to find the best algorithm to use for your hardware, e.g., wingrad conv op
torch.backends.cudnn.benchmark = True
NAME = 'dcgan'
batch_size = 1
latent_dim = 100
img_size = 256
channels = 3
#... | mikepapadim/collage-non-tvm-fork | python/collage/workloads/baselines/pytorch/dcgan.py | dcgan.py | py | 9,512 | python | en | code | 1 | github-code | 1 |
42281958081 | """A wonderful, simple database app
by Georgina Paál"""
import common
import query
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def main_page():
""" Lists all functions on the main page"""
return render_template('main_page.html')
@app.route('/men... | ginapaal/basic_sql_si_week | main.py | main.py | py | 2,165 | python | en | code | 0 | github-code | 1 |
6584305006 | import copy # To duplicate materials.
from PyQt6.QtCore import pyqtSignal, pyqtSlot, QObject, QUrl
from PyQt6.QtGui import QDesktopServices
from typing import Any, Dict, Optional, TYPE_CHECKING
import uuid # To generate new GUIDs for new materials.
from UM.Message import Message
from UM.i18n import i18nCatalog
from ... | Ultimaker/Cura | cura/Machines/Models/MaterialManagementModel.py | MaterialManagementModel.py | py | 14,258 | python | en | code | 5,387 | github-code | 1 |
31979524390 | from django.views import View
from django.http import JsonResponse, HttpResponseForbidden
from django.shortcuts import get_object_or_404
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
import json
from api.settings import ALLOWED_TOKENS
from . import models
from... | arklual/api | marks/views.py | views.py | py | 1,640 | python | en | code | 0 | github-code | 1 |
26674788073 | """
Place to keep data persistence between requests
"""
import os
import json
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
class Datastore:
STORAGE = os.path.join(BASE_DIR, 'storage.txt')
def load(self):
try:
handle = open(self.STORAGE, 'r')
except IOError:
r... | albertyw/indoor-localization | server/datastore.py | datastore.py | py | 545 | python | en | code | 24 | github-code | 1 |
6034089894 | from typing import List
"""
Summary: Single pass, comparing current interval with the previous one. If
overlap - increment the counter. Depending on the overlap type (case 2 vs 3),
the prev interval is either updated or not.
Possible cases:
1. Don't overlap
-----
------
2. Overlap 1
-----
-... | EvgeniiTitov/coding-practice | coding_practice/sample_problems/leet_code/medium/435_non_overlapping_intervals.py | 435_non_overlapping_intervals.py | py | 2,012 | python | en | code | 1 | github-code | 1 |
16692477655 | class Solution:
def checkIfPrerequisite(
self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]
) -> List[bool]:
@cache
def dfs(a, b):
if b in g[a] or a == b:
return True
for c in g[a]:
if dfs(c, b):
... | QinHongZhe/hongzhe-leetcode | solution/1400-1499/1462.Course Schedule IV/Solution.py | Solution.py | py | 506 | python | en | code | 1 | github-code | 1 |
23253320504 | from uuid import uuid4
from sqlalchemy.orm import Session
from models.model import Student, Course
from schemas.student import CreateStudent
from bcrypt import hashpw, gensalt
def get_students(session: Session):
query = session.query(Student).all()
return query
def get_student_by_id(_id: str, session: Sessi... | samvalvi/school-admin-api | repository/student.py | student.py | py | 1,805 | python | en | code | 1 | github-code | 1 |
990635797 | import random
#Trainer class
class Trainer:
def __init__(self,name,pokemon,healingitems,reward):
self.name = name
self.pokemon = pokemon
self.healingitems = healingitems
self.reward = reward
def trainerturn(self,player):
if self.pokemon.temphealth < .33*self.... | ljwenger99/Pokemon-P | Pokemon P/Trainer.py | Trainer.py | py | 708 | python | en | code | 0 | github-code | 1 |
29457232613 | import json
import os
from botocore.vendored import requests
# PCE API request call using requests module
def pce_request(pce, org_id, key, secret, verb, path, params=None,
data=None, json=None, extra_headers=None):
base_url = os.path.join(pce, 'orgs', org_id)
print(base_url)
headers = {
... | illumiolabs/illumio-security-hub-connector | security-hub-quarantine-action/src/lambda_function.py | lambda_function.py | py | 4,164 | python | en | code | 4 | github-code | 1 |
32247087925 | DESCRIPTION = "shows the current module options"
def autocomplete(shell, line, text, state):
return None
def help(shell):
shell.print_plain("")
shell.print_plain("Use %s for advanced options" % (shell.colors.colorize("info -a", shell.colors.BOLD)))
shell.print_plain("")
def execute(shell, cmd):
e... | offsecginger/koadic | core/commands/info.py | info.py | py | 1,328 | python | en | code | 216 | github-code | 1 |
38164794895 | from django.conf.urls import patterns, url
from notes import views
urlpatterns = patterns('',
url(r'^$', views.all_notes, name='all_notes'),
url(r'^resolved', views.resolved_notes, name='resolved_notes'),
url(r'^(?P<note_id>\d+)/$', views.note_detail, name='note_detail'),
url(r'^(?P<note_id>\d+)/edit/... | nicmatts/3DP | threedp/notes/urls.py | urls.py | py | 629 | python | en | code | 0 | github-code | 1 |
42176940574 | """
Question:
Given a binary tree, write a function to get the maximum width of the given tree.
Width of a tree is maximum of widths of all levels.
For example:
__1__
/ \
2 3
/ \ \
4 5 8
/ \
6 7
For the above tree,
width of level 1 is 1.
width of level 2 is 2.
... | viniciuschiele/solvedit | btree/find_max_width.py | find_max_width.py | py | 1,278 | python | en | code | 0 | github-code | 1 |
72409327714 | def parser():
while 1:
data = list(input().split(" "))
for number in data:
if len(number) > 0:
yield (number)
input_parser = parser()
def get_word():
global input_parser
return next(input_parser)
def get_number():
data = get_word()
try:
retur... | HliasOuzounis/xtreme | Candy Shop/candy_shop_recursive (.py | candy_shop_recursive (.py | py | 884 | python | en | code | 1 | github-code | 1 |
11494310897 | import inspect
import os
import numpy as np
import pickle
import regex
import tensorflow as tf
from tensorflow import keras
from transformers import BertConfig, TFBertMainLayer
from .utils import found_package
import transformers
import tensorflow_addons as tfa
from .utils import iobes_iob, parse_lr_method
from .con... | CederGroupHub/MatEntityRecognition | materials_entity_recognition/scripts/model_framework.py | model_framework.py | py | 34,451 | python | en | code | 1 | github-code | 1 |
5152990982 | #!/usr/bin/python
import math
import numpy as np
import rospy as rp
from geometry_msgs.msg import Twist
class VelocityController:
def __init__(self):
#controller gain
self.kp = 1.2
self.goal_angle = 0.0
self.current_yaw = 0.0
self.vel_pub = rp.Publisher('/cmd_vel'... | srperry96/turtlebot_testing | turn_north/src/velocity_controller.py | velocity_controller.py | py | 2,207 | python | en | code | 0 | github-code | 1 |
9351150330 | from workers.serializers import *
from workers.models import *
from projects.models import *
from rest_framework import viewsets, permissions, status
from rest_framework.response import Response
from rest_framework.views import APIView
from django.db.models import Q
from django.db.models import Prefetch
import datetime... | Nikola-code/Portfolio | BonaAkademia/projekt-main/app/workers/views.py | views.py | py | 11,140 | python | en | code | 0 | github-code | 1 |
19774300465 | class Solution:
# 1-D Dynamic Programming - Bottom-Up Approach
# T: O(m*n), M: O(n), where m is num of rows, n is num of cols
def uniquePaths(self, m: int, n: int) -> int:
prev_row = [0] * n # Solve last row base case
for row in range(m-1, -1, -1):
curr_row = [0] * n
... | Reddimus/LeetCode_Notes | 2-D_Dynamic_Programming/Medium/LC_62-Unique_Paths/LC_62-Unique_Paths.py | LC_62-Unique_Paths.py | py | 1,531 | python | en | code | 0 | github-code | 1 |
73471784993 | # F06 - Mengubah stok game
def update_stok(role,hasil):
if role == 'Admin':
id_game = input('Masukkan ID game: ')
jumlah = int(input('Masukkan jumlah: '))
for line in hasil:
if id_game == line[0]:
if (line[5] + jumlah) >= 0:
... | IvanLeovandi/Tugas-Besar-IF1210-Dasar-Pemrograman-2021-2022 | Source Code/fungsi tubes.py | fungsi tubes.py | py | 3,311 | python | id | code | 3 | github-code | 1 |
16057035198 | import numpy as np
class User:
def __init__(self, select_num, itemProb):
self.L = select_num
self.K = len(itemProb)
self.itemProb = itemProb
#for each items, user makes clicked or unclicked with itemProb
def react(self, items, itemProb_idx):
assert len(items) == self.L
... | Weaasel/MAB_Offline_Test | user.py | user.py | py | 587 | python | en | code | 1 | github-code | 1 |
74538549792 | import json
import os
import pathlib
from tempfile import TemporaryDirectory
from typing import Any, Dict
from jsonschema import ValidationError
from pep440 import is_canonical
from nbformat import __version__ as nbf_version
from nbformat import current_nbformat, read, write, writes
from nbformat.reader import get_ve... | jupyter/nbformat | tests/test_api.py | test_api.py | py | 3,517 | python | en | code | 226 | github-code | 1 |
5303899982 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head):
try:
fast = head.next.next
slow = head.next
while fast != slow:
fast ... | yutohub/leetcode | leetcode/0142_Linked_List_Cycle_II/0142_Linked_List_Cycle_II.py | 0142_Linked_List_Cycle_II.py | py | 630 | python | en | code | 0 | github-code | 1 |
74719824672 | from django.shortcuts import render,redirect
from .forms import *
from .models import *
from django.contrib.auth.decorators import login_required
def gestionarPersonas(request):
if request.method == 'POST':
persona_form = PersonaForm(request.POST)
if persona_form.is_valid():
persona_for... | EvelinSenghaas/Contratos | project/personas/views.py | views.py | py | 2,726 | python | en | code | 0 | github-code | 1 |
2566857256 | # Jan Faryad
# 3. 7. 2017
#
# extracting information about coreference from onf file
class Onto_coreference_getter:
def __init__( self, onto_input):
""" onto input ... onf file """
self.onto_input = onto_input
def process_file( self):
"""
main method, calle from out... | Jankus1994/Coreference | Coreference/OntoNotes/onto_coreference_getter.py | onto_coreference_getter.py | py | 2,953 | python | en | code | 0 | github-code | 1 |
2408123049 | import numpy as np
import pytest
from numpy import testing as np_testing
import pymanopt
from . import _backend_tests
class TestNumPyBackend:
@pytest.fixture(autouse=True)
def setup(self):
self.n = 10
@pymanopt.function.numpy(
_backend_tests.manifold_factory(point_layout=3)
... | pymanopt/pymanopt | tests/backends/test_numpy.py | test_numpy.py | py | 1,347 | python | en | code | 651 | github-code | 1 |
43020131914 | #!/usr/bin/python
import config_default
class Dict(dict):
def __init__(self,name=(),value=(),**kw):
super(Dict,self).__init__(**kw)
for k,v in zip(name,value):
self[k]=v
def __getattr__(self,key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute ... | lilululu/python | www/config.py | config.py | py | 1,034 | python | en | code | 0 | github-code | 1 |
38981554044 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
import re
import random
import collections
from scipy import stats
import jieba
import jieba.posseg as pseg
import wordcloud
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import Trun... | restart2013/biliTechVideo | analyse.py | analyse.py | py | 12,912 | python | en | code | 2 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.