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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
14289022638 | from copy import deepcopy
import numpy as np
def mark_points_in_diagram(coordinates: list[tuple],
diagram: np.ndarray,
consider_diagonal: bool = False):
all_points = deepcopy(coordinates)
x1, y1 = coordinates[0]
x2, y2 = coordinates[1]
# conform to artificial rule of x1 >= x2 for simpler c... | SinanTang/adventofcode | 2021/day5/day5.py | day5.py | py | 2,207 | python | en | code | 0 | github-code | 36 |
71713005863 | import requests
class ApiBaseActions:
def __init__(self, base_url):
if base_url.endswith("/"):
self.base_url = base_url
else:
self.base_url = base_url + "/"
self.session = requests.Session()
def make_request(self, method: str, route_url: str = None, **kwargs):
... | HarshDevSingh/python-behave | api/api_base.py | api_base.py | py | 906 | python | en | code | 0 | github-code | 36 |
14159899947 | from seqeval.metrics import classification_report
from seqeval.metrics import f1_score
from typing import List
import os
# the order for evaluating the script is in the main function
def create_fake_conll_form_without_iob_to_emNER_input():
"""tokenized sentences for emNER
input: iob format"""
with open("... | huspacy/huspacy-resources | scripts/benchmark/emNER_eval.py | emNER_eval.py | py | 3,617 | python | en | code | 0 | github-code | 36 |
12118485844 | """Training a Transformer Builder model to be used for adversarial attacks."""
import argparse
import random
from functools import partial
from typing import Dict
import numpy as np
import torch
from sklearn.metrics import precision_recall_fscore_support, confusion_matrix
from torch.utils.data.sampler import BatchSamp... | copenlu/fever-adversarial-attacks | builders/train_transformer.py | train_transformer.py | py | 8,288 | python | en | code | 11 | github-code | 36 |
30942866367 | from rest_framework import serializers
from .models import Product, Ingredient
class IngredientSerializer(serializers.ModelSerializer):
class Meta:
model = Ingredient
fields = ('title', 'price')
class ProductSerializer(serializers.ModelSerializer):
ingredients = IngredientSerializer(read_onl... | Dawid-Dahl/stereo-nightclub-api | api/serializers.py | serializers.py | py | 495 | python | en | code | 0 | github-code | 36 |
17952996407 | """
following file contains example commands used to use the library
it is focused on airfoil design, which uses parameteric definitions of airfoils and runs optimization procedures
"""
# 1. will build the airfoil using the cst parametric definition
# 1.1. define some arbitrary parameters for cst, as vectors P and Q:
P... | Witekklim/propellerDesign | example_runs.py | example_runs.py | py | 3,608 | python | en | code | 1 | github-code | 36 |
10691268780 | import sqlite3 as sql
from sqlite3 import OperationalError
from pythonobjet.exo1_formesgeometriques.point.Point import Point
class PointDao:
"""Ma classe"""
def __init__(self):
pass
def initialisation(self):
connecteur = sql.connect("donnee.db")
curseur = connecteur.cursor()
... | silvaplana/pythontraining | pythonobjet/exo1_formesgeometriques/point/PointDao.py | PointDao.py | py | 1,627 | python | fr | code | 0 | github-code | 36 |
451100359 | #!/usr/bin/python3
from __future__ import division
from core.class_utils import MalwareUrl
from core.config_utils import get_base_config
from datetime import datetime, timedelta
from core.dns_utils import resolve_dns
from core.log_utils import get_module_logger
from core.virus_total import get_urls_for_ip
import dat... | phage-nz/ph0neutria | core/plugins/cymon.py | cymon.py | py | 8,062 | python | en | code | 299 | github-code | 36 |
35810319147 | import numpy as np
class PatchSampler():
def __init__(self, train_images_list, gt_segmentation_maps_list, classes_colors, patch_size):
self.train_images_list = train_images_list
self.gt_segmentation_maps_list = gt_segmentation_maps_list
self.class_colors = classes_colors
self.patc... | IsmailKent/ComputerVision2Submissions | Sheet02/Sampler.py | Sampler.py | py | 2,536 | python | en | code | 0 | github-code | 36 |
75215887145 | import streamlit as st
from transformers import pipeline
# 👈 Add the caching decorator
@st.cache(allow_output_mutation=True)
def load_model():
return pipeline("sentiment-analysis")
model = load_model()
query = st.text_input("Your query")
if query:
result = model(query)[0] # 👈 Classify the query text
... | Jaggusms/sentiment_analysis_higgingFace | app.py | app.py | py | 349 | python | en | code | 0 | github-code | 36 |
20353033243 | from __future__ import absolute_import
import itertools
from django import forms
from .models import Episode
class ScoreboardForm(forms.Form):
def __init__(self, *args, **kwargs):
classes = kwargs.pop("classes")
super(ScoreboardForm, self).__init__(*args, **kwargs)
classes_choices = [(c.... | ocadotechnology/rapid-router | game/forms.py | forms.py | py | 1,935 | python | en | code | 53 | github-code | 36 |
10623176651 | """An AWS Python Pulumi program"""
import pulumi
from pulumi_aws import eks
import networking
config = pulumi.Config();
environment = config.require('environment');
instance_size = config.require('instance-size');
eks_service_role = config.require('eks-service-role');
node_instance_role = config.require('node-instan... | dtorresf/iac | pulumi/eks/__main__.py | __main__.py | py | 1,663 | python | en | code | 0 | github-code | 36 |
19834995573 | import numpy as np
from metrics import r2_score
class LinearRegression():
def __init__(self):
self._theta = None
self.cofficients_ = None
self.intercept_ = None
def fit_normal(self,X_train,y_train):
"""通过训练数据 fit模型参数"""
X_temp = np.hstack([np.ones((X_train.shape[0],1))... | anbingxu666/Machine-learning-with-Python | LinearRegression.py | LinearRegression.py | py | 3,693 | python | en | code | 4 | github-code | 36 |
12083042499 | import json
import logging
from django.contrib import messages
from django.contrib.auth.decorators import login_required, user_passes_test
from django.core.management import call_command
from django.http import HttpRequest, HttpResponse
from django.http.response import HttpResponseRedirect
from django.urls import reve... | yunojuno/django-linear | linear/views.py | views.py | py | 2,704 | python | en | code | 3 | github-code | 36 |
13217684501 | # -*- coding: UTF-8 -*-
__author__ = 'admin'
import sys,math,os
import module1
j = 3
i = 2
j = 3
i = 2
for i in range(2, 100):
x = 'foo'
if i % 2 == 1:
sys.stdout.write(x + '\n' + str(i) + x)
module1.printname(x)
i += 1
else:
sys.stdout.write(x + '\n' + str(i))
i... | wanseanpark/shell | 1.project/1.test/01.input.py | 01.input.py | py | 329 | python | en | code | 0 | github-code | 36 |
36899051077 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
import math
import matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d import Axes3D
#Global Variables
num_iter=0
saved_theta=np.zeros((2, 1))
cost=np.zeros(1)
def h(X, theta):
return np.dot(X, ... | ashishgupta97/Machine-Learning | LinearRegression.py | LinearRegression.py | py | 2,417 | python | en | code | 0 | github-code | 36 |
34463656888 | import mainBMRSA as Bmrsa
import mainBRSA as Brsa
import matplotlib.pyplot as plt
from useful import funcs
# number of bs
bsize = 1
while bsize < 4:
# Start from prime size = 10 bits
# mrsa and bmrsa time
itr = 10
mrsa = []
bmrsa = []
# points needed to be marked on graph
pts = [1024]... | SUMUKHA-PK/RSA-efficient-variants | src/BMRSA/main.py | main.py | py | 1,574 | python | en | code | 0 | github-code | 36 |
34109397178 | import requests
from tunga_tasks import slugs
EVENT_PUSH = 'push'
EVENT_CREATE = 'create'
EVENT_DELETE = 'delete'
EVENT_COMMIT_COMMENT = 'commit_comment'
EVENT_PULL_REQUEST = 'pull_request'
EVENT_PULL_REQUEST_REVIEW_COMMENT = 'pull_request_review_comment'
EVENT_ISSUE = 'issue'
EVENT_ISSUE_COMMENT = 'issue_comment'
EV... | jonathanzerox/tunga-api | tunga_utils/github.py | github.py | py | 3,509 | python | en | code | 0 | github-code | 36 |
4502539107 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import sys
import os
from service.singleton import Singleton
class Config(Singleton):
def __init__(self):
parser = self.__get_praser()
self.args = parser.parse_args()
self.port = self.args.port
self.token = self.args.... | comzyh/VerifyBot | service/config.py | config.py | py | 1,711 | python | en | code | 4 | github-code | 36 |
13782320879 | from fastapi import APIRouter
from conn import conn
from model.kitchen import Kitchen
kitchen_router = APIRouter(
prefix="/kitchen",
tags=["kitchen"],
)
@kitchen_router.get("/")
async def read_items(attr: list, where: dict):
cursor = conn.cursor()
sql = Kitchen.querySql(attr=attr, where=where)
cur... | JulioHey/Banco-de-Dados---EP | server/router/kitchen.py | kitchen.py | py | 1,060 | python | en | code | 0 | github-code | 36 |
35620233152 | """Runs training and evaluation of Prophet models."""
import importlib
import json
import os
import sys
from pathlib import Path
import click
import matplotlib.pyplot as plt
import mlflow
from dask import distributed
from prophet import plot
from prophet.diagnostics import cross_validation, performance_metrics
from pr... | axiom-data-science/project-s2s-sea-ice-guidance | src/experiments/runner.py | runner.py | py | 6,063 | python | en | code | 0 | github-code | 36 |
16568956344 | from RW import readAll
import os
import json
from PrettyPrint import pretty, prettyJarInfo, prettyNameSpace1, prettyElementKind
import sys
#pathToRawData = r"C:\Users\t-amketk\RawData\RawData"
def get_all_projects(path):
return readAll("Projects", "Project", pathToProtos=os.path.join(path, "ProtosOut"))
def get... | ameyaKetkar/TypeChangeMiner | scripts/ProtosToJson.py | ProtosToJson.py | py | 4,967 | python | en | code | 1 | github-code | 36 |
16117948354 | import os
from builtins import classmethod, int
from datetime import datetime
from models.country import Country
from es import es
class State:
def __init__(self):
pass
@classmethod
def list(cls, country):
if country != "":
state_data = es.search(
index=os.en... | RakeshMallesh123/flask-elasticsearch | models/state.py | state.py | py | 3,380 | python | en | code | 1 | github-code | 36 |
9385088011 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 27 01:30:02 2022
@author: Syeda Fatima Zahid
"""
import time
import datetime
import pandas as pd
ticker = 'MSFT'
period1 = int(time.mktime(datetime.datetime(2020, 12, 1, 23, 59).timetuple()))
period2 = int(time.mktime(datetime.datetime(2020, 12, 31, 23, 59).timetuple())... | syedafatimah/Stock-Price-Analyzer | Prediction Using Numerical Data/Data Extraction.py | Data Extraction.py | py | 576 | python | en | code | 0 | github-code | 36 |
36255089286 | import setuptools
NAME = "oka"
VERSION = "0.2108.0"
AUTHOR = 'Rafael A. Bizao, Davi P. dos Santos'
AUTHOR_EMAIL = 'rabizao@gmail.com'
DESCRIPTION = 'Python client for oka'
with open('README.md', 'r') as fh:
LONG_DESCRIPTION = fh.read()
LICENSE = 'GPL3'
URL = 'https://github.com/davips/lange'
DOWNLOAD_URL =... | rabizao/oka | setup.py | setup.py | py | 1,764 | python | en | code | 0 | github-code | 36 |
31282026948 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import tensorflow as tf
from bs4 import BeautifulSoup
from pagi.utils.embedding import Embedding
def main(args):
print("Args:", args)
# data_dir = '/home/dave/agi/ptb_err'
# count_file = ... | Cerenaut/rsm | rsm/scripts/preprocess_reuters.py | preprocess_reuters.py | py | 5,812 | python | en | code | 1 | github-code | 36 |
13906055504 | import cv2
import matplotlib.pyplot as plt
import statistics
"""
this code reads in the ratio values that were created
in newTitration.py. It then checks to see if those ratios
correlate to a pink color. If they do, it will write the frame
number to a file called frameNames.txt
"""
#reads in file
infile = open("... | asembera/portfolio | Python/titration/newMethod.py | newMethod.py | py | 1,628 | python | en | code | 0 | github-code | 36 |
31676458963 | # Example 6.3
# Calculation of the discrete Sine and Cosine transform
from pylab import*
from dtrans import*
# Define the function
f = lambda x: np.power((x/pi), 2)
# Sine and Cosine transform
N = 16
X = asmatrix(r_[0.:pi+pi/N:pi/N])
k = r_[0:N+1]
cos_coeff = dct1(f(X).T)
sin_coeff = dst1(f(X).T)
# ... | mdclemen/py-fena | ch6ex3.py | ch6ex3.py | py | 553 | python | en | code | 5 | github-code | 36 |
70786051623 | '''Author: - Devang A Joshi
Version 1.0
Description: This program is a mini guessing game where User need to think a value between 1 to 100
an Array of 100 is created, Initial vales were set. then sorting is made by midpoint selection
Guided By : - Gula Nurmatova
'''
print("------------------------------... | dave2711/python | HW_Devang_1.py | HW_Devang_1.py | py | 3,455 | python | en | code | 0 | github-code | 36 |
27688294612 | import pickle, tensorflow as tf, tf_util, numpy as np
import pdb
# def load_policy(filename):
# with open(filename, 'rb') as f:
# data = pickle.loads(f.read())
#
# # assert len(data.keys()) == 2
# nonlin_type = data['nonlin_type']
# policy_type = [k for k in data.keys() if k != 'nonlin_type'][0... | rhiga2/DeepRL | hw1/load_policy.py | load_policy.py | py | 7,636 | python | en | code | 0 | github-code | 36 |
11277919959 | class Solution:
def isPalindrome(self, string: str):
'''
A function to check if a sequence is Palindrome or not!
:param string: Sequence to be checked
:return: True if it is palindrome else False
'''
sequence=""
for i in string:
if i.isalpha():
... | DundeShini/CSA0838-PYTHON-PROGRAMMING- | valid palindrome.py | valid palindrome.py | py | 854 | python | en | code | 1 | github-code | 36 |
31410757057 | from django.db import models
from django.contrib.auth import get_user_model
# Create your models here.
class MailList(models.Model):
"""
database table that stores all
users that subscribe to recieve notifications
"""
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
recieve... | andela/ah-backend-valkyrie | authors/apps/notify/models.py | models.py | py | 1,042 | python | en | code | 0 | github-code | 36 |
30545475363 | import gettext
import os
uilanguage=os.environ.get('fchart3lang')
try:
lang = gettext.translation( 'messages',localedir='locale', languages=[uilanguage])
lang.install()
_ = lang.gettext
except:
_ = gettext.gettext
from time import time
from .label_potential import *
from .np_astroc... | skybber/fchart3 | fchart3/skymap_engine.py | skymap_engine.py | py | 80,302 | python | en | code | 9 | github-code | 36 |
38384503953 | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import logging
import datetime
logname = "Trying"+datetime.date.today().strftime("%d-%m-%Y")+".log"
logging.basicConfig(filename=logname,
filemode='a',
format='%(asctime)s,%(msecs)d %(... | amynav/Testing_repo | trying.py | trying.py | py | 1,339 | python | en | code | 0 | github-code | 36 |
40600848751 | from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import render
from watchlist.models import Movie
from django.http import JsonResponse
# Create your views here.
def movie_list(request):
movies = Movie.objects.all()
data = {
'movies': list( movies.values() )
}
retur... | shubham2637/DRF | watchmate/watchlist/views.py | views.py | py | 684 | python | en | code | 0 | github-code | 36 |
22783587958 | #
# @lc app=leetcode id=970 lang=python3
#
# [970] Powerful Integers
#
# https://leetcode.com/problems/powerful-integers/description/
#
# algorithms
# Easy (39.91%)
# Likes: 99
# Dislikes: 44
# Total Accepted: 35.7K
# Total Submissions: 84.4K
# Testcase Example: '2\n3\n10'
#
# Given three integers x, y, and boun... | Zhenye-Na/leetcode | python/970.powerful-integers.py | 970.powerful-integers.py | py | 1,739 | python | en | code | 17 | github-code | 36 |
23278209087 | def get_letter_guess():
while True:
try:
guess = input("Enter your letter guess: ")
if not guess.isalpha() or len(guess) != 1:
raise ValueError
except ValueError:
if not guess.isalpha():
print("Invalid input. Numbers and symbols are... | fong-a/software_engineering | error_handling.py | error_handling.py | py | 559 | python | en | code | 0 | github-code | 36 |
5940101912 | # -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import pickle
import configparser
import copy
import subprocess
from distutils.util import strtobool
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
from torch.cuda.amp import autocast, GradScaler
# from AutoE... | MDIFS/DeepKoopmanDynamicalFSI | mpc.py | mpc.py | py | 8,203 | python | en | code | 0 | github-code | 36 |
3859314216 | import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('../Images/abc.png')
kernel = np.ones((9, 9), np.float32) / 10
print(kernel)
dst = cv2.filter2D(img, -1, kernel)
cv2.imshow("imange",dst)
cv2.waitKey(0)
cv2.destroyAllWindows() | trunghopro098/Image-Processing | ProcessImg/Filter2D.py | Filter2D.py | py | 263 | python | en | code | 1 | github-code | 36 |
17956410019 | import pygame as pg
from random import random as r
from neurobiba import Weights, load_weights, save_weights
import copy
import itertools
W, H, size = 100, 60, 10
pg.init()
screen = pg.display.set_mode((W*size, H*size), 0, 32)
pg.display.set_caption('CYBERBIBA')
def update():
nn = Weights([27,3])
canvas1 = [... | displaceman/neurobiba | examples/neural cellular automata/neuroautomata.py | neuroautomata.py | py | 1,435 | python | en | code | 4 | github-code | 36 |
35396799058 | from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
from contextlib import contextmanager
import tempfile
from pex.pex_builder import PEXBuilder
from twitter.common.collections import OrderedSet
from pants.backend.cor... | fakeNetflix/square-repo-pants | src/python/pants/backend/python/tasks/python_task.py | python_task.py | py | 4,295 | python | en | code | 0 | github-code | 36 |
31803868279 | # /usr/bin/python3.6
# -*- coding:utf-8 -*-
import heapq
class Solution(object):
def openLock(self, deadends, target):
"""
:type deadends: List[str]
:type target: str
:rtype: int
"""
heap = []
heapq.heappush(heap, (0, "0000"))
visited = set(deadends)... | bobcaoge/my-code | python/leetcode/752_Open_the_Lock.py | 752_Open_the_Lock.py | py | 1,351 | python | en | code | 0 | github-code | 36 |
31550946314 | """ Faça um programa que leia o sexo de uma pessoa, mas só aceite os valores 'M' ou 'F'.
Caso esteja errado, peça a digitação novamente até ter um valor correto. """
sexo = str(input('Sexo [M/F]: ')).upper().strip()
while sexo not in 'MF':
print('Opção invalida, tente novamente!\n')
sexo = str(input('Sexo [M/F... | ClebersonGarcia05/curso-python | Mundo python 02/exercicíos/WHILE/ex057.py | ex057.py | py | 686 | python | pt | code | 0 | github-code | 36 |
73881050665 | import six
from sse.exceptions import SseException
__all__ = ['MethodNotAllowed', 'NotFound']
class StreamProtocolException(SseException):
"""
To avoid confusing with class naming or maybe I need some brain surgery
"""
def __init__(self, **kwargs):
for key, value in six.iteritems(kwargs):
... | Axik/instamute.io | apps/stream/exceptions.py | exceptions.py | py | 974 | python | en | code | 0 | github-code | 36 |
19052049620 | import numpy as np
from abc import ABC, abstractmethod
class Agent(ABC):
"""
Base agent class.
Represents the concept of an autonomous agent.
Attributes
----------
name: str
Name for identification purposes.
observation: np.ndarray
The most recent ... | BeatrizVenceslau/MastersDegree-Projects | Autonomous Agents and Multi Agent Systems/Code/aasma/agent.py | agent.py | py | 5,564 | python | en | code | 0 | github-code | 36 |
21365635224 | import numpy as np
from dptb.utils.tools import j_must_have
from dptb.utils.make_kpoints import ase_kpath, abacus_kpath, vasp_kpath
from ase.io import read
import ase
import matplotlib.pyplot as plt
import matplotlib
import logging
log = logging.getLogger(__name__)
from matplotlib.ticker import MultipleLocator, Format... | deepmodeling/DeePTB | dptb/postprocess/bandstructure/band.py | band.py | py | 6,701 | python | en | code | 21 | github-code | 36 |
26500786049 | import os
import cv2
import json
import random
import itertools
import numpy as np
import argparse
import cv2
from time import gmtime, strftime
def predict(image, predictor, list_labels):
outputs = predictor(image)
boxes = outputs['instances'].pred_boxes
scores = outputs['instances'].scores
classes =... | tiendv/MCOCR2021 | Task2/submit_task2/detect_receipt_api/src/predict.py | predict.py | py | 1,032 | python | en | code | 9 | github-code | 36 |
25523783356 | import os
from flask import Flask, make_response, request, redirect, url_for, send_from_directory
from werkzeug.utils import secure_filename
from database import app
UPLOAD_FOLDER = './uploads'
ALLOWED_EXTENSIONS = { 'png', 'jpg', 'mp3' } #to change for music files
app.config['UPLOAD_FOLDER'] = os.path.join(os.getcwd... | arkea-tech/YEP_EpiKodi3_2020 | server/file_transfer/views.py | views.py | py | 1,512 | python | en | code | 0 | github-code | 36 |
17736596508 | # -*- coding: utf-8 -*-
import rhinoscriptsyntax as rs
import scriptcontext as sc
import Rhino
import time
import gc
# この中の変数は処理終了後に消えない/////////////////////////////////////////////////
if 'count_loop' not in sc.sticky:
sc.sticky['count_loop'] = 0# 何個目の壁なのか示す数字
if 'dict_distance' not in sc.sticky:
sc.sticky['dict_dis... | fuku0211/wallconstructor | wallconstructor/wallconstructor.py | wallconstructor.py | py | 8,744 | python | en | code | 0 | github-code | 36 |
19982370070 | from defaults import * # noqa
SECRET_KEY = open(SECRET_KEY_FILE).read()
DEBUG = False
TEMPLATE_DEBUG = False
ALLOWED_HOSTS = ['.tutorons.com']
STATICFILES_DIRS += ((os.path.join(os.path.abspath(os.sep), 'var', 'www', 'tutorons')),)
STATIC_ROOT = os.path.join(os.path.abspath(os.sep), 'usr', 'local', 'tutorons', 'stat... | andrewhead/tutorons-server | tutorons/settings/production.py | production.py | py | 1,374 | python | en | code | 6 | github-code | 36 |
8439507443 | # Given a number sequence, find the length of its Longest Increasing Subsequence (LIS).
# In an increasing subsequence, all the elements are in increasing order (from lowest to highest).
# Input: {4,2,3,6,10,1,12}
# Output: 5
# Explanation: The LIS is {2,3,6,10,12}.
def find_LIS(arr):
return find_LIS_rec(arr, 0,... | kashyapa/coding-problems | educative.io/medium-dp/longest-common-subsequence/4_longest_increasing_subsequence.py | 4_longest_increasing_subsequence.py | py | 1,793 | python | en | code | 0 | github-code | 36 |
14575225186 | def filter(lines, val0, val1):
for i in range(len(lines[0])):
count = [0, 0]
for line in lines:
count[int(line[i])] += 1
if count[0] > count[1]:
lines = [line for line in lines if line[i] == val0]
else:
lines = [line for line in lines if line[i] =... | vfolunin/archives-solutions | Advent of Code/2021/3.2.py | 3.2.py | py | 568 | python | en | code | 0 | github-code | 36 |
34743814847 | from typing import List
file = "input02.txt"
with open(file, "rt") as f:
ids = f.readlines()
# Part 1
doubles = 0
triples = 0
for id in ids:
double_found = False
triple_found = False
for c in id:
reps = id.count(c)
if reps == 2 and not double_found:
doubles += 1
... | acanizares/advent_of_code | day02.py | day02.py | py | 1,405 | python | en | code | 0 | github-code | 36 |
12859158519 | import torch
import numpy as np
import matplotlib.pyplot as plt
print("PyTorch Version:", torch.__version__)
if torch.backends.mps.is_available():
mps_device = torch.device("mps")
print(mps_device)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
X, Y = np.mgrid[-4.0:4:0.01, -4.0:4:0.0... | rwardd/comp3710 | prac1/gaussian.py | gaussian.py | py | 509 | python | en | code | 0 | github-code | 36 |
21374477352 | from django import template
register = template.Library()
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
@register.filter
def first_letter_word(value):
stop_words = set(stopwords.words('english'))
word_tokens = word_tokenize(value)
filtered_sentence = [w for w in wor... | 4akhilkumar/akira_project | akira_apps/staff/templatetags/first_letter_word.py | first_letter_word.py | py | 744 | python | en | code | 0 | github-code | 36 |
12760265976 | import numpy as np
import matplotlib.pyplot as plt
sp_LL=np.loadtxt('spline_LL.txt')
sp_LH=np.loadtxt('spline_LH.txt')
sp_HT=np.loadtxt('spline_HT.txt')
sp_R=np.loadtxt('spline_R.txt')
##
AA=np.loadtxt('HT_p_T_c')
BB=np.loadtxt('LH_p_T_c')
CC=np.loadtxt('R_p_T_c')
DD=np.loadtxt('LL_p_T_c')
EE=np.loadtxt('TP_T-x-Perr-... | yufang67/CO2-look-up-table | program/isotherm.py | isotherm.py | py | 7,331 | python | en | code | 3 | github-code | 36 |
4108034467 | from sys import stdin
input = stdin.readline
intersections = int(input())
roads = {x: {} for x in range(1, intersections + 1)}
distance, adj, before = {}, {}, [0] * (intersections + 1)
queue = []
# print(roads)
num = int(input())
for _ in range(num):
m, n, d, s = [int(x) for x in input().split()]
time = float... | AAZZAZRON/DMOJ-Solutions | dmopc14ce1p4.py | dmopc14ce1p4.py | py | 1,714 | python | en | code | 1 | github-code | 36 |
25607474641 | class Solution:
def isMatch(self, s: str, p: str) -> bool:
cache={}
lenS,lenP=len(s),len(p)
def dfs(i,j):
if (i,j) in cache:
return cache[(i,j)]
if i>=lenS and j>=lenP:
return True
if j>=lenP:
... | Nirmalkumarvs/programs | Backtracking/Regular Expression Matching.py | Regular Expression Matching.py | py | 729 | python | en | code | 0 | github-code | 36 |
228457289 | """
"""
import time
def print_execute_time(func):
def wrapper(*args, **kwargs):
start = time.time()
# 执行旧功能
result = func(*args, **kwargs)
stop = time.time()
print("执行时间:", stop - start)
return result
return wrapper
@print_execute_time
def sum_data(n):
s... | testcg/python | code_all/day19/exercise04.py | exercise04.py | py | 477 | python | en | code | 0 | github-code | 36 |
22017042868 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 15 11:48:04 2020
@author: Paradeisios
"""
from utils.computeCost import computeCost
import numpy as np
def gradientDescent(X,y,theta,alpha, iterations):
m = len(y)
J_history = np.zeros((iterations,1))
derivative = 0
for i in range(iterations):
... | paradeisios/Coursera_Machine_Learning | week2/python/utils/gradientDescent.py | gradientDescent.py | py | 514 | python | en | code | 0 | github-code | 36 |
12552816029 | my_list = [1, 2, 3, 4, 5]
for i in my_list:
print(i)
else:
print('Hit the For\Else Statement')
print()
print('********************************')
print()
j = 1
while j <= 5:
print(j)
j += 1
if j == 3:
break
else:
print('Hi the While\Else Statement')
print()
print('***********************... | iampaavan/Pure_Python | Else Clauses on Loops.py | Else Clauses on Loops.py | py | 1,118 | python | en | code | 1 | github-code | 36 |
192760992 | from flask import Flask, render_template, url_for, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import requests
import paralleldots
import stripe
app = Flask(__name__)
pub_key = ''
secret_key = ''
stripe.api_key = secret_key
class Analyze:
report_key = ''
sentiment... | mikeyj777/siraj_midterm_take3 | app.py | app.py | py | 1,955 | python | en | code | 0 | github-code | 36 |
30591789155 | from __future__ import annotations
from grammar import Grammar, reduce_left_recursion, chomsky_normal_form
from dacite import from_dict
import json
def main():
filename = input("Input file name:") or "data.json"
print(f'using file {filename}')
with open(filename, "r") as f:
data = json.load(f)
... | fairay/Compilers | lab2/main.py | main.py | py | 682 | python | en | code | 0 | github-code | 36 |
23080854641 | from consts import piConst, hwConst
from spa.serverside import CSocketProServer, CSocketProService,\
CClientPeer, BaseServiceID, Plugin
from spa.clientside import CAsyncQueue, CStreamingFile, CMysql, COdbc, CSqlite, CSqlServer, CPostgres
from spa.udb import DB_CONSTS
from pub_sub.ps_server.hwpeer import CHelloWorld... | udaparts/socketpro | tutorials/python/all_servers/all_servers.py | all_servers.py | py | 7,957 | python | en | code | 27 | github-code | 36 |
3207021660 | """ Helper functions used by tests for the locate subpackage."""
from pdf2gtfs.datastructures.gtfs_output.handler import GTFSHandler
from pdf2gtfs.datastructures.gtfs_output.stop_times import Time
def add_stops_to_handler(handler: GTFSHandler, n: int = 5) -> None:
""" Add n unique stops to the given handler. """... | heijul/pdf2gtfs | test/test_locate/__init__.py | __init__.py | py | 1,918 | python | en | code | 1 | github-code | 36 |
39086540253 | import logging
import sys
def two_sum_sorting(numbers_set, range_start, range_end):
logger.info('Started function that uses sorting')
numbers_sorted = sorted(numbers_set)
logger.info('Done sorting')
start = 0
end = len(numbers_set) - 1
result = set()
logger.info('Entering main while loop'... | nickslavsky/Algorithms-pt1 | Week 6/2sum.py | 2sum.py | py | 2,209 | python | en | code | 0 | github-code | 36 |
10741283794 | from __future__ import unicode_literals
import os
import unittest
import tempfile
import textwrap
import decimal
import shutil
import transaction as db_transaction
class TestAlembic(unittest.TestCase):
def setUp(self):
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_sessio... | vdt/billy | billy/tests/functional/test_alembic.py | test_alembic.py | py | 4,718 | python | en | code | null | github-code | 36 |
72164652584 | from model.action.Action import Action
from model.action.Actions import Actions
class SendingMessageAction(Action):
def __init__(self, _message: str, _agt_id: int):
Action.__init__(self, "sending_message", Actions.Sending_message)
self.message = _message
self.agt_id = _agt_id
| alejeau/cocoma-td | model/action/SendingMessageAction.py | SendingMessageAction.py | py | 311 | python | en | code | 0 | github-code | 36 |
31353500311 | #!/usr/bin/env python3
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import os
import sys
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
from colorama import Fore
import config
from da... | KoapT/img_classification_pytorch | main.py | main.py | py | 7,409 | python | en | code | 0 | github-code | 36 |
4255371054 | from typing import List
from data_structures.list_node import ListNode
from heapq import *
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
min_heap = []
for i in range(len(lists)):
curr_list = lists[i]
if curr_list:
heappush(min_heap... | blhwong/algos_py | leet/merge_k_sorted_lists/main.py | main.py | py | 844 | python | en | code | 0 | github-code | 36 |
26172267037 | # Easy Python project :P
# Random friend selector to decide who to FaceTime!
import random
friends =[
'Arnab','Dipankar','Sandeep Sir','Aman','Virat','Pant'
]
selected = random.choice(friends) #randomly choose a friend
print('Who should I facetime today? ')
print(selected)
# random.randint(1,5)
# random.ch... | Sib-git/madlibs | selector.py | selector.py | py | 333 | python | en | code | 0 | github-code | 36 |
27909840260 | import time
import pandas as pd
import numpy as np
import sys
CITY_DATA = { 'chicago': 'chicago.csv',
'new york': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
... | nadertadrous/nadertadrous | bikeshare.py | bikeshare.py | py | 8,211 | python | en | code | 0 | github-code | 36 |
24014680066 | # https://www.hackerrank.com/challenges/bigger-is-greater/
# No such impl in Python lib: https://stackoverflow.com/questions/4223349
class strings:
def next_permutation(w):
stk=[]
n=len(w)
def nextperm(sc):
i=0
for x in stk:
if x > sc:
... | liruqi/topcoder | Library/strings.py | strings.py | py | 674 | python | en | code | 6 | github-code | 36 |
13070318133 | import time, collections
class RateLimiter:
def __init__(self, max_number, interval):
self.timeStamp = collections.defaultdict(collections.deque)
self.interval = interval
self.max_number = max_number
def call(self, id):
currTime = time.time()
if len(self.timeStamp[id]) ... | Jason003/Interview_Code_Python | stripe/rate limiter.py | rate limiter.py | py | 813 | python | en | code | 3 | github-code | 36 |
70230238504 | # Advent of Code, Day 3, Part 2
testInput = '''\
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010
'''
testResult = 230
def solve(input):
lines = [line for line in input.split('\n') if line != '']
def searchForRating(bitCriteria):
remLines = lines
for i in range(len(lin... | BlueFerox/AoC2021 | day3/part2.py | part2.py | py | 965 | python | en | code | 0 | github-code | 36 |
41614185208 | from django.shortcuts import HttpResponseRedirect
from django.http import JsonResponse
from urllib.parse import quote
class AuthRequiredMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# Code to be executed for each request be... | comiconomenclaturist/django-icecast-stats | stats/middleware.py | middleware.py | py | 1,051 | python | en | code | 1 | github-code | 36 |
34980505423 | #存在重复
# 给定一个整数数组,判断是否存在重复元素。
# 如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。
#===============================================================================
# 输入: [1,2,3,1]
# 输出: true
#===============================================================================
from collections import Counter
class Solution:
... | huowolf/leetcode | src/array/containsDuplicate.py | containsDuplicate.py | py | 775 | python | fr | code | 0 | github-code | 36 |
3285800905 | import re
from parsers.InsideParser.InsideParserBase import InsideParserBase
from parsers.RegexpBuilder import RegexpBuilder
from parsers.ValuesStriper import ValuesStripper
class InsideSetArrayParser(InsideParserBase):
def __init__(self, fileExt):
InsideParserBase.__init__(self, fileExt)
self.values = None
d... | TouchInstinct/BuildScript | scripts/TouchinBuild/parsers/InsideParser/InsideSetArrayParser.py | InsideSetArrayParser.py | py | 1,162 | python | en | code | 1 | github-code | 36 |
29540265563 | import telebot
from telebot import types
bot = telebot.TeleBot('1507860102:AAH3y4nFwQgnYJCFP49PMRRqQVEvhIGrLmw')
user_dict = {}
class User:
def __init__(self, name):
self.name = name
self.age = None
self.sex = None
# Handle '/start' and '/help'
@bot.message_handler(commands=['help', 'st... | HKarpenko/teleBot | main.py | main.py | py | 2,905 | python | en | code | 0 | github-code | 36 |
4671110554 | #!/usr/bin/python3
"""Graph data structure traversal"""
def canUnlockAll(boxes):
"""Check if all boxes can be recursively opened
Function, by the help of helper function `recurse`, checks whether all
boxes in `boxes` 2D list can be opened by begining with keys found on box
at index 0.
Args:
... | leykun-gizaw/alx-interview | 0x01-lockboxes/0-lockboxes.py | 0-lockboxes.py | py | 1,053 | python | en | code | 0 | github-code | 36 |
32542353820 | from google.cloud import storage
from configparser import ConfigParser
from google.oauth2 import service_account
from googleapiclient.discovery import build
from utils.demo_io import (
get_initial_slide_df_with_predictions_only,
get_fovs_df,
get_top_level_dirs,
populate_slide_rows,
get_histogram_df,... | alice-gottlieb/nautilus-dashboard | examples/spot_cropping_example.py | spot_cropping_example.py | py | 2,247 | python | en | code | 0 | github-code | 36 |
14191916255 | # TODO: prevent utf-8 encoding errors in CSVs
# TODO: add a progress bar for all timed processes
# TODO: Maintain History of organizations analyzed
# TODO: Show time taken to scrape and analyze (tock - tick)
#Importing Libraries
import contextlib
import csv
import json
import os
import re
import time
import warnings
f... | HighnessAtharva/CRIF-Hackathon-2023 | SCRAPER.py | SCRAPER.py | py | 17,393 | python | en | code | 1 | github-code | 36 |
3918203704 | import re
import os
import string
import shutil
import tempfile
import fontforge
import argparse
from string import Template
from pathlib import Path
from bs4 import BeautifulSoup
from bs4.formatter import XMLFormatter
class Colors:
OK = '\033[92m'
INFO = '\033[94m'
WARN = '\033[93m'
FAIL = '\033[91m'... | 10f7c7/hershey2TTF | test.py | test.py | py | 11,054 | python | en | code | 0 | github-code | 36 |
35622258622 | import boto3
import base64
import os
ENDPOINT_NAME = os.environ['ENDPOINT_NAME']
def lambda_handler(event, context):
""" Handler of the lambda function """
# The SageMaker runtime is what allows us to invoke the endpoint that we've created.
runtime = boto3.Session().client('sagemaker-runtime')
# ... | jorgeramirezcarrasco/udacity-capstone-project-dog-breed-classifier | lambda/lambda_function.py | lambda_function.py | py | 1,216 | python | en | code | 0 | github-code | 36 |
6184910677 | """
My simple timing wsgi middleware. Should serve as wsgi app for gunicorn, and
as wsgi server for django. Starts timing berfore calling django routines,
stops upon receiving the start_response
"""
import time
class TimingWSGIMiddleware:
def __init__(self, djangoapp):
"""
We instatiate the middl... | temaput/practica.ru | practica/practica/timingwsgi.py | timingwsgi.py | py | 3,289 | python | en | code | 0 | github-code | 36 |
15466868724 | # name = "marine"
# hp = 40
# atk = 5
# print("Unit {0} is created.".format(name))
# print("HP {0}, Attack {1}\n".format(hp, atk))
# tank_name = "tank"
# tank_hp = 150
# tank_atk = 35
# print("Unit {0} is created.".format(tank_name))
# print("HP {0}, Attack {1}\n".format(tank_hp, tank_atk))
# tank2_name = "tank"
# ta... | hss69017/self-study | basic/class.py | class.py | py | 2,243 | python | en | code | 0 | github-code | 36 |
5547367389 | """
Tests for Voting 21/06/2022 [Lido app for Goerli].
"""
import pytest
from brownie import interface
from scripts.vote_2022_06_21_goerli_lido_app import (
start_vote,
get_lido_app_address,
get_lido_app_old_version,
)
from utils.test.tx_tracing_helpers import *
from utils.config import network_name
from ... | lidofinance/scripts | archive/tests/test_2022_06_21_2_goerli_lido_app.py | test_2022_06_21_2_goerli_lido_app.py | py | 3,523 | python | en | code | 14 | github-code | 36 |
43165325383 | # Python code to run a loop for the number of files in a folder.
# Importing required libraries
import os
# Initializing loop for the files in the defined folder
for filename in os.listdir("/Users/walikhan/Work/Python_YouTube_Auto/vid"):
# Applying condition to check for a particular file type
if fi... | WaliKhan09/Programming | Python/Folder_Loop.py | Folder_Loop.py | py | 719 | python | en | code | 1 | github-code | 36 |
20471993107 | from pprint import pprint
from bs4 import BeautifulSoup
import requests
import pandas as pd
import pprint
election = []
user_agent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.37"
URL = "https://en.wikipedia.org/wiki/List_of_United_States_presidential_e... | Eleanor-Shellstrop/presidents | python/elections.py | elections.py | py | 1,183 | python | en | code | 0 | github-code | 36 |
19406336160 | #
# @lc app=leetcode id=404 lang=python3
#
# [404] Sum of Left Leaves
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def traversal(self... | Matthewow/Leetcode | vscode_extension/404.sum-of-left-leaves.py | 404.sum-of-left-leaves.py | py | 791 | python | en | code | 2 | github-code | 36 |
4472055866 | from math import sin, cos
from components.bubble import Bubble
from components.utils import HF
from data.constants import CONFUSION_COLORS
class EnemyEvent:
def __init__(self, owner, game, data: dict):
self.owner = owner
self.game = game
self.trigger_value = data["trigger value"]
... | IldarRyabkov/BubbleTanks2 | src/components/enemy_event.py | enemy_event.py | py | 1,981 | python | en | code | 37 | github-code | 36 |
31792102222 | # coding:utf-8
import sys
import window
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.QtGui import QIcon
from PyQt5 import QtCore
# import pymysql
import threading
import pymysql
path = "./"
class Controller:
def __init__(self):
pass
def show_login(self):
self.login = Login... | northboat/Aides | app/app.py | app.py | py | 3,509 | python | en | code | 0 | github-code | 36 |
21253725938 | from objdetection1 import *
import cv2 as cv
import numpy as np
from PIL import Image
import random
import math
def make_cluster(img):
Z = img.reshape((-1,3))
# convert to np.float32
Z = np.float32(Z)
# define criteria, number of clusters(K) and apply kmeans()
criteria = (cv.TERM_CRITERIA_EPS + ... | DvnGBulletZz/Computer_Vision_Kenan | Eind_Opdracht/clustering.py | clustering.py | py | 2,219 | python | en | code | 0 | github-code | 36 |
39472170581 | from flask import request
from werkzeug.exceptions import NotFound, BadRequest, Conflict
from db import db
from managers.brand import BrandManager
from managers.category import CategoryManager
from models import BrandModel, CategoryModel
from models.enums import GenderType
from models.products import ProductsModel, P... | a-angeliev/Shoecommerce | server/managers/products.py | products.py | py | 9,324 | python | en | code | 0 | github-code | 36 |
31875266103 | # from .word2vec_functions.text_processing_functions import *
from .word2vec_functions.word2vec_companion import similar_words
from gensim.models import Word2Vec
import json
BASE_PATH = 'w2v/word2vec_functions/'
def load_filters():
with open(BASE_PATH + 'Raw Data/test_data.json', 'r') as file:
test_data ... | CarsonDavis/InteractiveWord2VecWebsite | w2v/utils.py | utils.py | py | 1,911 | python | en | code | 0 | github-code | 36 |
1750954085 | from ex2_utils import *
import matplotlib.pyplot as plt
from random import randrange
import numpy as np
import cv2
def presentation(plots, titles):
n = len(plots)
if n == 1:
plt.imshow(plots[0], cmap='gray')
plt.title(titles[0])
plt.show()
return
if n == 2... | MoriyaBitton/Ex2_Convolution_and_Edge_Detection | ex2_main.py | ex2_main.py | py | 5,008 | python | en | code | 0 | github-code | 36 |
37393924840 | from django.urls import path
from . import views
app_name = 'tenants'
urlpatterns = [
path('', views.index, name='index'),
path('device_network/', views.device_network, name='device_network'),
path('device_location/', views.device_location, name='device_location'),
path('device/', views.device, name=... | Being-rayhan/iot | tenants/urls.py | urls.py | py | 1,265 | python | en | code | 0 | github-code | 36 |
4509075711 | import cv2
import numpy as np
import depthai
import threading
import sys
import os
import time
# Global variables
selected_points = []
completed = False
# Global variables
dataset = "kitti"
img_size = [3, 352, 1216] # for kitti
frame = None
is_frame_available = False
stop_capture = threading.Event() # Event object to ... | surajiitd/jetson-documentation | model_compression/capture_dataset.py | capture_dataset.py | py | 11,499 | python | en | code | 0 | github-code | 36 |
41272460993 | from imutils import paths
import face_recognition
import os
from shutil import copy
from PIL import Image, ImageDraw
from tkinter import Tk
from tkinter.filedialog import askopenfilename
Tk().withdraw()
filename = askopenfilename()
obama = face_recognition.load_image_file(filename)
folder = 'obama'
obamaface_encodi... | SankojuRamesh/face_recognation | fr.py | fr.py | py | 1,295 | python | en | code | 0 | github-code | 36 |
36127467524 | import json
from typing import Dict
from kafka import KafkaConsumer
from main import StationStatus, Station
station_status = dict()
if __name__ == '__main__':
consumer = KafkaConsumer(
'city_bike_topic',
bootstrap_servers = ['localhost:9092'],
auto_offset_reset='earliest',
... | Kelvingandhi/kafka_sample | city_bike_consumer.py | city_bike_consumer.py | py | 1,167 | python | en | code | 2 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.