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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
1410835140 | #!/usr/bin/env python
"""
Module for parsing FASTA format files.
Usage: fasta <FILE>
"""
def open_file(filename):
"""
Opens a FASTA format file for parsing.
"""
try:
with open(filename) as f:
lines = f.readlines()
if lines[0][0] != '>':
raise IOError
except IOError:
raise IOErro... | savanto/bio | fasta.py | fasta.py | py | 3,400 | python | en | code | 0 | github-code | 1 |
24010630821 | from skimage import io, img_as_float, filters, data, color
from sklearn.decomposition import PCA
from os import listdir
from os.path import isfile, join
import pandas as pd
import numpy as np
from PIL import Image
from sklearn.linear_model import LogisticRegression
from joblib import dump, load
test_true = "test_data... | Diadochokinetic/HackBay2019 | hail_model/train_model.py | train_model.py | py | 3,583 | python | en | code | 0 | github-code | 1 |
195011804 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from collections import OrderedDict
from .. import backend as K
from ..layers.core import Layer, Merge, Siamese, SiameseHead
from six.moves import range
class Sequential(Layer):
'''
Simple linear stack of... | jem0101/BigSwag-SQA2022-AUBURN | TestOrchestrator4ML-main/resources/Data/supervised/GITLAB_REPOS/mynameisfiber@keras/keras/layers/containers.py | containers.py | py | 16,375 | python | en | code | 2 | github-code | 1 |
43165897458 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 2 20:45:19 2021
@author: ankon
"""
#%%Importing modules and the data
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from kneed import KneeLocator
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from... | Ankon1708/TSFTask-2 | Task-2 Program.py | Task-2 Program.py | py | 3,003 | python | en | code | 0 | github-code | 1 |
32118220966 | print ("************************")
print ("* Activity 6-Iteration *")
print ("************************")
name = input("Name:")
print ("Hello ",name, "!")
print ("--------------------------------")
count=0
total=0
average=0
while True:
num= input (" Enter a number:")
if num == 'done':
break
try :
... | KimTanay7/py4e | Excercise6_Iteration.py | Excercise6_Iteration.py | py | 590 | python | en | code | 0 | github-code | 1 |
11397836838 | from django.urls import path
from .views import (ShopIndexView, GroupsListView,
ProductDetailsView, ProductsListView,
OrdersListView, OrdersDetailsView,
CreateProductView, UpdateProductView,
DeleteProductView, CreateOrderView,
... | GlebSmor/skillbox | Python_Django/M_07_CBV/mysite/shopapp/urls.py | urls.py | py | 1,347 | python | en | code | 0 | github-code | 1 |
73811183074 | from django.shortcuts import render
from django.http import HttpResponse
from .models import Product,Comment,Favorite,User
import csv
import pandas as pd
import random
# Create your views here.
gender_list = ['M','W']
type_list = ['TOP','BOTTOM']
# 랜덤된 이미지를 보여준다
# 메인페이지
def index(request):
answer... | limjun92/team8_project | web/first_django/firstproject/firstapp/views.py | views.py | py | 2,495 | python | en | code | 0 | github-code | 1 |
192978086 | import asyncio
from unittest.mock import patch, MagicMock
import pytest
from httpx import AsyncClient
from tests.data_test import Activate, ItemData
class TestItems:
ITEM_DATA = ItemData.DATA_LIST
ACTIVATE_DATA = Activate.DATA_LIST
@patch('app.routers.items.orders')
@patch('app.routers.items.databas... | Vadim-AM/Async_tests | tests/v1/test_items.py | test_items.py | py | 2,640 | python | en | code | 0 | github-code | 1 |
6811634399 | import numpy as np
from utils.homography import RansacModel, make_homog, H_from_ransac
class Match(object):
def __init__(self, detector, img_left, img_right):
self.img_left = img_left
self.img_right = img_right
self.img_shape = img_left.shape
self.detector = detector
sel... | PonsletV/Structure-from-motion | Descriptors/matching.py | matching.py | py | 3,221 | python | en | code | 3 | github-code | 1 |
41004027942 | __author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "shyue@mit.edu"
__date__ = "Mar 18, 2012"
import os
import unittest
import warnings
from pymatgen.apps.borg.hive import VaspToComputedEntryDrone
from pymatgen.apps.bo... | jsyony37/pymatgen | pymatgen/apps/borg/tests/test_queen.py | test_queen.py | py | 1,076 | python | en | code | 1 | github-code | 1 |
34342014376 | with open('source', 'r') as file:
file = file.read().splitlines()
games = [(game[0], game[2]) for game in file]
points = {
'X': 1,
'Y': 2,
'Z': 3
}
tie_against = {
'A': 'X',
'B': 'Y',
'C': 'Z'
}
win_against = {
'A': 'Y',
'B': 'Z',
'C': 'X'
}
lose_against = {
'A': 'Z',... | BartekWrzalski/Advent-of-Code-2022 | Day 2 Rosk Paper Scissors/day2.py | day2.py | py | 911 | python | en | code | 0 | github-code | 1 |
14398919098 | # El objetivo del ejercicio es crear un sistema de calificaciones, como sigue:
# El usuario proporcionará un valor entre 0 y 10.
# Si está entre 9 y 10: imprimir una A
# Si está entre 8 y menor a 9: imprimir una B
# Si está entre 7 y menor a 8: imprimir una C
# Si está entre 6 y menor a 7: imprimir una D
# Si está entr... | jrfullstack/Aprendizajes-Python | 02 - Prof Ubaldo Acosta/05 - Sentencias de Control/Tarea 06 sistema de calificaciones.py | Tarea 06 sistema de calificaciones.py | py | 963 | python | es | code | 0 | github-code | 1 |
13051880080 | import argparse
import tempfile
import shutil
from utils import *
BASE_DIR = 'benchmark'
TARGET = "band/tool:band_benchmark"
DEFAULT_CONFIG = 'script/config_samples/benchmark_config.json'
def benchmark_local(debug, trace, platform, backend, build_only, config_path):
build_cmd = make_cmd(
build_only=buil... | mrsnu/band | script/run_benchmark.py | run_benchmark.py | py | 3,837 | python | en | code | 10 | github-code | 1 |
38638907219 | """
'datadir' and 'plotdir' hold the location of my data and plots which is different on different systems, so it is
modified here rather than in each script individually.
"""
import os
import numpy as np
from metpy import constants
homepath = os.path.expanduser('~/Documents/meteorology/')
datadir = homepath + 'data... | leosaffin/scripts | myscripts/__init__.py | __init__.py | py | 723 | python | en | code | 2 | github-code | 1 |
21400079972 | from django.db.models import Q, Prefetch
from django.db.models.base import ModelBase
from service.models import Orders, OrderComments
def get_choices_from_query(model: ModelBase, filter_params: dict) -> list:
"""Return choices list for select widget from model by filter"""
query = model.objects.filter(**fil... | i1gr/django_proj_ignat | service/services.py | services.py | py | 2,357 | python | en | code | 0 | github-code | 1 |
13184674712 | from faker import Faker
from kafka import KafkaProducer
from time import sleep
from random import randint
import json
from dataclasses import dataclass, asdict
from typing import List
from datetime import datetime, timedelta
fake = Faker("en_GB")
total_riders = 0
total_time = 0
@dataclass
class Rider:
name: str... | GeorgeVince/streaming_producer_consumer | producer/producer.py | producer.py | py | 2,202 | python | en | code | 0 | github-code | 1 |
18520736249 | import math
import numpy as np
import matplotlib.pyplot as plt
MTOM = 4000
MTOW = MTOM*9.81
dl = 1.15
M = 1
velocityTAS = 0
N = 2
B = 3
DL = np.arange(20, 100, 1)
r = np.sqrt(MTOM/(DL*2*math.pi))
c = 0.2358
omega = 85
def density(height):
temp = 288.15-0.0065*height
pressure = 101325*math.pow(temp/288.15,(... | kdally/hydrogen-aircraft-system-design | IterationTools/aerodynamics/DiskLoading.py | DiskLoading.py | py | 1,945 | python | en | code | 0 | github-code | 1 |
41903459117 | """Holds the model for prediction
"""
import joblib
from util import fibonacci, get_logger
import numpy as np
import pandas as pd
from finta import TA
from sklearn.neighbors import KNeighborsRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.svm import... | ckinateder/blackswan-mini | src/model.py | model.py | py | 3,149 | python | en | code | 0 | github-code | 1 |
32479719220 | import numpy as np
import torch
from numba import njit
def is_power2(num):
'checks if a number is a power of two'
return num != 0 and ((num & (num - 1)) == 0)
def fortran_reshape(x, shape, batch=True):
if batch:
return x.permute([0] + list(np.arange(1, len(x.shape))[::-1]))\
... | prs-eth/c-pic | utils/shape.py | shape.py | py | 4,630 | python | en | code | 8 | github-code | 1 |
74274047714 | def a(s):
segments = []
segment_type = None
count = 1
for i in range(1, len(s)):
if s[i] != s[i - 1]:
if segment_type is not None:
segments.append((segment_type, count))
segment_type = s[i]
count = 1
else:
count... | SanyogitaPiya/Test-Driven-Development-with-LLM | RQ1/code903.py | code903.py | py | 681 | python | en | code | 0 | github-code | 1 |
73809479712 | class Return_roi():
def __init__(self):
self.current_user = None
self.name = input("What is your name? ").title()
self.portfolio = ['dummy']
self.income = {}
self.expenses = {}
self.cashflow = []
self.roi = {}
def __str__(self):
return se... | thejenniferliu/week3ROI | week3ROI.py | week3ROI.py | py | 5,908 | python | en | code | 0 | github-code | 1 |
26484206776 | import unittest
import tempfile
import numpy
import os
from osgeo import gdal, ogr
from gdalhelpers.classes.DEM import DEM
from gdalhelpers.helpers import layer_helpers
RASTER_PATH = os.path.join(os.path.dirname(__file__), "..", "test_data", "dsm.tif")
POINTS_PATH = os.path.join(os.path.dirname(__file__), "..", "test_... | JanCaha/gdalhelpers | tests/classes/test_DEM.py | test_DEM.py | py | 4,627 | python | en | code | 0 | github-code | 1 |
16264533720 | ''' Chapter 11.28 '''
def main():
m1 = []
m2 = []
createMatrix(m1,m2)
equal(m1, m2)
# 51 22 25 6 1 4 24 54 6
# 51 25 22 6 1 4 24 54 6
def createMatrix(m1, m2):
numbers1 = input("Enter m1: ")
numbers2 = input("Enter m2: ")
elements1 = numbers1.split()
elements2 = numbers2.split()
... | JMCSci/Introduction-to-Programming-Using-Python | Chapter 11/11.28/strictlyidentical/StrictlyIdentical.py | StrictlyIdentical.py | py | 1,364 | python | en | code | 0 | github-code | 1 |
73505118755 | from signals.MovingAverageCalculator import MovingAverageCalculator
from CleanedPriceData import CleanedPriceData
class SMATradingSignal:
def __init__(self, price_map, dates, short_sma, long_sma, long_length):
self.price_map = price_map
self.dates = dates
self.short_sma = short_sma
... | joedangel/quant | SMATradingSignal.py | SMATradingSignal.py | py | 2,686 | python | en | code | 0 | github-code | 1 |
13942092637 | from math import floor
from PIL import ImageFont, Image, ImageDraw
from io import BytesIO
import datetime
def AutoFont(font: ImageFont.FreeTypeFont, text: str, max_width: int,*, check) -> ImageFont.FreeTypeFont:
if isinstance(font, tuple):
font = ImageFont.truetype(*font)
while check(font.getsize(tex... | BooAngeldust/test_ | src/libs/utils.py | utils.py | py | 3,054 | python | en | code | 0 | github-code | 1 |
13492421383 | #in this program we are using text fields to handle the inputs
from tkinter import *
root = Tk()
inp = Entry(root, width = 50)
inp.pack()
inp.insert(0,"Enter your year of brith : ")
def click():
out = "You are " + str(2020-int(inp.get())) + " years old."
label = Label(root,text=out)
label.pack()
myButton = Butt... | Gupta-sparsh/tkinter | Input Fields.py | Input Fields.py | py | 420 | python | en | code | 0 | github-code | 1 |
28686055264 |
from math import inf
class Graph:
def __init__(self, arr):
self.data = arr
self.num_nodes = len(self.data)
def bellman(self, start):
dist = [inf] * self.num_nodes
dist[start] = 0
for i in range(self.num_nodes-1):
for edge in ... | Kunvuthi/pythonlearningprojects | Python Projects/Algorithms/Path finding Algorithms/bellman_ford_algorithm_SPSP.py | bellman_ford_algorithm_SPSP.py | py | 1,421 | python | en | code | 1 | github-code | 1 |
35315377250 | import os
import math
import numpy as np
import pandas as pd
from glob import glob
from datetime import datetime as dt, timedelta
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import Dense, Activation, LSTM
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
... | TISKYIT/e_power_pred | pred_app/demand_pred.py | demand_pred.py | py | 3,313 | python | en | code | 0 | github-code | 1 |
36816273599 | from django.shortcuts import render
from django.http import HttpResponse
from json import dumps
from django.forms.models import model_to_dict
from models1.models import User
from django.core import serializers
from django.views.decorators.csrf import csrf_exempt
# Create your views here.
def get_user(request):
res... | rheno/Django-CRUID-to-JSON | models1/views.py | views.py | py | 3,682 | python | en | code | 0 | github-code | 1 |
897857612 | # Use FastbinAttack to control a fd pointer
# Alloc a chunk to make a fake chunklist
# Use fake chunklist to falsify *(struct IO_FILE*)stdout and make a new vtable
from pwn import *
context.os='linux'
context.arch='amd64'
r=process('./blind')
def new(index,content):
r.sendlineafter('Choice:','1')
r.sendlineafter('I... | Cossack9989/SEC_LEARNING | PWN/2018WangDing/2018WangDing-1/pwn1_blind/exp1.py | exp1.py | py | 1,307 | python | en | code | 13 | github-code | 1 |
11140863904 | import pytest
from flask import Flask
from flask.testing import FlaskClient
from unittest.mock import patch
from app import app
@pytest.fixture
def client() -> FlaskClient:
app.config["TESTING"] = True
with app.test_client() as client:
yield client
def test_chatbot(client: FlaskClient):
with patc... | TemitayoAfolabi/ChatBot | test.py | test.py | py | 1,050 | python | en | code | 0 | github-code | 1 |
9934181014 | class game:
def __init__(self, rc_num):
self.rc_num = rc_num
self.resource = dict() # 사용하는 리소스
self.card = dict() # card 에 대한 정보
self.player = [0] * 500001
def get_resource_owner(self, rn):
if rn not in self.resource:
return -1
return self.resource.... | cdog-gh/gh_coding_test | 1/5/random_generator/game.py | game.py | py | 1,495 | python | en | code | 33 | github-code | 1 |
12168433142 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | AppImageX/standards | source/conf.py | conf.py | py | 3,414 | python | en | code | 1 | github-code | 1 |
17905113695 | #Kickstart 2020 round E
def longest_arithmetic(arr):
nmax = 2
ind = 1
while ind < len(arr) - 1:
n = 2
while ind < len(arr) - 1 and (arr[ind] - arr[ind - 1]) == (arr[ind+1] - arr[ind]):
n += 1
ind += 1
nmax = max(n,nmax)
ind += 1
return nmax
a... | vijaygirish2001/Interview_prep_algo_ds_Python | Google competition/q1.py | q1.py | py | 3,576 | python | en | code | 0 | github-code | 1 |
41466021992 | '''
File Name: add_delete.py
Made By: Steven Kerr
Date: 08/09 Apr 2015
Purpose: Add new question to list - delete question from list
FILES REQUIRED: user_choice.py
'''
import time
from userChoice import *
#ADDING QUESTION
'''
get question, check for \n, \t, etc, remove it add \t, add to new question
variable, get 4 ch... | stevenkerr/quiz | Add_and_Delete_Line.py | Add_and_Delete_Line.py | py | 3,680 | python | en | code | 1 | github-code | 1 |
30643387941 | from .verificationError import *
from snappy.snap import t3mlite as t3m
from sage.all import vector, matrix, prod, exp, RealDoubleField, sqrt
import sage.all
__all__ = ['HyperbolicStructure']
class HyperbolicStructure:
def __init__(self, mcomplex, edge_lengths,
exact_edges = None, var_edges = N... | ekim1919/SnapPy | dev/vericlosed/hyperbolicStructure.py | hyperbolicStructure.py | py | 10,619 | python | en | code | null | github-code | 1 |
32869459782 | import json
from textwrap import dedent
import pendulum
from airflow import DAG
from airflow.operators.python import PythonOperator
with DAG(
'dh_print_dag_sample',
# [START default_args]
# These args will get passed on to each operator
# You can override them on a per-task basis during operator initi... | DennisHsu/AirFlow-dh-practice | printDag.py | printDag.py | py | 1,681 | python | en | code | 1 | github-code | 1 |
29668671915 | """
Knowledge-based Decision Support Systems
Natural Language Processing Basics 1
"""
from nltk import tokenize
from nltk import tag
from nltk import chunk
from nltk.stem import PorterStemmer, WordNetLemmatizer
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from nltk imp... | tschibu/hslu-kbds-exercises | SW03_Natural_Language_Processing_Basics_1/NLP.py | NLP.py | py | 4,058 | python | en | code | 0 | github-code | 1 |
2619331181 | from typing import Callable, Optional
from game_agent import GameAgent
from enum import Enum
class TurnContext:
def __init__(self, turn: int, game_manager, current_player: GameAgent, non_current_player: GameAgent, battle_gui):
self.turn = turn
self._game_manager = game_manager
self.current... | jgbakke/Sorcery | turn_context.py | turn_context.py | py | 1,715 | python | en | code | 0 | github-code | 1 |
27662251925 | # coding: utf-8
import re
from utils import url2filetype
from .base import BaseParser
__all__ = [
'PagesParser',
]
class PagesParser(BaseParser):
def parse(self):
file_type = url2filetype(self.article.url)
if not file_type:
return {'urls':[]}
pages = set([self.article.url])
prefix = self.article.url[:-... | endsh/haoku-open | kread/read/html/article1/pages.py | pages.py | py | 792 | python | en | code | 6 | github-code | 1 |
18334711904 | _map_axis_values = {
-11: -3,
-9: -3,
-7: -2,
-5: -2,
-3: -1,
-1: -1,
1: 1,
3: 1,
5: 2,
7: 2,
9: 3,
11: 3,
}
class Learner:
def __init__(self, id, lower_time, upper_time, active_reflexive, sensory_intuitive, visual_verbal, sequential_global, learning_goals):
... | martinsadw/evolutionary-computation | acs/learner.py | learner.py | py | 2,150 | python | en | code | 4 | github-code | 1 |
16438700374 | import sys
sys.stdin=open('input.txt','r')
def bt(ans,cnt,j):
if ans<cnt:ans=cnt
for i in L[j]:
if i not in V:
V.add(i);cnt+=1
ans=bt(ans,cnt,i)
V.remove(i);cnt-=1
return ans
for t in range(1,int(input())+1):
n,m=map(int,input().split())
L=[[]for _ in'a'*... | ttppggnnss/CodingNote | 2003/0317/swea 2814 최장경로.py | swea 2814 최장경로.py | py | 611 | python | en | code | 0 | github-code | 1 |
70342576994 | import numpy
from numpy import *
class Parameters:
def __init__(self):
super(Parameters, self).__init__()
self.stim_training_length = None
self.threshold_imp = None
self.threshold_frequency = None
self.threshold_amplitude = None
self.muscle = None
self.muscl... | s2mLab/Ergocycle | source/Parameters.py | Parameters.py | py | 17,319 | python | en | code | 0 | github-code | 1 |
8917837143 | import random
import globals
class Classes():
# ---- Ranged ---- #
global MainStatMage
MainStatMage = 'Intellect'
global ResourceMage
ResourceMage = 'Mana'
global trait1Mage
trait1Mage = 1
global trait1descriptionMage
trait1descriptionMage = '[' + str(trait1Mage) + '%] chance when y... | TristanAnglin/Dungeon-Crawler | Dungeon Crawler-1/classes.py | classes.py | py | 8,871 | python | en | code | 0 | github-code | 1 |
20380333160 | import time
import logging
import argparse
import curses
import operator
import numpy
from cv2 import VideoCapture
from networktables import NetworkTables
from grip import GripPipeline
URL = 'http://raspberrypi.local:1180/?action=stream'
TEAM_NUMBER = 3863
NT_SERVER = 'roboRIO-%s-FRC.local' % (TEAM_NUMBER)
NT_TABLE_N... | Pantherbotics/RobotVision | main.py | main.py | py | 5,224 | python | en | code | 0 | github-code | 1 |
671095898 | from keras.models import Model
from keras.optimizers import SGD,Adam
from keras.layers import Input, Dense, Dropout, Flatten
from keras.layers.convolutional import Convolution1D, MaxPooling1D
def model(filter_kernels, dense_outputs, maxlen, vocab_size, nb_filter, mode='1mse', cat_output=1, optimizer='adam'):
prin... | snikolenko/char-level | crepe/py_crepe.py | py_crepe.py | py | 2,977 | python | en | code | 0 | github-code | 1 |
1589566811 | """database_migrations
Revision ID: a7e31f3a9fe3
Revises:
Create Date: 2023-01-27 00:27:04.392742
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a7e31f3a9fe3'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands aut... | MbxrAteeq/ToDo-App | alembic/versions/a7e31f3a9fe3_database_migrations.py | a7e31f3a9fe3_database_migrations.py | py | 2,212 | python | en | code | 0 | github-code | 1 |
13356105805 | class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
self.alphabet = order
if words == sorted(words, key=self.alien_sort):
return True
else:
return False
def alien_sort(self, word):
result = []
for letter in word:
... | Biruk-Tassew/Competitive_programming | 953-verifying-an-alien-dictionary/953-verifying-an-alien-dictionary.py | 953-verifying-an-alien-dictionary.py | py | 389 | python | en | code | 0 | github-code | 1 |
20390686972 | import random
import numpy as np
import torch
from torch.backends import cudnn
# Random seed to maintain reproducible results
random.seed(0)
torch.manual_seed(0)
np.random.seed(0)
# Use GPU for training by default
device = torch.device("cuda") if torch.cuda.is_available() else "cpu"
# Turning on when the image size d... | HeGuannan-duludulu/IRSRGAN | irsrgan_config.py | irsrgan_config.py | py | 2,789 | python | en | code | 0 | github-code | 1 |
15708518703 | def is_haiku(input_string):
"""
Checks if input_string follows the syllabic and line structure of a haiku and outputs True if so.
:param input_string: A string
:return: True or False
"""
split_lines = input_string.split("/")
if len(split_lines) == 3:
line_1 = split_lines[0]
... | casuallysentient/lab_07 | haiku.py | haiku.py | py | 2,121 | python | en | code | 0 | github-code | 1 |
16004047484 | # /nlp/preprocess.py
import nltk
import sys
import os
lib_directory = os.path.dirname(__file__)
print(lib_directory)
nltk.data.path.append(lib_directory + "/lib/corpora/")
# from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
import re
import numpy as np
import sys
INVALID_STRING = 'Er... | text-ninja/text-ninja | nlp/preprocess.py | preprocess.py | py | 2,918 | python | en | code | 0 | github-code | 1 |
23807172670 | from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
from cart.models import ShoppingCart
from goods.models import Goods
def add_cart(request):
if request.method == 'POST':
# 接受商品和数量和价格
# 组装成存储商品的格式[goods_id,num,is_select]
# 组装多个商品... | lorrybz/fresh_shop_everyday | fresh_shop/cart/views.py | views.py | py | 6,155 | python | en | code | 1 | github-code | 1 |
19136450354 | from bs4 import BeautifulSoup as BS
import re
from requests import get
def soupify_url(url):
request = request_url(url)
return BS(request.text,'html.parser')
def request_url_text(url):
return request_url(url).text
def request_url(url):
return get(url, timeout=60.0)
def json_url(url):
request = r... | patsmad/BMTTools | utils/url_tools.py | url_tools.py | py | 1,807 | python | en | code | 0 | github-code | 1 |
30546496925 | '''The script will implement a Bloom filter.
Bloom filter will be loaded with values from rockyou.txt.
The software will automate the testing of values in test.txt.
The software will calculate and display statistics on true positive, true negative, false positive, and false negative for the test.txt based on the rockyo... | saminoorsyed/cyber_security | week3/programmingProject2/bloom_filter.py | bloom_filter.py | py | 7,989 | python | en | code | 0 | github-code | 1 |
15894564483 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# file: ppc_eprv3.py
# Dependencies
from model_rvrd_kepler import lnlike, lnprior, preprocess
import config
import numpy as np
import time
import datetime
import argparse
import pickle
import subprocess
import pdb
import os
# PolyChord imports
import PyPolyChord as PPC
fr... | nicochunger/RV_NestedSampling | src/real_data/ppc_harps.py | ppc_harps.py | py | 6,138 | python | en | code | 1 | github-code | 1 |
40033177433 | # -*-coding: utf-8 -*-
# Python 3.6
# Author:Zhang Haitao
# Email:13163385579@163.com
# TIME:2018-05-10 10:15
# NAME:zht-test.py
import pandas as pd
import pandas_profiling as pp
import numpy as np
if __name__ == '__main__':
path=r'e:\a\Meteorite_Landings.csv'
df=pd.read_csv(path,parse_dates=['year'],encod... | luilui163/zht | learning_python/pandas_profiling/test.py | test.py | py | 851 | python | en | code | 0 | github-code | 1 |
29825633413 | import re
import json
w = open("dic.txt", "w")
problem = []
index = 1
with open("fit.txt", "r") as f:
dic_list = []
dic = {}
pivot = None
for line in f.readlines():
new_line = re.sub(r'(?is)\[\[',' ',line)
new_line = re.sub(r'(?is)\]\]',' ',new_line)
new_line = re.sub(r'\]', ... | JishnuRamesh/MonashUnitGuideDataFetcher | test.py | test.py | py | 8,720 | python | en | code | 0 | github-code | 1 |
34842074530 | # Basic Calculator: https://leetcode.com/problems/basic-calculator/
# Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.
# Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, suc... | KevinKnott/Coding-Review | Month 01/Week 03/Day 01/a.py | a.py | py | 2,962 | python | en | code | 0 | github-code | 1 |
30146488541 | #!/usr/bin/env python
# -*- coding: utf-8 *-*
import enum
import inspect
class Direction(enum.IntEnum):
NONE = 5
NW = 1
N = 2
NE = 3
E = 6
SE = 9
S = 8
SW = 7
W = 4
def dist_steps(pos1, pos2):
(x1, y1) = pos1
(x2, y2) = pos2
return max(abs(x1 - x2), abs(y1 - y2))
def which_way(pos, goal):
(x, y) = p... | r41d/pyants | ai.py | ai.py | py | 5,658 | python | en | code | 0 | github-code | 1 |
10193343514 | import tensorflow as tf
#import tensorflow.keras.layers as L
class BahdanauAttention(tf.keras.layers.Layer):
def __init__(self, units):
super(BahdanauAttention, self).__init__()
self.W1 = tf.keras.layers.Dense(units)
self.W2 = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
def cal... | Shahraizz/NMT-PSL | NMT_PSL/RNNAttentionLayers.py | RNNAttentionLayers.py | py | 4,093 | python | en | code | 0 | github-code | 1 |
23033488402 | #!/usr/bin/env python2
import sys
import os
import capnp
from madara.knowledge import *
geo = capnp.load(os.environ["MADARA_ROOT"] + "/tests/capnfiles/Geo.capnp")
Any.register_int32("i32");
Any.register_class("Point", geo.Point)
Any.register_class("Pose", geo.Pose)
a = Any("i32")
a.assign(10);
print(a.to_integer(... | sawtoothgeek/madara | port/python/tests/test_any.py | test_any.py | py | 838 | python | en | code | null | github-code | 1 |
40010355396 | # Given a reference of a node in a connected undirected graph.
# Return a deep copy (clone) of the graph.
import collections
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
def cloneGraph(node):
if not node:
... | wyy1234567/leetcode_problems | graph.py | graph.py | py | 725 | python | en | code | 0 | github-code | 1 |
74830227553 | import os
import cv2
import torch
from nets.model import Model
from nets.yoloModel import YoloModel
from nets.yolo_loss import YOLOLoss
from utils import non_max_suppression
import numpy as np
os.environ["CUDA_VISIBLE_DEVICES"] = '0'
batch_size = 1
w, h = (416, 416)
# w, h = (640, 640)
anchors = [[10, 13], [16, 30], [... | lin001126/Hand-written-yolov3 | test.py | test.py | py | 4,234 | python | en | code | 0 | github-code | 1 |
18420474569 | from cv2 import cv2
from pyzbar.pyzbar import decode
import time
cap = cv2.VideoCapture(0)
received_data = []
time_start = time.time()
while True:
_, frame = cap.read()
time_now = time.time()
if time_now > time_start+60:
if received_data == []:
break
time_st... | tirodkar79/QR-Scanner | qr_scanner.py | qr_scanner.py | py | 665 | python | en | code | 0 | github-code | 1 |
6846867931 | # -*- encoding: utf-8 -*-
import cv2
import numpy as np
import scipy.interpolate
class Histogram1D :
def __init__(self) :
self.histSize = [256,]
self.hranges = [0.0, 256.0]
self.ranges = self.hranges
self.channels = list(range(1))
def getHistogram(self, image) :
if i... | tulare/smile-in-the-light | processors/utils.py | utils.py | py | 4,868 | python | en | code | 1 | github-code | 1 |
14965145273 | """my_controller_001 controller."""
# You may need to import some classes of the controller module. Ex:
# from controller import Robot, Motor, DistanceSensor
from deepbots.supervisor.controllers.robot_supervisor import RobotSupervisor
from utilities import normalizeToRange, plotData
from PPO_agent import PPOAgent, Tr... | LuranWang/hexapod-robot | my_controller_001.py | my_controller_001.py | py | 6,067 | python | en | code | 0 | github-code | 1 |
38275092786 | '''
Search contents of a provided file
'''
fname = input('Enter file name:')
fterm = input('Enter search term:')
try:
fhand = open(fname)
except:
print(f'File {fname} cannot be opened')
exit()
count = 0
for line in fhand:
if line.startswith(fterm): # or whatever
count += 1
print(f'{count} li... | tcu93/py4e_exercises | file_searcher2.py | file_searcher2.py | py | 347 | python | en | code | 0 | github-code | 1 |
31469791084 | from collections import deque,defaultdict
import heapq
class Graph:
def __init__(self,V):
self.graph = defaultdict(set)
self.V = V
def add_edge(self,u,v,weight=1,directed = True):
self.graph[u].add((v,weight))
if not directed:
self.graph[v].add((u,weight))
def bfs(self,start):
visited = [False for _ i... | Ravi-Maurya/Competitive_Programming | Basics/Graph.py | Graph.py | py | 2,430 | python | en | code | 1 | github-code | 1 |
15834327489 | import argparse
from .movements import NaoMover
from .utils import read_config
if __name__ == "__main__":
cfg = read_config()
parser = argparse.ArgumentParser()
parser.add_argument('yaw', type=float)
parser.add_argument('pitch', type=float)
parser.add_argument('speed', type=float, nargs='?', def... | ltskv/kick-it | pykick/setangles.py | setangles.py | py | 467 | python | en | code | 1 | github-code | 1 |
4623128227 | from .api import session
class Repo:
def __init__(self, github_data):
self.data = github_data
self.full_name = self.data["full_name"]
self.html_url = self.data["html_url"]
self.avatar_url = self.data["owner"]["avatar_url"]
self.private = self.data["private"]
self.fo... | dropseed/github-traffic-report | github_traffic_report/repos.py | repos.py | py | 2,451 | python | en | code | 2 | github-code | 1 |
42467786060 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import base64
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import pandas as pd
import numpy as np
from datetime import datetime
from elasticsearch import Elasticsearch
from PIL import Image
from io import BytesIO
# In[2]:
es = Elasticsearch([{'ho... | cristianpazos9/Cristian_Manex_Reto07 | indexar_imagenes_reconocimiento.py | indexar_imagenes_reconocimiento.py | py | 4,345 | python | en | code | 0 | github-code | 1 |
30107513035 | from django.contrib import admin
from django.utils.html import format_html
from Bot.bot import bot
from Bot.models import TelegramUser
from WalletTransition.WalletRequest import cancel_buy_transition, cancel_sell_transition
from SiteSetting.SiteSettingRequest import point_fee
from WalletTransition.models import Transi... | MasoudHeidary/django-telegram-bot-trade | Point/admin.py | admin.py | py | 5,665 | python | fa | code | 0 | github-code | 1 |
8266803345 | from PIL import Image
import dither
img = Image.open("kittensmall.png")
dither.floydDither(img,((0,0,0),(255,255,255)))
w = img.width
h = img.height
w += (w%2)
if h%3 != 0: h += (3-h%3)
print(w,h)
nimg = Image.new('RGB',(w,h),color=(255,255,255))
nimg.paste(img)
img = nimg.copy()
del nimg
grid = ... | matcool/random-scripts | imgtobraille.py | imgtobraille.py | py | 1,036 | python | en | code | 1 | github-code | 1 |
26106552391 | import hashlib
from sha1 import sha1
test_messages = ['abc', 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', 'hello world', '😎😎😎😎']
print(f'My SHA-1 {" " * 31} | Builtin SHA-1{" " * 27} | Message')
for msg in test_messages:
my_hash = sha1(msg)
builtin_hash = hashlib.sha1(msg.encode())... | VladMosiychuk/dlabs | lab_03/main.py | main.py | py | 382 | python | en | code | 0 | github-code | 1 |
18772000988 | import json
from wsgiref.simple_server import make_server
import json
def home_view():
with open('wsgi/tmp.json', 'r', encoding='utf-8') as json_data:
data = json_data.read()
parsed_data = json.loads(data)
print(parsed_data)
text = json.dumps(parsed_data)
print(text)
... | MyodsOnline/python_files | Work/kuznecov_a/Lessons/server.py | server.py | py | 1,295 | python | en | code | 0 | github-code | 1 |
34013524854 | '''
Option 1: Cyclic Sort
Option 2: XOR Elements
- XOR all elements together
- Then XOR result with elements 0 to n
- Result will be missing Number
'''
# Option 1: Cyclic Sort
'''
class Solution:
def missingNumber(self, nums: List[int]) -> int:
i = 0
while i < len(nums):
to... | kjingers/Leetcode | Problems/MissingNumber/MissingNumber.py | MissingNumber.py | py | 960 | python | en | code | 0 | github-code | 1 |
19399647925 | from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QTextEdit
class Editor(QTextEdit):
def __init__(self, file, parent=None):
super(Editor, self).__init__(parent)
self.file = file
self.setReadOnly(True)
text = open(self.file).read()
self.setText(text)
layout_... | ovidiupop/drive_indexer | mymodules/EditorWidget.py | EditorWidget.py | py | 445 | python | en | code | 0 | github-code | 1 |
34539016350 | import librosa
import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
from sklearn.metrics import accuracy_score, confusion_matrix
import seaborn as sns
import pandas as pd
from sklearn.decomposition import PCA
from scipy.signal import hamming
import scipy.signal.windows
def segment_vowel_silence(audio... | YukiTinNguyen/XLTHS | Bai2Trinh.py | Bai2Trinh.py | py | 10,259 | python | vi | code | 0 | github-code | 1 |
39117183843 | #####################################################################
#
# CAS CS 320, Spring 2015
# Midterm (skeleton code)
# interpret.py
# Aleksander Skjoelsvik
#
# ****************************************************************
# *************** Modify this file for Problem #2. ***************
# ****************... | alekplay/schoolwork | CS320/midterm/interpret.py | interpret.py | py | 2,984 | python | en | code | 0 | github-code | 1 |
36343107979 | # -*- coding: utf-8 -*-
# 从扑克牌中随机抽5张牌,判断是不是一个顺子,即这5张牌是不是连续的。
# 2~10为数字本身,A为1,J为11,Q为12,K为13,而大、小王为 0 ,可以看成任意数字。A 不能视为 14。
A = 1
J = 11
Q = 12
K = 13
i = 0
j = 0
k = 0
nums = [11, 0, 9, 0, 0]
for a in range(0, len(nums)):
if nums[a] == 'A':
nums[a] = A
elif nums[a] == 'J':
nums[a] = j
elif n... | Liabaer/Test | learn_algorithm/leetcode/is_straight.py | is_straight.py | py | 998 | python | ko | code | 0 | github-code | 1 |
19416019270 | # Time complexity - O(n log(n) + m log(m))
def smallestDifference(arrayOne: list, arrayTwo: list):
arrayOne.sort()
arrayTwo.sort()
idxOne = 0
idxTwo = 0
smallest = float("inf")
current = float("inf")
smallestPair = []
while idxOne < len(arrayOne) and idxTwo < len(arrayTwo):
fi... | shashilsravan/Programming | Programs/Smallest difference.py | Smallest difference.py | py | 810 | python | en | code | 0 | github-code | 1 |
11749355278 | from kivy.app import App
from kivy.core.window import Window
from kivy.uix.screenmanager import Screen, SlideTransition
class Options(Screen):
def detect(self):
Window.size=(800,600)
print("Emotion Detection")
self.manager.transition = SlideTransition(direction="right")
self.... | lordbeerus0505/EmotionDetection | Options.py | Options.py | py | 768 | python | en | code | 0 | github-code | 1 |
911740610 | from django.http import HttpResponse
from django.shortcuts import render,redirect
import requests
import urllib.parse
# Create your views here.
def home(request):
if 'username' in request.session:
return render(request,'home.html')
else:
return redirect(login)
def login(request):
if request... | nitsuh21/clienttest | home/views.py | views.py | py | 5,633 | python | en | code | 0 | github-code | 1 |
16558036935 | # https://www.hackerrank.com/contests/kakao-adtech-devday-1st-codejam/challenges/2022-12
# Solved Date: 22.04.14.
import sys
from collections import Counter
read = sys.stdin.readline
def calc_value(bid_floor, prices):
sum_price = 0
for price in prices:
if price < bid_floor:
continue
... | imn00133/algorithm | kakaoJam/3.optimize_bidfloor.py | 3.optimize_bidfloor.py | py | 1,129 | python | en | code | 0 | github-code | 1 |
8092163165 | # Импортируем модуль для работы с win32api
import win32api
# Импортируем модуль для работы с pyqt5
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QPainter, QBrush
from PyQt5.QtCore import Qt, QThread
# Создаем класс для виджета с цветом
class ColorWidget(QWidget):
# Конструкто... | AkiraShiro/Color-with-system-language | main.py | main.py | py | 3,907 | python | ru | code | 0 | github-code | 1 |
40046474103 | #-*-coding: utf-8 -*-
#@author:tyhj
from Tkinter import *
root = Tk()
cv = Canvas(root, bg='white', width=500, height=650)
rt = cv.create_rectangle(10, 10, 110, 110, outline='red', stipple='gray12', fill='green')
imgs = [PhotoImage(file='c:\\' + str(i) + '.gif') for i in range(1,3)]
for img in imgs:
cv.create_im... | luilui163/zht | py27/zht/study/tkinter/demo/image.py | image.py | py | 393 | python | en | code | 0 | github-code | 1 |
5089361721 | import cv2
from PIL import Image
import easyocr
import numpy as np
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import aiocv
import matplotlib.pyplot as plt
# creating list
# creating numpy array
# path=_file_.split("\\")
# path.append("haarcascades")
# path=... | monalisa22/Smart_Pillars | ANPR.py | ANPR.py | py | 1,922 | python | en | code | 0 | github-code | 1 |
71730049634 | from decimal import Decimal, InvalidOperation
from math import isinf
from pathlib import Path
from hyprfire_app.exceptions import TimestampException
MAX_TIMESTAMP = 32503680000
def validate_file_path(file_path):
"""
validate_file_path
A file path is valid if it points to an existing file
Parameter... | kshannoninnes/hyprfire | hyprfire_app/utils/validation.py | validation.py | py | 1,558 | python | en | code | 0 | github-code | 1 |
13342367800 |
import sys
import numpy as np
from basic.common import checkToSkip, printStatus, makedirsforfile
INFO = __file__
def process(options, inputfile, resultfile):
assert(inputfile.endswith('.pkl'))
#resultfile = inputfile[:-4] + '_rank.pkl'
if checkToSkip(resultfile, options.overwrite):
return 0... | li-xirong/jingwei | instance_based/tagrel_to_concept_rank.py | tagrel_to_concept_rank.py | py | 1,938 | python | en | code | 48 | github-code | 1 |
36706943936 | from TGP_compute import amuon_uncertainty
from TGP_compute import alpha_uncertainty
import numpy as np
Mmuon = 105.6583755e-3 #Mass muon = 105.6583755 ± 0.0000023 MeV
Mz = 91.1876 #Mass Z = 91.1876 ± 0.0021 GeV
Mpion = 139.57039e-3 #Mass pion = 139.57039 ± 0.00018 MeV
alpha = 1/137.035999084 #fine-structure constant: ... | qiao688/TGP_for_g-2 | Cov_with_TGP.py | Cov_with_TGP.py | py | 919 | python | en | code | 0 | github-code | 1 |
14760552115 | import sys
from pathlib import Path
import numpy as np
import pandas as pd
from loguru import logger
import matplotlib.pyplot as plt
from catboost import Pool
from satio.utils.logs import proclogs
from worldcereal.utils.spark import get_spark_context
from worldcereal.utils.training import get_pixel_data
from worldcer... | WorldCereal/worldcereal-classification | src/worldcereal/train/worldcerealpixelcatboost_realms.py | worldcerealpixelcatboost_realms.py | py | 13,657 | python | en | code | 12 | github-code | 1 |
69821012834 | import numpy as np
import onnx_script
def gen_composites_loop(n):
gb = onnx_script.GraphBuilder('gen_sieve')
iter = gb.input('composites_iter', 0)
cond = gb.input('composites_cond', True)
# To workaround ONNX's restriction for Loop. The number of inputs
# must be greater than 2.
dummy = gb.inp... | shinh/test | onnx_gen_sieve.py | onnx_gen_sieve.py | py | 2,204 | python | en | code | 25 | github-code | 1 |
11211769615 | def total(basket):
price = 800
discount = {
2: 5,
3: 10,
4: 20,
5: 25
}
# Make group of books
groups = list()
while basket:
books = list()
for book in set(basket):
books.append(book)
basket.pop(basket.index(book))
g... | stimpie007/exercism | python/book-store/book_store.py | book_store.py | py | 672 | python | en | code | 0 | github-code | 1 |
29865512662 | import torch
import tensorflow
from pytorch_pretrained_bert import BertTokenizer, BertModel, BertForMaskedLM
import os
import wget
import pandas as pd
from transformers import BertTokenizer
from sklearn.model_selection import train_test_split
# If there's a GPU available...
if torch.cuda.is_available():
# Tell... | joeljang/haaforchallenge2019 | evaluate.py | evaluate.py | py | 2,382 | python | en | code | 0 | github-code | 1 |
415355000 | # pylint: disable=too-many-lines
import abc
import os
import sys
import argparse
import logging
from urllib.parse import urlparse
from typing import Optional, Dict, Any, Type
import fsspec
from jinja2 import Template
from dae.import_tools.import_tools import MakefilePartitionHelper, \
construct_import_annotation... | iossifovlab/gpf | impala_storage/impala_storage/schema1/import_commons.py | import_commons.py | py | 36,738 | python | en | code | 1 | github-code | 1 |
31708657528 | ''' Luigi Poker - Python Version
This version of Luigi Poker should be used
to be used in Discord Red.
'''
import discord
from random import randint
from discord.ext import commands
class Card:
def __init__(self):
self.__number = randint(1,6)
self.__suit = self.__suit()
def __suit(s... | themario30/MyPersonalCogs | LuigiPoker/LuigiPoker.py | LuigiPoker.py | py | 13,688 | python | en | code | 0 | github-code | 1 |
31512597056 | def image_parse(match, model):
try:
image = model.image_set.get(shortuuid=match.group('shortuuid'))
except model.image_set.model.DoesNotExist:
image = None
return image
def image_sub(content, repl):
import re
IMAGE_RE = r'\[image (?P<shortuuid>[a-z\d]+)\]'
return re.sub(IMAG... | megaprojectske/megaprojects.co.ke-archive | megaprojects/core/utils.py | utils.py | py | 1,537 | python | en | code | 0 | github-code | 1 |
73771882595 | import os
import json
class CompitiObject:
"""
descrizione obj compiti
"datGiorno", "desMateria", "done", "desCompiti, "datCompiti", "id"
"""
daTenere=["datGiorno" ,"desMateria", "desCompiti" ,"datCompiti", "id"]
def __init__(self,fs,fh):
self.fs=fs
self.fh=fh
content=... | giospada/ScaricaCompiti | src/CompitiObject.py | CompitiObject.py | py | 916 | python | en | code | 0 | github-code | 1 |
38889833201 | import cv2
import mediapipe as mp
import math
class HandDetector:
"""
Finds Hands using the mediapipe library. Exports the landmarks
in pixel format. Adds extra functionalities like finding how
many fingers are up or the distance between two fingers. Also
provides bounding box info of th... | lironfarzam/Gestures-IO | branch_main/hand_tracking_module.py | hand_tracking_module.py | py | 10,960 | python | en | code | 0 | github-code | 1 |
17338841793 | import unittest
import unittest
import numpy as np
from hmm.logprob import LogProb, ZERO
from hmm.fwd_bwd import fwd, bwd, infer
from hmm.tests.left_right_hmm import HMM
class FwdBwdTest(unittest.TestCase):
@classmethod
def dp2path(cls, dp):
(T, N) = dp.shape
path = []
for t in rang... | dkohlsdorf/hidden_markov_models | hmm/tests/test_fwd_bwd.py | test_fwd_bwd.py | py | 1,127 | python | en | code | 1 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.