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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
12178759835 | import os
import json
import pickle
import csv
import time
from collections import defaultdict
from typing import List, Dict, Set, Tuple, Union, Any, DefaultDict
from numpy import mean, median, ndarray
from corpus import Corpus as Cp
from embeddings import Embeddings, get_emb
from clustering import Clustering
from scor... | jagol/BA_Thesis | pipeline/generate_taxonomy.py | generate_taxonomy.py | py | 29,029 | python | en | code | 2 | github-code | 13 |
3190931939 | import sys
import copy
def count_num(ll, n, m):
flag = [False] * n
for i in range(m):
new = []
for j in range(n):
new.append(ll[j][i])
b = copy.deepcopy(new)
b.sort()
x = b.pop()
while True:
try:
a = new.index(x)
... | GGGWB/LeetCode | practice/1.py | 1.py | py | 723 | python | en | code | 0 | github-code | 13 |
1042385791 | import telebot
from telebot import types
from random import choice
bot = telebot.TeleBot('')
begin = 221
total = begin
limit = 28
@bot.message_handler(commands=['start'])
def star(message):
man = message.from_user.first_name
bot.send_message(message.chat.id, f'Привет, {man}!')
rules(message)
button(... | yakdd/python_seminars | bonbones/main.py | main.py | py | 2,943 | python | ru | code | 0 | github-code | 13 |
5348615799 | from __future__ import print_function
from rdkit import Chem
from rdkit.Chem import AllChem
from collections import defaultdict
import copy
import numpy as np
import dgl
import torch
def set_atommap(mol, num = 0):
for i,atom in enumerate(mol.GetAtoms(), start = num):
atom.SetAtomMapNum(i)
return mol
#... | toshikiochiai/NPVAE | model/utils.py | utils.py | py | 32,905 | python | en | code | 8 | github-code | 13 |
38639948396 | import random
class RSA():
def __init__(self, p=None, q=None, m=None) -> None:
#获取输入的两个质数p,q和等待加密的明文m
self.p = p
self.q = q
self.m = m
if p != None and q != None:
self.generate_key() #完成公钥和私钥的初始化
def generate_key(self):
self.n = self.p * self.q
... | UniqueMR/Self-RSA | RSA.py | RSA.py | py | 1,537 | python | en | code | 2 | github-code | 13 |
29760699556 | import cv2
import numpy as np
import argparse
parse = argparse.ArgumentParser()
parse.add_argument('--shape', type=int, nargs='+', default=[720, 1280])
parse.add_argument('--box', type=int, nargs='+', default=[0, 0, 720, 1280])
parse.add_argument('--mask_path', type=str, default='assets/mask/mask.jpg')
def create_rec... | 1000happiness/RoadGradientEstimation | create_rect_mask.py | create_rect_mask.py | py | 716 | python | en | code | 2 | github-code | 13 |
32647107021 | import logging as log, json, sys, time, socket
from threading import Thread, Lock, Event as TreadEvent
from telnetlib import Telnet
from homecontrol.event import Event
class Listener(Thread):
def __init__(self, host, port, event_limit):
self.host = host
self.port = port
self.event_limit = event_limit
self.c... | homecontrol/server | src/homecontrol/listener.py | listener.py | py | 3,244 | python | en | code | 2 | github-code | 13 |
17061182654 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class UserDetails(object):
def __init__(self):
self._user_change_mobile = None
self._user_mobile = None
self._user_name = None
self._user_relation = None
@property
... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/UserDetails.py | UserDetails.py | py | 2,541 | python | en | code | 241 | github-code | 13 |
4491805262 | import random
import time
class TicTacToe:
random_game = 1
user_game = 0
minimax_game = 2
ai_only_game = 3
fair_game = 4
alpha_beta = 5
def __init__(self, type = None):
self.board = "\t1\t2\t3\nA\t-\t-\t-\nB\t-\t-\t-\nC\t-\t-\t-\n"
# self.user_game = 0
# self.rand... | dmuhlner/ATCS-2021 | Semester 2/TicTacToe/tictactoe.py | tictactoe.py | py | 11,488 | python | en | code | 0 | github-code | 13 |
36727299020 | from code import interact
import os
import sys
import re
import argparse
import datetime as dt
import webbrowser as wb
def intro():
print("*****************************************************************")
print(
'''
____ ____ __ __ ___ _ __
/ __ \ / __ \ / / / // | | |/ /
/ /_/ // /_/ ... | shariethernet/RPHAX | rphax.py | rphax.py | py | 14,636 | python | en | code | 12 | github-code | 13 |
8928056338 | import requests
from bs4 import BeautifulSoup
from collections import Counter, defaultdict
import re
from nltk import bigrams, trigrams
import nltk
import datetime
nltk.download('stopwords')
def get_post_titles(url):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, li... | primaryobjects/bogleheads-keywords | bogleheads_scraper.py | bogleheads_scraper.py | py | 3,053 | python | en | code | 1 | github-code | 13 |
10683988809 | import json
import paho.mqtt.client as mqtt
import random
import time
import threading
from dataclasses import dataclass
from typing import Dict
from mqtt import FakeMQTTDevice
class FakeSensor(FakeMQTTDevice):
"""Defines a fake sensor.
Objects of this class have periodically publish a random value to the ... | hacker-club/home-automation | part1/simulated-smart-devices/src/sensors.py | sensors.py | py | 1,415 | python | en | code | 0 | github-code | 13 |
20534088235 | from __future__ import annotations
from typing import Union
from gi.repository import Gio, GObject
import turtlico.lib as lib
import turtlico.lib.legacy as legacy
from turtlico.locale import _
FILE_VERSION_FORMAT = 2
DEFAULT_PROJECT = [('fver', FILE_VERSION_FORMAT), ('plugin', 'turtle')]
class CorruptedFileExcept... | saytamkenorh/turtlico | turtlico/lib/projectbuffer.py | projectbuffer.py | py | 8,869 | python | en | code | 3 | github-code | 13 |
29197187505 | """
Given an array arr[] of length N and an integer X, the task is to find the
number of subsets with a sum equal to X.
Examples:
Input: arr[] = {1, 2, 3, 3}, X = 6
Output: 3
All the possible subsets are {1, 2, 3},
{1, 2, 3} and {3, 3}
Input: arr[] = {1, 1, 1, 1}, X = 1
Output: 4
"""
def count_subsets_with_sum(arr... | sunank200/DSA | dynamicProgramming/0-1_knapsack/count_of_subset_with_sum_equal_to_sum.py | count_of_subset_with_sum_equal_to_sum.py | py | 1,023 | python | en | code | 0 | github-code | 13 |
7736093211 | from CDD2.iface.iWriter import writer
from CDD2.driver.driver import config
class bqWriter(writer):
def write(self, df):
df.write.format("bigquery") \
.option("temporaryGcsBucket", config.get("DEFAULT", "tempBucketPath")) \
.option("table", config.get("DEFAULT", "targetTableName"))... | shivanianjikar-97/CDD-Python | CDD2/impl/bqWriter.py | bqWriter.py | py | 466 | python | en | code | 0 | github-code | 13 |
22262644474 | """
This module only contains functions that others modules call.
I moved them to a separate file because all modules use these functions,
and they can't call each other in a circle.
"""
import itertools
import math
import os
import numpy as np
def get_subclip_soundarray(wavio_oblect, start, end):
framerate = w... | mishadobrits/SVA4 | some_functions.py | some_functions.py | py | 5,229 | python | en | code | 3 | github-code | 13 |
45595274174 | from dbac_lib import dbac_util, dbac_data, dbac_primitives, dbac_feature_ext
import numpy as np
import logging
from sklearn.metrics import average_precision_score, precision_recall_fscore_support
logger = logging.getLogger(__name__)
def _learn_primitives(db_name, db_dir, split_file, prim_rpr_file, ex_size=10, num_e... | rfsantacruz/neural-algebra-classifiers | src/dbac_learn_primitives.py | dbac_learn_primitives.py | py | 8,062 | python | en | code | 3 | github-code | 13 |
20214537653 | num = int(input('Enter the number : '))
exponent = int(input('Enter exponent value : '))
count = 0
power = 1
copy = num
while copy:
copy % 10
count += 1
for i in range(1, exponent + 1):
power = copy * exponent
print(f'{num} has {count} number of digits')
print(f'{num} power {exponent} = {power}') | Jayabhaskarreddy98/python_practice | while_loops/count_and_power_of_number.py | count_and_power_of_number.py | py | 313 | python | en | code | 1 | github-code | 13 |
22526990773 | import asyncio
import os
from pprint import pprint
import nest_asyncio
from pyppeteer import launch
from pyppeteer_stealth import stealth
nest_asyncio.apply()
API_KEY = "API_KEY"
API_USER = "API_USER"
API_URL = "API_URL"
def get_proxy_auth() -> dict:
"""
Check if the proxy authentication keys are set
:... | zhou-en/pyppeteer-scraper | scraper.py | scraper.py | py | 5,662 | python | en | code | 0 | github-code | 13 |
39556517281 | from imagekit.specs import ImageSpec
from imagekit import processors
from PIL import ImageOps
import Image as PILImage
# Helper functions
def make_linear_ramp(white):
# putpalette expects [r,g,b,r,g,b,...]
ramp = []
r, g, b = white
for i in range(255):
ramp.extend((r*i/255, g*i/255, b*i/255))
return ramp
def ... | kevinatienza/CodeSSIU | imageupload/core/ikspecs.py | ikspecs.py | py | 1,473 | python | en | code | 4 | github-code | 13 |
70958962897 | import pygame, sys, random
import model
import view
class EventController:
#Variables that keep track of the model and view class.
model = ""
view = ""
def __init__(self, model, view):
self.model = model
self.view = view
def input(self):
font = pygame.font.SysFont(None, 20)... | DonNamTran/Squid-Knight | eventController.py | eventController.py | py | 2,160 | python | en | code | 0 | github-code | 13 |
23607838259 | # data_local_storage_filepath = '/home/zem/labs/trading-project/rt-persistence'
data_local_storage_filepath = '/home/zembrzuski/labs/the-trading-project/rt-persistence'
elasticsearch_address = 'http://localhost:9200'
# company_code, from_epoch, to_epoch, crumb
yahoo_historical_url = \
'https://query1.finance.yah... | zembrzuski/finance_poller | src/config/local.py | local.py | py | 2,598 | python | en | code | 1 | github-code | 13 |
20173735833 | import arcpy
arcpy.env.overwriteOutput=True
arcpy.env.workspace ="D:/Lesson6_Data"
fc="D:/Lesson6_Data/Cities.shp"
fieldList= ["NAME" ,"SHAPE@XY"]
cipath ='D:/Lesson6_Data/cities.txt'
ciFile = open (cipath, "w")
cursor = arcpy.da.SearchCursor(fc,fieldList)
for row in cursor:
Name = row [0]
X,Y = row [1]
c... | Daviey52/GIS-Python-programming | Geometries02/geometries.py | geometries.py | py | 417 | python | en | code | 0 | github-code | 13 |
40726715894 | from app.server import server
from flask import jsonify
from app.server.check_service import check_database
from datetime import datetime, timedelta, timezone
from flask import current_app, request
@server.route('/info')
def server_status():
"""Get DB and email status
Returns:
json: {
upd... | RainMeoCat/CipherAirSig | backend/app/server/routes.py | routes.py | py | 953 | python | en | code | 0 | github-code | 13 |
15799838965 | #!/usr/bin/python3
import rospy
from geometry_msgs.msg import Twist
from turtlesim.msg import Pose
class turtlesim:
#Initialization
def __init__(self):
rospy.init_node('node_turtle_revolve', anonymous=True)
self.velocity_publisher = rospy.Publisher('/turtle1/cmd_vel', Twist, q... | RoopanJK/Eyantra-AgriBot | src/pkg_task0/scripts/node_turtle_revolve.py | node_turtle_revolve.py | py | 1,646 | python | en | code | 0 | github-code | 13 |
15520805075 | from kafka import KafkaConsumer
def listen():
consumer = KafkaConsumer("sf.police.department.calls",
bootstrap_servers=["localhost:9092"],
client_id="sf-crime-consumer"
)
for message in consumer:
print(f"{message.to... | maribowman/data-streaming | sf_crime_statistics/consumer_server.py | consumer_server.py | py | 428 | python | en | code | 0 | github-code | 13 |
28987233010 | # coding:utf-8
from PyQt5.QtWidgets import QApplication,QMainWindow,QWidget
from untitled_1 import Ui_MainWindow
from untitled_2 import Ui_Form
import sys
class Example(QMainWindow,Ui_MainWindow):
def __init__(self):
super(Example,self).__init__()
self.setupUi(self)
self.children = Childre... | raojixian/pyqt | PyQt5-master/Chapter03/learning/界面跳转.py | 界面跳转.py | py | 747 | python | en | code | 0 | github-code | 13 |
39657779742 | import wx.lib.wxcairo as wxcairo
from .. import _api
from .backend_cairo import cairo, FigureCanvasCairo
from .backend_wx import _BackendWx, _FigureCanvasWxBase, FigureFrameWx
from .backend_wx import ( # noqa: F401 # pylint: disable=W0611
NavigationToolbar2Wx as NavigationToolbar2WxCairo)
@_api.deprecated(
... | cautionlite32/data-science | lib/matplotlib/backends/backend_wxcairo.py | backend_wxcairo.py | py | 1,104 | python | en | code | 0 | github-code | 13 |
20065697368 | from flask import Flask, jsonify, request, send_from_directory, render_template
import requests
requests.packages.urllib3.disable_warnings()
from pytrends.request import TrendReq
pytrends = TrendReq(hl='en-US', tz=360)
app = Flask(__name__, static_url_path='')
@app.route('/')
def root():
return render_template('ind... | spMohanty/SoniTrends | app.py | app.py | py | 1,052 | python | en | code | 0 | github-code | 13 |
34894300929 | import ipdt.player
class Player(ipdt.player.Player):
"""Tit-for-Tat, a strategy that is all about equivalent retaliation."""
name = "Tit-for-tat"
def play(self,last_move):
if last_move is None:
return True
else:
if last_move:
return True
e... | geeklhem/ipdt | ipdt/players/tft.py | tft.py | py | 354 | python | en | code | 2 | github-code | 13 |
15801337295 | # Find the factorial value
# getting input value from the user
n = int(input("Enter a number: "))
# create a function for finding factorial for the given number
def fact(n):
# initialize the value x = 1, factorial of 1 is 1
x = 1
# if user enter the input value is 1, then print value of 1 facto... | satz2000/Python-practiced-notes | Factorial.py | Factorial.py | py | 670 | python | en | code | 0 | github-code | 13 |
948725473 | import sys, re, operator, string, time
## Constraints
# - larger problem decomposed into entities using some form of abstraction
# - entities are never called on directly for actions
# - existence of an infrastructure for publishing and subscribing to events,
# AKA the `bulletin board`
# - entities post event subs... | DEGoodman/EiPS | python/16_bulletinboard.py | 16_bulletinboard.py | py | 3,855 | python | en | code | 0 | github-code | 13 |
34150090829 | # model.py
import torch
from torchvision import models
from torchvision.models.resnet import ResNet50_Weights
from typing import Optional
from utils import load_weights
from config import *
def load_model(snn_type: str,
plant_type: Optional[str] = None
) -> tuple[torch.nn.Module, int] or... | shaharelys/plant_disease_classification | model.py | model.py | py | 1,814 | python | en | code | 0 | github-code | 13 |
28367303569 | """
Core idea of value-iterations is to compute all values of Q(s, a) and for each
state calculate the max action of Q(s, a) given the state. We then know that
V(s) = the action that maximized Q(s, a)
"""
import numpy as np
import gym
def compute_q(P, s, nA, gamma, prev_v):
q = np.zeros(nA)
for a in range(nA... | ASzot/random-implementations | reinforcement-learning/value_iteration.py | value_iteration.py | py | 1,770 | python | en | code | 0 | github-code | 13 |
6168189054 | import numpy as np
from flask import Flask, render_template, request, jsonify
from wl_model import wl_model
import ttide as ttide
import json
app = Flask(__name__)
@app.after_request
def cors(environ):
environ.headers['Access-Control-Allow-Origin']='*'
environ.headers['Access-Control-Allow-Method']... | ggonekim9/flask_harmonic | web_back/app.py | app.py | py | 2,509 | python | en | code | 1 | github-code | 13 |
21984985365 |
nn = all_data.shape[0]
np.random.seed(999)
sample_idx = np.random.random_integers(0, 3, nn)
n_trees = 4100
predv_xgb = 0
batch = 0
day_test = 31
output_logloss = {}
pred_dict = {}
for idx in [0, 1, 2, 3]:
filter1 = np.logical_and(np.logical_and(day_values >= 17, day_values < day_test),
... | zxlmufc/penguin_click | script/generate_gbdt_feature_for_fm.py | generate_gbdt_feature_for_fm.py | py | 1,280 | python | en | code | 0 | github-code | 13 |
15812274833 | """
Implementation of alternating least squares with regularization.
The alternating least squares with regularization algorithm ALS-WR was first
demonstrated in the paper Large-scale Parallel Collaborative Filtering for
the Netflix Prize. The authors discuss the method as well as how they
parallelized the algorithm i... | GrierPhillips/Recommendation-Models | src/als.py | als.py | py | 15,434 | python | en | code | 0 | github-code | 13 |
8805203936 | """
people을 내림차순으로 정렬한 후에 무거운 사람부터 새 보트에 집어넣습니다. limit/2보다 초과하는 사람은 다 넣어요.(어차피 이들끼리는 같이 보트를 탈 수 없기때문)
그리고나서 남은 사람들 중 가장 무거운 사람과 마지막 보트만 체크합니다. 왜냐하면 현재 있는 타고 있는 보트 중에서 마지막에 집어넣은 보트가 가장 여유가 클 것이기 때문에 거기에 못들어가면 어차피 다른 보트에도 못 들어가요. limit보다 작다면 그 보트에 넣어주면 됩니다.
이렇게 구현하니까 반복문 딱 2번만 돌고 효율성 통과했습니다!
"""
def solution(people, li... | Chung-SungWoong/Practice_Python | Python_Test55.py | Python_Test55.py | py | 974 | python | ko | code | 0 | github-code | 13 |
71083990099 | import math
# Cooking Masterclass
# one student package:
# 1 package of flour
# 10 eggs
# 1 apron
budget = float(input())
students = int(input())
flour_pack_price = float(input()) # every fifth package is free
an_egg_price = float(input())
apron_price = float(input()) # increase aprons by 20% because they get dirty... | bobsan42/SoftUni-Learning-42 | ProgrammingFunadamentals/20RegularMidExam/01.py | 01.py | py | 817 | python | en | code | 0 | github-code | 13 |
19481859765 | """
Fetch test lists from https://github.com/citizenlab/test-lists
Populate citizenlab table from the tests lists git repository and the
url_priorities table
The tables have few constraints on the database side: most of the validation
is done here and it is meant to be strict.
Local test run:
PYTHONPATH=analysis... | ooni/backend | analysis/analysis/citizenlab_test_lists_updater.py | citizenlab_test_lists_updater.py | py | 3,782 | python | en | code | 43 | github-code | 13 |
12224635093 | import logging
import os
import re
import uuid
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import CallbackContext
from .constants import *
CALLBACK_SESSION = "callback_session"
logger = logging.getLogger(__name__)
def make_keyboard(buttons: list, context: CallbackContext = No... | eciavatta/merdetti-bot | merdetti/helpers.py | helpers.py | py | 2,982 | python | en | code | 9 | github-code | 13 |
32656791020 | from dataclasses import asdict, dataclass
from typing import ClassVar, Dict
from undictify import type_checked_constructor
from .checksum_algorithm import ChecksumAlgorithm
@type_checked_constructor()
@dataclass
class Checksum:
algorithm: ChecksumAlgorithm
## algorithm: str
value: str
#: The Avro S... | cedardevs/onestop-clients | onestop-python-client/onestop/schemas/psiSchemaClasses/org/cedar/schemas/avro/psi/checksum.py | checksum.py | py | 1,206 | python | en | code | 1 | github-code | 13 |
22002120764 | import random
value = 0
while value < 1:
# Initialize the throw count and the dice values
throw_count = 0
dice1 = 0
dice2 = 0
# Keep rolling the dice until they match
while dice1 != dice2:
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
throw_count += 1
... | YumiVR/SDAM | Sem1/week5/dice_match.py | dice_match.py | py | 471 | python | en | code | 0 | github-code | 13 |
74648744017 | from googleapiclient.discovery import build
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
import os
from google.oauth2.credentials import Credentials
def move_email_to_trash(email_id):
# If modifying these scopes, delete the token.json file.
SCOPES = ... | aryankhatana01/real-time-email-spam-detection | delete_spam/delete_emails_api.py | delete_emails_api.py | py | 1,581 | python | en | code | 0 | github-code | 13 |
10012564808 | import random
global used_question
global count
used_question = [ ]
count = 0
##Gets answer and adds the questions that have been used to a list
def get_answer():
answer = input("Please enter an answer: ")
answer = int(answer)
if answer > 4:
answer = input("Please enter a vali... | tsega200/Driving-Tutor | Actual Program/Quiz_Redone.py | Quiz_Redone.py | py | 7,342 | python | en | code | 0 | github-code | 13 |
25867771712 | from django_filters import FilterSet, DateFilter
from django.forms import DateInput
from .models import Advert, AdvertReply
class AdvertsFilter(FilterSet):
datetime = DateFilter(field_name='datetime',
widget=DateInput(attrs={'type': 'date'}),
lookup_expr='gt',
... | egoranisimov/bboard | bboard/boardapp/filters.py | filters.py | py | 1,012 | python | en | code | 0 | github-code | 13 |
38073407298 | import sys
import traceback
def exc2string2():
"""Provide traceback ehen an exception has been raised"""
llist = sys.exc_info()
errmsg = str(llist[0])
errmsg += str(llist[1])
errmsg += ' '.join(traceback.format_tb(llist[2]))
return errmsg
| rushioda/PIXELVALID_athena | athena/Trigger/TriggerCommon/TriggerMenu/python/jet/exc2string.py | exc2string.py | py | 265 | python | en | code | 1 | github-code | 13 |
37086424886 | import pandas as pd
from itertools import islice
from collections import Counter
file_path = "./Harry Potter.txt"
test_file_path = "./originText.txt"
bksp_rate = 0
evaluation_switch = True
[21111212111, 21121112111, 21112112111, 21211212111, 21121112111, 21111112111, 21211212111, 21121121111, 21121211211, 21112112111,... | Klareliebe7/EMEmanationSEEMOO | hmm.py | hmm.py | py | 26,198 | python | en | code | 0 | github-code | 13 |
19466064085 | def unique_in_order(iterable):
result = []
prev = None
for char in iterable[0:]:
if char != prev:
result.append(char)
prev = char
return result
def main():
result = unique_in_order('AAAABBBCCDAABBB')
print(result)
if __name__ == "__main__":
main() | turo62/exercise | exercise/codewar/unique_in_order.py | unique_in_order.py | py | 309 | python | en | code | 0 | github-code | 13 |
9480889085 | # ---------------------------------------------------------------------------- #
# Title: Assignment 7
# Description: Description of a pickle
# ChangeLog (Who,When,What):
# MCLARK, 02.29.2021, created script
# ---------------------------------------------------------------------------- #
import pickle
# code... | MClark89/IntroToProg-Python-Mod07 | Pickling.py | Pickling.py | py | 870 | python | en | code | 0 | github-code | 13 |
3490030351 | def flames(name1,name2):
total=len(name1)+len(name2)
count=0
flame=['Just "Friends"','Uh-huh, "LOVE!"','Hmm, "Affection."',
'Congrats, "Marriage.."','Whooops.."Enemy!"','Huh.."Sister."']
for let1 in name1:
if let1 in name2:
name2.remove(let1)
count+=1
fi... | PrinceofChum/100-Days-Of-Code | Day 22/flames.py | flames.py | py | 680 | python | en | code | 6 | github-code | 13 |
4005770687 | import matplotlib.pyplot as plt
import datetime
import numpy as np
import re
LOG_FILE_NAME = '20231002_13.04.14.log'
batt_status_re = re.compile(
r'(?P<timestamp>\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2},\d{3})\s'
r'\[\s+INFO\]\s(?:\w+:){6}\sBC300\s(?P<serial>A\d{10})\s-\sBattery\sStatus:'
r'\sVoltage:\s(?P<vo... | rene-becker-setec/BC300_WiringTest | analyze.py | analyze.py | py | 1,432 | python | en | code | 0 | github-code | 13 |
30172046093 | #!/usr/bin/env python
import barobo
from barobo import Linkbot, Dongle
import time
import sys
if __name__ == "__main__":
if len(sys.argv) < 2:
print ("Usage: {0} <Com_Port> [Linkbot Serial ID]".format(sys.argv[0]))
quit()
if len(sys.argv) == 3:
serialID = sys.argv[2]
else:
... | davidko/PyBarobo | demo/with_BaroboCtx_sfp/checkEncoders.py | checkEncoders.py | py | 594 | python | en | code | 0 | github-code | 13 |
70875592979 | # -*- coding: utf-8 -*-
"""
@author: Gabriel Maccari
"""
import pandas
import docx
from datetime import datetime
# Essas são as colunas que se espera que a tabela da caderneta terá
# (com exceção de colunas de estruturas, cujo nome varia com a estrutura)
COLUNAS_TABELA_CADERNETA = {
"Ponto": {
"dtype": ... | FrostPredator/template-builder | Controller.py | Controller.py | py | 21,845 | python | pt | code | 1 | github-code | 13 |
2449670057 | # 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 getMode(self,root,ans):
if not root:
return
ans[root.val] += 1
self.... | asnakeassefa/A2SV_programming | find-mode-in-binary-search-tree.py | find-mode-in-binary-search-tree.py | py | 667 | python | en | code | 1 | github-code | 13 |
11032612897 | import os
from typing import Optional
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from Data_Analysis import Data_Analyse
class Data_Load_Old(object):
column_drop = ['Duplicate_Check',
'PdI Width (d.... | calvinp0/AL_Master_ChemEng | DataLoad.py | DataLoad.py | py | 16,990 | python | en | code | 0 | github-code | 13 |
24218901240 | from collections import Counter, defaultdict
with open('in.txt') as f:
lines = f.read().splitlines()
lines.sort()
guard_minutes = defaultdict(Counter)
for line in lines:
command = line[19:]
current_minute = int(line[15:17])
if command == 'falls asleep':
sleep_start = current_minute
elif ... | prplz/aoc-2018-python | 04/04.py | 04.py | py | 911 | python | en | code | 1 | github-code | 13 |
42960432710 | import datetime
import sys
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Dict, Union
from boto3 import client
from botocore import UNSIGNED
from botocore.client import ClientError, Config
from loguru import logger
from buckets_hunter.utils import dns, hunter_utils
from buckets_hun... | DanielAzulayy/BucketsHunter | buckets_hunter/modules/aws/aws_scanner.py | aws_scanner.py | py | 5,287 | python | en | code | 2 | github-code | 13 |
72739974417 | N, K = map(int, input().split())
A = list(map(int, input().split()))
count = 0
history = [1]
index = -1
while count <= K:
current = history[-1]
_next = A[current - 1]
if _next in history:
index = history.index(_next)
break
else:
history.append(_next)
count += 1
if index ==... | uu64/at-coder | 20200510-ABC167/D.py | D.py | py | 473 | python | en | code | 0 | github-code | 13 |
44716838431 | #!/usr/bin/env python3
# coding: utf-8
'''
Script para formatar e filtrar a tabela do HMMER.
Necessário python3 e o pacote pandas para rodar
o script.
- Para instalar o pacote pandas use:
pip3 install pandas
- Uso:
python3 mtr_00_hmm_table_filtering.py
'''
import pandas as pd
# Arquivo do hmmer e arquivo de saida
hmmer... | Tiago-Minuzzi/lab-stuff | for_colleagues/mtr_01_hmm_table_formatting.py | mtr_01_hmm_table_formatting.py | py | 1,326 | python | pt | code | 0 | github-code | 13 |
10521125344 | # This script uses Python to read in .tif files I downloaded from
# https://croplandcros.scinet.usda.gov/
#import tifffile and pillow to use this script
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
from tifffile import imread, TiffFile, memmap
from PIL import Image
... | 9ngribbenc1/crops | read_tif.py | read_tif.py | py | 1,430 | python | en | code | 0 | github-code | 13 |
2263210201 | import sys
fname = sys.argv[1]
with open(fname,'r') as datfile:
data = datfile.readlines()
for i in range(len(data)):
if 'MISSING' in data[i]:
print(data[i-6].strip())
| mobergd/OneDMin | perl/find_missing.py | find_missing.py | py | 180 | python | en | code | 0 | github-code | 13 |
26570515575 | """Websocket server."""
import asyncio
import base64
import hashlib
import json
import time
import websockets
import auth
from typing import Callable
from configs import config_utils
from exceptions import exceptions
from log import LOG
from obs import obs_base_classes, obs_event_manager, obs_events
class OBSConn... | amorphousWaste/twitch_bot_public | twitch_bot/obs/obs_connection.py | obs_connection.py | py | 9,268 | python | en | code | 0 | github-code | 13 |
73662946896 | import numpy as np
def load_a9a(data_folder):
L = []
file_path = data_folder + 'phpwCsLLW.csv'
with open(file_path, 'r') as f:
first_line = True
for line in f.readlines():
if first_line:
first_line = False
continue
line = line.strip()... | dingdian110/alpha-ml | alphaml/datasets/cls_dataset/a9a.py | a9a.py | py | 710 | python | en | code | 1 | github-code | 13 |
41130638133 | import pygame, sys
from utilidades import intro_transition, cambiar_musica, dibujar_grid
from configuracion import *
from class_personaje import Personaje
from class_enemigo import Enemigo
from class_proyectil import Proyectil
from levels.class_stage_1 import Stage_1
from levels.class_stage_2 import Stage_2
from levels... | HoracioxBarrios/mi_juego_final_limpio | game.py | game.py | py | 19,127 | python | es | code | 2 | github-code | 13 |
38363900596 | """
Data Persistent Loader
Utilities
"""
from simpledbf import Dbf5
import pandas as pd
import pyarrow.parquet as pq
import pyarrow as pa
import os
from tqdm import tqdm
import re
from datetime import datetime
from database_settings import hdfs_utilities as hdfs
import numpy as np
def exports_ingestion(files_folder,... | sergiopostigo/supertrade | data_persistent_loader/utilities.py | utilities.py | py | 6,425 | python | en | code | 0 | github-code | 13 |
22125973749 | from base_classes.article import Article
from base_classes.ArticleMetadata import ArticleMetadata
"""
An Article contains enough information for the article to be rendered anywhere.
"""
class DefaultArticle(Article):
def __init__(self, meta: ArticleMetadata, display_title: str = "", display_content: str ="", next_... | madCode/rss-to-e-reader | default_modules/DefaultArticle.py | DefaultArticle.py | py | 2,152 | python | en | code | 1 | github-code | 13 |
6343926669 | #!/usr/bin/env python
import sys
import unittest
from app.parselog import ParseLog
class TestParseLog(unittest.TestCase):
# CONSIDER ADDING PYTEST FIXTURES FOR CONSTANTS
def setUp( self):
self.parse = ParseLog()
self.goodlog = open('data/test_good.log','r')
self.badlog = open('da... | jonneff/parselog | test/unit/parselog_test.py | parselog_test.py | py | 2,930 | python | en | code | 0 | github-code | 13 |
14848644011 | from flask.scaffold import F
from backend import UPLOAD_FOLDER, app
from flask.globals import request
from flask.json import jsonify
from backend.models import Notification, Report, Student, StudentSchema, Submission, SubmissionRequest, Teacher, TeacherSchema
from backend import db
from collections import defaultdict
... | yajatvishwak/smartclassroom-backend | backend/routes.py | routes.py | py | 9,477 | python | en | code | 1 | github-code | 13 |
30627247997 | # %% Setup
from sklearn.model_selection import learning_curve
from sklearn.datasets import make_blobs
from sklearn.ensemble import RandomForestClassifier as RandForClassy
import numpy as np
import mratplotlib.pyplot as plt
import seaborn as sns
sns.set()
# %% Getting Data
X, y = make_blobs(500, 2, centers=10, cluster... | Negative-light/EGR491-PYMLDS | PROJECT 5/CODE/randForClass.py | randForClass.py | py | 4,570 | python | en | code | 0 | github-code | 13 |
10087228446 | class LRUCache:
#http://chaoren.is-programmer.com/posts/43116.html
#the collections.OrderedDict
#the elements inserted later is behind the elements inserted earlier
#
# @param capacity, an integer
def __init__(self, capacity):
LRUCache.Dict = collections.OrderedDict()
LRUCache.capacity = capacity
LRUCache.nu... | xiaochenai/leetCode | Python/LRU Cache.py | LRU Cache.py | py | 1,232 | python | en | code | 0 | github-code | 13 |
23896881445 | from .d_exceptions import *
def get_logger(file_name: str, level: int) -> logging.Logger:
logger = logging.getLogger(file_name)
handler = logging.StreamHandler()
formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
handler.setFormatter(formatter)
logg... | hacker-DOM/adoc-math | adoc_math/_common/e_utils.py | e_utils.py | py | 3,163 | python | en | code | 4 | github-code | 13 |
15803989636 | import tkinter as tk
# Define the conversion fxn
def convert():
input_value = float(input_entry.get())
from_unit = from_unit_var.get()
to_unit = to_unit_var.get()
# Define conversion rates
conversidon_rates = {
("Miles", "Kilometers"): 1.60934,
("Kilometers", "Miles"): 0.621371,
... | Jensen416/UnitConverter | unitconv.py | unitconv.py | py | 577 | python | en | code | 0 | github-code | 13 |
19283676709 | from object_checker.base_object_checker import AbacChecker
from apps.core.models import User, Image
class ImageChecker(AbacChecker):
@staticmethod
def check_delete(request_user: User, image: Image):
if request_user.is_superuser:
return True
if request_user == image.offer.user:
... | Philliip/MTAA_SELLIT_BACKEND | apps/core/checkers/image.py | image.py | py | 364 | python | en | code | 0 | github-code | 13 |
40067170739 | # This Python file uses the following encoding: utf-8
# Question 1
# Author: Kelvin Zhang
# Date Created: 2015-10-15
# Prompt for initial user input
initialCost = float(input("What is the initial cost of the flight? £"))
suitcaseWeight = float(input("Enter the weight of your suitcase (kg): "))
totalCost = initialCost... | kz/compsci-homework | 1. AS Level/1. IF Statements/Question 1.py | Question 1.py | py | 1,593 | python | en | code | 1 | github-code | 13 |
71702512659 | import socket
from dataclasses import dataclass, field
from os import getpid
from typing import List, Callable, Optional
from icmplib import ICMPRequest, ICMPv6Socket, ICMPv4Socket, is_ipv4_address, is_ipv6_address
from icmplib.exceptions import *
from icmplib.sockets import ICMPSocket
@dataclass
class Hop:
succ... | illided/PyTrace | trace.py | trace.py | py | 2,989 | python | en | code | 0 | github-code | 13 |
21781131883 | #!/usr/bin/env python
import rospy
from std_srvs.srv import Empty
class clearService:
def __init__(self):
rospy.init_node('service_node_1')
rospy.wait_for_service('/move_base/clear_costmaps')
self.client = rospy.ServiceProxy('/move_base/clear_costmaps',Empty)
def request(self):
... | ssahn0806/ROSLA | skeleton/clear_costmap.py | clear_costmap.py | py | 680 | python | en | code | 1 | github-code | 13 |
1339880961 | import statsmodels.api as sm
from gauge import tester
class detector():
def __init__(self, video, cropX1, cropY1, cropX2, cropY2):
self.video= video
self.cropX1 = cropX1
self.cropY1= cropY1
self.cropX2 = cropX2
self.cropY2=cropY2
def detect(self):
... | pranav168/Fauty-Gauge-Detector | detector.py | detector.py | py | 682 | python | en | code | 0 | github-code | 13 |
22626023122 | import mysql.connector
from random import randint, choice
import datetime
# Устанавливаем соединение с базой данных
connection = mysql.connector.connect(
host='localhost',
user='roanvl',
password='!And487052!',
database='co_crm'
)
# Создаем объект для выполнения SQL-запросов
cursor = connection.cursor... | ROANVL/python-django-crm-graduation | fill_scripts/fill_db_orders.py | fill_db_orders.py | py | 2,094 | python | ru | code | 0 | github-code | 13 |
15369395925 | from repofish.utils import save_json
import numpy
import pandas
import json
folder = "/home/vanessa/Documents/Dropbox/Code/Python/repofish/analysis/pypi"
packages = pandas.read_csv("%s/pypi_filtered.tsv" %folder,sep="\t",index_col=0)
meta_folder = "%s/packages" %(folder)
# Making a dataframe will take too much memor... | vsoch/repofish | analysis/pypi/3.map_dependencies.py | 3.map_dependencies.py | py | 6,398 | python | en | code | 3 | github-code | 13 |
72063071379 | x = int(input())
y = int(input())
z = int(input())
n = int(input())
permutations = []
x_values = range(0, x+1)
y_values = range(0, y+1)
z_values = range(0, z+1)
for i in x_values:
for j in y_values:
for k in z_values:
sum = i+j+k
if sum != n and i<= x and j<=y and k<=... | 1realjoeford/learning-python | HackerRankanswers/list_que.py | list_que.py | py | 457 | python | en | code | 1 | github-code | 13 |
72245973139 | import random
class Question:
def __init__ (self, q_text, q_right_answer, q_all_answers):
self.text = q_text
self.right_answer = q_right_answer
self.all_answers = q_all_answers
class Quiz:
def __init__ (self, q_list):
self.question_list = q_list
self.score = 0
... | kacpergondek/100daysofcode | Day_17_Quiz/objects.py | objects.py | py | 1,362 | python | en | code | 0 | github-code | 13 |
70095624018 | # The file contains internal elements for cards and components
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash_devices.dependencies import Input, Output, State, MATCH, ALL
import dash_table
import plotly.express as px
import pandas
import io
impo... | MalekovAzat/DashExp | workersSample/tools/internalComponentCreator.py | internalComponentCreator.py | py | 3,990 | python | en | code | 0 | github-code | 13 |
13523980417 | import numpy as np
import cv2 as cv
import sys
import numpy as np
import imutils
def box_centers(boxes):
'''Args:
boxes: array of [x,y,w,h], where (x,y) is the
top left corner and w and h are the width and length'''
return np.array([[x+w/2, y+h/2] for [x,y,w,h] in boxes])
def cluster_boxes(box... | cesargvcompsci/Zephyrus | Tests/clustering_test.py | clustering_test.py | py | 5,071 | python | en | code | 0 | github-code | 13 |
73860127696 | # # Modified Simple Notebook Visualiser from psychemedia at https://gist.github.com/psychemedia/9b7808d81e3ee3461444330f3b0971ac
"""
Script to visualize time series for notebooks
Authors: Jerry Song (jerrysong1324), Doris Lee (dorisjlee)
"""
import glob
import json
import os
import shutil
import matplotlib.pyplot as p... | dorisjlee/jupyter_analysis | AnalysisNotebooks/nbvis.py | nbvis.py | py | 3,573 | python | en | code | 0 | github-code | 13 |
15637362873 | import pyttsx3
import datetime
import os
import smtplib
engine = pyttsx3.init('sapi5') #used for intake api voices from windows
voices = engine.getProperty('voices')
print(voices[0].id)
engine.setProperty('voice',voices[0].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
pass
... | Yogishm22/Yogishm22 | nova.py | nova.py | py | 776 | python | en | code | 0 | github-code | 13 |
72922402577 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
unit tests for the add_af.cwl
"""
import os
import sys
from pluto import (
PlutoTestCase,
CWLFile
)
class TestAddAFCWL(PlutoTestCase):
cwl_file = CWLFile('add_af.cwl')
def test_add_af(self):
"""
Test IMPACT CWL with tiny dataset
... | mskcc/pluto-cwl | tests/test_add_af_cwl.py | test_add_af_cwl.py | py | 1,962 | python | en | code | 1 | github-code | 13 |
40016754761 | import numpy as np
import matplotlib.pyplot as plt
from openbox import Optimizer, sp, ParallelOptimizer
import warnings
warnings.filterwarnings("ignore")
# Define Search Space
space = sp.Space()
x1 = sp.Real(name="x1", lower=-5, upper=10, default_value=0)
x2 = sp.Real(name="x2", lower=0, upper=15, default_value=0)
x3 ... | HuangHaoyu1997/Parallel-CGP | search_v4.py | search_v4.py | py | 3,438 | python | zh | code | 0 | github-code | 13 |
74076923216 | import base64
import json
import os
import zlib
import numpy as np
import cv2
from pietoolbelt.datasets.common import get_root_by_env, BasicDataset
__all__ = ['SuperviselyPersonDataset']
class SuperviselyPersonDataset(BasicDataset):
def __init__(self, include_not_marked_people: bool = False, include_neutral_obj... | HumanParsingSDK/datasets | human_datasets/supervisely_person.py | supervisely_person.py | py | 3,663 | python | en | code | 2 | github-code | 13 |
72952640658 | __author__ = 'ando'
import numpy as np
from time import time
import logging as log
import random
import networkx as nx
from itertools import zip_longest
from scipy.io import loadmat
from scipy.sparse import issparse
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import cpu_count
from os impo... | andompesta/ComE | utils/graph_utils.py | graph_utils.py | py | 7,648 | python | en | code | 58 | github-code | 13 |
37086365706 | from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
def main_keyboard(send_url):
markup = InlineKeyboardMarkup()
markup.row_width = 1
markup.add(
InlineKeyboardButton(
text='Ссылка на оплату 👁',
url=f'{send_url}'
),
InlineKeyboardB... | KlareoN/Simple_Payment | keyboard.py | keyboard.py | py | 472 | python | ru | code | 1 | github-code | 13 |
34655342851 | import langchain
from langchain.schema import SystemMessage
from langchain.agents import OpenAIFunctionsAgent,initialize_agent
from langchain.agents import AgentType
from langchain.chat_models import ChatOpenAI
#from langchain.chains.conversation.memory import ConversationBufferWindowMemory
from langchain.memory import... | statscol/ocr-LLM-image-summarizer | src/text_summarizer.py | text_summarizer.py | py | 2,381 | python | en | code | 1 | github-code | 13 |
28880450855 | from checkers.constants import WHITE
from checkers import simulation
import random
def alpha_beta(board, depth, max_player, game, heuristic, max_color, min_color, alpha, beta):
"""
Create a minimax tree by recursively exploring every legal move till max depth is reached. We pass down our alpha and beta
va... | mh022396/Checkers-AI | src/minimax/alpha_beta.py | alpha_beta.py | py | 3,391 | python | en | code | 0 | github-code | 13 |
43728150643 | import numpy as np
import cv2
import pandas as pd
# Import required libraries
# read image
img = cv2.imread('./synthetic.jpg') # Read the image file
# convert to gray scale
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Convert the image to grayscale
'''
IF you have a multi-channel image, then extract the cha... | ahmadSoliman94/Computer-Vision | Image Processing/Gabor filter/gabor_filter_banks.py | gabor_filter_banks.py | py | 2,953 | python | en | code | 0 | github-code | 13 |
4882971427 | import sqlite3
# Define the path to your SQLite database
db_path = "data/bronze/comp_db_2.db"
# Create a connection to the database
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
try:
# Calculate and update change_180d and change_90d columns in mcap_change
cursor.execute(
"""
UPDATE m... | PaulApivat/data_engineer | practice/data-pipeline-project/comp_scripts/add_mcap_change.py | add_mcap_change.py | py | 1,206 | python | en | code | 0 | github-code | 13 |
6703466685 | starting_number = int(input('Enter Number of Organisms: '))
daily_increase = int(input('Enter Daily Increase: ')) / 100
total_days = int(input('Enter Days Left to Multiply: '))
first = True
print('Day Approximate',' ',' Population')
print('------------------------------')
for total_days in range (starting_number, t... | alecmsmith18/Project-1 | pop.py | pop.py | py | 560 | python | en | code | 0 | github-code | 13 |
70054571859 | # pylint: skip-file
# vim: expandtab:tabstop=4:shiftwidth=4
#pylint: disable=too-many-branches
def main():
''' ansible module for gcloud iam service-account keys'''
module = AnsibleModule(
argument_spec=dict(
# credentials
state=dict(default='present', type='str', choices=['pres... | openshift/openshift-tools | ansible/roles/lib_gcloud/build/ansible/gcloud_iam_sa_keys.py | gcloud_iam_sa_keys.py | py | 2,395 | python | en | code | 161 | github-code | 13 |
70958163218 | fname = input("Enter a filename: ")
try:
fhand = open(fname)
# finp = fhand.read()
except:
print("File cannot be found: ", fname)
quit() #or break or continue
count = 0
for line in fhand:
if not line.startswith("Subject:") :
continue
count = count + 1
print("There were", count, " subjec... | geniusboywonder/PY4E-Assignments | Course 2 - Python Data Structures/Openfile.py | Openfile.py | py | 342 | python | en | code | 1 | github-code | 13 |
20888441933 | from fastapi import APIRouter, status, UploadFile, File
from scripts.utils.s3_image_util import S3
from scripts.core.handlers.image_handler import ImageHandler
image_router = APIRouter(prefix='/api')
@image_router.post('/upload', status_code=status.HTTP_200_OK)
def upload_image(file: UploadFile = File(...)):
ima... | Sayed-Imran/AWS-S3-fastapi | scripts/services/images_service.py | images_service.py | py | 666 | python | en | code | 0 | github-code | 13 |
34766458600 | from unittest import TestCase
from piicatcher.explorer.files import Tokenizer
from piicatcher.piitypes import PiiTypes
from piicatcher.scanner import ColumnNameScanner, NERScanner, RegexScanner
class RegexTestCase(TestCase):
def setUp(self):
self.parser = RegexScanner()
def test_phones(self):
... | dm03514/piicatcher | tests/test_scanner.py | test_scanner.py | py | 4,741 | python | en | code | null | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.