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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
650432757 | import os
import luigi
import json
import z5py
import numpy as np
from ..cluster_tasks import WorkflowBase
from ..relabel import RelabelWorkflow
from ..relabel import find_uniques as unique_tasks
from ..node_labels import NodeLabelWorkflow
from ..features import RegionFeaturesWorkflow
from .. import write as write_tas... | constantinpape/cluster_tools | cluster_tools/postprocess/postprocess_workflow.py | postprocess_workflow.py | py | 19,543 | python | en | code | 32 | github-code | 6 |
10176346880 | import requests
import re
import warnings
import json
class NHGIS:
'''API wrapper for the IPUMS NHGIS API.
API Documentation: https://developer.ipums.org/docs/get-started/
Arguments:
api_key: Authorization key required for use of the IPUMS API. *Required*
API keys can be obta... | joelsewhere/ipumspy | ipumspy.py | ipumspy.py | py | 18,512 | python | en | code | 0 | github-code | 6 |
5736450663 | #Esse programa tem o intuito de calcular o desconto progressivo de uma simulação de um pacote de viagem
#Solicitando as informações para a pessoa calcular o pacote
valor_bruto = float(input("Insira o valor bruto do pacote de viagem: "))
categoria = input("Insira o nome da categoria do pacote (Economica, executiva ou p... | pedrokli/estudos-python | agencia_viagem.py | agencia_viagem.py | py | 2,257 | python | pt | code | 0 | github-code | 6 |
10424289451 | #-*- coding: utf-8 -*-
u"""
.. moduleauthor:: Martí Congost <marti.congost@whads.com>
"""
from cocktail import schema
from woost.models import Configuration
from woost.extensions.audio.audiodecoder import AudioDecoder
from woost.extensions.audio.audioencoder import AudioEncoder
pos = Configuration.groups_order.index(... | marticongost/woost | woost/extensions/audio/configuration.py | configuration.py | py | 926 | python | en | code | 0 | github-code | 6 |
26053689790 | from itertools import permutations
vowels = ["о", "а"]
consonants = ["в", "т", "р"]
result = set()
for index, i in enumerate(permutations("авторота")):
correct = True
for symbol_index in range(0, len(i) - 1):
if (i[symbol_index] in vowels and i[symbol_index + 1] in vowels) or \
(i[symb... | Woolfer0097/UGE_IT | 8 task/236.py | 236.py | py | 501 | python | en | code | 0 | github-code | 6 |
14018247881 | import cv2
import numpy as np
def motion_detector(videofile):
window_raw = "Raw video"
window_preprocessed = "Preprocessed video"
window_motion = "Video motion"
window_finished = "Thermal Video"
window_test1 = "Test1"
cv2.namedWindow(window_raw)
cv2.namedWindow(window_preprocessed)
c... | Christdej/gas-analysis | src/gas_analysis/gas_detection.py | gas_detection.py | py | 4,763 | python | en | code | null | github-code | 6 |
73996523069 | import torch
from torch import nn, optim
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
import random
import os
import glob
import sys
import wandb
import gru_models
import build_vocab
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# TODO: Get rid of these, just pass t... | JayOrten/controllableRNN | scripts/train_gru.py | train_gru.py | py | 11,462 | python | en | code | 0 | github-code | 6 |
20154269616 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, print_function, absolute_import,
unicode_literals)
__all__ = ["get_locations"]
from .geocode import geocode
from .ads import get_author_locations
def get_locations(name):
affils = get_author_locations(name)
... | dfm/careermap | careermap/get_locations.py | get_locations.py | py | 826 | python | en | code | 0 | github-code | 6 |
28509751362 | # coding: utf-8
"""
Messente API
[Messente](https://messente.com) is a global provider of messaging and user verification services. * Send and receive SMS, Viber, WhatsApp and Telegram messages. * Manage contacts and groups. * Fetch detailed info about phone numbers. * Blacklist phone numbers to make sure yo... | messente/messente-api-python | messente_api/models/delivery_report_response.py | delivery_report_response.py | py | 6,393 | python | en | code | 0 | github-code | 6 |
6907369998 | from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
from firebase import firebase
# from flask_cors import CORS
from twilio.rest import Client
import pyrebase
config = {
"apiKey": "AIzaSyAEEO1frXfzyL6MCkRvgGz7qURfsTLajRc",
"authDomain" : "covid-19-fake-news-... | mayankchauhan96/Fake-news-detector | app.py | app.py | py | 2,112 | python | en | code | 1 | github-code | 6 |
31698964136 | import pytorch_lightning as pl
import torch
from src.training_class import CFG, BertModule
if __name__ == "__main__":
torch.cuda.empty_cache()
model = BertModule()
trainer = pl.Trainer(
accelerator="gpu",
devices=1,
max_epochs=CFG.epochs,
precision=32,
gradient_cli... | ArturYasnov/Quora-Insincere-Questions-using-BERT | train.py | train.py | py | 500 | python | en | code | 0 | github-code | 6 |
8266532966 | import logging
import shutil
import sys
import click
from cekit.cache.artifact import ArtifactCache
from cekit.config import Config
from cekit.crypto import SUPPORTED_HASH_ALGORITHMS
from cekit.descriptor.resource import create_resource
from cekit.log import setup_logging
from cekit.tools import Map
from cekit.versio... | cekit/cekit | cekit/cache/cli.py | cli.py | py | 5,730 | python | en | code | 70 | github-code | 6 |
71889450427 | # -*- coding: utf-8 -*-
from django.conf import settings
from django.views.generic import CreateView
from levangersundet.forms import DeltagerForm
from post_office import mail
class TestCreateView(CreateView):
form_class = DeltagerForm
template_name = 'test.html'
def get_success_url(self):
return... | fivethreeo/jsdev | mainapp/views.py | views.py | py | 1,070 | python | en | code | 0 | github-code | 6 |
71477031868 | import sys
input = sys.stdin.readline
data1 = input().rstrip()
data2 = input().rstrip()
n1 = len(data1)
n2 = len(data2)
ans = 0
i = 0
while i <= n1-n2:
if data1[i:i+n2] == data2:
ans += 1
i += n2
else:
i += 1
print(ans)
| YOONJAHYUN/Python | BOJ/1543.py | 1543.py | py | 259 | python | en | code | 2 | github-code | 6 |
49771831 | from typing import *
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
res = []
if root is None:
return res
que =... | code-cp/leetcode | solutions/429/main.py | main.py | py | 991 | python | en | code | 0 | github-code | 6 |
41563667577 | from src.models.caja_moneda import CajaMoneda
from src.models.moneda_digital import MonedaDigital
from src.models.tipo_operacion import TipoOperacion
from src.models.transaccion import Transaccion
class Usuario(object):
def __init__(self, nombre, codigo):
self._nombre = nombre
self._codigo = codig... | Andres-Fernandez-Caballero/monedero_virtual | src/models/Usuario.py | Usuario.py | py | 3,049 | python | es | code | 0 | github-code | 6 |
25549591929 | import logging
import os
import sys
def configLogger():
root = logging.getLogger()
root.setLevel(logging.DEBUG)
file_handler = logging.FileHandler(_get_logfile_name())
file_handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fil... | cipriantruica/news_diffusion | news-spreading-master/logger/logger.py | logger.py | py | 529 | python | en | code | 0 | github-code | 6 |
1918587531 | import sys
import datetime
import csv
from os import path
""""
This section describes all functions called when the program is started.
"""
def startup():
create_date_file()
create_bought_file()
create_sold_file()
def create_date_file():
"""Check if there is already a file present contai... | YorrickvB/SuperpyV2 | startup.py | startup.py | py | 1,282 | python | en | code | 0 | github-code | 6 |
44091065220 | import os
import gc
import re
import sys
import copy
import time
import random
import tempfile
import logging
import cPickle as cp
import multiprocessing
import subprocess
import deepity
import numpy as np
import numpy.random as npr
import smat as sm
import scipy
import scipy.stats
from . import std
from . impor... | jisraeli/DeepBind | code/libs/deepity/deepity/hypertrain.py | hypertrain.py | py | 25,376 | python | en | code | 85 | github-code | 6 |
12207565885 | from exercises import *
from graders import *
from training_util import *
from rlbottraining.common_exercises.kickoff_exercise import *
def make_default_playlist():
exercises = [
# KickoffExercise('Both Corners', blue_spawns=[Spawns.CORNER_R, Spawns.CORNER_L], orange_spawns = []),
#KickoffExercise... | mattlegro/Teach | training/kickoff_playlist.py | kickoff_playlist.py | py | 976 | python | en | code | 0 | github-code | 6 |
16413370006 | import json
import os
import pygame
from pprint import pformat
from pyggui.core import TRANSPARENT
pygame.font.init()
_DEFAULT_THEME_PATH = 'assets/themes/default_theme.json'
_DEFAULT_THEME_PATH = os.path.join(os.path.dirname(__file__), _DEFAULT_THEME_PATH)
NULL_THEME_DEFAULTS = {
"col": TRANSPARENT,
"width... | sam57719/PygGUI | pyggui/theme.py | theme.py | py | 2,672 | python | en | code | 0 | github-code | 6 |
44284258376 | import sys, dpkt, socket
from dpkt.compat import compat_ord
class Statistics: #Statistic Class: Used just to store global stats of the following info
connCount = 0
rstCount = 0
openCount = 0
closeCount = 0
duration = 0
minDuration = 0
meanDuration = 0
maxDuratio... | dmahw/CSC_361_TCPTrafficAnalysis | TCPTrafficAnalysis.py | TCPTrafficAnalysis.py | py | 17,576 | python | en | code | 0 | github-code | 6 |
34003465685 | mylist = ["eat", "tea", "tan", "ate", "nat", "bat"]
emptylist = []
for i in mylist:
tempSet = set(i)
templist = []
for j in range(len(mylist)):
if tempSet == tempSet.intersection(set(mylist[j])):
templist.append(mylist[j])
if templist not in emptylist:
emptylist.... | Tommyhappy01/1-IT_FUNDAMENTAL | python/try/anagram v11.py | anagram v11.py | py | 379 | python | en | code | 5 | github-code | 6 |
12173424287 | import numpy as np
def calibrate(input_path, output_path, filename):
X = np.load(input_path + filename + '.npy')
y_gt = np.zeros(X.shape[0], dtype=int);
m = 0
# for i in range(0,1250):
# y_gt[i] = 1
# m += 1
for i in range(9346,13577):
y_gt[i] = 1
m += 1
# for i... | MarcWong/wavelet | utils/calibrate.py | calibrate.py | py | 629 | python | en | code | 0 | github-code | 6 |
39627561667 | import time
import json
import math
import csv
import serial # conda install pyserial
import sys
import glob
# pygame needs python 3.6, not available for 3.7
import pygame # conda install -c cogsci pygame; maybe because it only is supplied for earlier python, might need conda install -c evindunn pygame ; sudo apt-get i... | SensorsINI/DeltaGRU-cartpole | cartpole_robot/python_controller/control.py | control.py | py | 19,414 | python | en | code | 0 | github-code | 6 |
7661449629 | import numpy as np
import netCDF4
from datetime import datetime, timedelta
from glob import glob
import os, sys
"""
This program is used to read input data.
"""
#******************************************
# Edit here (input file directories)
#------------------------------------------
slpbasedir = "/mnt/nas02/data/... | nbykutsumi/wsd | dataloader_CMIP6.py | dataloader_CMIP6.py | py | 5,339 | python | en | code | 1 | github-code | 6 |
41685726399 | import boto3
import sys
import time
# input value 'ansible-controller' while running the instance
#import json
ec2_client = boto3.client('ec2', region_name = "us-east-1")
instances = ec2_client.describe_instances()
for reservation in instances['Reservations']:
for instance in reservation["Instances"]:
if i... | sudhann92/project-repo | aws-python/aws-boto-start-instance.py | aws-boto-start-instance.py | py | 979 | python | en | code | 0 | github-code | 6 |
12300903394 | import numpy as np
from sklearn.datasets import make_classification
import pytest
from pygbm.binning import BinMapper
from pygbm.grower import TreeGrower
from pygbm import GradientBoostingRegressor
from pygbm import GradientBoostingClassifier
X, y = make_classification(n_samples=150, n_classes=2, n_features=5,
... | ogrisel/pygbm | tests/test_plotting.py | test_plotting.py | py | 2,201 | python | en | code | 175 | github-code | 6 |
71050106107 | __doc__ = """
=====================
Plugs Introduction
=====================
:Author: Limodou <limodou@gmail.com>
.. contents::
About Plugs
----------------
Plugs is an apps collection project for uliweb. So you can use any app of it
to compose your project.
License
------------
Plugs is releas... | limodou/plugs | setup.py | setup.py | py | 1,424 | python | en | code | 23 | github-code | 6 |
38958617780 | from unittest import mock
from django.test import TestCase
from django.urls import resolve, reverse
from nltk import word_tokenize
from .models import ScrapeHistory
from .views import WordCountView
class ScrapeTest(TestCase):
def _mock_response(
self,
status=200,
content="CO... | iqbalalo/word_counter | src/scrape/tests.py | tests.py | py | 3,441 | python | en | code | 0 | github-code | 6 |
9109600438 | import sys
from PyQt5.QtWidgets import *
class Main(QDialog):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
main_layout=QVBoxLayout()
#버튼 만들기
btn = QPushButton("Click me")
main_layout.addWidget(btn)
... | kangminzu/battleship | battleship/import sys.py | import sys.py | py | 527 | python | en | code | 0 | github-code | 6 |
69997166908 | import time
def test1():
now = 1543786615000
time_array = time.localtime(now / 1000)
other_style_time = time.strftime("%Y--%m--%d %H:%M:%S", time_array)
print(other_style_time)
def test2():
k = None
if isinstance(k, dict):
print(111)
else:
print(222)
def test3():
co... | HasakiWMC/LOL_project | src/webserver/test/test.py | test.py | py | 538 | python | en | code | 0 | github-code | 6 |
71951872187 | class Persona():
def __init__(self, nombre, edad, lugar):
self.nombre = nombre
self.edad = edad
self.lugar = lugar
def descripcion(self):
print("Nombre: ", self.nombre, " Edad: ", self.edad, " Lugar: ", self.lugar)
class Empleado(Persona):
def __init__(self, nombre_empl... | xanpena/phython-sintaxis | objetos/herencia_super.py | herencia_super.py | py | 854 | python | es | code | 0 | github-code | 6 |
25653326394 | from socket import NI_NAMEREQD
import sw_utils as utl
def assign_crew_members(starship, crew_positions, personnel):
"""Maps crew members by position to the passed in < starship > 'crew_members'
key. Both the < crew_positions > and < personnel > lists should contain the same number
of elements. The individ... | Tianhongge/Python_SI506 | last_assignment/swapi.py | swapi.py | py | 30,085 | python | en | code | 0 | github-code | 6 |
29214803056 | from django.views.generic.simple import direct_to_template
from django.db.models import get_app, get_models, get_model
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.forms import ModelForm
from django.forms.models import modelform_factory
from django.forms import Mo... | dest81/test_dm | dynamic_models/views.py | views.py | py | 1,631 | python | en | code | 1 | github-code | 6 |
20398018702 | import wx
[wxID_NUMBERINGPANEL, wxID_NUMBERINGPANELALPHA, wxID_NUMBERINGPANELALPHA_PAD,
wxID_NUMBERINGPANELALPHA_UC, wxID_NUMBERINGPANELASC,
wxID_NUMBERINGPANELCOUNT, wxID_NUMBERINGPANELCOUNTBYDIR,
wxID_NUMBERINGPANELDESC, wxID_NUMBERINGPANELDIGIT,
wxID_NUMBERINGPANELDIGIT_AUTOPAD, wxID_NUMBERINGPANELDIGIT_PAD,
w... | metamorphose/metamorphose1 | numbering.py | numbering.py | py | 25,919 | python | en | code | 7 | github-code | 6 |
11192585843 | """
CP1404 Prac 07 - More Guitars!
Estimated Time: 30 minutes
Actual time 50 minutes
"""
from prac_06.guitar import Guitar
def main():
"""Guitars - keep track of guitars and sort them."""
guitars = []
load_file(guitars)
for guitar in guitars:
print(guitar)
guitars.sort()
for guitar in ... | alexdamrow/cp1404practicals | prac_07/myguitars.py | myguitars.py | py | 1,067 | python | en | code | 0 | github-code | 6 |
8209601687 | import os
import pytest
import requests_mock
from newsApi.models.request import EverythingRequestModel, Language, TopHeadlinesRequestModel, SourcesRequestModel
from newsApi.models.response import EverythingResponseModel, TopHeadlinesResponseModel, SourcesResponseModel
from newsApi.service import NewsAPIService
@pytes... | roachseb/NewsAPI-Python-Client | tests/test_news_service.py | test_news_service.py | py | 1,664 | python | en | code | 0 | github-code | 6 |
22250933699 | n = 0
s = '9' * 65
while '999' in s or '222' in s:
if '222' in s:
s = s.replace('222', '9', 1)
else:
s = s.replace('999', '2', 1)
for i in s:
num = int(i)
n += num
print(n)
| MakinFantasy/xo | 12/16.06/4.py | 4.py | py | 205 | python | en | code | 0 | github-code | 6 |
70374265789 | from owlready2 import *
import csv
def loadOntology(path):
onto = get_ontology(path).load()
print("Loaded " + onto.base_iri)
return onto
def get_parents(ontology, cls):
# print(cls.name)
return cls.ancestors(include_self=False)
if __name__ == '__main__':
path_to_ontology = "file:///Use... | daniwelter/python_owl_sandbox | ontology_extractor/covid_parent_accessor.py | covid_parent_accessor.py | py | 3,745 | python | en | code | 0 | github-code | 6 |
30347048151 | #from exam_word import word_04
from .exam_func import TEST, MEAN,EXAMPLE, EXAMPLE_test, SIMILAR
import json
from collections import OrderedDict
from .W2V_word import W2V
import random
# word = word_04
def REMOVE(st):
row = ' '.join(s for s in st)
remove = "}"
for x in range(len(remove)):
row1 = row.... | GeulNoon/server | geulnoon/Word/test04.py | test04.py | py | 1,699 | python | en | code | 0 | github-code | 6 |
2103471277 | import numpy as np
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams['pdf.fonttype'] = 42
plt.rcParams['ps.fonttype'] = 42
sns.set_context(rc={'figure.figsize': (9, 9)}, font_scale=2... | IBM/sensitive-subspace-robustness | utils.py | utils.py | py | 7,600 | python | en | code | 13 | github-code | 6 |
27277101793 | from flask import Flask, redirect, render_template, request, url_for, session, flash
import sqlite3
import random
import datetime
import smtplib
from email.mime.text import MIMEText
# sqlite3 connection
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS us... | Jordan1570/ID-proj | app.py | app.py | py | 7,120 | python | en | code | 0 | github-code | 6 |
32717559608 | import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
addr = ('localhost', 9000)
sock.connect(addr)
msg = sock.recv(1024)
print(msg.decode())
sock.send("Jeonghyun Song".encode())
msg_stu = sock.recv(1024)
student_number = int.from_bytes(msg_stu, 'big')
print(student_number)
sock.close() | Jeong613/net_programming | HW2/first_client.py | first_client.py | py | 305 | python | en | code | 0 | github-code | 6 |
12066160544 | import enum
from typing import Dict, List, Tuple
# --------------------------
# Basic (string, float, int)
# --------------------------
name: str = "Tay May"
weight: float = 60.2
age: int = 16
print(name)
print(weight)
print(age)
# --------------------------
# List
# --------------------------
thanhvien_cs102: List[... | Greninja2021/Steam2022 | Lesson_1_CS102-CrazyRobot/example_typing.py | example_typing.py | py | 1,344 | python | en | code | 2 | github-code | 6 |
40327669141 | from easy_pyechart import _funnel_base_config, constants
from pyecharts import options as opts
from pyecharts.commons.utils import JsCode
from typing import Any, Optional
from pyecharts.charts import Funnel
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
'''漏斗图'''
c... | jayz2017/easy_pyechart.py | easy_pyechart/easy_funnel.py | easy_funnel.py | py | 1,050 | python | en | code | 1 | github-code | 6 |
11773636601 | import requests
import json
from pprint import pprint
access_token='<put your access token here>'
page_id='<put your page id here>'
url='https://graph.facebook.com/v2.0/'+page_id+'?feed&access_token='+access_token
r = requests.get(url)
try:
response_json = json.loads(r.text)
except (ValueError, KeyError, TypeError... | mehta-a/FacebookDataExtraction | src/extract.py | extract.py | py | 367 | python | en | code | 1 | github-code | 6 |
39468004248 |
__doc__ = "this module contains varoous tools"
from datetime import date, datetime
# built in modules:
# import sys
# import os
# modules from pypi (install using `pip install module_name`)
# paramiko
# requests
def input_int(num_range: tuple):
"""
`range`: tuple like (from, to)
"""
frm, to = num_r... | MrPupik/python-examples | zero_to_hero/tools.py | tools.py | py | 753 | python | en | code | 0 | github-code | 6 |
26529063971 | from copy import deepcopy
from flask import abort
from flask import Blueprint
from flask import request
from flask_api import status
from oneview_redfish_toolkit.api.event import Event
from oneview_redfish_toolkit.api.event_service import EventService
from oneview_redfish_toolkit.blueprints.util.response_builder impor... | HewlettPackard/oneview-redfish-toolkit | oneview_redfish_toolkit/blueprints/event_service.py | event_service.py | py | 3,130 | python | en | code | 16 | github-code | 6 |
70101583869 | from SlackClient import SlackClient
class SlackCalls(SlackClient):
class SlackCallUser(SlackClient):
def __init__(self):
self.slack_id = None
self.external_id = None
self.display_name = None
self.avatar_url = None
def generate_json_user(self):
... | cthacker-udel/Python-Slack-API | SlackCalls.py | SlackCalls.py | py | 2,336 | python | en | code | 1 | github-code | 6 |
10247855105 | #-*- coding: utf-8 -*-
from itertools import chain
from os.path import dirname, splitext
from sys import platform
from typing import Dict, List, Set, Union
from backend.converters import FileConverter, rar_executables
from backend.db import get_db
from backend.files import scan_files
from backend.volumes import Volum... | Casvt/Kapowarr | backend/conversion.py | conversion.py | py | 5,191 | python | en | code | 221 | github-code | 6 |
27516705586 | from typing import Literal
ver_num = "3.2.2"
online_message = "Oh no, pas encore..."
mods = {}
def enable_module(mod):
mods[mod] = "✅"
def disable_module(mod):
mods[mod] = "❌"
def get_modules():
return mods
ban_domain = ["twitter", "deezer", "spotify"]
values = Literal[1, 2, 3, 4, 5, 6, 7... | Tintin361/Kiri-Chan | tools/variables.py | variables.py | py | 2,005 | python | en | code | 0 | github-code | 6 |
24746745289 | # -*- coding: utf-8 -*-
import json
import urllib
from django.contrib import auth
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.conf import settings
from common import utils, page
from www.misc... | lantianlz/zx | www/admin/views_topic.py | views_topic.py | py | 4,554 | python | en | code | 1 | github-code | 6 |
34858917903 |
# script to find best results of mnist evaluation based on accuracy, same accuracy is not taken care of
import numpy as np
# opening file
with open('log.txt') as file:
# reading all lines from file, skipping first 2 lines
lines = file.readlines()[2:]
# closing file
file.close()
# decla... | maixnor/mnist | mnist/findBest.py | findBest.py | py | 657 | python | en | code | 0 | github-code | 6 |
2001310411 | # -*- coding: utf-8 -*-
from django.db import models
from django.conf import settings
from .base import BaseModel
from .user_group import UserGroup
class Event(BaseModel):
TYPE_1, TYPE_2 = xrange(2)
SOURCE_GROUP, SOURCE_INDIVIDUAL = xrange(2)
EVENT_TYPES = (
(TYPE_1, 'Collecting'),
(TYPE... | luhonghai/expense | expense/apps/mobile_api/models/event.py | event.py | py | 2,818 | python | en | code | 1 | github-code | 6 |
34832289590 | import cv2
import numpy as np
cap = cv2.VideoCapture(0) #取得視訊鏡頭的畫面
#不同顏色的筆
pen_color_HSV = [[86, 121, 205, 111, 245, 255],
[46, 78, 172, 71, 255, 255],
[22, 70, 214, 31, 255, 255]
]
#不同顏色的筆對應的筆尖
pen_color_BGR = [[255, 0, 0],
[0, 255, 0],
... | jim2832/Image-Recognition | virtual_pen.py | virtual_pen.py | py | 2,304 | python | en | code | 0 | github-code | 6 |
30297740447 | # Seq2Seq model with attention
import torch
import torch.nn as nn
import torch.nn.functional as F
import random
from copy import copy
def init_weights(m):
for name, param in m.named_parameters():
if 'weight' in name:
nn.init.normal_(param.data, mean=0, std=0.01)
else:
nn.ini... | three0-s/KT-ETRI | model.py | model.py | py | 7,755 | python | en | code | 0 | github-code | 6 |
15038954927 | import tkinter
from PIL import Image
import time
import pygame
# Ссылка на гугл диск, на котором файл с музыкой. Он не прошла по размеру на github. https://drive.google.com/drive/folders/1RzTOtOH4LLt6UE6C6TCYG-0Quf38lkTE
pygame.init()
pygame.mixer.music.load("music.wav")
pygame.mixer.music.play(-1)
def game()... | PashaSeleznev/Lab_4 | main.py | main.py | py | 2,652 | python | en | code | 0 | github-code | 6 |
33272740574 | from random import random
import numpy
from copy import deepcopy
from texttable import Texttable
class Ant:
def __init__(self, size):
self._size = size
self._representation = [[] for i in range(size * 2)]
self._graph = [self._representation]
self._freeSpots = size - ... | CMihai998/Artificial-Intelligence | Lab4 - ACO/models/ant.py | ant.py | py | 5,321 | python | en | code | 3 | github-code | 6 |
3596407711 | from tkinter import *
#tkinter module GUI application
fruits=["dragon fruits","Apple","banana","grapes","pine apple","papaya"]
win=Tk()
win.title("Demo GUI 1")
win.geometry("400x400")
li=Listbox(win,foreground="blue",bg="tomato")
index=1
for fruit in fruits:
li.insert(index,fruit+str(index))
index=ind... | AshishSirVision/Mysql-python-code | p6.py | p6.py | py | 373 | python | en | code | 1 | github-code | 6 |
44313582014 | from tkinter import *
import sqlite3
from PIL import ImageTk, Image
from backend import Database
import requests
database=Database("books.db")
class Window(object):
def __init__(self,window):
self.window=window
self.window.title("Bookstore")
self.window.configure(bg='#856ff8')
#T... | mertwithamouth/Py_Projects | Book Store/bookstore.py | bookstore.py | py | 5,422 | python | en | code | 0 | github-code | 6 |
24168954856 | import asyncio
import importlib
import re
from contextlib import closing, suppress
from uvloop import install
from pyrogram import filters, idle
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message
from Yukinon.menu import *
from Yukinon import *
from Yukinon.plugins import ALL_MODULES
from Yu... | TechShreyash/Yukinon_Robot | Yukinon/__main__.py | __main__.py | py | 13,537 | python | en | code | 3 | github-code | 6 |
35253557105 | """
Classes containing different occlusion models (e.g. estimators for shadows, sky view factor etc.)
"""
import hylite
import matplotlib.pyplot as plt
import numpy as np
from hylite.correct import get_hull_corrected
from hylite.multiprocessing import parallel_chunks
def estimate_path_radiance(image, depth, thresh=1... | hifexplo/hylite | hylite/correct/illumination/path.py | path.py | py | 4,573 | python | en | code | 24 | github-code | 6 |
20674612571 | import logging
import sys
from tracker import LogawareMixin, getenv_or_fail
from tracker.fetch.online import JsonEndpointFetcher
from tracker.metadata.retriever import LiftMetadataRetriever
from tracker.metadata.store import LiftMetadataDatabaseRecorder
class LiftMetadataInserter(LogawareMixin):
def __init__(sel... | dachrisch/dolomiti-lift-queue | tracker/metadata/insert.py | insert.py | py | 1,298 | python | en | code | 0 | github-code | 6 |
21124445086 | import linecache
import math
import os
# numpy and revise it with numpy
# multiple sets of 100 test cases
# cosine similarity
# 100 test cases for sum squared errors
# 100 test cases for Average
# small standard deviation -> good prediction
# smaller mean -> the better -> (mean = better prediction)
# transpose m... | R3xKyle-CP/cpe400 | jester/prediction2.py | prediction2.py | py | 12,781 | python | en | code | 0 | github-code | 6 |
10649208417 | """
Example
Description: Showcasing the use of Example Images from 'Images.py'
"""
from IMAGES import *
import pygame,sys
pygame.init()
w,h = (1920,1080)
win = pygame.display.set_mode([w,h])
img1 = Rock((255,255,255),(0,0))
img2 = Testing((255,255,255),(0,0))
while True:
for e in pygame.event.get():
if e... | LandenTy/GeometricEngine | CustomTexturer/Example Images/Example.py | Example.py | py | 487 | python | en | code | 0 | github-code | 6 |
74874759867 | import sys
import os
import argparse
from pypiscout.SCout_Logger import Logger as sc
import gprof2dot # pylint: disable=unused-import
# Rationale: Not directly used, but later we do a sys-call wich needs the library. This is needed to inform the user to install the package.
sys.path.append("../... | bmwcarit/Emma | genDoc/genReadmeHtmlFromMd.py | genReadmeHtmlFromMd.py | py | 6,000 | python | en | code | 2 | github-code | 6 |
34673770578 | import typed_args as ta
from typing import List, Callable
@ta.argument_parser()
class Args(ta.TypedArgs):
"""
Process some integers.
"""
integers: List[int] = ta.add_argument(
metavar='N', type=int, nargs='+',
# help='an integer for the accumulator'
)
"""
an integer for th... | SunDoge/typed-args | examples/prog.py | prog.py | py | 611 | python | en | code | 11 | github-code | 6 |
6296479069 | turn = ''
shown_turn = ''
winner= ''
check_if_win = False
check_if_tie = False
board = ["-", "-", "-",
"-", "-", "-",
"-", "-", "-"]
def Play_game():
while check_if_win == False or check_if_tie == False:
check_trun = False
print_board = board[0] + " | " + board[1] + " | " + board... | SackBiscuit/TicTacToe | ExOo.py | ExOo.py | py | 2,783 | python | en | code | 0 | github-code | 6 |
7919695077 | #Задать список из N элементов, заполненных числами из [-N, N]. Найти произведение элементов
#на указанных позициях. Позиции хранятся в списке positions - создайте этот список
# (например:positions = [1, 3, 6]).
# 1 вариант
n = int(input("Введите число n:"))
positions = [1, 3, 6]
x = max(positions)
y = int(len(position... | Savitskiyov/Python | Seminar 2/DZ_4.py | DZ_4.py | py | 1,593 | python | ru | code | 0 | github-code | 6 |
71484286908 | import sys
import ctypes
def popcount(N):
if sys.platform.startswith('linux'):
libc = ctypes.cdll.LoadLibrary('libc.so.6')
return libc.__sched_cpucount(ctypes.sizeof(ctypes.c_long), (ctypes.c_long * 1)(N))
elif sys.platform == 'darwin':
libc = ctypes.cdll.LoadLibrary('libSystem.dylib')... | knuu/competitive-programming | atcoder/arc/arc007_c.py | arc007_c.py | py | 719 | python | en | code | 1 | github-code | 6 |
34970808449 | from main import speak, sing
import unittest
class TestMain(unittest.TestCase):
def test_speak(self):
INP = EXP ='OK'
OUT = speak(INP)
assert OUT == EXP, 'It must speak exactly what I asked'
def test_sing(self):
INP = EXP = 'Lala land'
OUT = sing(INP)
assert O... | nhtua/log2mongo | tests/test_main.py | test_main.py | py | 416 | python | en | code | 0 | github-code | 6 |
21446386978 | import csv
from pylab import *
import sys
if len(sys.argv) != 4:
print('Error, ejecucion: python estadisticas.py <topico> <fecha_ini(yyyy-mm-dd)> <fecha_fin(yyyy-mm-dd)>')
print('Para omitir un parametro dejar el valor \'\'')
exit()
topico = str(sys.argv[1]) #str(input("ingrese topico: "))
date_ini = s... | gonzalezf/tweetometro | estadisticas.py | estadisticas.py | py | 2,282 | python | es | code | 1 | github-code | 6 |
40725138206 | from turtle import Turtle, Screen
import random
screen = Screen()
screen.setup(width=500, height=400)
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
user_bet = ""
while user_bet not in colors:
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color:... | abishekbalaji/hundred_days_of_code_python | turtle-race/main.py | main.py | py | 1,085 | python | en | code | 1 | github-code | 6 |
13488129623 | #!/usr/bin/python3
"""Returns the number of lines of a text file"""
def read_lines(filename="", nb_lines=0):
"""Reads a text file and return the number of lines"""
lines = 0
with open(filename) as a_file:
i = len(list(a_file))
if nb_lines >= i or nb_lines <= 0:
nb_lines = i
... | 1uiscalderon/holbertonschool-higher_level_programming | 0x0B-python-input_output/2-read_lines.py | 2-read_lines.py | py | 422 | python | en | code | 0 | github-code | 6 |
1909503331 | import unittest
import mock
from hpOneView.connection import connection
from hpOneView.resources.networking.sas_logical_interconnects import SasLogicalInterconnects
from hpOneView.resources.resource import ResourceClient
class SasLogicalInterconnectsTest(unittest.TestCase):
def setUp(self):
self.host = '... | HewlettPackard/python-hpOneView | tests/unit/resources/networking/test_sas_logical_interconnects.py | test_sas_logical_interconnects.py | py | 5,962 | python | en | code | 86 | github-code | 6 |
32072532623 | class Player:
def __init__(self, name, id, pos, switch, order, sub, sub_id, status, team):
self.name = name
self.id = id
self.pos = pos
self.switch = switch
self.order = order
self.sub = sub
self.sub_id = sub_id
self.status = status # 'available', 'en... | milesokamoto/pbpy | modules/player.py | player.py | py | 391 | python | en | code | 5 | github-code | 6 |
21917306491 | from django.shortcuts import render, redirect
from .models import *
from hashlib import sha1
from django.http import JsonResponse, HttpResponseRedirect
from . import user_decorator
from df_goods.models import *
def register(request):
return render(request, 'df_user/register.html')
def register_handle(request):
... | junjie0825/dailyfresh | dailyfresh/df_user/views.py | views.py | py | 4,210 | python | en | code | 0 | github-code | 6 |
14177953222 | """Holds environmental variables, sets up custom logger."""
import logging
import os
log = logging.getLogger(name="log")
# declare environment constants
COSMOSDB_CONNECTION_STRING: str = os.environ["COSMOSDB_CONNECTION_STRING"]
COSMOSDB_DATABASE_ID: str = os.environ["COSMOSDB_DATABASE_ID"]
COSMOSDB_CONTAINER_ID: str... | wieczorekgrzegorz/ksef-krportal-communication | utilities/setup.py | setup.py | py | 1,194 | python | en | code | 0 | github-code | 6 |
30925855450 | from Game import Game
from Player import Player
from Players import Players
print('::::: PROBLEM 1 :::::')
player_1 = Player( 1 , "Kirat Boli" , [5,30,25,10,15,1,9,5] )
player_2 = Player( 2 , "N.S Nodhi" , [10,40,20,5,10,1,4,10] )
player_3 = Player( 3 , "R Rumrah" , [20,30,15,5,5,1,4,20] )
... | jonafrank13/python_example | GameSimulator.py | GameSimulator.py | py | 1,264 | python | en | code | 0 | github-code | 6 |
27672728231 | from typing import Optional
import torch
from torch import nn
from config import dt_config
from block import TransformerBlock
class DecisionTransformer(nn.Module):
def __init__(self,
cfg: dt_config,
state_dim: int,
action_dim: int) -> None:
super().__init... | zzmtsvv/rl_task | decision_transformer/model.py | model.py | py | 3,401 | python | en | code | 8 | github-code | 6 |
25289541604 | from os import mkdir, getcwd
from os.path import join,exists
def new_file(file_name, data):
"""
create new file
"""
with open(file_name, 'w', encoding='utf-8') as file:
file.write(data)
def new_static_dir(project_name):
"""
root_dir/static
"""
static_path = join(getcwd(), pro... | LABELNET/my-ctl | my_ctl/py_template/app_dir_static.py | app_dir_static.py | py | 1,037 | python | en | code | 0 | github-code | 6 |
23158389057 | import os
import argparse
import torch
from torchvision import datasets, transforms
from torch.utils.data.sampler import WeightedRandomSampler
from sklearn.model_selection import train_test_split
from collections import Counter
import numpy as np
# Transform and to normalize the data [0.0, 1.0]
transform_train = trans... | minkeshtu/Imbalanced-Cifar-10-classification | dataset/cifar10Loader.py | cifar10Loader.py | py | 8,218 | python | en | code | 3 | github-code | 6 |
3407362691 | from queue import Queue
from adjacencyset import *
def sort_topology(graph):
queue = Queue()
in_degree_map = {}
for v in range(graph.numVertices):
in_degree_map[v] = graph.get_indegree(v)
if in_degree_map[v] == 0:
queue.put(v)
sorted = []
while not queue.empty():
... | VimleshS/python-graph-ds | topological_sort.py | topological_sort.py | py | 860 | python | en | code | 0 | github-code | 6 |
25328118850 | import cv2
import numpy as np
from scipy.spatial import cKDTree
from sklearn.decomposition import PCA
def sample_to_heatmap(points, x_adjust=0, y_adjust=0, z_threshold=None, nearest_k=3):
# If a threshold is provided, keep only points with a z-coordinate above this threshold
if z_threshold is not None:
... | jichengzhi/cube-sampling | heatmap.py | heatmap.py | py | 2,657 | python | en | code | 0 | github-code | 6 |
6969826416 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import torch
class EMA_FM():
def __init__(self, decay=0.9, first_decay=0.0, channel_size=512, f_map_size=196, is_use = False):
self.decay = decay
self.first_decay = first_decay
self.is_use = is_use
self.shadow = {}
... | ada-shen/icCNN | utils/utils.py | utils.py | py | 4,582 | python | en | code | 18 | github-code | 6 |
20801228142 | from itertools import chain
y, x = [int(i) for i in input().split()]
matrix = [[] for _ in range(y)]
for i in range(y):
s = input()
for u in s:
if u == ".":
matrix[i].append(True)
elif u == "#":
matrix[i].append(False)
def step(y, x, matrix):
matrix[y][x] = True
... | michbogos/olymp | eolymp/dynamic_programming/cut_paper.py | cut_paper.py | py | 915 | python | en | code | 0 | github-code | 6 |
21705447470 | from glob import glob
from os import makedirs
from shutil import copy2
from tqdm import tqdm
SINGER = 'mixed'
RELEASE_DIR = 'release/mixed_---'
PATH_QUESTION = 'conf/jp_qst001_nnsvs_simple_4-4_mix.hed'
NAME_EXPERIMENT = 'simple_4-4_mix'
def copy_question(path_question, release_dir):
"""
hedファイル(question)をコピ... | oatsu-gh/nnsvs_mixed_db | recipe/00-svs-world/make_it_for_release.py | make_it_for_release.py | py | 1,761 | python | en | code | 0 | github-code | 6 |
25200222730 | #For example, given [(30, 75), (0, 50), (60, 150)], you should return 2.
classes = [(900, 910), (940, 1200), (950, 1120),(1100, 1130), (1500, 1900), (1800, 2000)]
started = []
for x,i in classes:
started+= [(x,'started'),(i,'ended')]
started = sorted(started)
needed = 0
ongoing = 0
print(started)
for i in ... | etukleris/various | python/timers.py | timers.py | py | 540 | python | en | code | 0 | github-code | 6 |
24966970253 | #!/usr/bin/env python
from netCDF4 import Dataset
import copyNCVariable as copync
import sys, os
import random
import pdb
import numpy as np
import datetime as dt
#
#
#
def usage():
print("Usage")
print(" "+sys.argv[0]+" [filename] [dim name]")
exit(1)
def change_time_units(var):
"""Change the ti... | NCAR/rda-dataset-curation | common/removeDimension.py | removeDimension.py | py | 8,646 | python | en | code | 1 | github-code | 6 |
74118290427 | import os
import sys
import yt_dlp
from tqdm import tqdm
def download_videos(links_file):
if not os.path.exists(links_file):
print("Error: The links file '{}' does not exist.".format(links_file))
return
ydl_opts = {
'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/bes... | vishnu012/Personal-Scripts | pydownload/downloader.py | downloader.py | py | 961 | python | en | code | 0 | github-code | 6 |
27104562564 | import os
import pickle
import uvicorn
from fastapi import FastAPI
FAKE_HASH_TABLE_DB = './database/FakeHashTable.pickle'
class FakeHashTable:
def __init__(self, bit_limitation=10):
self.limitation = 2 ** bit_limitation
self.hashtable = dict()
self.id_list = set()
self.history = ... | hoangperry/system-design-implementation | unique-id-generator/hash_service.py | hash_service.py | py | 2,812 | python | en | code | 2 | github-code | 6 |
73510589947 | n = int(input())
arr = list(map(int,input().split()))
left = 0
right = n-1
wube = 0
henock = 0
flag = True
while left<=right:
if flag:
if arr[left]>arr[right]:
wube += arr[left]
left += 1
else:
wube += arr[right]
right -= 1
flag = False
el... | yonaSisay/a2sv-competitive-programming | cardGame.py | cardGame.py | py | 529 | python | en | code | 0 | github-code | 6 |
2374031473 | from torchvision import models
import torch
import torch.nn as nn
from PIL import ImageGrab
import cv2
import torch.nn.functional as F
# import albumentations as A
# from albumentations.pytorch import ToTensorV2
from torchvision import transforms
import numpy as np
from PIL import Image
from input_keys import PressKey,... | DH-an/Metaverse_Autonomous_Driving_AI_Project | Data_Collecting/ingame_testing.py | ingame_testing.py | py | 3,032 | python | en | code | 0 | github-code | 6 |
71601955069 | import datetime
dogdict = {
"american staffordshire terrier": True,
"pitbull terrier": True,
"bullterrier": True,
"bullmastiff": True,
"staffordshire bullterrier": True,
"cane corso": True,
"dogo argentino": True,
"bordeaux dogge": True,
"fila brasileiro": True,
"mastin espanol"... | MHin504/OZG-Hundesteuer | Server.py | Server.py | py | 4,498 | python | de | code | 0 | github-code | 6 |
1798043180 | import time
import json
import board
import busio
import adafruit_ads1x15.ads1015 as ADS
from adafruit_ads1x15.analog_in import AnalogIn
max_val = None
min_val = None
# Create the I2C bus
i2c = busio.I2C(board.SCL, board.SDA)
# Create the ADC object using the I2C bus
ads = ADS.ADS1015(i2c)
# Create single-ended input ... | pdany1116/is-iot-collector | helpers/light_intensity_moisture_calibration.py | light_intensity_moisture_calibration.py | py | 1,305 | python | en | code | 0 | github-code | 6 |
21987190006 | import pytest
@pytest.fixture(name="fixer")
def fixer_fixture(two_to_three_test_case):
return two_to_three_test_case("methodattrs")
attrs = ["func", "self", "class"]
def test(fixer):
for attr in attrs:
b = "a.im_%s" % attr
if attr == "class":
a = "a.__self__.__class__"
... | ryanwersal/crosswind | fixer_suites/two_to_three/tests/test_methodattrs.py | test_methodattrs.py | py | 847 | python | en | code | 11 | github-code | 6 |
19581566047 | from os.path import join as osjoin
paper_root_dir = 'paper'
stdj_dir = osjoin(paper_root_dir, 'stdj')
ctu_dir = osjoin(paper_root_dir, 'ctu')
stats_about_file_dir = osjoin('..', 'stats_about_files')
root_dir = osjoin('..', 'corpus')
# store all documents
all_doc_dir = osjoin(root_dir, 'all_doc')
# store source doc... | oldguard69/lvtn | server/core/directory.py | directory.py | py | 1,627 | python | en | code | 0 | github-code | 6 |
6673888762 | import bs4
import requests
url = 'https://id.carousell.com/carousell_id'
contents = requests.get(url)
response = bs4.BeautifulSoup(contents.text, 'html.parser')
data = response.find('div', attrs={'class': 'D_apq D_eZ M_gF D_fb M_gH'})
datas = data.findAll('div', attrs={'class': 'D_jg', 'class': 'D_qq', 'class': '... | AlfaRiza/ScrapingCarousell | getImg.py | getImg.py | py | 748 | python | en | code | 0 | github-code | 6 |
70514418749 | import numpy as np
import json
import matplotlib.pyplot as plt
import os
# Joints such as ear, eyes are not necassary
wanted_joints = list(range(5,18)) + [19]
def normalize_halpe26(poses, img):
hip_idx = 13 #19 before removal of unneeded joints
for i, det in enumerate(poses):
nrows = det['box'][3]
... | DiscipleOfProgramming/hockey-pose-estimation | parse_halpe26.py | parse_halpe26.py | py | 893 | python | en | code | 0 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.