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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
25344510269 | from __future__ import print_function
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
torch.backends.cudnn.bencmark = True
import os,sys,cv2,random,datetime
import argparse
import numpy as np
from dataset import ImageDataset
from matl... | clcarwin/sphereface_pytorch | train.py | train.py | py | 4,350 | python | en | code | 704 | github-code | 1 |
27508254805 | # Regex to get CiviCRM ID from parentheses in contact name
# https://stackoverflow.com/a/38999572/1191545
import logging
from django.core.exceptions import MultipleObjectsReturned
from tqdm import tqdm
from contact.models import (
Meeting,
MeetingAddress,
MeetingWorshipTime,
Organization,
)
from cont... | WesternFriend/WF-website | content_migration/management/import_civicrm_contacts_handler.py | import_civicrm_contacts_handler.py | py | 7,892 | python | en | code | 46 | github-code | 1 |
16845084048 | #!/usr/bin/env/python3
import logging
import argparse
import time
import queue
import json
from datetime import datetime
from cellscan.panel import PanelThread
from cellscan.radio import RadioThread
from cellscan.gnss import GnssThread
from cellscan.data import saveCellSite, db, Cellsite, Location
from cellscan.uploa... | jcrawfordor/cellscan | cellscan/start.py | start.py | py | 4,801 | python | en | code | 25 | github-code | 1 |
8530391067 | print('-'*30)
print(' CADASTRE UMA PESSOA')
print('-'*30)
tot18 = toth = totmulher20 = 0
while True:
idade = int(input('Idade: '))
sexo = ' '
while sexo not in 'MF':
sexo = str(input('Sexo: [M/F] ')).strip().upper()
print('-'*25)
if idade >= 18:
tot18 += 1
if sexo in 'M':
... | jabes-christian/Curso-Python | Python-Exercícios&Aulas/Ex069 - Analise e Dados do Grupo.py | Ex069 - Analise e Dados do Grupo.py | py | 704 | python | pt | code | 0 | github-code | 1 |
5966845104 | def is_perfect(num):
num = int(num)
dividers = []
for divider in range(1, num//2+1):
if num % divider == 0:
dividers.append(divider)
if sum(dividers) == num:
return True
number = input()
if is_perfect(number):
print("We have a perfect number!")
else:
print("It's no... | LachezarKostov/SoftUni | 01_Python-Basics/functions/Perfect Number.py | Perfect Number.py | py | 338 | python | en | code | 1 | github-code | 1 |
11460182872 | class Stack:
def __init__(self):
self.stack = []
def push(self, num):
self.stack.append(num)
def pop(self):
return self.stack.pop()
stack1 = Stack()
n = int(input())
idx = 0
numbers = list(range(1,n+1))
seq = []
for i in range(n):
num = int(input())
seq.append(num)
for i i... | A-by-alimelon/PB_python3 | 1874.py | 1874.py | py | 636 | python | en | code | 0 | github-code | 1 |
25037492498 | from fastapi import FastAPI, APIRouter, Depends, HTTPException, Request, Response, Header
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from ..db import profile_crud, anime_crud, users_crud, auth_crud, s3_crud, anilist_crud
from ..schemas.profile_schema import Profile, UserAnimesPost, UserA... | konn1ehuang/Backend | app/routers/anilist.py | anilist.py | py | 3,131 | python | en | code | null | github-code | 1 |
35636630591 | #!/usr/bin/env python
# coding: utf-8
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix, f1_score
pd.options.display.max_columns = None
import warnings
warnings.filterwarnings('ignore')
# Read the CSVs
data... | rajrdas/tcd-group-competition-team70--rec-alg-click-pred | RecClickPred-d1.py | RecClickPred-d1.py | py | 7,983 | python | en | code | 0 | github-code | 1 |
25014218796 | import tkinter as tk
from tkinter import ttk
from datetime import datetime, timedelta
from woocommerce import API
from customtkinter import *
# WooCommerce API credentials
url = "https://bedrock-computers.co.uk/"
consumer_key = "ck_e63f2847761567231436732f8c753e392fd81614"
consumer_secret = "cs_d40131313ebeeb4e1bd8b8fb... | BenedictCallander/Bedrock_Inventory | order.py | order.py | py | 3,024 | python | en | code | 0 | github-code | 1 |
71097951074 | from django.conf import settings
from django.template.loader import render_to_string
def google_analytics(request):
"""
Returns analytics code.
"""
if settings.GA_TRACKING_ID:
return {
"google_analytics": render_to_string(
"ga.html", {"GA_TRACKING_ID": settings.GA_T... | iodide-project/iodide | server/context_processors.py | context_processors.py | py | 512 | python | en | code | 1,482 | github-code | 1 |
9795231579 | #定制曲线颜色
#使用plot函数中的color关键字参数
import numpy
import matplotlib.pyplot as plt
#将-6到6分成1024份,形成1024个值
X=numpy.linspace(-6,6,1024)
#定义曲线的颜色集合,所有的颜色都从这个列表中选取
colors=['red','yellow','b','c','#FF00FF','0.75']
#绘制20条一元二次曲线,并从colors中依次取颜色值
for i in range(20):
plt.plot(X,-X**2 + (i+1)*2,color=colors[i % len(colors)]... | 081327/python-matplotlib | li24.7.py | li24.7.py | py | 503 | python | zh | code | 0 | github-code | 1 |
74736809314 | import pytest
from boxsdk.exception import BoxOAuthException
def test_expired_access_token_is_refreshed(box_oauth, box_client, mock_box):
# pylint:disable=protected-access
mock_box.oauth.expire_token(box_oauth._access_token)
# pylint:enable=protected-access
box_client.folder('0').get()
assert len(... | box/box-python-sdk | test/functional/test_token_refresh.py | test_token_refresh.py | py | 767 | python | en | code | 395 | github-code | 1 |
71989646113 | from typing import TYPE_CHECKING
from urllib.parse import quote, urlencode
from osp.core.namespaces import emmo
from osp.models.catalytic.utils import make_arcp
if TYPE_CHECKING:
from typing import List, Union
from osp.core.cuds import Cuds
from osp.core.ontology import OntologyClass
def _make_internal... | simphony/simphony-catalytic | osp/wrappers/simcatalyticfoam/utils.py | utils.py | py | 3,425 | python | en | code | 0 | github-code | 1 |
37319513334 | import turtle
import math
seq = "A"
def get_new_seq(seq):
newseq = ""
for i in seq:
if(i == "A"):
newseq += "ABCD"
elif(i == "B"):
newseq += "BBCD"
elif(i == "C"):
newseq += "CBCD"
elif(i == "D"):
newseq += "DBCD"
return newse... | Skoppek/Fractals-Turtle | KochSnowFlake.py | KochSnowFlake.py | py | 1,615 | python | en | code | 0 | github-code | 1 |
4848671373 | #!/usr/bin/env python3
import argparse
import os
import sys
import tempfile
import uuid
import tator
from .extractor import process_file
if __name__ == "__main__":
""" CLI Frontend to extractor """
parser = argparse.ArgumentParser(description="Thumbnail Extractor")
tator.get_parser(parser)
parser.a... | cvisionai/tator-py | tator/extractor/__main__.py | __main__.py | py | 3,621 | python | en | code | 4 | github-code | 1 |
32903246276 | """
This module contains the class that encapsulates the conversation history and context
"""
import traceback
import re
from .openaicli import OpenAICli
from .prompt import Prompt
from .pineconecli import PineconeCli
from .tools import Tools
class Conversation:
"""
This class is used to encapsulate the conve... | mazharm/openaichatbot | server/conversation.py | conversation.py | py | 5,580 | python | en | code | 0 | github-code | 1 |
353415061 | #-*- coding:utf-8 -*-
import argparse
import os
import process_file
def main():
parser = argparse.ArgumentParser(description='데이터 검증')
parser.add_argument('--project', type=str, required=True,
help='프로젝트명')
parser.add_argument('--datadir', type=str, required=True,
... | acho98/Validator | check.py | check.py | py | 1,024 | python | en | code | 1 | github-code | 1 |
32482842311 | #!/usr/bin/env python
# Martin Kersner, m.kersner@gmail.com
# 2016/01/18
from __future__ import print_function
import os
import sys
import lmdb
from random import shuffle
from skimage.io import imread
from scipy.misc import imresize
import numpy as np
from PIL import Image
import caffe
from utils import get_id_classes... | MasazI/crfasrnn-training | data2lmdb.py | data2lmdb.py | py | 5,632 | python | en | code | 16 | github-code | 1 |
30951637732 | #/usr/bin/python
# An electronic piggy bank that sorts and securely stores your coins.
# It uses a Raspberry Pi, an Arduino, a Coin Acceptor, the Adafruit LCD Shield,
# and 3 LEGO Mindstorms motors connected to an NXT.
# Both the NXT and Arduino are connected to a USB hub connected to the Raspberry Pi
# Adafruit's... | alexstrandberg/Raspberry-Pi-Piggy-Bank-with-Coin-Sorter | main.py | main.py | py | 15,106 | python | en | code | 13 | github-code | 1 |
21771337536 | import mblib
import itertools
def main():
num = ["1","2","3","4","5","6","7"]
for x in list(itertools.permutations(num, len(num)))[::-1]:
print(f"Checking: {x}")
if mblib.isPrime(int("".join(x))):
res = int("".join(x))
resdigit = len(x)
break
pri... | Gamesbydo/PE_python | problem41.py | problem41.py | py | 412 | python | en | code | 0 | github-code | 1 |
35885764850 | # Написати валідації за допомогою регулярних виразів:
# - Мобільний номер телефону (тільки цифри, можлива наявність плюса, довжина номера)
# - домашній номер телефону (тільки цифри та довжина номера)
# - email (наявність @, домену: gmail.com наприклад, мінімальна довжина та максимальна на ваш вибір)
# - ПІБ клієнта (3 ... | TooManyTurtles/Homework_10 | main.py | main.py | py | 2,677 | python | uk | code | 0 | github-code | 1 |
37688974065 | # from cgitb import text
import types
from aiogram.types import ReplyKeyboardMarkup,KeyboardButton
from aiohttp import request
# from sqlalchemy import true
# from telegram import Contact
startbut = ReplyKeyboardMarkup(
keyboard=[
[
KeyboardButton(text = "Buyurtma berish"),
],
[
... | onlysharifjon/O_N_L_Y_bot | keyboards/default/startkey.py | startkey.py | py | 435 | python | en | code | 7 | github-code | 1 |
38124692196 | from django.db.models.signals import post_save
from django.dispatch import receiver
import csv
from student.admin import lopTinChiDetailAdmin
from users.models import Student
from management.models import vien_dao_tao, lop_chung
from .models import csvStudent, sinhVien_dangKi_lopTinChi, sinhVien_lopTinChiDetail
@recei... | tannguyen1100/Project_KTPMUD | student/signals.py | signals.py | py | 1,620 | python | en | code | 0 | github-code | 1 |
70198769954 | import numpy as np
import networkx as nx
from networkx import Graph
import matplotlib.pyplot as plt
from calculations import *
from plotting import *
import os
from itertools import product
# 3-regular graphs
G_3reg0 = Graph()
G_3reg1 = Graph()
G_3reg2 = Graph()
G_3reg0.add_edges_from([(0,2), (1,2), (2,3), (3,4), (... | obstjn/ws-qaoa-transfer | scripts/plot_0-1_edge.py | plot_0-1_edge.py | py | 1,098 | python | en | code | 0 | github-code | 1 |
2406363964 | '''
def fib1(num):
a=0
b=1
for i in range(num):
yield a
temp=a
a=b
b=temp+a
for i in fib1(10):
print(i)
'''
def fib2(n):
a=0
b=1
result=[]
for i in range(n):
result.append(a)
temp=a
a=b
b=temp+b
return result
... | shahadatcs/python-learning-steps | Advanced Python Generators/exercise_generator.py | exercise_generator.py | py | 336 | python | en | code | 1 | github-code | 1 |
32937855897 | import urllib2
from malparser.anime import Anime
from malparser.manga import Manga
HEADERS = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en",
"User-Agent": "Scrapy/0.24.2 (+http://scrapy.org)",
}
class MAL(object):
def _fetch(self, obj):
... | JohnDoee/web-parsers | myanimelist/malparser/mal.py | mal.py | py | 818 | python | en | code | 1 | github-code | 1 |
72894744993 | # Python script for additional style validation
# Author: Rintze M. Zelle
# Version: 2011-12-17
# * Requires lxml library (http://lxml.de/)
#
# Add CC by-sa license
import os, glob, re
from lxml import etree
path = 'C:\Documents and Settings\zelle\My Documents\CSL\styles\\'
verbatims = {}
for independentStyle in glo... | citation-style-language/utilities | csl-add-rights.py | csl-add-rights.py | py | 1,295 | python | en | code | 18 | github-code | 1 |
73811735393 | #from numba import njit # compile python
#import matplotlib
#matplotlib.rcParams['text.usetex'] = True
import matplotlib.pyplot as plt # plotting facility
from matplotlib.colors import Normalize, SymLogNorm
from matplotlib import cm
from matplotlib import gridspec
import numpy as np
import os, datetime, math
import tim... | dibondar/NonseparableSplitOperator | WignerPlot_221104.py | WignerPlot_221104.py | py | 14,749 | python | en | code | 0 | github-code | 1 |
42811143128 | """
이름, 주민번호 (950101-1), 주소를 입력받아서
회원명부를 관리하는 어플을 제작하고자 한다.
출력되는 결과는 다음과 같다.
### 자기소개어플 ###
********************************
이름: 홍길동
나이: 25세 (만나이)
성별: 남성
주소: 서울
********************************
"""
class Person(object):
def __init__(self, name, num, adress):
self.name = name
self.age = 0
s... | gangsanlee2/flask-program | src/uss/mpe/service/person.py | person.py | py | 1,778 | python | ko | code | 0 | github-code | 1 |
32537602552 | """
This is done watching the video 5 Mini Python Projects - For Beginners on https://www.youtube.com/watch?v=DLn3jOsNRVE
I watched the videos and after that did the project not looking the actual codes.
25:05 | Project #2 - Number Guessing Game
---
pick a random number
then ask the user to guess this number and as... | kimteapung/pythonExercisesMixedFromDiffSources | 5_Mini_Python_Projects_Tech_With_Tim/project2_number_guessing_game.py | project2_number_guessing_game.py | py | 4,367 | python | en | code | 2 | github-code | 1 |
22791740620 | # name = 'trứng rán'
# name = 'bắp'
# name = 'bơ'
# name = 'mỡ'
# name = 'mắm tôm'
# # list, array
mon_an = ['trung ran', 'bap', 'bo', 'mo', 'mam tom','bun cha']
# print(mon_an)
# name = 'sushi'
# mon_an.append(name)
# print(mon_an)
# mon_an [6] = 'banh gio'
# print(mon_an)
# # for i in range(len(mon_an)):
# # prin... | tientran269/tranthuytien-fundamental-d4e12 | session3/menu.py | menu.py | py | 807 | python | en | code | 0 | github-code | 1 |
70839110753 | from collections import deque
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]
R, C = map(int, input().split())
arr = [list(input()) for _ in range(R)]
visited = [[0] * C for _ in range(R)]
w_visited = [[0] * C for _ in range(R)]
def bfs(start, end, w):
e_x, e_y = end.pop()
x, y, cnt = start.popleft()
for i in r... | ckdfh0917/Algorithm | 기웅스터디/BFS/3055. 탈출.py | 3055. 탈출.py | py | 2,306 | python | en | code | 0 | github-code | 1 |
13944333408 | for _ in range(int(input())):
q=[]
s= input()
q.append('(')
if s[0]!='(':
print('NO')
continue
flag=True
for el in s[1:]:
if el=='(':
q.append('(')
else:
if not q:
flag= False
break
... | Taein2/PythonAlgorithmStudyWithBOJ | Minjae/2021-02-08/9012_Parenthes.py | 9012_Parenthes.py | py | 405 | python | en | code | 1 | github-code | 1 |
16052209240 | from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
storing = requests.get('https://zenquotes.io/api/random')
json_storing = storing.json()
quote = json_storing[0]
return render_template('podo.html', quote=quote)
if __name__ == '__main__':
app.run(debug=Tr... | haileylwb/TeamEdge-Final-Project | app.py | app.py | py | 341 | python | en | code | 0 | github-code | 1 |
71108406113 | def search(arr, x, temp, now):
global candi, visited
if x == N-1:
candi.append(temp + arr[now][0])
else:
for i in range(1, N):
if not visited[i]:
visited[i] = 1
search(arr, x+1, temp + arr[now][i], i)
visited[i] = 0
for T in range(... | bcking92/TIL | 01_Algorithm/Week13/SWEA_5189_전자카트.py | SWEA_5189_전자카트.py | py | 526 | python | en | code | 0 | github-code | 1 |
36327419981 | """
This module takes care of starting the API Server, Loading the DB and Adding the endpoints
"""
from flask import Flask, request, jsonify, url_for, Blueprint
from api.models import db
from api.utils import generate_sitemap
import random
#from models import Person
api = Blueprint('api', __name__)
@api.route('/card... | gmihov001/Random-card-dealer-JS-Flask | src/api/routes.py | routes.py | py | 722 | python | en | code | 0 | github-code | 1 |
18621936653 | import unittest
from outpost24hiabclient.entities.scanner import Scanner
from outpost24hiabclient.clients.hiabclient import HiabClient
from outpost24hiabclient import ScannerService
from unittest.mock import patch
import xml.etree.ElementTree as ET
class HiabClientTest:
def get_scanners(self):
... | schubergphilis/outpost24hiabclient | tests/test_scanner_service.py | test_scanner_service.py | py | 3,750 | python | en | code | 2 | github-code | 1 |
13343320060 | from tqdm import tqdm
import jittor as jt
from jittor import optim
from jittor.lr_scheduler import MultiStepLR
import argparse
import random
import sys
import glob
import pickle
import os
import numpy as np
from tensorboardX import SummaryWriter
from dataset.dota import DOTA
from dataset.transforms import train_transfo... | li-xl/SCRDet.jittor | train.py | train.py | py | 7,503 | python | en | code | 1 | github-code | 1 |
19907396281 | from datetime import datetime
from flask import Flask, render_template, url_for, flash, redirect, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'bf2a0fbecd7030220d754389dcbd5ij9'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://ipnx:root.Account#20@ipNX@... | Greyacey/SiteList | site/flaskapp.py | flaskapp.py | py | 2,125 | python | en | code | 0 | github-code | 1 |
43016664506 | import mysql.connector
import tkinter as tk
from tkinter import ttk
from style import *
from util import *
from tkinter import messagebox as mb
from datetime import datetime, timedelta
class MenuTampilPesanan(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.con... | alliefn/sistem-tracking-covid19 | src/pesanan.py | pesanan.py | py | 18,480 | python | en | code | 0 | github-code | 1 |
22501226002 | #!/usr/bin/env python3
"""LRU.py - algorytm LRU"""
import ramka
from os import strerror
print("\nAlgorytm LRU\n")
try:
odwolania=open("odwolania.txt","r")
except Exception as exc:
print("Błąd: ",strerror(exc.errno))
ciag_odwolan=odwolania.readline().split()
try:
odwolania.close()
except Exception as ex... | Sivinho/Paging-and-scheduling-algorithms | LRU.py | LRU.py | py | 1,922 | python | pl | code | 0 | github-code | 1 |
12095875596 | from __future__ import absolute_import
import rules
from rotations.models import Rotation, RotationRequest, RotationRequestResponse, RotationRequestForward
@rules.predicate
def is_owner(user, object):
"""
Check if the user owns the passed object, which may be one of: Rotation, RotationRequest,
RotationR... | msarabi95/easy-internship | rotations/rules.py | rules.py | py | 807 | python | en | code | 1 | github-code | 1 |
35915365701 | # Python > Itertools > itertools.product()
# Find the cartesian product of 2 sets.
#
# https://www.hackerrank.com/challenges/itertools-product/problem
#
from itertools import product
A = list(map(int, input().split()))
B = list(map(int, input().split()))
P = list(product(A, B))
print(" ".join(str(x) for x in P))... | rene-d/hackerrank | python/py-itertools/itertools-product.py | itertools-product.py | py | 321 | python | en | code | 72 | github-code | 1 |
19368667201 | import json
import os
import re
from sieglib.bdt import Bdt
from sieglib.bhd import Bhd, BhdHeader, BhdRecord, BhdDataEntry
from sieglib.dcx import Dcx
from sieglib.log import LOG
from pyshgck.time import time_it
class ExternalArchive(object):
""" Combination of BHD and BDT. Contains methods to export files to t... | dece/DarkSoulsDev | Programs/SiegLib/sieglib/external_archive.py | external_archive.py | py | 13,672 | python | en | code | 1 | github-code | 1 |
41978066268 | #开发人员 :Hongjian SU
#开发时间 :4/19/2019
#开发工具 :PyCharm
import datetime
a = "Ericsson"
b = "Hongjian SU"
c = input("Note: ")
c = "Note: " + c
d = datetime.datetime.now()
fp = open(r'Test_internal.txt', 'a+')
print(a, b, "\n", c, "\n", d, file=fp)
print(chr(38))
fp.close()
'''
就是
添加点
备注
'''
| SUHONGJIAN/leisure-time | Python learning/Pycharm_project/Third.py | Third.py | py | 339 | python | en | code | 0 | github-code | 1 |
38958993008 | import logging
from cliff import command
from smiley import db
from smiley import db_linecache
from smiley import output
class Replay(command.Command):
"""Query the database and replay a previously captured run.
"""
log = logging.getLogger(__name__)
_cwd = None
def get_parser(self, prog_name... | smiley-debugger/smiley | smiley/commands/replay.py | replay.py | py | 1,820 | python | en | code | 391 | github-code | 1 |
27891458937 | rating = [8, 8, 7, 5, 5, 5, 4, 2, 1, 1, 1, 1]
print("Существующий рейтинг: ", rating)
elem = input("Введите новое значение: ")
while elem:
if rating.count(int(elem)) > 0:
rating.insert(rating.index(int(elem)) + rating.count(int(elem)), int(elem))
print("Новый рейтинг: ", rating)
elif rating[len... | BaturinaYu/python_lessons | 2_5.py | 2_5.py | py | 803 | python | ru | code | 0 | github-code | 1 |
28031190806 | import functools
import os.path
import sys
import delphyne.trees
import delphyne.behaviours
import delphyne.blackboard
import delphyne.maliput as maliput
import delphyne_gui.utilities
from delphyne_gui.utilities import launch_interactive_simulation
from . import helpers
############################################... | maliput/delphyne_demos | demos/city.py | city.py | py | 4,495 | python | en | code | 0 | github-code | 1 |
35688631062 | """
Unit tests for the bcl_tokenizer submodule.
"""
from bcl_tokenizer import tokenizer as tkn
def __verify_first_token(source: str, expected_type: str, expected_value: str):
"""Verify that the first token produced by the tokenized source has the expected type and value."""
tokenizer = tkn.Tokenizer(source)... | psysrc/barnacle-python | test_barnacle/test_tokenizer.py | test_tokenizer.py | py | 12,071 | python | en | code | 0 | github-code | 1 |
22390441137 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""K-means clustering with points on a 2D surface."""
import random
import math
import operator
from k_means_plot import *
from k_means_types import *
SECOND_ITEM = operator.itemgetter(1)
INVALID = -1
def dist(point_a: Point, point_b: Point) -> float:
"""Retourne... | tbagrel1/machine_learning | clustering/k_means/k_means.py | k_means.py | py | 9,660 | python | fr | code | 0 | github-code | 1 |
2006635343 | from __future__ import print_function
from kafka import KafkaConsumer
import time
from datetime import datetime
import json
import argparse
def print_log(message):
print("%s:%d:%d: key=%s value=%s" % (message.topic, message.partition,
message.offset, message.key,
... | DanThomp507/DDOS-Protector | Consumer.py | Consumer.py | py | 2,973 | python | en | code | 0 | github-code | 1 |
18709240600 | # program to find uncommon words from two Strings
# Input : A = "apple banana mango"
# B = "banana fruits mango"
# Output : ['apple', 'fruits']
print("======== dictionary + list ========")
def uncommonWords(A, B):
count = {}
for word in A.split(" "):
count[word] = count.get(word,0) + 1
... | dilipksahu/Python-Programming-Example | String Programs/uncommonWords.py | uncommonWords.py | py | 1,055 | python | en | code | 0 | github-code | 1 |
719002111 | import threading
import logging
from core import fb_interface
class FB(threading.Thread, fb_interface.FBInterface):
def __init__(self, fb_name, fb_type, fb_obj, fb_xml, monitor=None):
threading.Thread.__init__(self, name=fb_name)
fb_interface.FBInterface.__init__(self, fb_name, fb_type, fb_xml, m... | howcroft/dinasore | core/fb.py | fb.py | py | 2,333 | python | en | code | null | github-code | 1 |
3195612483 | class Solution(object):
def kSmallestPairs(self, nums1, nums2, k):
"""
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[List[int]]
"""
import heapq
res = []
seen = set()
hq = [(nums1[0] + nums2[0], 0, 0)]
... | niufenjujuexianhua/Leetcode | 373-find-k-pairs-with-smallest-sums/373-find-k-pairs-with-smallest-sums.py | 373-find-k-pairs-with-smallest-sums.py | py | 813 | python | en | code | 0 | github-code | 1 |
10805907792 | vegitables = {
"potato" : 2,
"tomato" : 3,
"onion" : 1,
"cabbage" : 0.20,
"carrot" : 2,
"brinjal" : 3,
"cauliflower" : 2,
"spinach" : 3,
"capsicum" : 4,
"cucumber" : 2,
}
meat = {
... | krasenHristov/pythonL | shop/main.py | main.py | py | 2,763 | python | en | code | 1 | github-code | 1 |
33800619515 | import csv
import json
# Open up the CSV File
with open("filename.output.csv", "r") as f:
reader = csv.reader(f)
# Ignore the headers as an individual row
next(reader)
data = []
# Iterate across the reader object
for row in reader:
# Append to the empty data list
d... | elemasamuel/Backend-Devs---show-your-skills | show_your_skills/csvToJson.py | csvToJson.py | py | 858 | python | en | code | 0 | github-code | 1 |
2773540722 | """
Zadání:
S využitím principů OOP vytvořte simulaci jednoduché hry, v níž se v zápase (Match) virtuálně utkají vždy dva hráči (Player).
Zápas tvoří symbolické souboje (výměny) na 10 vítězných bodů.
Hráč získává bod, když hodí vyšší hodnotu symbolickou kostkou než jeho protihráč.
Objekty hráčů mohou být načteny z... | OndraVicha/python-projekt | game/game.py | game.py | py | 9,311 | python | cs | code | 0 | github-code | 1 |
3243317035 | import math
import torch
import torch.nn as nn
def matrix_2d_decode(matrix, inH, inW, scale, device, add_scale=True):
matrix = matrix[0]
scale_int = int(math.ceil(scale))
h_offset = matrix[0][:inH*scale_int]
w_offset = matrix[1][:inW*scale_int]
# [outH, outW]: Every Row is the same
h_offset_m... | miracleyoo/Meta-SSSR-Pytorch-Publish | model/matrix.py | matrix.py | py | 7,881 | python | en | code | 4 | github-code | 1 |
38751583253 | print("Electricity bill estimator\n")
TARIFF_11 = 0.244618
TARIFF_31 = 0.136928
tariff = int(input("Which tariff? 11 or 31: "))
while tariff != 11 and tariff != 31:
print("Invalid choice!")
tariff = int(input("Which tariff? 11 or 31: "))
if tariff == 11:
dollar_per_kwh = TARIFF_11
else:
dollar_per_kw... | PhyuCin/CP1404PRAC | Prac_01/Extension 1.py | Extension 1.py | py | 559 | python | en | code | 0 | github-code | 1 |
43293306618 | # - 제공된 영화 제목을 검색하여 해당 영화의 출연진(`cast`) 그리고 스태프(`crew`) 중 연출진으로 구성된 목록만을 출력합니다.
# - requests 라이브러리를 활용하여 TMDB에서 영화제목으로 영화를 검색(Search Movies)합니다. # 04.py 에서 검색코드 가져옴 id 값까지 가지고 옴
# - 응답 받은 결과 중 첫번째 영화의 id 값을 활용하여 TMDB에서 해당 영화에 대한 출연진과 스태프 목록(Get Credits)을 가져옵니다.
# 1. credits 검색 & 목록 가져오기
# - 출연진 중 `cast_id` 값이 `10 미만`인 ... | yangu1455/01-PJT-02 | 2회차/황지선/05.py | 05.py | py | 3,338 | python | ko | code | null | github-code | 1 |
40133336715 | def check(w):
if w == '':
return True
stack = []
for i in w:
if i == '(':
stack.append(i)
elif i == ')':
if len(stack) == 0:
return False
if stack[-1] == ')':
stack.append(i)
else:
stack.p... | Woojung0618/algorithmSolve | Programmers/Lv2/괄호변환.py | 괄호변환.py | py | 915 | python | en | code | 0 | github-code | 1 |
19124700343 | import logging
import sys
import shutil
import click
import subprocess
import platform
import re
import os
import errno
import time
import ast
import math
from anime_downloader import session
from anime_downloader.sites import get_anime_class
from anime_downloader.const import desktop_headers
def check_in_path(app):
... | PradipH31/anime-downloader | anime_downloader/util.py | util.py | py | 6,601 | python | en | code | null | github-code | 1 |
1440817879 | import numpy as np
from openquake.hazardlib.imt import PGA, PGV
class Wald99(object):
"""
Implements the ground motion intensity conversion equations (GMICE) of
Wald et al. (1999). This module implements a simplified version in that
it only uses one of PGV or PGA, and not a combination of the two (PG... | ynthdhj/shakemap | shakelib/gmice/wald99.py | wald99.py | py | 7,459 | python | en | code | 1 | github-code | 1 |
32147856698 | import numpy
import elice_utils
def main():
num_flips = int(input())
prob_head = float(input())
coin_results = flip_multiple_times(num_flips, prob_head)
print(visualize(coin_results))
def flip_a_coin(prob_head):
random_num = numpy.random.random()
# exercise
if(random_num < prob_head):
... | iwannab1/python-ml | 2_17.py | 2_17.py | py | 1,109 | python | en | code | 1 | github-code | 1 |
2549644044 | import torch
ck = torch.load('/data1/liuyidi/scene_cls/V4.1/log_dir/V4.2_duibi3/ckpt/checkpoint-iter-002000.pyth')['model_state']
ck2 = torch.load('/data1/liuyidi/scene_cls/V4.1/log_dir/V4.1_test27_1_fix/ckpt/checkpoint-iter-008000.pyth')['model_state']
for i,j in zip(ck.keys(),ck2.keys()):
if torch.equal(... | Yidi299/yy_moco | four_pic/weight_ckeck.py | weight_ckeck.py | py | 507 | python | en | code | 0 | github-code | 1 |
41306846620 | import os
from unittest import TestCase
from aksara.morphological_feature import MorphologicalFeature
class MorphologicalFeatureInputFileTest(TestCase):
""" class to test Morphological Feature input file"""
def setUp(self) -> None:
self.morphological_feature = MorphologicalFeature()
self.forma... | ir-nlp-csui/aksara | tests/morphological_feature_test/test_morphological_feature_input_file.py | test_morphological_feature_input_file.py | py | 2,569 | python | en | code | 8 | github-code | 1 |
2032287182 | import datetime
import matplotlib.pyplot as plt
import re
import requests
from urllib.request import urlopen
from django.conf import settings as conf_settings
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.templatetags.static import static
from .forms import ... | zacniewski/weather-manager | weather/views.py | views.py | py | 9,866 | python | en | code | 0 | github-code | 1 |
33385652042 | import matplotlib.pyplot as plt
import sys
import os
import numpy as np
log_folders = ['covtype_test_100rounds_1']
log_folders_10 = [f'covtype_test_10rounds_{i}' for i in range(1, 6)]
fig_path = f'../logs/plots/'
max_rounds = [0 for i in range(len(log_folders))]
for i in range(len(log_folders)):
cur_dir = os.list... | WVLeeuw/BC_Unsupervised_FL | plots/time_taken_multiple.py | time_taken_multiple.py | py | 2,902 | python | en | code | 2 | github-code | 1 |
8490100067 | import pandas as pd
import csv
from math import sqrt
from math import pow
sal_players = []
sal_salaries = []
player_game_stats = []
game_stats = []
game_ids = []
# read in precollected players
with open('players.csv', 'r', newline='\n') as f:
csv_r = csv.reader(f)
header = next(csv_r)
for... | Matts52/Money-is-Motivation | Scraping/PrepForBuilding.py | PrepForBuilding.py | py | 6,227 | python | en | code | 1 | github-code | 1 |
12095789614 | # -*- coding: utf-8 -*-
import logging
import pickle
from pathlib import Path
import matplotlib.pyplot as plt
import optuna
import torch
from torch import nn, optim
from torchvision import datasets, transforms
from src.models.classifier import Classifier
def train_model(
data_filepath,
trained_model_filepat... | ThordurPall/MLOpsExercises | src/models/train_model.py | train_model.py | py | 7,265 | python | en | code | 0 | github-code | 1 |
37429972971 | '''
This file contains functions and classes related to importing corpora into
a script.
'''
import os, re, sys
from pavdhutils.cleaning import clean, toremove
from pavdhutils.tokenize import Tokenize
from sklearn.feature_extraction.text import TfidfVectorizer
class Corpus:
''' This takes the path to a corpus fol... | vierth/pavut | pavdhutils/corpus.py | corpus.py | py | 9,049 | python | en | code | 0 | github-code | 1 |
6106079677 | '''
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
'''
# brute force s... | chuckinator0/Projects | scripts/moveZeros.py | moveZeros.py | py | 1,672 | python | en | code | 17 | github-code | 1 |
29966398423 | import os
import numpy as np
class CSVParser(object):
def __init__(self, filename):
self._filename = filename
def read_file(self):
ret = ""
with open(self._filename, "r") as f:
while True:
buf = f.read()
if len(buf) == 0:
... | Royz2123/Biometric-Attack | csv_parser.py | csv_parser.py | py | 916 | python | en | code | 6 | github-code | 1 |
30277322074 | from __future__ import absolute_import
from __future__ import print_function
import os
from collections import namedtuple, MutableMapping
from copy import deepcopy, copy
from itertools import ifilter
import logging
import pyros_utils
import rospy
import rosservice, rostopic, rosparam
import re
import ast
import sock... | pyros-dev/pyros-rosinterface | pyros_interfaces_ros/ros_interface.py | ros_interface.py | py | 25,186 | python | en | code | 1 | github-code | 1 |
34084522015 | import matplotlib
import matplotlib.pyplot as plt
import dataset
import numpy as np
import tensorflow as tf
import os
import time
tf.compat.v1.reset_default_graph()
np.random.seed(42)
tf.compat.v1.set_random_seed(42)
###################################################################################
##################... | Laalasa137/Classification-of-Artwork | capsuleNet.py | capsuleNet.py | py | 18,067 | python | en | code | 1 | github-code | 1 |
70987912033 | from flask import Flask, render_template
from flask import jsonify, request
from flask import Blueprint, abort
from flask_mysqldb import MySQL
from flask_cors import CORS
from ..Config import Config as cfg
from ..run import db
kriteria = Blueprint('kriteria',__name__)
# READ
@kriteria.route('/kriteria', methods=['GET... | soyidwahyud/Proyek_3 | Backend/objectClass/Kriteria/Kriteria.py | Kriteria.py | py | 3,114 | python | en | code | 1 | github-code | 1 |
12730312192 | import gettext
import tempfile
from collections import defaultdict
import polib
from carcade.utils import get_template_source
def get_translations(po_file_path):
"""Creates :class:`gettext.GNUTranslations` from PO file `po_file_path`."""
po_file = polib.pofile(po_file_path)
with tempfile.NamedTemporaryF... | aromanovich/carcade | carcade/i18n.py | i18n.py | py | 1,271 | python | en | code | 18 | github-code | 1 |
70025505634 | import random
def yaziTura():
yaziTuraListesi = []
for para in range(100000):
yaziTuraListesi.append(random.randrange(1,3))
return yaziTuraListesi
def altiDefaPespese():
listem = yaziTura()
altiliGrup = []
n = 0
altiDefaPesPeseTura = 0
while len(listem) >= 6:
... | Efe-Haspolat/Efe_Volkan | Kopf_Zahl.py | Kopf_Zahl.py | py | 825 | python | tr | code | 0 | github-code | 1 |
71860433633 | import tkinter as tk
class Aplicacion:
def __init__(self):
self.ventana1=tk.Tk()
self.ventana1.title("Ventana con botones")
self.seleccion=tk.IntVar()
self.seleccion.set(1)
self.radio1=tk.Radiobutton(self.ventana1, text="Rojo", variable=self.seleccion, value=1, comma... | GalvanLautaro/PythonProjects | InterfazGrafica/Ex60/ex1.py | ex1.py | py | 1,049 | python | es | code | 0 | github-code | 1 |
24631100750 | import joblib
from pickle import load
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error,r2_score,accuracy_score
from preprocessing import for_evaluate
from preprocessing import s... | pannawit2541/Forex-Trend-Prediction | Project/API/Evaluate_model.py | Evaluate_model.py | py | 4,043 | python | en | code | 0 | github-code | 1 |
72498744034 | '''
Create input features YAML for Ludwig configuration.
'''
import yaml
import argparse
import pandas as pd
if __name__ == "__main__":
# Argument parsing.
parser = argparse.ArgumentParser()
parser.add_argument("input_file", help="Input file")
parser.add_argument("output_file", help="Output file")
... | jgoecks/transcriptional-signatures-ludwig | create_input_features.py | create_input_features.py | py | 760 | python | en | code | 2 | github-code | 1 |
71446585953 | # 739. Daily Temperatures
# Medium
#
# 4298
#
# 130
#
# Add to List
#
# Share
# Given a list of daily temperatures temperatures, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 inst... | laiqjafri/LeetCode | problems/00739_daily_temperatures.py | 00739_daily_temperatures.py | py | 992 | python | en | code | 0 | github-code | 1 |
29182363036 | # 预处理Node Extraction数据,生成字粒度标注序列
# 可配置生成: 有类别(E/V/T/VT) / 无类别(仅BIO) 的标签序列
import json
import sys
sys.path.append('../')
from transformers import DebertaV2Tokenizer, RobertaTokenizer
from tqdm import tqdm
from annotation.preprocess import parse_sparql
from QG.util import qg_tag2id
# tokenizer标志空格的标志
TOKENIZER_START_... | AOZMH/Crake | src_main/NE/prepare_ne_data.py | prepare_ne_data.py | py | 13,893 | python | en | code | 8 | github-code | 1 |
71823946915 | import tensorflow as tf
from defs import *
import numpy as np
#------ State encoder decoder -----#
class state_encoder_decoder():
def __init__(self, name):
self.name = name
self.en_name = name+"_encode_"
self.dec_name = name+"_decode_"
self.opt = tf.train.AdamOptimizer(0.0001)
... | NAVEENMN/PersonalArchives | tf_experiments/SR/models.py | models.py | py | 5,063 | python | en | code | 0 | github-code | 1 |
13430338873 | # Photo.py
import io
import os
from enum import Enum, unique
import hashlib
from typing import List
from datetime import datetime
import base64
from mongoengine import (
Document,
IntField,
FloatField,
StringField,
ListField,
ReferenceField,
BooleanField,
ImageField,
DateTimeField,
... | ydethe/photomanagement | PhotoManagement/Photo.py | Photo.py | py | 13,214 | python | en | code | 0 | github-code | 1 |
16823262942 | import py_trees
class GlobalBlackboard:
_instance = None
@staticmethod
def get_instance():
if GlobalBlackboard._instance is None:
GlobalBlackboard._instance = py_trees.blackboard.Client(name="Global")
return GlobalBlackboard._instance
def get_port_content(port_v... | JdeRobot/bt-studio | backend/tree_gardener/tree_gardener/tree_tools.py | tree_tools.py | py | 1,286 | python | en | code | 21 | github-code | 1 |
35968046668 | '''
Code taken from rochakgupta repository
Github Reference : https://github.com/rochakgupta/aco-tsp.git
Reference : http://www.theprojectspot.com/tutorial-post/ant-colony-optimization-for-hackers/10
'''
import random
import math
import numpy as np
from aco_tsp import *
from kmeans import *
depot = []
# ca... | Akshay-Kawlay/MTSP-throughput-max | approach1&2/aco_kmeans_main.py | aco_kmeans_main.py | py | 3,823 | python | en | code | 1 | github-code | 1 |
22584360544 | darrc_template = """
--min-digits={settings.digits}
--slice {settings.slice_size_KiB:0.0f}K
# make crypto block size larger to reduce
# likelihood of duplicate ciphertext
--crypto-block 131072
# DO NOT specify the AES key here: this script is burned on every
# backup disc, in the clear
--key aes:
# don't back up cache... | jaredjennings/darbrrb | darbrrb.py | darbrrb.py | py | 64,180 | python | en | code | 9 | github-code | 1 |
13807442077 | import cv
cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE)
capture = cv.CaptureFromCAM(0)
def repeat():
while True:
frame = cv.QueryFrame(capture)
cv.ShowImage("w1", frame)
cv.WaitKey(10)
repeat()
cv.WaitKey(0)
| sivajipr/python-course | days/4/applications/opencv/cam2.py | cam2.py | py | 238 | python | en | code | 0 | github-code | 1 |
43753328895 | #!/usr/bin/env python3
# coding=utf-8
import rospy
from math import *
from sensor_msgs.msg import Image
import cv2, cv_bridge
import numpy as np
from geometry_msgs.msg import Twist
from yolo_new.msg import position_color as PositionMsg
from yolo_new.msg import color_ik_result_new as color_ik_result_Msg
from std_msgs.m... | Anxy02/Refuse-Classification-Machine | src/yolo_new/scripts/serialCom.py | serialCom.py | py | 4,737 | python | en | code | 1 | github-code | 1 |
17020636318 |
# In[ ]:
discord_token = 'tokenhere' #@param {type:"string"}
# ##Module installation
# this will install all the necessary modules
# In[ ]:
# ##Download and load GPT NEO model.
# It will take a little bit
# In[3]:
from transformers import GPTNeoForCausalLM, GPT2Tokenizer
model = GPTNeoForCausalLM.from_pre... | graylan0/gpt5-ptt | gpt5discordloop.py | gpt5discordloop.py | py | 3,939 | python | en | code | 4 | github-code | 1 |
75172920353 | import os
import tensorflow as tf
import dataset
import numpy as np
import matplotlib.pyplot as plt
import math
import yaml
from django.conf import settings
base_dir = os.path.dirname(__file__)
root_dir = settings.CLASSIFIED_SETTING['app']['root']
import scipy.misc
def visual_network(modelConfig,network):
# load c... | yaakov300/finalProjectDeepLearning | src/classified/visualising_network.py | visualising_network.py | py | 3,656 | python | en | code | 0 | github-code | 1 |
3178055024 | # coding=utf-8
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import argparse
import numpy as np
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation, Input
from keras.utils.np_utils import to_categori... | scrssys/semantic_segment_RSImage | temp/unet_train_binary.py | unet_train_binary.py | py | 11,213 | python | en | code | 49 | github-code | 1 |
8715524858 | import pygame
from random import randint, random
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load("Stuff/Music/music.ogg")
pygame.mixer.music.play(-1)
pygame.mixer.music.set_volume(0.5)
#create screen
screen = pygame.display.set_mode((1000, 800))
pygame.display.set_caption('Flappy by Motus')
timer = pygame.t... | Motusdevop/Flappy | main.py | main.py | py | 3,634 | python | en | code | 0 | github-code | 1 |
6690963513 | import re
from django.db.models import Q
from django.utils.text import smart_split
from django.views.generic import ListView
from home.models import Noticia
from utils.mixinscomuns import ComunsNoticiasMixin
class NoticiaListView(ComunsNoticiasMixin, ListView):
model = Noticia
template_name = "noticias/notic... | GustavoCruz12/educacao | src/noticias/views.py | views.py | py | 1,638 | python | en | code | 0 | github-code | 1 |
20495973574 | import numpy as np
from parakeet import jit
@jit
def fdtd(input_grid, steps):
grid = input_grid.copy()
old_grid = np.zeros_like(input_grid)
previous_grid = np.zeros_like(input_grid)
l_x = grid.shape[0]
l_y = grid.shape[1]
for i in range(steps):
previous_grid[:, :] = old_grid
... | iskandr/parakeet | examples/finite-difference.py | finite-difference.py | py | 999 | python | en | code | 232 | github-code | 1 |
5885623337 | import itertools
n = int(input())
answer = 0
if n < 2:
print (answer)
elif n == 2:
print ("1")
else:
answer = 4
i = 3
add = 7
add2 = 8
while i != n:
answer += add
add += add2
add2 *= 2
i += 1
print (answer)
| cliodhnaharrison/kattis | character.py | character.py | py | 273 | python | en | code | 5 | github-code | 1 |
32487778371 | import numpy as np
import pickle
#import models
paper_data = np.loadtxt('paper_data/published_data.txt')
XGBoost_data = np.loadtxt('XGBoost_data.txt')
DecTrees_data = np.loadtxt('DecisionTree_data.txt')
FFNN_sigmoid_lin_data = np.loadtxt('FFNN_sigmoid_lin_data.txt')
FFNN_sigmoid_tanh_data = np.loadtxt('FFNN_sigmoid_ta... | Cyangray/ML-project-3 | comparisons.py | comparisons.py | py | 3,743 | python | en | code | 0 | github-code | 1 |
39212108561 | import tensorflow as tf
#import numpy as np
#import pandas as pd
#import networkx as nx
#import matplotlib
#import matplotlib.pyplot as plt
#from mpl_toolkits.mplot3d import Axes3D
#from pathlib import Path
#import random,math,sympy
#import re
#from turtle import *
#import time,datetime
#import argparse
#import logging... | 774799513/learngit | keras/4-2.py | 4-2.py | py | 1,464 | python | en | code | 0 | github-code | 1 |
43766192577 | # mysql数据操作模块
from functools import wraps
import logging
import pymysql
import time
logging.basicConfig(level=logging.INFO,
# format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', #返回值:Thu, 26 May 2016 15:09:31 t11.py[line:92] INFO
format='[%... | Kewei-Lu/Scrapy_Project | Include/BUFF/BUFF/mysql_processor.py | mysql_processor.py | py | 4,154 | python | en | code | 0 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.