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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
35566203783 | import os
from os.path import splitext
from subprocess import check_call, Popen
import tempfile
import logging
import urllib.request
import urllib.parse
VOXYGEN_URL_FMT = 'https://www.voxygen.fr/sites/all/modules/voxygen_voices/assets/proxy/index.php?method=redirect&text={message}&voice=Marion'
VOICERSS_URL_FMT = 'ht... | jujumo/conteur | conteur/tts.py | tts.py | py | 2,519 | python | en | code | 0 | github-code | 1 |
41898377707 | import numpy as np
from os import listdir
from os.path import join
from data_containers import shard
def load_normalized_bstars(normed_bstar_path, orders):
# 1: Get normalized B star names
fnames = [f for f in listdir(normed_bstar_path) if f.endswith(".npz")]
fnames = [join(normed_bstar_path, f) for f in fnam... | chrisleet/selenite | selenite/load_store/load_normalized_spectra.py | load_normalized_spectra.py | py | 1,574 | python | en | code | 0 | github-code | 1 |
39994274479 | from qiskit import QuantumCircuit, execute
from qiskit import IBMQ, Aer
from qiskit.visualization import plot_histogram
from qiskit.providers.aer.noise import NoiseModel
# Build noise model from backend properties
provider = IBMQ.load_account()
print(provider)
backend = provider.get_backend('ibmq_vigo')
noise_model = ... | simonetome/QuantumGeneticAlgorithm | GQA/quantum/prova.py | prova.py | py | 908 | python | en | code | 3 | github-code | 1 |
9539235134 | """
Handles retrieving policies from:
ACL/COLING 2014 Dataset Zip File
Policies Directory
Scraped from webpage
"""
from zipfile import ZipFile
import re
import pickle
policy_dict = {
'cbc': './policies/CBC.txt',
'bbc': './policies/BBC.txt',
'nytimes': './policies/NYT.txt',
'thestar': '.... | krishnr/Priv | server/src/get_policies.py | get_policies.py | py | 1,620 | python | en | code | 0 | github-code | 1 |
5747429962 | import sys
import tensorflow as tf
import keras
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from scipy.io import loadmat
import cv2
from skimage.io import imshow
from keras.models import Sequential
from keras.layers import Conv2D,Conv2DTranspose, Cropping2D, Dense, Activation, Dropout, Flat... | suhaschowdaryj/semantic_segmentation | fcn32.py | fcn32.py | py | 7,416 | python | en | code | 0 | github-code | 1 |
24837006891 | from PIL import Image, ImageDraw
import io
IMAGE_WIDTH = 38
IMAGE_HEIGHT = 32
N_RESIZE = 64
NUMBER_OF_POSITIONS = 51 # [0;100]
file = open("progressArc.h", "w")
file.write("#ifndef LCD_PROGRESS_ARC_H_\n")
file.write("#define LCD_PROGRESS_ARC_H_\n\n")
file.write("namespace lcd\n{\n\n")
file.write("static const uint8_t... | zukaitis/midi-grid | Misc/image_generation/generateProgressArc.py | generateProgressArc.py | py | 1,781 | python | en | code | 74 | github-code | 1 |
38592902934 | class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def push(self, value):
newnode = Node(value)
newnode.nex... | polszewski443/cwiczeniaAISD2 | zad1.py | zad1.py | py | 3,190 | python | en | code | 0 | github-code | 1 |
3242822152 | import sys
sys.path('../../../')
import torch
import torch.nn as nn
import Datasets.medutils_torch as medutils_torch
from Datasets.medutils_torch import complex
from Datasets.medutils_torch.fft import fft2, ifft2
from Datasets.medutils_torch.mri import \
adjointSoftSenseOpNoShift, \
forwardSoftSenseOpNoShift
... | YuyangXueEd/MRI_Recon_Tutorial | Models/sigmanet/modules/datalayer.py | datalayer.py | py | 7,826 | python | en | code | 6 | github-code | 1 |
35429618954 | import sys
sys.stdin = open('input_1358.txt', 'r')
W, H, X, Y, P = map(int, input().split())
result = 0
for _ in range(P):
x_point, y_point = map(int, input().split())
radius = H // 2
conditions = [
X <= x_point <= X + W and Y <= y_point <= Y + H, # 직사각형 범위 판단
((x_point - X) ** 2 + (y_poin... | wally-wally/TIL | 02_algorithm/baekjoon/all_problem/1358.py | 1358.py | py | 611 | python | en | code | 32 | github-code | 1 |
21840890275 | import sys, itertools
input = sys.stdin.readline
def dfs(start, ls):
visited[start] = True
for i in graph[start]:
if not visited[i]:
if i in j or i in unselect:
ls.append(i)
dfs(i, ls)
N =int(input())
population = [0] +list(map(int, input().split... | pearl313/BOJ | 백준/Gold/17471. 게리맨더링/게리맨더링.py | 게리맨더링.py | py | 1,287 | python | en | code | 0 | github-code | 1 |
14919840293 | import os
import sys
from datetime import timedelta
from dotenv.main import load_dotenv
# BASE_DIR = Path(__file__).resolve().parent.parent
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.join(BASE_DIR, 'apps'))
if os.getenv("GITHUB_ACTIONS") == "true":
load_dotenv('... | GaniyevUz/Digital-Ecommerce | root/settings.py | settings.py | py | 7,697 | python | en | code | 6 | github-code | 1 |
5895415014 | import pandas as pd
import matplotlib.pyplot as plt
import Utils as utils
from operator import itemgetter
# reading data
#da = utils.combine_data()
da = pd.read_csv('rawdata/heathrowRawData.csv')
class knn:
def __init__(self, *args, **kw):
pd.set_option('display.max_rows', 2000)
plt.rcParams['fi... | omarali0703/MachineLearning | kNN.py | kNN.py | py | 2,412 | python | en | code | 0 | github-code | 1 |
5178387272 |
while True:
a = int(input('Enter the side a: '))
b = int(input('Enter the side b: '))
c = int(input('Enter the side c: '))
if a + b < c or a + c < b or b + c < a:
print(f'There is no triangle with such sides!')
elif a != b != c:
print(f'The triangle is versatile')
elif a == b ==... | Levigin/Introduction-to-python | HW1/task1.py | task1.py | py | 608 | python | en | code | 0 | github-code | 1 |
73614605793 | from unittest.mock import Mock
import pytest
import requests
from parking_permit.html_parser import HtmlParser
from parking_permit.queue_service import *
LICENSE_PLATE = "AB-123-C"
CLIENT_NUMBER = "1234567"
URL = (
"https://www.amsterdam.nl/parkeren-verkeer/parkeervergunning/"
+ "parkeervergunning-bewoners/w... | janheindejong/parking-permit | tests/test_queue_service.py | test_queue_service.py | py | 1,976 | python | en | code | 0 | github-code | 1 |
20690038334 | # interpolação
nome = "Weslley"
sobrenome = "Ferraz"
idade = 26
print("Meu nome é {nome} {sobrenome} e a minha idade é {idade}".format(
nome=nome, sobrenome=sobrenome, idade=idade))
# reduz as casas decimais
valor = 15.4678
print("O valor é R$ {valor:.2f}".format(valor=valor))
| weslley281/curso-python | Dominando strings/format.py | format.py | py | 289 | python | pt | code | 0 | github-code | 1 |
16779060864 | nombres = [
"Torres, Ana",
"Hudson, Kate",
"Quesada, Benicio",
"Campoamores, Susana",
"Santamaría, Carlos",
"Skarsgard, Azul",
"Catalejos, Walter"
]
sexos = ["f","f","m","f","m","f","m"]
fechas = [
"02/05/1943",
"07/09/1984",
"10/02/1971",
"21/12/1967",... | pablokan/23prog1 | practicos/pr01/practico01_Aguirrre_Andres.py | practico01_Aguirrre_Andres.py | py | 1,370 | python | en | code | 0 | github-code | 1 |
28399981836 | """Support for automation and script tracing and debugging."""
from homeassistant.core import callback
from .const import DATA_TRACE
@callback
def get_debug_trace(hass, automation_id, run_id):
"""Return a serializable debug trace."""
return hass.data[DATA_TRACE][automation_id][run_id]
@callback
def get_deb... | robertdelpeut/core | homeassistant/components/trace/trace.py | trace.py | py | 966 | python | en | code | null | github-code | 1 |
4062540397 |
# Pandigital products
# Problem 32
# We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example,
# the 5-digit number, 15234, is 1 through 5 pandigital.
# The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and ... | IgorKon/ProjectEuler | 032.py | 032.py | py | 2,843 | python | en | code | 0 | github-code | 1 |
43701751013 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 23 11:15:58 2015
@author: erkmaa04
"""
def makeDir(dirname):
import os
if not os.path.isdir(dirname):
os.makedirs(dirname) # if this fails (e.g. permissions) we will get error
def writeCsv(fileName, thisTrial):
import codecs, csv, os
... | marsja/psypy | cross-modality_matching_FD15/trialhandling.py | trialhandling.py | py | 4,181 | python | en | code | 12 | github-code | 1 |
20495938604 | """
NMR Pulse propagation
From http://themodernscientist.com/posts/2013/2013-06-09-simulation_of_nmr_shaped_pulses/
"""
import numpy as np
pulseLength = 1000. # in microseconds
offset = [-5000., 5000.] # in hertz
n_freq = 500
inputMagnetization = 'Mz' # 'Mx', 'My', or 'Mz'
deltaomega = np.abs(offset[1]-offset[0])... | iskandr/parakeet | benchmarks/pulseprop.py | pulseprop.py | py | 3,441 | python | en | code | 232 | github-code | 1 |
40046608603 | #-*-coding: utf-8 -*-
#@author:tyhj
import ast
import operator
import pandas as pd
_ops = {'<': operator.lt, '>': operator.gt,
'<=': operator.le, '>=': operator.ge,
'==': operator.eq,
'endswith': lambda element, s: element.endswith(s),
'in':lambda element,l:element in l,
'contains... | luilui163/zht | py27/zht/util/dfFilter.py | dfFilter.py | py | 2,822 | python | en | code | 0 | github-code | 1 |
17291005352 | import boto3
import requests
import os
import smtplib
import paramiko
import time
import schedule
EMAIL_ADDRESS = os.environ.get('EMAIL_ADDRESS')
EMAIL_PASSWORD = os.environ.get('EMAIL_PASSWORD')
instance_id = "i-0c90f5640105608c3"
host_ip = "13.234.116.18"
def send_notification(email_text):
with smtplib.SMTP('... | himanshupant4899/boto3-project | Monitoring_Website/monitor-website.py | monitor-website.py | py | 2,321 | python | en | code | 0 | github-code | 1 |
35955347175 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayCommerceEducateTuitioncodeOrderdetailQueryModel(object):
def __init__(self):
self._include_plans = None
self._out_order_no = None
self._scene = None
self._sm... | co1in9/alipay-sdk-python-all | alipay/aop/api/domain/AlipayCommerceEducateTuitioncodeOrderdetailQueryModel.py | AlipayCommerceEducateTuitioncodeOrderdetailQueryModel.py | py | 2,370 | python | en | code | null | github-code | 1 |
11778563292 | from PyQt5.QtWidgets import QLabel, QSizePolicy, QRubberBand
from PyQt5.QtGui import QImage, QPixmap
from PyQt5 import QtCore
from PyQt5.Qt import QSize, QRect, QRectF, QPoint, QPointF
import numpy as np
class ImageWidget(QLabel):
def __init__(self, parent=None):
super().__init__(parent)
self.ima... | hovren/visualsearch | vsearch/gui/image.py | image.py | py | 4,771 | python | en | code | 2 | github-code | 1 |
40239177456 | #!/usr/bin/env python
"""This script identifies the controller and plots the results."""
# builtin
import os
import argparse
# external
import matplotlib.pyplot as plt
# local
import utils
from gait_landmark_settings import settings
PATHS = utils.config_paths()
def main(event, structure, recompute, normalize):
... | csu-hmc/gait-control-direct-id-paper | src/identify_controller.py | identify_controller.py | py | 3,224 | python | en | code | 3 | github-code | 1 |
25913908039 | #!/usr/bin/env python3
from propulate import Propulator
from propulate.utils import get_default_propagator
NUM_GENERATIONS = 10
limits = {
'x' : (-10., 10.),
'y' : (-10., 10.),
'z' : (-10., 10.),
'u' : (-10., 10.),
'v' : (-10., 10.),
'w' : (-10., 10.),
}
def ... | oskar-taubert/propulate | scripts/example.py | example.py | py | 536 | python | en | code | 2 | github-code | 1 |
9862990084 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="agilent-format",
version="0.4.4",
author="Stuart Read",
author_email="stuart.read@lightsource.ca",
description="File reader for Agilent Resolutions Pro FT-IR images",
long_description=... | stuart-cls/python-agilent-file-formats | setup.py | setup.py | py | 710 | python | en | code | 2 | github-code | 1 |
5290977217 | """
This file contains the implememtation of the class Log.
Author: Alejandro Mujica (aledrums@gmail.com)
Date: 07/11/2020
"""
import random
import pygame
import settings
from log import Log
class LogPair:
def __init__(self, x, y):
self.x = x
self.lower_log = Log(x, y, 'lower')
gap = s... | R3mmurd/Bird-py | log_pair.py | log_pair.py | py | 969 | python | en | code | 0 | github-code | 1 |
20111198660 | # coding: utf-8
from __future__ import print_function, absolute_import, division, unicode_literals
_package_data = dict(
full_package_name='nim_install',
version_info=(0, 6, 0),
__version__='0.6.0',
author='Anthon van der Neut',
author_email='a.van.der.neut@ruamel.eu',
description='install nim... | gitrootside/vokker | venv/Lib/site-packages/nim_install/__init__.py | __init__.py | py | 2,696 | python | en | code | 0 | github-code | 1 |
22290887005 | import sys
input = sys.stdin.readline
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
with open('p4.in', 'r') as f:
read = f.read().strip().split('\n')
dataiter = iter(read)
def input():
return next(dataiter)
N, Q = map(int, input().strip().split())
money = list(map(int, input()... | dhrumilp15/Puzzles | dmopc20feb/p4.py | p4.py | py | 959 | python | en | code | 0 | github-code | 1 |
33010746822 | from django.urls import include, path
from rest_framework.routers import DefaultRouter
from . import views, viewsets
router = DefaultRouter()
router.register('questions', viewsets.QuestionViewSet, basename='question')
router.register('answers', viewsets.AnswerViewSet, basename='answer')
app_name = 'Questans_API_v1'... | Seth250/qenea-backend | questans/api/v1/urls.py | urls.py | py | 1,100 | python | en | code | 1 | github-code | 1 |
35575650885 | email_to_name = {}
email = input("Email: ")
while email != "":
name, domain = email.split("@")
if "." in name:
first_name, last_name = name.split(".")
name = first_name + " " + last_name
name_check = input("Is your name {0}? (Y/n) ".format(name.title())).lower()
while name_check == "y" o... | brightlee93/cp1404practicals | prac_05/emails.py | emails.py | py | 823 | python | en | code | 0 | github-code | 1 |
27471926358 | n = int(input())
v = [0] * n
s = 0
for i in range(0, n):
v[i] = float(input())
s += v[i]
m = s/n
nd = 0
for i in range(0, n):
nd += (v[i] - m) ** 2
dp = (nd/(n-1))**(1/2)
print(f"O desvio padrao vale {dp:.2f}.")
| matheusalefe/PI-Q2-2023 | Semana 6/Ex12.py | Ex12.py | py | 227 | python | en | code | 0 | github-code | 1 |
1569004540 | """Provides interface for training the model."""
import os
import pathlib
import numpy as np
import torch
from matplotlib import pyplot as plt
from tqdm import tqdm
from . import models
from .preprocessing import ImageDataPipeline
def save(model, path):
"""
Saves the model's parameter states.
Paramete... | MarxSoul55/cats_vs_dogs | cats_vs_dogs/src/pytorch_impl/src/train.py | train.py | py | 3,279 | python | en | code | 5 | github-code | 1 |
73221180195 | import datetime
import pytz
class Account:
""" Simple account class with balance """
@staticmethod
def _current_time():
utc_time = datetime.datetime.utcnow()
return pytz.utc.localize(utc_time)
def __init__(self, name, balance):
self.name = name
self.balance = balance
... | chuckwm/PycharmProjects | oop/teacher_accounts.py | teacher_accounts.py | py | 1,578 | python | en | code | 1 | github-code | 1 |
25441538667 | import pygame
from .funcs import *
from .restart_button import Restart_Button
from .resume_button import Resume_Button
from .sfx_disable_button import SFX_Disable_Button
from .music_disable_button import Music_Disable_Button
class Pause_Menu:
def __init__(self, game):
self.game = game
self.image = ... | pratripat/Dungeon-Game | scripts/pause_menu.py | pause_menu.py | py | 1,597 | python | en | code | 1 | github-code | 1 |
13917637840 | from django.contrib import admin
from .models import Activity
@admin.register(Activity)
class ActivityAdmin(admin.ModelAdmin):
list_display = (
'id',
'created_at',
'activity',
'description',
)
list_filter = ('created_at',)
date_hierarchy = 'created_at' | jafarjtown/Drim | activities/admin.py | admin.py | py | 317 | python | en | code | 0 | github-code | 1 |
17217608702 | import sys
sys.path.append('../TS2VEC')
from pathlib import Path
import hydra
from omegaconf import OmegaConf, DictConfig
import numpy as np
from base.network import TS2Vec
from task.classification.model import TSC
PROJECT_PATH = Path('.').absolute()
DATA_PATH = Path(PROJECT_PATH, 'data', 'UCRArchive_2018', 'FordA')
... | tae73/TS2Vec-Tensorflow | experiments/classification/FordA/forda.py | forda.py | py | 2,840 | python | en | code | 2 | github-code | 1 |
18451705552 | import neoml.PythonWrapper as PythonWrapper
import neoml.Dnn as Dnn
import neoml.Utils as Utils
class ConcatChannels(Dnn.Layer):
"""Implements a layer that concatenates several blobs into one along the Channel dimension.
"""
def __init__(self, input_layers, name=None):
if type(input_layers) is PythonWrapper.Conc... | SAngeliuk/neoml_python | NeoML/Python/neoml/ConcatChannels.py | ConcatChannels.py | py | 646 | python | en | code | 1 | github-code | 1 |
12047340102 | import argparse
import os
import numpy as np
import tqdm.auto as tqdm
import math
import torch
import torch.optim as optim
from torch.distributed.fsdp import (
FullyShardedDataParallel as FSDP,
ShardingStrategy,
FullStateDictConfig,
StateDictType,
)
import datasets
import torch.nn.functional as F
from t... | zphang/minimal-llama | minimal_llama/gist/convert_fsdp_checkpoint.py | convert_fsdp_checkpoint.py | py | 2,450 | python | en | code | 447 | github-code | 1 |
70813688993 | from cmd import PROMPT
from lib2to3.pgen2 import driver
import time
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import... | massiagostini/Tesi | ws_molise.py | ws_molise.py | py | 1,978 | python | en | code | 0 | github-code | 1 |
43514365618 | class Solution(object):
def maxSubArray(self, nums):
"""
方法:动态规划
"""
# step 1:判空
nums_len = len(nums)
if nums_len==0:
return 0
res = -9999999999
pre = 0
# step 2:遍历数组
for i in range(nums_len):
# step 3:取... | km1994/leetcode | topic4_dynamic_planning_study/ms1617_maxSubArray/interview.py | interview.py | py | 560 | python | en | code | 24 | github-code | 1 |
23972292939 | from django.shortcuts import render
from rest_framework import viewsets
from .models import ApartmentModel, Comment
from apps.apartment.forms import CommentForm
from apps.apartment.api.serializers import ApartmentSerializers
from apps.contact.models import ContactModel
from apps.hoteInfo.models import HotelInfo
def a... | Strannik1424/Luxen-Hotel | apps/apartment/views.py | views.py | py | 1,778 | python | en | code | 0 | github-code | 1 |
6386202648 | # Bismillah
from sys import stdin, stdout
# import threading
# import queue
# from collections import Counter
# from math import inf, gcd
# import heapq
# import itertools
str_stdin = lambda: stdin.readline()[:-1]
# strs_stdin = lambda: list(map(str, stdin.readline().split()))
# int_stdin = lambda: int(stdin.readline(... | oneku16/CompetitiveProgramming | ICPC/ICPC2022/Preparation/2019h.py | 2019h.py | py | 2,054 | python | en | code | 0 | github-code | 1 |
6208729995 | import logging
import os
import sentry_sdk
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, RegexHandler, ConversationHandler
from handlers import conversation
from settings import PROXY
logging.basicConfig(format='%(name)s - %(levelname)s - %(message)s',
level=logging.... | KaltakhchyanD/lp_project_orders_tg_bot | bot.py | bot.py | py | 749 | python | en | code | 0 | github-code | 1 |
44847088453 | from setuptools import setup
import os
def _get_version():
filename = os.path.join('src', 'cyclone', '__init__.py')
glb = {}
with open(filename) as fp:
for line in fp:
if '__version__' in line:
exec(line, glb)
return glb['__version__']
raise RuntimeE... | IOR88/cyclone | setup.py | setup.py | py | 731 | python | en | code | 0 | github-code | 1 |
71845052193 | from django.core.paginator import Paginator
from django.shortcuts import render, get_object_or_404
from django.db.models import Q, Count
from ..models import Question, Category
def index(request, category_name='qna'):
page = request.GET.get('page', '1')
kw = request.GET.get('kw', '') # 검색어
so = request.... | ShinHyeongcheol/mysite | pybo/views/base_views.py | base_views.py | py | 2,112 | python | en | code | 0 | github-code | 1 |
37716038335 | import streamlit as st
import time
import torch
import torchvision.transforms as transforms
import torch.nn as nn
from PIL import Image
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))
])
class CNN(nn.Module):
def __init__(se... | waizwafiq/fakeshoe_detection | run.py | run.py | py | 4,940 | python | en | code | 0 | github-code | 1 |
18801120419 | import numpy as np
import pandas as pd
import pyvista as pv
import sys
import logging
import tetgen
from dragen.utilities.InputInfo import RveInfo
class MeshingHelper:
def __init__(self, rve_shape: tuple = None, rve: pd.DataFrame = None, grains_df: pd.DataFrame = None):
self.rve = rve
self.grains... | ibf-RWTH/DRAGen | dragen/utilities/PvGridGeneration.py | PvGridGeneration.py | py | 8,377 | python | en | code | 10 | github-code | 1 |
20274777739 | # coding=utf-8
import unittest
import time
import HTMLTestRunner
import os
curpath = os.path.dirname(os.path.realpath(__file__))
report_path = os.path.join(curpath, ".\\report")
if not os.path.exists(report_path): os.mkdir(report_path)
case_path = os.path.join(curpath, ".\\testCase")
def add_case(casepath=case_path, ru... | shuhaiye/python | jiaoben/api/runAll.py | runAll.py | py | 1,226 | python | en | code | 0 | github-code | 1 |
9361751702 | # %%
from matplotlib import pyplot as plt
import numpy as np
file = "log.txt"
def preprocessing(line):
new=line.replace('\n','').replace(',','').replace('=','').replace(':','').replace('/','').replace('(','').replace(')','').replace('%','')
lineData=new.strip().split(' ')
return lineData
def line1(lineData)... | SunZekai-CN/obj3 | benchmark/readlog.py | readlog.py | py | 7,318 | python | en | code | 0 | github-code | 1 |
25204853716 | __author__ = "jhurley@gmail.com (James Hurley)"
import cgi
import datetime
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.db import djangoforms
from google.appengine.ext.webapp... | JamesHurley/gifty | controllers/helper.py | helper.py | py | 1,835 | python | en | code | 1 | github-code | 1 |
37369359207 | clientes = []
rut = ""
nombre = ""
direccion = ""
comuna = ""
correo = ""
edad = -1
genero = ""
celular =""
tipo =""
suscrito = True
opcion = 0
while opcion != 4:
print("************** M E N Ú - JUAN MAESTRO **************")
print("1.- Registro")
print("2.- Suscripción")
print("3.- Consultar")
p... | patricioyanez/PGY1121_004 | EA3/EnsayoEvaluacion.py | EnsayoEvaluacion.py | py | 4,651 | python | es | code | 6 | github-code | 1 |
75186846753 | import base64
import os
import glob
import tempfile
from time import sleep
import plaid
from dotenv import load_dotenv
from google.cloud import storage
from plaid.api import plaid_api
from plaid.model.institutions_get_request import InstitutionsGetRequest
from plaid.model.country_code import CountryCode
from plaid.mode... | shashwot-acme/wallet_function | plaid/main.py | main.py | py | 3,859 | python | en | code | 0 | github-code | 1 |
16265289610 | # problem: write code to remove duplicates from an unsorted linked list.
# intial idea
# create a set
# loop through the list
# if value in set, remove it
# add val to set
class Node:
def __init__(self):
self.value = None
self.next = None
def remove_dupes(head):
hs = set()
on = head
p... | jmcs811/interview_prep | ctci/2_linked_lists/1_remove_dups.py | 1_remove_dups.py | py | 530 | python | en | code | 0 | github-code | 1 |
218368900 | import math
import weakref
#If we want attributes and values of cls or self - convert to dict
#Relearn arges and kwarges (and uses)
#Learn function notation - EX. global().get - callable stuff
#Learn USE of @classmethod
#git gut
class Combustion:
x = 1
instances = []
num_of_instances = 0
... | EVM-4/loop-varible-appender | main.py | main.py | py | 4,660 | python | en | code | 0 | github-code | 1 |
12459437168 | import os
from twosheds import transform
def working_directory(transforms, short=False):
"""The current working directory."""
try:
pwd = os.getcwdu()
except OSError:
return "?"
else:
rv = transform(pwd, transforms, word=True, inverse=True)
if short:
parts =... | Ceasar/Shell | helpers.py | helpers.py | py | 528 | python | en | code | 5 | github-code | 1 |
20623953099 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: zhendongyang
@contact: yangzd1993@foxmail.com
@file: mazefactory.py
@time: 2018/7/27 22:31
"""
from errors import InvalidNumberException, IncorrectCommandException
from maze import Maze
class MazeFactory(object):
"""迷宫工厂
静态工厂,不需要实例化
"""
@staticmeth... | qqxx6661/python_practise | ThoughtWorks/factory/MazeFactory.py | MazeFactory.py | py | 1,534 | python | en | code | 1 | github-code | 1 |
10100352992 | import pygame
from .base import BaseState
class CustomizeCharacter(BaseState):
def __init__(self):
super().__init__()
self.title = self.font.render("Customize Character", False, 'White')
self.title_rect = self.title.get_rect(center=self.screen_rect.center)
def draw(self, surface):
... | JeffMcCracken/run-escape | code/states/customize_character.py | customize_character.py | py | 411 | python | en | code | 0 | github-code | 1 |
41734018625 | from guts.loader import Loader
class Solver:
def __init__(self, input):
self._input = input
def part_one(self, destination):
return sum(
abs(origin - destination)
for origin in self._input
)
def part_two(self, destination):
return sum(
... | leNEKO/adventofcode | 2021/day7_test.py | day7_test.py | py | 1,234 | python | en | code | 0 | github-code | 1 |
33967386144 | def lfsr_custom(seed, r, q, l, N=100):
A = seed
for i in range(1,len(list(range(1,(N*l)+1)))+1):
if i>q:
pr=i-(r+1)
pq=i-(q+1)
A.append(A[pr] ^ A[pq])
return A
def to_decimal(result, l, N=100):
B = []
jump = l
const = 2**l
for i in range(0, l... | IvanUlloa098/simulacion | tarea_4/ejemploPython.py | ejemploPython.py | py | 603 | python | en | code | 0 | github-code | 1 |
31188279715 | from math import *
import turtle
# Get the value for Theta from the user and convert it to radians.
theta = float(input("Enter a value for theta: ")) * (pi/180)
# Get the value for initial velocity from the user.
v0 = float(input("Enter a value for the initial velocity: "))
# Get the Turtle canvas and creat... | MoKamalian/CSCI2202 | Solutions for lab 1-B nd assing1 nd test/Lab 7/turtle_projectile_iterative.py | turtle_projectile_iterative.py | py | 3,526 | python | en | code | 0 | github-code | 1 |
5965575419 | # -*- coding: iso-8859-1 -*-
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.cm as mpl_cm
import iris
import iris.quickplot as qplt
import iris.plot as iplt
from iris.util import unify_time_units
import cartopy.crs as ccrs
import cartopy.feature as cfeat
impo... | vpoertge/SatEX | climate_index_calculation/plot_indices/plot_ghcndex_indices.py | plot_ghcndex_indices.py | py | 21,522 | python | en | code | 0 | github-code | 1 |
40808949145 | from torch.nn import Module
import torch.nn as nn
class RNN(Module):
def __init__(self, num_in, num_layers, num_hidden, num_out):
super(RNN, self).__init__()
self.lstm = nn.LSTM(num_in, num_hidden, num_layers, dropout=0.3)
self.body = nn.Sequential(nn.Linear(num_hidden, num_hidden),nn.Dropo... | Aryan187/Music-Recommendation-System | Model/rnn.py | rnn.py | py | 457 | python | en | code | 0 | github-code | 1 |
33533072018 | import asyncio
import os
import requests
import time
from PIL import Image
from io import BytesIO
from datetime import datetime
import random
from telethon import events
from userbot.utils import admin_cmd
from userbot import ALIVE_NAME
from telethon.tl.types import ChannelParticipantsAdmins
DEFAULTUSER = s... | RDX-ANONYMOUS/MASTER-MIND-BOT | userbot/plugins/alive.py | alive.py | py | 2,629 | python | en | code | 1 | github-code | 1 |
21589746404 | import torch.nn as nn
import torch
import numpy as np
def gen_sequential(
channels,
Norm_feature = 0,
force_zero = False,
force_zero_ceiling = 0.01,
**kwargs
):
assert len(channels) > 0
modulist = []
from_channel = channels[0]
mid_layers = channels[1:]
for layer in ra... | TurquoiseKitty/BCGmeta_git | models/block_models.py | block_models.py | py | 1,614 | python | en | code | 0 | github-code | 1 |
9571528493 | from django.urls import path,include
# from watchlist_app.api.views import movie_list, movie_detail
from watchlist_app.api.views import GamePlatformVS,GamePlatform,ReviewCreate,ReviewDetail,ReviewList,WatchListAV,WatchDetailAV,GamePlatformAV,GamePlatformDetailAV
from rest_framework.routers import DefaultRouter
router=... | hyeonseong0917/smilegate_personal_project | watchmate/watchlist_app/api/urls.py | urls.py | py | 1,098 | python | en | code | 0 | github-code | 1 |
14179302218 | from scripts.helpful_scripts import get_account
from scripts.get_weth import get_weth
from brownie import config, network, interface
from web3 import Web3
amount = Web3.toWei(0.1, "ether")
def main():
account = get_account()
erc20_address = config["networks"][network.show_active()]["weth_token"]
# call g... | Brar-Paul/aave_brownie_py | scripts/aave_borrow.py | aave_borrow.py | py | 4,151 | python | en | code | 0 | github-code | 1 |
41407468762 |
# 205. Isomorphic Strings
# https://leetcode.com/problems/isomorphic-strings/
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
s2t_map= {}
for ss, tt in zip(s, t):
if ss not in s2t_map.keys():
if tt in s2t_map.values():
return False
... | aszx4510/LeetCode | python/0205-isomorphic_strings.py | 0205-isomorphic_strings.py | py | 436 | python | en | code | 0 | github-code | 1 |
24398367329 | import logging
import os
import random
from urlparse import urlparse
from bs4 import BeautifulSoup
import pickle
from PIL import Image
import requests
import twitter_oauth
logging.basicConfig(level=logging.DEBUG, filename='cuties.log')
logging.debug('Cuties start')
class Dog(object):
'''
Scrapes the SF SPC... | ecalifornica/CutePetsSF | cuties.py | cuties.py | py | 7,219 | python | en | code | 3 | github-code | 1 |
5357527996 | from watson_developer_cloud import ToneAnalyzerV3
import json
import os as os
import config
from watson_developer_cloud import WatsonException
class Tono():
def __init__(self):
self.vTone_analyzer = ToneAnalyzerV3(
username=config.WTAusername,
... | joaquinpunales1992/Python-AIServices | AnalisisComportamiento_JPunales/WatsonToneAnalyzer.py | WatsonToneAnalyzer.py | py | 1,042 | python | es | code | 0 | github-code | 1 |
43236512740 | from __future__ import print_function
import os
import rospkg
import rospy
from python_qt_binding import loadUi
from python_qt_binding.QtCore import Qt
from python_qt_binding.QtCore import Signal
from python_qt_binding.QtGui import QIcon
from python_qt_binding.QtGui import QGraphicsScene
from python_qt_binding.QtGui... | graziegrazie/my_turtlebot | rocon/src/rqt_capabilities/src/rqt_capabilities/capability_graph.py | capability_graph.py | py | 5,052 | python | en | code | 0 | github-code | 1 |
6054905118 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
if inorder==[]:
return None
... | Starangle/leetcode | 106/subin.py | subin.py | py | 820 | python | en | code | 0 | github-code | 1 |
4709205719 | #GCD implemented using recursion
#
#This program implements calculation of GCD using the Euclidean recursive algorithm.
#Given two positive integers a and b such that a<b, gcd is calculated as follows:
# If a=0 or b=0, gcd(a,b) = 0
# Otherwise, gcd(a,b) = gcd(a,b%a)
#
#Example:
# Input: 15 21
# Output: 3
def gcd(... | moogacs/problem-solving | Python/GCDRecursion.py | GCDRecursion.py | py | 582 | python | en | code | 13 | github-code | 1 |
72708313633 |
from functools import reduce
import discord
import linkbot.utils.queries.cmdban as cmdban
import neo4jdb as db
class Command:
"""
A parsed message that looks for the prefix, a command, and args following the command.
:message: (discord.Message) The message that was sent.
:author: (discord.User/dis... | tjbrockmeyer/LinkBot | linkbot/utils/command.py | command.py | py | 6,880 | python | en | code | 1 | github-code | 1 |
16995858646 | from percolation import Percolation
import numpy as np
import random
import math
class PercolationStats:
'''Classe utilizada para estimar o limiar de percolação.
'''
def __init__(self, shape, T):
self.T = T
if type(shape) == int:
self.nlin, se... | IzumiAkio/perc_mmc | percolation_stats.py | percolation_stats.py | py | 2,450 | python | en | code | 0 | github-code | 1 |
42426529533 | import sys
from collections import defaultdict
from copy import deepcopy
input=sys.stdin.readline
n,k=map(int,input().split())
l=[tuple(map(int,input().split())) for _ in range(n)]
dp=[0]*(k+1)
dp_idx=defaultdict(set)
for i in range(1,k+1):
for idx,(w,v) in enumerate(l):
if 0<=i-w<=k and idx not in dp_idx[i... | jhchoy00/baekjoon | 12865.py | 12865.py | py | 515 | python | en | code | 0 | github-code | 1 |
13576462360 | """
Laboratorio de Programación Básica en Python para Manejo de Datos
-----------------------------------------------------------------------------------------
Este archivo contiene las preguntas que se van a realizar en el laboratorio.
No puede utilizar pandas, numpy o scipy. Se debe utilizar solo las funciones de p... | classroom-fundamentos-de-analitica/lab---python-basico-andresmonsalve19 | preguntas.py | preguntas.py | py | 10,852 | python | es | code | 1 | github-code | 1 |
12090885747 | from html.parser import HTMLParser
# create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print(tag)
if len(attrs)!= 0:
for i in attrs:
print("-> {0} > {1}".format(i[0],i[1]))
def handle_startendtag... | moamen-ahmed-93/hackerrank_sol | python3/detect-html-tags-attributes-and-attribute-values.py | detect-html-tags-attributes-and-attribute-values.py | py | 596 | python | en | code | 6 | github-code | 1 |
10686813347 | from threading import Lock
import grpc
from google.protobuf.empty_pb2 import Empty as EmptyResponse
from kmol.core.logger import LOGGER as logging
from ...configs import ServerConfiguration
from ...exceptions import ClientAuthenticationError
from ...protocol_buffers import mila_pb2, mila_pb2_grpc
from .server_manager... | elix-tech/kmol | src/mila/services/server_manager/grpc_servicer.py | grpc_servicer.py | py | 3,599 | python | en | code | 33 | github-code | 1 |
71145325473 | #조합 주어진 집합 내에서 >> 특정 개수의 요소를 선택
# selected : 해당 인덱스의 요소를 집합에 포함할지 여부를 결정
# idx : 인덱스
# cnt : 현재까지 선택된 요소의 개수
# N : 원집합의 크기
# T : 조합의 개수
def comb(selected,idx,cnt,N,T):
if cnt == T:
print(selected)
# for i in range(N):
# if selected[i]:
# print(arr[i],end=" ")
prin... | danzzang/python_algorithm | sw expert/etc/comb.py | comb.py | py | 795 | python | ko | code | 0 | github-code | 1 |
20496366314 |
from dsltools import ScopedSet
from .. analysis.collect_vars import collect_var_names, collect_binding_names
from .. analysis.escape_analysis import may_alias
from .. analysis.syntax_visitor import SyntaxVisitor
from .. ndtypes import ImmutableT, ArrayT, PtrT
from .. syntax import Var, Assign, Return, While, If, I... | iskandr/parakeet | parakeet/transforms/licm.py | licm.py | py | 6,540 | python | en | code | 232 | github-code | 1 |
8076964586 | import tkinter as tk
import matplotlib
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
class Application(tk.Frame):
def __init__(self, master=None):
matplotlib.use('TkAgg')
tk.Frame.__init__(self, master)
... | radovan-urban/MeC_python | tools/tkinter_matplot3.py | tkinter_matplot3.py | py | 809 | python | en | code | 0 | github-code | 1 |
4912088125 | from django.urls import path, include
from . import views
urlpatterns = [
path('',views.application,name='application'),
path('upload',views.upload,name='upload'),
path('preview', views.preview, name='preview'),
path('modification', views.modification, name='modification'),
path('status', views.sta... | kevalunagar/National-Voter-Service-Portal | nvsp/application/urls.py | urls.py | py | 388 | python | en | code | 2 | github-code | 1 |
11626599818 | # -*- coding: utf-8 -*-
# @Time : 19-8-5 下午5:31
# @Author : huziying
# @File : half_circle.py
# 半圆形
import cv2
import numpy
import uuid
import base64
import os
from django.db import connection
from .utils_huziying import horizontal_measurements, vertical_measurements
numpy.set_printoptions(threshold=numpy.inf)... | huzing2524/circuit_board | measurement/utils/half_circle.py | half_circle.py | py | 4,641 | python | en | code | 4 | github-code | 1 |
21182582713 | # creation du shapefile pour les zones de l'acpg
import numpy as np
import GGlib
zones = ['Baie des chaleurs','Canal de Grande-Rivière','Nord Shediac Valley','Western Bradelle Valley','Eastern Bradelle Valley']
sud_coordinates = [("47°56’13’’","65°18’01’’"),("47°54’25’’","65°18’01’’"),("48°06’18’’","64°36’00’’"),("48... | CIDCO-dev/PecheFantome | src/GIS/example_polygon_to_shapefile.py | example_polygon_to_shapefile.py | py | 2,303 | python | en | code | 1 | github-code | 1 |
25484810000 | from typing import overload
from unicodedata import category
from django.core import exceptions
from datetime import datetime
from django.http.response import HttpResponseNotAllowed
from .models import (
FurnitureModels, OrderModels, ReviewModels, ChatTopicModels,
ChatContentModels, OrderModels,ShoppingCartMode... | arif-teguh/jepara-furniture | webapp/user/views.py | views.py | py | 17,655 | python | en | code | 1 | github-code | 1 |
37566094961 | def Txt():
txt = input("Saisir le texte : \n")
txt = txt.lower()
return txt
def CbInTxt(lettre, txt):
count = 0
for k in txt:
if k == lettre:
count += 1
return count
def PrintStats(lettre, count):
print(lettre, "=", count, "%")
print("")
txt = Txt()
total = len(txt... | RKople/TestFirstFunPy | FrequencyAnalysis.py | FrequencyAnalysis.py | py | 486 | python | en | code | 0 | github-code | 1 |
24476936848 | import pandas as pd
from ml_pipeline.utils import count_fn, conv_values, flatten_list, feat_imp
def score_fn(data, count_path, features, list_cols, seed_ids,
neighbors, label):
"""
Function to score each user in the extended set
:param data: Dataset containing user features
:para... | krishnakaushik25/Locality-Sensitive-Hashing | src/ml_pipeline/score.py | score.py | py | 3,605 | python | en | code | 1 | github-code | 1 |
19253180210 | import numpy as np
class Physics():
'''Physics constants and equations for the quadcopter'''
def __init__(self, init_eta=None, init_upsilon=None, runtime=None):
'''Initialize parameters
Params
======
init_position: 1D numpy array, initial position in x-y-z coordi... | vanttec/neural-network-usv-control | physics.py | physics.py | py | 6,120 | python | en | code | 1 | github-code | 1 |
41146178388 | import pandas as pd
import torch
from src.common.tools import model_device
from src.callback.progressbar import ProgressBar
from configs.basic_config import config
class Generator(object):
def __init__(self, model, tok, logger, n_gpu, input_len=None):
self.model = model
self.tok = tok
... | THU-BPM/CoEP | src/test/generator_CoEP.py | generator_CoEP.py | py | 17,988 | python | en | code | 2 | github-code | 1 |
8000089766 | """
Leia 5 valores Inteiros. A seguir mostre quantos valores digitados foram pares, quantos valores digitados foram ímpares, quantos valores digitados foram positivos e quantos valores digitados foram negativos.
Entrada
O arquivo de entrada contém 5 valores inteiros quaisquer.
Saída
Imprima a mensagem conforme o exem... | JonathasVeras/URI | Iniciante/1066 - Pares, Ímpares, Positivos e Negativos.py | 1066 - Pares, Ímpares, Positivos e Negativos.py | py | 1,315 | python | pt | code | 0 | github-code | 1 |
2426576447 | from odoo import api, fields, models
class ProductTemplate(models.Model):
_inherit = "product.template"
@api.multi
def action_fix_uom_consistency(self):
for rec in self:
self.env['stock.move'].search(
['product_tmpl_id', '=', rec.id],
['product_uom.cate... | decgroupe/odoo-addons-dec | uom_wide_fix/models/product_template.py | product_template.py | py | 362 | python | en | code | 2 | github-code | 1 |
24240566551 | import setuptools
import versioneer
DESCRIPTION_FILES = ["pypi-intro.rst"]
long_description = []
import codecs
for filename in DESCRIPTION_FILES:
with codecs.open(filename, 'r', 'utf-8') as f:
long_description.append(f.read())
long_description = "\n".join(long_description)
setuptools.setup(
name = ... | aragilar/root-solver | setup.py | setup.py | py | 1,577 | python | en | code | 0 | github-code | 1 |
43482876476 | import asyncio
import logging
import threading
from typing import List
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from starlette.websockets import WebSocket, WebSocketDisconnect
from .saver import Saver
from .transport import Transfer, InputData
logging.basicConfig(level=logging... | coma8765/gorocket-monitoring-backend | app/main.py | main.py | py | 2,255 | python | en | code | 0 | github-code | 1 |
6257445976 | from art import logo
def resources_sufficient(order_ingredients):
"""Returns True if the drink can be made, returns False if resources are insufficient"""
for item in order_ingredients:
if order_ingredients[item] > resources[item]:
print(f"Sorry there is not enough {item}. Please make anot... | wintermute111/100DaysOfPython | Day015/coffee-machine/main.py | main.py | py | 2,888 | python | en | code | 0 | github-code | 1 |
8073935641 | #############################################################################
# Simplex Algorithm
# by David You
#############################################################################
#################################################
# Note:
# Although the code does not have 2dList function to output values,
#... | dyou3968/homeWorkoutProgram | simplexProgram.py | simplexProgram.py | py | 31,453 | python | en | code | 0 | github-code | 1 |
24522935947 | # Create by Abhiram
# This file has binary tree implemented using Linked List Method.
# I am also implementing different methtods related to the Binary tree.
# Pre-Order, In-Order and Post Order traversal. I am also implementing the level order traversal which is similar to Breadth first search for the graphs.
# Search... | abhi0203/DSAndAlgorithms | BinaryTreeLinkedList.py | BinaryTreeLinkedList.py | py | 8,232 | python | en | code | 0 | github-code | 1 |
40463001775 | from bs4 import BeautifulSoup
import requests
from datetime import datetime
# https://amzn.to/3E7V45Y -> Cetus Pro FPV
def cetus_price():
url = 'https://amzn.to/3E7V45Y'
headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
... | enriquetecfan11/Telegram-Bot | amazonprice.py | amazonprice.py | py | 583 | python | en | code | 0 | github-code | 1 |
28752304494 |
"""
Created on Fri Dec 3 09:10:44 2021
@author: adaskin
"""
import random
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from sim_tree import generate_tree_elements,sum_of_nonzeropaths
import sklearn.datasets as datasets
import scipy.sparse
def polar2xy(r, t... | adaskin/app_with_schmidt | reduction_of_rings.py | reduction_of_rings.py | py | 2,608 | 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.