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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
30622885552 | from pybricks.hubs import CityHub
from pybricks.pupdevices import Motor, ColorDistanceSensor
from pybricks.parameters import Port, Stop, Color
from pybricks.tools import wait
# Initialize devices.
hub = CityHub()
motor = Motor(Port.B)
colorSensor = ColorDistanceSensor(Port.A)
while True:
colors = []
angles ... | olivia-tomassetti/CEEO-smartmotors | SmartMotorPython/Pybricks/SmartMotorLEGOBoost.py | SmartMotorLEGOBoost.py | py | 2,282 | python | en | code | 0 | github-code | 36 |
72692461223 | #!/usr/bin/env python3
import asyncio
import unittest
from click.testing import CliRunner
from base_cli import _handle_debug, async_main, main
class TestCLI(unittest.TestCase):
def test_async_main(self) -> None:
self.assertEqual(0, asyncio.run(async_main(True)))
def test_debug_output(self) -> None... | cooperlees/base_clis | py/tests.py | tests.py | py | 597 | python | en | code | 2 | github-code | 36 |
18914948323 | import pytest
from src.guess_number_higher_or_lower import Solution
@pytest.mark.parametrize(
"n,pick,expected",
[
(10, 6, 6),
(1, 1, 1),
(2, 1, 1),
],
)
def test_solution(n, pick, expected, monkeypatch):
monkeypatch.setenv("SECRET", str(pick))
assert Solution().guessNumbe... | lancelote/leetcode | tests/test_guess_number_higher_or_lower.py | test_guess_number_higher_or_lower.py | py | 337 | python | en | code | 3 | github-code | 36 |
10392845560 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
import os
import copy
import time
import pickle
import numpy as np
from tqdm import tqdm
import yaml
import argparse
import torch
from tensorboardX import SummaryWriter
# from src.options import args_parser
from update import LocalUpdate
from utils i... | gongzhimin/Trojan-Attack-Against-Structural-Data-in-Federated-Learning | src/federated_main_nonattack.py | federated_main_nonattack.py | py | 4,103 | python | en | code | 1 | github-code | 36 |
12409403965 | import collections
import re
import furl
from django.core.urlresolvers import resolve, reverse, NoReverseMatch
from django.core.exceptions import ImproperlyConfigured
from django.http.request import QueryDict
from rest_framework import exceptions
from rest_framework import serializers as ser
from rest_framework.fields... | karenhanson/osf.io_rmap_integration_old | api/base/serializers.py | serializers.py | py | 49,061 | python | en | code | 0 | github-code | 36 |
70508461223 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
# Created on 2019-05-25 10:00
import re
"""
验证邮箱地址
"""
def verification(str):
re_str = re.compile('^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$')
result = re.match(re_str, str)
print(result)
if result is None:
return "error"
else:
... | lhtest429/Music-website-based-django | MyMusic/music/my_tools/verification.py | verification.py | py | 439 | python | en | code | 0 | github-code | 36 |
9480946225 | import random
from collections import defaultdict
import torch
from ltp import LTP
from .base_func import BaseFunc
class NerFunc(BaseFunc):
def __init__(self, config):
super(NerFunc, self).__init__(config)
self.augment_num = config.ner_func.augment_num
self.combine_dict = self.load_ner_f... | shawn0wang/Text_Augment | function/ner_func.py | ner_func.py | py | 1,703 | python | en | code | 0 | github-code | 36 |
71656882025 | # Based on https://github.com/NATSpeech/NATSpeech
import utils.commons.single_thread_env # NOQA
import json
import numpy as np
import os
import random
import traceback
from functools import partial
from resemblyzer import VoiceEncoder
from tqdm import tqdm
from utils.audio.align import get_mel2note
from utils.audio.... | jisang93/VISinger | preprocessor/base_binarizer.py | base_binarizer.py | py | 16,910 | python | en | code | 13 | github-code | 36 |
10834105092 | from turtle import Turtle
ALIGNMENT = 'center'
FONT = ('courier', 20, 'normal')
class GameOver(Turtle):
def __init__(self):
super().__init__()
self.hideturtle()
self.color('white')
self.penup()
self.write(arg=f'Game Over', align=ALIGNMENT, move=False, font=FO... | joshrivera116/snake | gameover.py | gameover.py | py | 325 | python | en | code | 0 | github-code | 36 |
3184473921 | # -*- coding: utf-8 -*-
import yaml
from . import instructions
from . import value_containers
from .exceptions import ParserException
from .method import Method
def _process_func(method, func):
if not func or not isinstance(func, dict):
raise ParserException('"func" not defined')
method.function_nam... | lukleh/Tiny-Stackbased-Virtual-Machine-in-Python | TSBVMIP/code_parser.py | code_parser.py | py | 4,024 | python | en | code | 4 | github-code | 36 |
12210284781 | import openpyxl
from openpyxl.utils import cell
def read(config):
try:
workbook = openpyxl.load_workbook(config.source_path, data_only=True)
datasets = {}
for source_tab_name in config.source_tabs:
datasets[source_tab_name] = extract_dataset(workbook, source_tab_name, config)
... | mcweglowski/codegens | codegen/excel/excel_reader.py | excel_reader.py | py | 1,239 | python | en | code | 0 | github-code | 36 |
8561617144 | stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
price = 0
for fruit in stock:
price += stock[fruit] * prices[fruit]
print(str(int(price)) + " bucks")
| EdyStan/homework_beetroot | homework/lms-homework/06_dicts-for-loops-comprehensions/task_2.py | task_2.py | py | 265 | python | en | code | 0 | github-code | 36 |
25086860267 | class SiteData:
lang_dict = {
'C++': 'image/langs/cpp-logo.png',
'Python': 'image/langs/python-logo.jpg',
'Go': 'image/langs/go-logo.png',
'PL/pgSQL': 'image/langs/plpgsql.png'
}
projects = [
{
'name': 'web-testing-tool',
'image': lang_dict['... | vnkrtv/my-site | app/projects.py | projects.py | py | 11,856 | python | en | code | 0 | github-code | 36 |
417669106 | from array import *
import os
from PIL import Image
Buttons=[0x300fd40bf,0x300fdc03f,0x300fd20df,0x300fda05f,0x300fd609f,0x300fde01f,0x300fd10ef,0x300fd906f,0x300fd50af,0x300fd30cf,0x300fdb24d,0x300fd728d,0x300fdf20d,0x300fd8877,0x300fd48b7]
ButtonsNames=["One","Two","Three","Four","Five","Six","Seven","Eight","Nine",... | Rakibuz/Robotics_HCI | Raspberry Pi/hypothetical_final_0.1.py | hypothetical_final_0.1.py | py | 4,522 | python | en | code | 0 | github-code | 36 |
957425679 | from flask import render_template, flash, redirect, url_for, request, current_app
from flask_login import login_required, current_user
from apps.app import db
from apps.model import Task, Kind
from apps.todolist import todolist
from apps.todolist.course import AddCategory, AddToDoList, ChangeToDoList
# User View Tas... | INversionNan/Flask | apps/todolist/base.py | base.py | py | 8,802 | python | en | code | 0 | github-code | 36 |
73917308585 | from __future__ import print_function, division
import vim
import subprocess
python_format = '/home/ekern/python_format/python_format.py'
if __name__ == '__main__':
start = vim.current.range.start
end = vim.current.range.end
buf = vim.current.buffer
while buf[end].rstrip().endswith('\\'):
end... | ekedaigle/python-format | python_format_vim.py | python_format_vim.py | py | 1,090 | python | en | code | 0 | github-code | 36 |
32409336010 | import time
from torch import optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from ..models import *
from ..utils import AverageMeter, calculate_accuracy, Logger, MyDataset
from visdom import Visdom
DatasetsList = ['CIFAR10', 'CIFAR100']
ModelList = {'AlexNet': Ale... | jimmy0087/model_zoo_torch | modelzoo/libs/train/train.py | train.py | py | 13,106 | python | en | code | 0 | github-code | 36 |
3274572845 | T = int(input())
for t in range(1, T+1):
n, m = map(int, input().split())
li = list(map(int, input().split()))
rli = []
for i in li:
if i%4 == 0 or i%6 == 0 or i%7 == 0 or i%9 == 0 or i%11 == 0: # 보석의 배수에 하나라도 해당되면
rli.append(i) # 새로운 리스트에 추가
result = []
for i in ran... | mihyeon1234/TIL | 알고수업/부울경_2반_이미현/Algo2_부울경_2반_이미현.py | Algo2_부울경_2반_이미현.py | py | 774 | python | ko | code | 0 | github-code | 36 |
37744864931 | import tagNtokenize
import correlation_cf as cf
import time
from os.path import dirname, join
import pickle
current_dir = dirname(__file__)
file_path = join(current_dir, 'question_answers.pickle')
with open(file_path, 'rb') as f:
question_answers= pickle.load(f)
current_milli_time = lambda: int(r... | msheroubi/Charles_the_Chatbot | charles.py | charles.py | py | 2,366 | python | en | code | 0 | github-code | 36 |
21683160230 | from flask import Flask, make_response, jsonify, request
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import requests
import numpy as np
import pandas as pd
import json
app = Flask(__name__)
rows = []
@app.route('/getDB')
def emplace():
prod_... | jane-k/RecommendationSystem | app.py | app.py | py | 4,148 | python | en | code | 0 | github-code | 36 |
20857956907 | # https://www.hackerrank.com/challenges/recursive-digit-sum/problem
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'superDigit' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. STRING n
# 2. INTEGER k
#
... | manu-karenite/Problem-Solving | Recursion/superNumber.py | superNumber.py | py | 920 | python | en | code | 0 | github-code | 36 |
37636221210 | # A full binary tree is a binary tree where each node has exactly 0 or 2 children.
# Return a list of all possible full binary trees with N nodes. Each element of the answer is the root node of one possible tree.
# Each node of each tree in the answer must have node.val = 0.
# You may return the final list of trees... | sunnyyeti/Leetcode-solutions | 894_All_Possible_Full_Binary_Trees.py | 894_All_Possible_Full_Binary_Trees.py | py | 2,512 | python | en | code | 0 | github-code | 36 |
9416483162 | # Cemantix game solver
import logging
import os
import yaml
from src import *
os.chdir(os.path.abspath(os.path.dirname(__file__)))
with open("config.yaml", "r") as config_file:
config = yaml.load(config_file, Loader=yaml.FullLoader)
logging.basicConfig(filename=f"./logs/cemantix_{dt.datetime.now().strftime(format... | CorentinMary/cemantix | main.py | main.py | py | 922 | python | en | code | 0 | github-code | 36 |
12530669262 | import torch
from torch import nn
from .strategy import Strategy
from .utils import ner_predict, re_predict
class EntropySampling(Strategy):
def __init__(self, annotator_config_name, pool_size, setting: str='knn', engine: str='gpt-35-turbo-0301',
reduction: str='mean'):
super().__init__(an... | ridiculouz/LLMaAA | src/active_learning/entropy_sampling.py | entropy_sampling.py | py | 1,745 | python | en | code | 5 | github-code | 36 |
29884394473 | """ Run Length Encoding """
def main():
""" print changed password """
text = input()
collector = []
each_al = ""
result = ""
count = ""
if len(text) > 1:
for jay in range(len(text)-1):
if text[jay] == text[jay+1]:
each_al += text[jay]
else:
... | DefinitelyNotJay/ejudge | Run Length Encoding.py | Run Length Encoding.py | py | 806 | python | en | code | 0 | github-code | 36 |
5030031968 | # Um professor quer sortear um dos seus quatro alunos para apagar o quadro.
# Faça um programa que ajude ele, lendo o nome dos alunos e escrevendo na tela o nome do escolhido.
import random
print('='*23, '\n QUEM APAGARÁ A LOUSA❓')
print('='*23)
n1 = input('Primeiro nome: ')
n2 = input('Segundo nome: ')
n3 = input('T... | hdtorrad/Estudos-Python3 | Só exercícios/ex019-Sortei Apagar lousa.py | ex019-Sortei Apagar lousa.py | py | 484 | python | pt | code | 1 | github-code | 36 |
20465273392 | # -*- coding: utf-8 -*-
# @Project : CrawlersTools
# @Time : 2022/6/21 17:06
# @Author : MuggleK
# @File : proxy.py
import httpx
from loguru import logger
def get_proxies(proxy_url=None, http2=False):
"""
默认httpx代理模式
@param proxy_url: 代理请求链接
@param http2: 默认http1.1规则
@return:
"""
... | MuggleK/CrawlersTools | CrawlersTools/requests/proxy.py | proxy.py | py | 697 | python | en | code | 16 | github-code | 36 |
899076815 | import sqlite3
import os
import bamnostic_mod as bn
import argparse
import bisect
import time
#Downloads\Lung\47b982b3-c7ce-4ca7-8c86-c71c15979620\G28588.NCI-H1915.1.bam
#Downloads\Lung\98a0206b-29f5-42d3-957b-6480e2fde185\G20483.HCC-15.2.bam
#Downloads\Lung\18004fb1-89a2-4ba1-a321-a0aa854e98c3\G25210.NCI-H510.1.bam
#... | InSilicoSolutions/Splicer | Splicer/splicerSampleProcessor.py | splicerSampleProcessor.py | py | 12,134 | python | en | code | 0 | github-code | 36 |
23971763808 | from replit import db
from util import str_to_arr
from person import Person
def matches_to_string(matches):
string = "List of matches:\n"
for match in matches:
string += match + "\n"
return string
async def make_connections(message, person_calling):
matches = []
person_1 = Person.str_to_person(db[f"{person_ca... | Sharjeeliv/monty-bot | connect.py | connect.py | py | 1,083 | python | en | code | 0 | github-code | 36 |
43552704116 | import os
from bot.misc.util import download, calculate_hash
from bot.functions import lessonsToday
from bot.database.main import filesDB
import hashlib
import datetime
files = filesDB()
def filesCheck(urls) -> list:
done = []
filesHash = []
for name, url in urls.items():
h = files.get(name)
... | i3sey/EljurTelegramBot | bot/functions/files.py | files.py | py | 651 | python | en | code | 2 | github-code | 36 |
43372121821 | import cv2
import numpy as np
video_path = '/Users/bigphess/Desktop/omnidirection/res/rabbit_250fps.mp4'
cap = cv2.VideoCapture(0)
cap2 = cv2.VideoCapture(video_path)
while True:
ret, frame = cap2.read()
# image = cv2.imread('/Users/bigphess/Downloads/IMG_6453.JPG')
debug = frame
if cv2.waitKey(100) & 0xFF ==... | Bigphess/Notes | OpenCV/polor.py | polor.py | py | 703 | python | en | code | 1 | github-code | 36 |
2532407157 | import re
import sys
import numpy as np
import pandas as pd
from sklearn.base import TransformerMixin
from sklearn.compose import ColumnTransformer
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder
class Preprocess... | kernc/Containersec | lib.py | lib.py | py | 3,012 | python | en | code | 0 | github-code | 36 |
19956578192 | """
Given an array of strings, return another array containing all of its longest strings.
Example
For inputArray = ["aba", "aa", "ad", "vcd", "aba"], the output should be
solution(inputArray) = ["aba", "vcd", "aba"].
Input/Output
[execution time limit] 4 seconds (py3)
[input] array.string inputArray
... | scottmm374/coding_challenges | codesignal/arcade/intro/all_longest_strings.py | all_longest_strings.py | py | 920 | python | en | code | 1 | github-code | 36 |
29454018683 | #!/usr/bin/python3 -u
import sys, re, math
from img2c import *
def ascii2c(lines, img, dest = sys.stdout, h = None, w = None):
width = max([len(line) for line in lines])
height = len(lines)
image = [[0 for x in range(width)] for y in range(height)]
y = 0
for line in lines:
x = 0
... | michaelrm97/Turnomatic | software/graphics/ascii2c.py | ascii2c.py | py | 1,863 | python | en | code | 1 | github-code | 36 |
20822639893 | import json
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import euclidean_distances
import numpy as np
from sklearn.linear_model import LogisticRegression
def load():
with open('C:/Users/Administrator/Desktop/backend-interview-1/samples/generated_test_cases.txt', 'r',
... | Qt7mira/LenovoIVProblem | mira/part3.py | part3.py | py | 4,656 | python | en | code | 1 | github-code | 36 |
8944245432 | import numpy as np
from numpy import linalg as LA
#
# a = np.array( [[1,2],
# [2,4]] )
# b = np.array( [[2,3],
# [3,4]])
#
# print(np.matmul(a,b))
# Excercise 1.1 => 3b
array_1 = np.array([0,-1,-2])
array_2 = np.array([1,-3])
array_3 = np.array([1,-3])
array_4 = np.array([1,-3])
array_5 = np.array([1,2])
arra... | Mithunjack/Optimization-and-Data-Science | Mithun/ODS- Final/ex1.py | ex1.py | py | 2,615 | python | en | code | 1 | github-code | 36 |
26579648710 | def uglyNumber(n):
if n<=0:
return False
while not n%2:
n//=2
while not n%3:
n//=3
while not n%5:
n//=5
return n==1
assert True == uglyNumber(1)
assert False == uglyNumber(-2125563)
assert True == uglyNumber(1024)
assert False == uglyNumber(19)
| msencer/leetcode-solutions | easy/python/UglyNumber.py | UglyNumber.py | py | 299 | python | en | code | 5 | github-code | 36 |
71300190183 | import time
import tqdm
import torch
import numpy as np
import torch.nn as nn
import torch.optim as optim
from utils import *
def prepare_sequence(seq, word2idx):
idxs = [word2idx[w] for w in seq]
return torch.tensor(idxs, dtype=torch.long)
class BiLSTM_CRF_S(nn.Module):
def __init__(self, vocab_size, l... | YaooXu/Chinese_seg_ner_pos | BiLSTM_CRF.py | BiLSTM_CRF.py | py | 20,207 | python | en | code | 5 | github-code | 36 |
31563331171 | import requests
from bs4 import BeautifulSoup
url = input("Entrer l'URL du site : ")
response = requests.get(url)
if response.status_code == 200:
html_content = response.content
else:
print("Erreur lors de la récupération de la page.")
soup = BeautifulSoup(html_content, "html.parser")
# Extraire le titre de... | Lenked/ScrappingApp | main.py | main.py | py | 690 | python | fr | code | 0 | github-code | 36 |
2363693116 | import os
def read(archivo):
try:
archivo=archivo+".txt"
print("El contenido es: ")
file=open(archivo,"r")
for line in file:
print(line, end="")
except FileNotFoundError:
print("No se encontro")
def encontrar():
count = 0
for dirpath, dir... | JulioGrimaldoM/LPC | Practica_1/Buscar.py | Buscar.py | py | 1,239 | python | es | code | 0 | github-code | 36 |
29005165219 | #The program should ask the user to enter three numbers (one number at a time) and should work out how many of these are even and odd. Finally, the program should display the number of even numbers and odd numbers entered.
# Ask user for numbers
print("Please enter the first whole number?")
first_number = int(input()... | Combei/QHO426 | week2/decisions/counter.py | counter.py | py | 978 | python | en | code | 0 | github-code | 36 |
830016519 | #!/usr/bin/env python
import gzip
import sys
import tarfile
import threading
import urllib.request
import zipfile
import lib.download.task as task
import lib.independence.fs as fs
import lib.ui.color as printer
# The greater purpose of (functions in) this file is
# to download a list of DownloadTasks
class Download... | Sebastiaan-Alvarez-Rodriguez/Meizodon | lib/download/downloader.py | downloader.py | py | 3,963 | python | en | code | 4 | github-code | 36 |
800426611 | import mtcnn
from mtcnn.mtcnn import MTCNN
import cv2
detector = MTCNN() # MTCNN is CNN based algorithm
video = cv2.VideoCapture(0)
video.set(3,2000)
video.set(4,3000) # Same as previous technique
while (True):
ret, frame = video.read()
if ret == True:
location = detector.detect_faces... | Sagar-Khode/Face-Detection | MTCNN.py | MTCNN.py | py | 1,089 | python | en | code | 0 | github-code | 36 |
43763780283 | # -*-coding:utf8-*-
################################################################################
#
#
#
################################################################################
"""
模块用法说明:达人推荐详情页
Authors: Turinblueice
Date: 2016/9/10
"""
from base import base_frame_view
from util import log
from gui_wid... | turinblueice/androidUIAutoTest | activities/discover_details_activities/talent_recommend_activity.py | talent_recommend_activity.py | py | 9,563 | python | en | code | 5 | github-code | 36 |
23497344492 | from io import BytesIO
from PIL import Image
from uuid import uuid4
from django.core.files import File
JPEG_IMAGE_QUALITY = 100
def crop_image(image):
im = Image.open(image)
(height, width) = (im.height, im.width)
shortest_side = min(height, width)
dimensions = (0, 0, shortest_side, shortest_side)
... | adrianeriksen/photographic | photographic/photos/utils.py | utils.py | py | 610 | python | en | code | 0 | github-code | 36 |
6800272551 | import yaml
from populate.populator.common.errors import ConfigurationError
from .projects_manager import ProjectsManager
def project_constructor(loader, node):
if isinstance(node, yaml.ScalarNode):
item = loader.construct_scalar(node)
if not isinstance(item, str) or not item:
raise... | tomasgarzon/exo-services | service-exo-projects/populator/projects/project_loader.py | project_loader.py | py | 715 | python | en | code | 0 | github-code | 36 |
10496867860 | import tensorflow as tf
from model.model_builder import ModelBuilder
from utils.model_post_processing import merge_post_process
from tensorflow.keras.models import Model
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
from utils.priors import *
import argparse
pa... | chansoopark98/Tensorflow-Keras-Object-Detection | convert_frozen_graph.py | convert_frozen_graph.py | py | 5,426 | python | en | code | 6 | github-code | 36 |
10178056973 | import bitstring
import collections
import math
from array import array
import os
""" HGR = 280 * 192
C64 = 40*24 chars => 320 * 192 ; display 3min 20 (2000 images) sec instead of 3min 40 (2200)
Video = 192 * 160 (24*20)
"""
if os.name == 'nt':
IMG_PREFIX = r'c:/PORT-STC/PRIVATE/tmp'
FFMPEG = r'c:... | wiz21b/badapple | utils.py | utils.py | py | 20,203 | python | en | code | 13 | github-code | 36 |
22918946072 | import unittest
import os
import lsst.utils.tests
import pandas as pd
import numpy as np
import asyncio
import matplotlib.pyplot as plt
from astropy.time import TimeDelta
from lsst.utils import getPackageDir
from lsst.summit.utils.enums import PowerState
from lsst.summit.utils.efdUtils import makeEfdClient, getDayObs... | lsst-sitcom/summit_utils | tests/test_tmaUtils.py | test_tmaUtils.py | py | 17,835 | python | en | code | 4 | github-code | 36 |
25717810431 | from cassiopeia import Queue, Summoner, SummonersRiftArea
def test_summonersrift_map():
summoner = Summoner(name="Kalturi", region="NA")
match = summoner.match_history(queues=[Queue.ranked_solo_fives])[0]
for frame in match.timeline.frames:
for event in frame.events:
if event.type == "... | meraki-analytics/cassiopeia | test/test_map_location.py | test_map_location.py | py | 713 | python | en | code | 522 | github-code | 36 |
36991126999 | """
A simple tool for converting 512x64x512 icemap files into vxl.
NOTE: this does NOT do the icemap footer variant. (Yet.)
GreaseMonkey, 2012 - Public Domain
"""
from __future__ import print_function
import sys, struct
# Backwards compatibility - make new code work on old version, not vice-versa
PY2 = sys.versio... | iamgreaser/iceball | tools/icemap2vxl.py | icemap2vxl.py | py | 1,637 | python | en | code | 111 | github-code | 36 |
23716751711 | import json
from PIL import Image
import os
def main(json_file_path):
json_file = open (json_file_path)
json_string = json_file.read()
json_data = json.loads(json_string)
image = json_data[0]
#for image in json_data:
image_file_path = image['image_path']
image_to_crop = Image.open(image_f... | Larbohell/datasyn | crop_image.py | crop_image.py | py | 1,446 | python | en | code | 1 | github-code | 36 |
33088736021 | import random
while 1:
a=input('''Press Enter to play <--- Rock! Paper! and Sciccor! -->
To 'QUIT' press any key and press enter !''')
if a=='':
l=["Rock","Paper","Scissor"]
a=random.randint(0,2)
print(l[a])
else:
break
| Kashyap03-K/Easy-and-simple-Python-games | Rock_Paper_Scissor.py | Rock_Paper_Scissor.py | py | 276 | python | en | code | 0 | github-code | 36 |
22347170498 | import os
from logging import (
CRITICAL,
DEBUG,
ERROR,
getLogger,
INFO,
Logger,
WARNING,
)
from pathlib import Path
from rich.logging import RichHandler
from rich.highlighter import NullHighlighter
from .config import BodyworkConfig
from .constants import (
DEFAULT_LOG_LEVEL,
DEFA... | bodywork-ml/bodywork-core | src/bodywork/logs.py | logs.py | py | 2,348 | python | en | code | 430 | github-code | 36 |
16571409721 | import os
import io
import hashlib
from base64 import standard_b64encode
from six.moves.urllib.request import urlopen, Request
from six.moves.urllib.error import HTTPError
from infi.pyutils.contexts import contextmanager
from infi.pypi_manager import PyPI, DistributionNotFound
from logging import getLogger
logger = ... | Infinidat/infi.pypi_manager | src/infi/pypi_manager/mirror/mirror_all.py | mirror_all.py | py | 6,623 | python | en | code | 2 | github-code | 36 |
37636102850 | # Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1.
# We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children.
# Return the number of binary tree... | sunnyyeti/Leetcode-solutions | 823 Binary Trees With Factors.py | 823 Binary Trees With Factors.py | py | 1,503 | python | en | code | 0 | github-code | 36 |
10589852930 | """
Limpieza de datos usando Pandas
-----------------------------------------------------------------------------------------
Realice la limpieza del dataframe. Los tests evaluan si la limpieza fue realizada
correctamente. Tenga en cuenta datos faltantes y duplicados.
"""
import pandas as pd
def clean_data():
... | ciencia-de-los-datos/data-cleaning-solicitudes-credito-paquijanoc | pregunta.py | pregunta.py | py | 3,360 | python | es | code | 0 | github-code | 36 |
18932441390 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author : MG
@Time : 19-4-3 下午5:28
@File : __init__.py.py
@contact : mmmaaaggg@163.com
@desc :
"""
import logging
from logging.config import dictConfig
# log settings
logging_config = dict(
version=1,
formatters={
'simple': {
'for... | IBATS/IBATS_Utils | ibats_utils/__init__.py | __init__.py | py | 1,277 | python | en | code | 3 | github-code | 36 |
40222438483 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
'''
Ideje kako poboljšati kod:
1. Kreirati novu klasu satelit koja je pod gravitacijskim utjecajem ostalih planeta ali ona ne utječe na njih
2. Ta klasa ima metodu boost koja ju odjednom ubrza
3. Pogledati i proba... | MatejVe/Solar-System-Simulation | Solar system for testing new code.py | Solar system for testing new code.py | py | 12,798 | python | en | code | 0 | github-code | 36 |
70388179303 | from django.contrib.auth import get_user_model
from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models
from foodgram_backend.settings import STANDARTLENGTH
User = get_user_model()
class Tag(models.Model):
name = models.CharField(
max_length=STANDARTLENGTH,
... | Gustcat/foodgram-project-react | backend/recipes/models.py | models.py | py | 4,848 | python | en | code | 0 | github-code | 36 |
4023780816 | from bs4 import BeautifulSoup
import urllib.request
import os
class Sachalayatan:
sachDS = {}
def __init__(self, BASE_URL):
self.sachDS['BASE_URL'] = BASE_URL
def getHtml(self, url=''):
if len(url) > 0:
source = urllib.request.urlopen(url).read()
soup = BeautifulSou... | kakanghosh/sachalayatan | scrapping.py | scrapping.py | py | 2,300 | python | en | code | 0 | github-code | 36 |
41242548190 | # -*- coding: utf-8 -*-
# @Date : 2017-08-02 21:54:08
# @Author : lileilei
def assert_in(asserqiwang,fanhuijson):
if len(asserqiwang.split('=')) > 1:
data = asserqiwang.split('&')
result = dict([(item.split('=')) for item in data])
try:
value1=([(str(fanhuijson[key])) for key... | mingming2513953126/pythondemo | FXTest-master/app/common/panduan.py | panduan.py | py | 859 | python | en | code | 0 | github-code | 36 |
13847534454 | from collections import namedtuple
# Define a namedtuple to represent search results
SearchResult = namedtuple(
"SearchResult", ["name", "location", "job_title", "profile_url"]
)
# Dummy data for testing
dummy_data = [
SearchResult(
name="John Smith",
location="New York, NY",
job_titl... | Kwekuasiedu315/PROJECTS | askademy/aska/web/dummy.py | dummy.py | py | 9,177 | python | en | code | 0 | github-code | 36 |
5543905270 | def fixLayout(str):
en = "qwertyuiop[]asdfghjkl;'zxcvbnm,./"
ru = "йцукенгшщзхъфывапролджэячсмитьбю."
res = ""
for i in range(len(str)):
pos = en.find(str[i])
if pos != -1:
res += ru[pos]
else:
pos = ru.find(str[i])
if pos != -1:
... | Grigorij-Kuzmin/Python | Раскладка клавиатуры.py | Раскладка клавиатуры.py | py | 473 | python | en | code | 0 | github-code | 36 |
33807342463 | from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QHBoxLayout
# 0 = empty
# 1 = X
# 2 = O
board = [0,0,0,0,0,0,0,0,0]
app = QApplication([])
window = QWidget()
layout1 = QHBoxLayout()
layout2 = QHBoxLayout()
layout3 = QHBoxLayout()
layoutMain = QVBoxLayout()
buttons = [QPushButton(' '),... | j-tetteroo/tictactoe-fpga | python/tictactoe.py | tictactoe.py | py | 7,748 | python | en | code | 0 | github-code | 36 |
29426080346 | import requests
from bs4 import BeautifulSoup
import csv
url = "https://www.gov.uk/search/news-and-communications"
page = requests.get(url)
soup = BeautifulSoup(page.content, "html.parser")
titres_bs = soup.find_all('a')
titres = []
for titre in titres_bs:
titres.append(titre.string)
print(titres)
en_tet... | Lemak243/python_ | ecrire.py | ecrire.py | py | 512 | python | fr | code | 0 | github-code | 36 |
42242684970 | import math
import numpy as np
import matplotlib.pyplot as plt
gap_list = [5.0e-6, 7.5e-6, 10e-6]
lam_list = np.logspace(-1.0,2.0,20)*1e-6
print(lam_list)
sens_vals_num = np.zeros((len(lam_list),len(gap_list)))
for i in range(len(gap_list)):
for j in range(4,len(lam_list)):
gap = gap_list[i]
la... | charlesblakemore/opt_lev_analysis | casimir/force_calc/plot_point_pot.py | plot_point_pot.py | py | 1,570 | python | en | code | 1 | github-code | 36 |
75127834344 | import sys
from cravat import BaseAnnotator
from cravat import InvalidData
import sqlite3
import os
class CravatAnnotator(BaseAnnotator):
def annotate(self, input_data):
chrom = input_data['chrom']
pos = input_data['pos']
ref = input_data['ref_base']
alt = input_data['alt_base']
... | KarchinLab/open-cravat-modules-karchinlab | annotators/thousandgenomes_european/thousandgenomes_european.py | thousandgenomes_european.py | py | 907 | python | en | code | 1 | github-code | 36 |
14451113965 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 19 15:27:09 2017
@author: Administrator
"""
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD
model = Sequential() #模型 初始化
model.add( Dense( 20, 64)) #添加 输入 层( 20 节点)、 第一 隐藏 层( 64 节点) 的 连接
... | golfbears/gameofclassname | keras_sample.py | keras_sample.py | py | 1,334 | python | zh | code | 0 | github-code | 36 |
12958605056 | import sys
from requests import get
from core.colors import bad, info, red, green, end
def honeypot(inp):
honey = 'https://api.shodan.io/labs/honeyscore/%s?key=C23OXE0bVMrul2YeqcL7zxb6jZ4pj2by' % inp
try:
result = get(honey).text
except:
result = None
sys.stdout.write('%s No inform... | s0md3v/ReconDog | plugins/honeypot.py | honeypot.py | py | 635 | python | en | code | 1,623 | github-code | 36 |
41133436478 | from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPalette
from PyQt5.QtWidgets import *
app = QApplication([])
app.setStyle('Fusion')
window = QWidget()
palette = QPalette()
palette.setColor(QPalette.ButtonText, Qt.blue)
app.setStyleSheet("QPushButton { margin: 10ex; background-color: #4747D2 }")
app.setPalette(pal... | imdiode/PythonExper | home5.py | home5.py | py | 476 | python | en | code | 0 | github-code | 36 |
21050437162 | import unittest
import json
from app import create_app, bad_request, forbidden, not_found, unauthorized, internal_error
class APITestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.app_context.push()
self.cli... | hungvm90/flask_tdd | tests/test_health_check_api.py | test_health_check_api.py | py | 2,834 | python | en | code | 0 | github-code | 36 |
8724066404 | """
Example of pi-IW: guided Rollout-IW, interleaving planning and learning.
"""
import numpy as np
import tensorflow as tf
from planning_step import gridenvs_BASIC_features, features_to_atoms
from online_planning import softmax_Q_tree_policy
# Function that will be executed at each interaction with the environment
... | aig-upf/pi-IW | online_planning_learning.py | online_planning_learning.py | py | 5,661 | python | en | code | 3 | github-code | 36 |
9580739784 | #!/usr/bin/python3
'''
File Storage
'''
import os
import json
import models
from models.base_model import BaseModel
from models.user import User
from models.state import State
from models.city import City
from models.amenity import Amenity
from models.place import Place
from models.review import Review
classes = {
... | Davidbukz4/AirBnB_clone | models/engine/file_storage.py | file_storage.py | py | 1,815 | python | en | code | 0 | github-code | 36 |
20149744558 | # from django.http import HttpResponseServerError
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import serializers, status
from holdmycomicsapi.models import User
class UserView(ViewSet):
"""HMC Users View"""
def create(self, request):
"""... | SeaForeEx/HoldMyComics-Server | holdmycomicsapi/views/user.py | user.py | py | 1,451 | python | en | code | 1 | github-code | 36 |
13820585974 | '''
You are given the following information, but you may prefer to do some research
for yourself.
- 1 Jan 1900 was a Monday.
- Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twe... | jydiw/assorted-algorithms | project-euler/python/19_counting-sundays.py | 19_counting-sundays.py | py | 1,172 | python | en | code | 0 | github-code | 36 |
41701093659 | # Returns maximal decimal precision of a list of coins
def get_decimal_precision(list_coins):
precision = 0
for c in list_coins:
if not '.' in str(c):
continue
p_coin = len(str(c).split('.')[1])
if p_coin > precision:
precision = p_coin
return precision
# Ret... | MatthMig/CoinChangeProblem | main.py | main.py | py | 1,683 | python | en | code | 0 | github-code | 36 |
71017062823 | """ som exception handling """
""" my own exception raise"""
#raise Exception("hell wrong one")
""" handle exception divide by 0"""
try:
a=int(input("Enter the first number :"))
b=int(input("Enter second numbe :"))
print(a/b)
except ZeroDivisionError:
print("Idiot, you have try to divide with zero")
el... | bg0csj/Pythonbeginners | exception.py | exception.py | py | 347 | python | en | code | 0 | github-code | 36 |
28240417211 | import requests
import argparse
import json
import pandas as pd
import streamlit as st
APP_URL = "http://127.0.0.1:8000/predict"
# Adding arguments to customize CLI
argparser = argparse.ArgumentParser(description='Process hyper-parameters')
argparser.add_argument('--movie_title', type=str, default='', help='movie t... | lethologicoding/text_summarization | app/server.py | server.py | py | 1,345 | python | en | code | 0 | github-code | 36 |
25380312208 | #!usr/bin/env python
# coding:utf-8
__author__ = 'sunyaxiong'
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import os
sys.path.append('E:/GitWorkspace/enndc_management/enndc_management')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
import django
django.setup()
from django.db.models import F, Co... | willsion/enndc_management | vmserver/pyvmomi_api/appinfo_excel_to_db.py | appinfo_excel_to_db.py | py | 1,630 | python | en | code | 0 | github-code | 36 |
32199462370 | #!/usr/bin/python3
"""hard coding is a hard working"""
import requests
import sys
if __name__ == '__main__':
moi = requests.get(sys.argv[1])
if moi.status_code >= 400:
print('Error code: {}'.format(moi.status_code))
else:
print(moi.text)
| jinDeHao/alx-higher_level_programming | 0x11-python-network_1/7-error_code.py | 7-error_code.py | py | 267 | python | en | code | 0 | github-code | 36 |
34112929148 | import requests
import json
battles_win_history = []
# Request Player History from splinterland API
resp = requests.get('https://api.splinterlands.io/battle/history?player=kingsgambit0615').json()
battles = resp['battles']
temp = []
for battle in battles:
temp.append(battle['mana_cap'])
output = []... | jomarmontuya/splinterlands-bot-python | data.py | data.py | py | 1,816 | python | en | code | 0 | github-code | 36 |
19500865293 | import csv
from ctypes import pointer
import math
from time import sleep
from unittest import result
from matplotlib import pyplot as plt
import matplotlib.animation as animation
from matplotlib.pyplot import MultipleLocator
import numpy as np
def write_csv_list_a(sk_list, path):
with open(path,'a',... | JYLinOK/3DSKeleton | showSkeleton.py | showSkeleton.py | py | 19,714 | python | en | code | 1 | github-code | 36 |
38966181487 |
def isChange(arr, n, before):
flag = True
new_arr = arr[:(n//2)]
new = []
for i in range(len(new_arr)):
new.append(new_arr[i][0])
for i in range(len(new_arr)):
if new[i] not in before:
flag = False
break
return flag, new
def solution(n, student, poi... | leehyeji319/PS-Python | 기출/22winter2.py | 22winter2.py | py | 936 | python | en | code | 0 | github-code | 36 |
30346539101 | import os
import psycopg2
from flask import Flask, render_template, request, url_for, redirect
from app import app
def get_db_connection():
conn = psycopg2.connect(host='localhost',
database='restaurant',
user=os.environ['DB_USERNAME'],
... | anthonygfrn/Restaurant-App-Demo1 | app/routes.py | routes.py | py | 1,668 | python | en | code | 0 | github-code | 36 |
26974973866 | from .helpers import fetch_one, create_and_return_id
def get_set_id(conn, source):
SQL = "SELECT id FROM Sets WHERE source=%s"
data = (source, )
return fetch_one(conn, SQL, data)
def create_set(conn, source, dj_id, venue_id, occasion_id):
SQL = "INSERT INTO Sets (dj_id, source, occasion_id, venue_id... | cocain-app/crawler | database/set.py | set.py | py | 511 | python | en | code | 0 | github-code | 36 |
28592053848 | import random
import time
#These have to do with importing the pictures
import io
import os
import PySimpleGUI as sg
import PIL
from PIL import Image
n = 49
image = Image.open(r'C:\Users\carte\OneDrive\Desktop\Coding\Hangman\HM_' + chr(n) + '.png')
image.thumbnail((200, 200))
bio = io.BytesIO()
image.save(bio, ... | CarterDFluckiger/Hangman | Hangman.py | Hangman.py | py | 7,079 | python | en | code | 0 | github-code | 36 |
33512429756 | # -*- coding: utf-8 -*-
#
# File: setuphandlers.py
#
#
# GNU General Public License (GPL)
#
__docformat__ = 'plaintext'
from collective.contact.core.interfaces import IContactCoreParameters
from plone import api
from z3c.relationfield.relation import RelationValue
from zope import component
from zope.intid.interfaces... | collective/collective.contact.core | src/collective/contact/core/setuphandlers.py | setuphandlers.py | py | 11,311 | python | en | code | 6 | github-code | 36 |
13395821581 | """
Entrypoints.
@author: gjorando
"""
import os
import json
from datetime import datetime
import torch
import click
from PIL import Image
import neurartist
def odd_int(value):
value = int(value)
if value % 2 == 0:
raise ValueError("Odd number required")
return value
def threshold_or_neg(value... | gjorando/style-transfer | neurartist/cli.py | cli.py | py | 10,810 | python | en | code | 2 | github-code | 36 |
8798334453 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""key.py: Handles the keysubmissions for groups"""
import json
import os
import sqlite3
import sys
import string
import auth
from httperror import HTTPError
RETURN_HEADERS = []
def __do_get():
RETURN_HEADERS.append('Status: 403')
return "This script is NOT g... | daGnutt/skvaderhack | api/key.py | key.py | py | 6,279 | python | en | code | 0 | github-code | 36 |
34603270416 | import tensorflow as tf
import pandas as pd
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
#mnist = input_data.read_data_sets('./data/', one_hot = True)
def numtolist(num):
'将标签转化为01数组'
r1... | cloud0606/AI | BP神经网络/bp3d_2l.py | bp3d_2l.py | py | 10,717 | python | en | code | 0 | github-code | 36 |
35206134452 | from typing import List
import random
##################################
# GENERAL STUFF
class Queen():
def __init__(self, pos: int, threats: int = -1):
# the position of the queen on the board
self.pos = pos
# the number of threats on the queen
self.threats = threats
def ... | Just-Hussain/n-queen | nqueen.py | nqueen.py | py | 12,806 | python | en | code | 0 | github-code | 36 |
36120976493 | from typing import Any, Dict
import os
import sys
from forte.data.caster import MultiPackBoxer
from forte.data.data_pack import DataPack
from forte.data.multi_pack import MultiPack
from forte.data.readers import OntonotesReader, DirPackReader
from forte.data.readers.deserialize_reader import MultiPackDirectoryReader
f... | asyml/forte | examples/serialization/serialize_example.py | serialize_example.py | py | 4,579 | python | en | code | 230 | github-code | 36 |
33908545643 | budget = float(input())
number_nights = int(input())
price_one_night = float(input())
percent_more_expenses = int(input())/100
if number_nights > 7:
price_one_night *= 0.95
total = (number_nights * price_one_night) + (percent_more_expenses * budget)
left_needed_money = abs(budget - total)
if budget >= total:
... | IvayloSavov/Programming-basics | exams/6_7_July_2019/family_trip.py | family_trip.py | py | 458 | python | en | code | 0 | github-code | 36 |
28078812679 | import numpy as np
from PIL import Image
img=Image.open("tiger.jpg")
img=np.array(img)
def rgb2gray(rgb):
return np.dot(rgb, [0.299, 0.587, 0.114])
img=rgb2gray(img)
row=img.shape[0]
col=img.shape[1]
print(row)
print(col)
# img.resize(1200,1920);
# row=img.shape[0]
# col=img.shape[1]
# print(row)
# print(col)
Ima... | NegiArvind/NeroFuzzyTechniques-Lab-Program | compressing_filter.py | compressing_filter.py | py | 787 | python | en | code | 2 | github-code | 36 |
43299849494 | #!/usr/bin/env python
bundle = ['sqlite3', 'ssl', 'crypto', 'ffi', 'expat', 'tcl8', 'tk8', 'gdbm',
'lzma', 'tinfo', 'tinfow', 'ncursesw', 'panelw', 'ncurses', 'panel',
'panelw']
import os
from os.path import dirname, relpath, join, exists, basename, realpath
from shutil import copy, copytree
impor... | mozillazg/pypy | pypy/tool/release/make_portable.py | make_portable.py | py | 4,560 | python | en | code | 430 | github-code | 36 |
35217427072 | from urllib.request import urlopen
import urllib
from selenium import webdriver
from bs4 import BeautifulSoup
import http.client
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.writer.excel import ExcelWriter
from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE
import json
import re
impor... | Just-Doing/python-caiji | src/work/2021年3月15日/chemical.py | chemical.py | py | 3,863 | python | en | code | 1 | github-code | 36 |
28493766698 | import time
import os
import numpy as np
import pyaudio
import tensorflow as tf
import speech_recognition as sr
from datetime import datetime
import wave
import threading
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from ThreeCharacterClassicInference import ThreeCharacterCl... | charis2324/SoundCube | src/main.py | main.py | py | 11,703 | python | en | code | 0 | github-code | 36 |
72467060903 | from edgar3.filing_13f import Filing_13F
from edgar3 import __version__
import os
import datetime
import csv
from google.cloud import storage
from distutils import util
from io import StringIO
def save_filing(fil: Filing_13F, year: int, quarter: int):
path_with_name = f"etl-13f/processed/reports/{year}/{quarter}... | kfarr3/etl-13f | process_filings/src/process_filings.py | process_filings.py | py | 4,530 | python | en | code | 0 | github-code | 36 |
1456859147 | class Node:
def __init__(self, ip, type=None, target=False):
self.ip = ip
self.hostname = ip
#node is default, we expect to work with 'endnode', 'router', ...
self.type = type
self.target = target
self.plugins = {}
def addPluginResults(self, name,lines):
... | xychix/gtrcrt | node.py | node.py | py | 2,369 | python | en | code | 0 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.