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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
28075594780 | import sklearn
import pandas as pd
from collections import Counter
import math
from sklearn.datasets import load_iris
### compute entropy for a set of classification, provided as a pandas Series
def entropy(classes) :
vals = set(classes)
counts = Counter(classes)
ent = 0.0
for val in vals :
fr... | He-Zhao17/USF_Works | Python_AI/Python-IntroToAI-Assign3-rMake/Python-IntroToAI-Assign3-rMake/dt.py | dt.py | py | 4,814 | python | en | code | 0 | github-code | 13 |
20953187542 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#import logging
#logging.basicConfig(level=logging.INFO)
import pdb
s = '0'
n = int(s)
pdb.set_trace() #运行到这里会自动暂停进入pdb调试环境
#logging.info('n = %d' %n)
print(10/n) | jsqwe5656/MyPythonNote | py_debug/test_err.py | test_err.py | py | 245 | python | en | code | 0 | github-code | 13 |
38387733909 | import pytest
from pydantic import ValidationError
from app.models.orm_models.advertisement import Advertisement
from app.models.orm_models.user import User
from app.repositories.advertisement_repository import AdvertisementRepo
from app.repositories.user_repository import UserRepository
from app.services.advertisemen... | devOceanblue/marketing-API-Server-project | tests/unit/services/test_advertisement.py | test_advertisement.py | py | 1,250 | python | en | code | 0 | github-code | 13 |
71964715858 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import re
import heapq
from collections import namedtuple, defaultdict, Counter
#from urlparse import urlparse
def get_lines(filename):
with open(filename, 'rU') as f:
for line in f:
yield line
def get_matches(reader, pattern, processor):
regex ... | avrybintsev/log_parser | parser.py | parser.py | py | 5,379 | python | en | code | 0 | github-code | 13 |
37563340364 | inputStr = '''57
2 2
50 30
30 27'''
count = -1
def input():
global count
count += 1
splitArr = inputStr.split('\n')
return splitArr[count]
import math
lowestAmount = -1
total = 0
def getAmount(price, count):
price = float(price)
count = float(count)
global total,lowestAmount
bundle_c... | JrontEnd/luogu | P1909/app.py | app.py | py | 801 | python | en | code | 0 | github-code | 13 |
19975332284 | """This module contains our main WebView widget for Kivy."""
from kivy.core.window import Window
from kivy.clock import Clock
from kivy.event import EventDispatcher
from kivy.uix.actionbar import ActionView, ActionBar, ActionButton
from kivy.uix.widget import Widget
from android.runnable import run_on_ui_thread
from... | nodegraph/youmacro | pythonwebview/webviewwrapper.py | webviewwrapper.py | py | 5,526 | python | en | code | 0 | github-code | 13 |
6251694636 | #!/usr/bin/env python2.6
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
#from __future__ import unicode_literals
import csv
import os
from StringIO import StringIO
import numpy as np
DIRLAHMAN = '/home/taro/src/s2r/lahman58'
class LahmanReader(object):
... | nomo17k/s2r | s2r/lahman58.py | lahman58.py | py | 7,388 | python | en | code | 1 | github-code | 13 |
43973352213 | from kivy.uix.image import Image
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition
from kiv... | janalencypino/posedetection | New UI/kivy_ready_made_routine.py | kivy_ready_made_routine.py | py | 17,646 | python | en | code | 0 | github-code | 13 |
26949461254 | #######2022-01-20
from asyncio.windows_events import NULL
import requests
from bs4 import BeautifulSoup as bs
from time import time
import datetime
import openpyxl ####### 엑셀 write에 사용
import all_companys_list as C ####### 종목 코드 리스트
import test_companys_list as T ####### 구동 테스트를 위한 종목 코드 샘플 리스트
from tqdm impor... | jongsung1/script | financial statements/financial_statements.py | financial_statements.py | py | 9,537 | python | en | code | 0 | github-code | 13 |
27236871527 | #!/usr/bin/env python3
import logging
import numpy
import math
import copy
import sys
from mini_op2.framework.core import DataType, Parameter, AccessMode
from mini_op2.framework.system import SystemSpecification, SystemInstance, load_hdf5_instance
from mini_op2.framework.control_flow import *
from numpy import ndarr... | joshjennings98/fyp | graph_schema-4.2.0/apps/nursery/op2/mini_op2/apps/odd_even_dot_product.py | odd_even_dot_product.py | py | 2,922 | python | en | code | 0 | github-code | 13 |
12973426181 | from django.urls import path
from . import views
app_name = "accounts"
urlpatterns = [
path('', views.homepage, name="homepage"),#url for homepage
path('register/', views.register, name="register"), #url for register
path("login/", views.loginpage, name="login"),#url for login
path('logout/', views.... | Pranayea/Heisenberg_ADC2 | Phoby/accounts/urls.py | urls.py | py | 366 | python | en | code | 0 | github-code | 13 |
74514476498 | '''
CHẴN – LẺ - NGUYÊN TỐ
Cho một số nguyên dương không quá 500 chữ số.
Hãy kiểm tra xem số đó có thỏa mãn đồng thời ba tính chất sau hay không?
Vị trí chẵn là chữ số chẵn
Vị trí lẻ là chữ số lẻ
Tổng chữ số là một số nguyên tố.
Input
Dòng đầu ghi số bộ test (không quá 10)
Mỗi bộ test ghi trên một dòng giá trị số nguyê... | cuongdh1603/Python-Basic | PY01056.py | PY01056.py | py | 1,030 | python | vi | code | 0 | github-code | 13 |
10345035357 | import numpy as np
def save_weights_model(model, filename):
"""
Save weights to file.
Args:
model: a instance of a Model class that has been trained
filename: string value representing the name of the file
"""
with open(filename, 'wb') as f:
np.save(filename, model.best_we... | IrinaMBejan/Higgs_Bosson_Project | scripts/utils.py | utils.py | py | 1,651 | python | en | code | 0 | github-code | 13 |
25055558595 | from random import randint, choice, shuffle
# number 21
num = 3
wins = 0
for i in range(10000):
n = randint(0, 9)
if n == num:
wins += 1
print(f'{wins/100}%')
# number 30
money = 0
for i in range(10000000):
ace = 1
cards = [1, 2, 3, 4, 5]
shuffle(cards)
pick = 0
while ace in cards:
cards.remo... | tinuh/applied-statistics | Chapter 10.py | Chapter 10.py | py | 552 | python | en | code | 0 | github-code | 13 |
6497821459 | from PyQt5.QtWidgets import *
import pafy
import os
import urllib.request
from os import path
import sys
import humanize
from moviepy.editor import VideoFileClip
from Main import Ui_MainWindow
class mainapp(QMainWindow , Ui_MainWindow):
def __init__(self , parent=None):
super(mainapp,self).__init__(paren... | MohamedMostafaSoliman/Download-Manager | DownloadManager/DM.py | DM.py | py | 7,769 | python | en | code | 0 | github-code | 13 |
30810020044 | from django.http import Http404
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from .forms import ProductForm #, RawProductForm
from .models import Product
# Create your views here.
#Created views for each of the CRUD actions
#Using Django l... | Shahran29/InventoryManagement | src/trydjango/products/views.py | views.py | py | 1,894 | python | en | code | 0 | github-code | 13 |
72915378898 | import os
import os.path
import io
import re
import sys
import enum
import json
import fnmatch
import datetime
import traceback
import functools
import contextlib
import shlex
import mimetypes
from typing import (Any, Callable, IO, Iterator,
Optional, Sequence, Tuple, List, Type, Union,
... | qutebrowser/qutebrowser | qutebrowser/utils/utils.py | utils.py | py | 26,444 | python | en | code | 9,084 | github-code | 13 |
17657437204 | # https://www.hackerrank.com/challenges/ip-address-validation/problem?h_r=next-challenge&h_v=zen&isFullScreen=false
import re
def main():
# define patterns
pattern4 = r"^(([\d]{1,2}|[1][\d][\d]|[2][0-5][0-5])[\.]?){4}$"
pattern6 = r"^(([a-f\d]?){3}[a-f\d][:]){7}([a-f\d]?){4}$"
# read input then proce... | dp-wu/HackerRank | regex/IP_Address_Validation.py | IP_Address_Validation.py | py | 667 | python | en | code | 0 | github-code | 13 |
12001537440 | # _*_ coding:utf8 _*_
'''
Pedagogical example realization of seq2seq recurrent neural networks, using TensorFlow and TFLearn.
More info at https://github.com/ichuang/tflearn_seq2seq
'''
from __future__ import division, print_function
import sys
# sys.setdefaultencoding('utf-8')
class DataLoad():
def __init__(sel... | liguoyu1/python | Learning/CNN/DataLoad.py | DataLoad.py | py | 1,280 | python | en | code | 49 | github-code | 13 |
30998852749 | from base import Tab
from PySide6.QtCore import Slot
class ScihubTab(Tab):
def __init__(self, app, window, backend) -> None:
super().__init__(app, window, backend)
self.window.refIdentifierEdit.setPlaceholderText('DOI|PMID|URL')
self.window.proxyEdit.setPlaceholderText('http://127.0.0.1:... | Roy-Kid/paperInspector | paperInspector/scihubTab.py | scihubTab.py | py | 1,808 | python | en | code | 0 | github-code | 13 |
27738677662 | import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from Resnet_fashion import*
from IPython import display
import time
import sys
import random
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import torch.nn.functional as F
import num... | Yekse/python_learning | 人脸识别/haarcascades/Run.py | Run.py | py | 3,956 | python | en | code | 0 | github-code | 13 |
31896747765 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 21 03:05:27 2020
@author: whorehay
"""
number10sec =0
dope= True
while(dope):
numToadd =0
if (number10sec%360 ==0):
print("fan running")
numToadd = numToadd+60;
if (number10sec%1440 ==0):
print("water running")
... | pequode/class-projects | ec441_intro_to_computer_networks/functions/testsers.py | testsers.py | py | 539 | python | en | code | 0 | github-code | 13 |
12272108210 | def solution(operations):
answer = []
for operation in operations:
cmd_list = operation.split(" ")
_oper , _v = cmd_list[0], int(cmd_list[1])
if _oper == "I":
answer.append(_v)
elif answer:
del answer[answer.index(max(answer) if _v > 0 else min(answer))]
... | DevNimo/https-github.com-DevNimo-BaekJoonHub | 프로그래머스/lv3/42628. 이중우선순위큐/이중우선순위큐.py | 이중우선순위큐.py | py | 377 | python | en | code | 0 | github-code | 13 |
29665042960 | ## This program will calculate hours worked based on a start time and endtime. Also with the option to calculate pay ##
import datetime
#Ask user for starting time
def start_time():
while True:
try:
a = datetime.datetime.strptime(input('What is your starting time??\nEnter in HH:MM(AM/PM) format ... | yseki12/personal_projects | CalcWorkHoursandPay.py | CalcWorkHoursandPay.py | py | 2,623 | python | en | code | 0 | github-code | 13 |
22322375918 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from urllib.parse import urlparse
import requests
import scrapy
URLS = [
"http://my.yoolib.com/mht/collection/2008-yacht-auxiliaire-de-10-5-metres/?n=2131"
]
DATA_DIR = "/home/jean-baptiste/mht_files"
TRANSLATE_TABLE = {
"\xa0": "Dimensions du document"
}
cl... | spanska/yoolib-scrapper | spiders/picture_spider.py | picture_spider.py | py | 1,543 | python | en | code | 0 | github-code | 13 |
73655943057 | import torch
def evaluate(model, loss_func, test_dl):
model.eval()
running_loss = 0.0
correct_labels = 0
total_labels = 0
predictions = []
probabilities = []
labels = []
with torch.no_grad():
for data in test_dl:
inputs, label = data
outputs = mode... | bjhammack/predict-at-bat-outcome | src/predict_at_bat_outcome/model/test.py | test.py | py | 1,489 | python | en | code | 1 | github-code | 13 |
27831006445 | from django.contrib import messages
from django.http import request
from django.http.response import Http404, HttpResponse
from django.shortcuts import redirect, render
from blog.models import *
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
import datetime
fr... | MayankBalyan/My-Personal-Website | blog/views.py | views.py | py | 5,255 | python | en | code | 0 | github-code | 13 |
1589607302 | """
堆排序:
"""
def heapify(arr, n, i):
largest = i
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
# 主要是比较出 left - root - right 谁最大, 并最终将最大的值赋给root
# 比较root和左节点大小, 如果左节点大, 就将largest指针赋值为左节点
if l < n and arr[i] < arr[l]:
largest = l
# 然后比较最大值和右节点比较, 如果右节点大, 就将large... | Abeautifulsnow/python_learning | sort_algorithm/堆排序.py | 堆排序.py | py | 1,312 | python | zh | code | 0 | github-code | 13 |
27079218695 | #!/usr/bin/env skeleton
# -*- coding: utf-8 -*-
#%%
"""
Created on Mon Sep 19 21:30:44 2022
@author: chenqu
"""
import numpy as np
import pandas as pd
import scanpy as sc
import scipy as sp
from scipy import stats
from collections import Counter
from collections.abc import Iterable
import rpy2
from rpy2.robjects.pack... | zktuong/dandelion-demo-files | dandelion_manuscript/utils/_chenqu_utils.py | _chenqu_utils.py | py | 6,665 | python | en | code | 0 | github-code | 13 |
4101846537 | x = int(input(" enter a number : "))
i = 0
lst = list()
while x > 0:
i = x % 2
x = x // 2
# print(i)
lst.append(i)
for num in reversed(lst):
print(num) | omithegr8/lets-code | decimal-to-binary.py | decimal-to-binary.py | py | 164 | python | en | code | 1 | github-code | 13 |
24088473900 | """
binjatron.py
A plugin for Binary Ninja to integrate Binary Ninja with Voltron.
Install per instructions here:
https://github.com/Vector35/binaryninja-api/tree/master/python/examples
Documentation here: https://github.com/snare/binja/blob/master/README.md
Note: requires the current version of Voltron from GitHub... | snare/binjatron | __init__.py | __init__.py | py | 13,988 | python | en | code | 159 | github-code | 13 |
70696504659 | # Problem Statement:-
# Take age or year of birth as an input from the user. Store the input in one variable. Your program should detect whether the entered input is age or year of birth and tell the user when they will turn 100 years old. (5 points).
current_year = 2021
last_year = current_year - 99
def age_calcu(a, b... | anant-harryfan/Python_basic_to_advance | PythonTuts/Python_Practise/Practise1.py | Practise1.py | py | 1,796 | python | en | code | 0 | github-code | 13 |
26790194421 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
sorted_list = []
while head:
sorted... | forestphilosophy/LeetCode_solutions | Interview Questions/sort_list.py | sort_list.py | py | 640 | python | en | code | 0 | github-code | 13 |
31993141125 | """rainforest URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-ba... | jessiicacmoore/django-rainforest | rainforest/urls.py | urls.py | py | 1,386 | python | en | code | 0 | github-code | 13 |
4973818106 | class Solution:
def isValid(self, s: str) -> bool:
#pair1 = ['{', '[', '(']
#pair2 = ['}', ']', ')']
pair = {'}': '{', ']': '[', ')': '('}
stack = []
for i in s:
'''
if i in pair1:
stack.append(i)
elif i in pair2 and len(sta... | yeos60490/algorithm | leetcode/easy/valid_parentheses.py | valid_parentheses.py | py | 732 | python | en | code | 0 | github-code | 13 |
2359221682 | from unittest import TestCase, skip
from src.dynamic.mutator import *
import types
class MutatorTest(TestCase):
def setUp(self):
self.mutator = Mutator()
def test_add_new_method(self):
mycode = '''def duration(env):
while True:
print('we are at moment %d' % env.now)
duratio... | bossiernesto/simulacion-dsl | test/test_mutator.py | test_mutator.py | py | 3,675 | python | en | code | 0 | github-code | 13 |
27396560774 | import matplotlib
from matplotlib import pyplot
matplotlib.use("Qt4Agg", warn=False)
pyplot.rcParams.update({'font.size': 22})
from scipy import special
import numpy
kpc2cm = 3.08568e+21
g2msun = 5.02785e-34
def p2(a):
return ((a)*(a))
def p3(a):
return ((a)*(a)*(a))
def analytical_mass(r, rho0, rc, rcut, be... | tlrh314/CygnusAMerger | plot_test.py | plot_test.py | py | 2,152 | python | en | code | 0 | github-code | 13 |
34787125758 | #!/usr/bin/env python3.6
"""
Provides ability to start a VM (with provided metadata), list available VMs and kill an existing VM.
"""
from __future__ import with_statement
import sys
import os
import logging
import subprocess
import traceback
# openstack source: https://github.com/openstack/openstacksdk/tree/master/o... | phenotips/deployment-tools | scripts/openstack_vm_deploy.py | openstack_vm_deploy.py | py | 11,679 | python | en | code | 1 | github-code | 13 |
30580587255 | #!/usr/bin/env python3
import argparse
import json
import re
import shutil
import time
from datetime import datetime
from os import chdir, fork, remove, rmdir
from sys import argv
def sub(tag_id, entry, body):
tag_string = f"{{- {tag_id} -}}"
return re.sub(tag_string, entry, body)
def modify_readme_content(c... | poyea/github.init | kickstart.py | kickstart.py | py | 4,225 | python | en | code | 3 | github-code | 13 |
2250427239 | """Training DAgger with an interactive policy that queries the user for actions.
Note that this is a toy example that does not lead to training a reasonable policy.
"""
import tempfile
import gymnasium as gym
import numpy as np
from stable_baselines3.common import vec_env
from imitation.algorithms import bc, dagger... | HumanCompatibleAI/imitation | examples/train_dagger_atari_interactive_policy.py | train_dagger_atari_interactive_policy.py | py | 1,163 | python | en | code | 1,004 | github-code | 13 |
4138974020 | import os
from flask import Flask, request, send_from_directory
from flask_socketio import SocketIO, emit
import subprocess
from subprocess import PIPE
from engine_communications import read_board_from_engine, read_possible_moves_from_engine, send_move_to_engine
app = Flask(__name__, static_folder="./build")
DEVELOP... | AmitAmitSari/chess_front | app.py | app.py | py | 1,853 | python | en | code | 0 | github-code | 13 |
10964348767 | import pygame, sys, copy
from pygame.locals import *
pygame.init()
# WICHTIGE VARIABLEN
res = (720,720)
framerate = 30
winCondition = 5 # = Anzahl der eig. Steine, die in gegn. Basis sein müssen, um zu gewinnen
grid_color = (161,115,81)
player1_color = (255,156,27)
player2_color = (106,199,229)
player_color_select =... | Sumpfgulasch/Python-Games | WurmiGame.py | WurmiGame.py | py | 25,516 | python | de | code | 0 | github-code | 13 |
20512767300 | import json
import requests
import os
from PIL import Image
input_file = "clipsubset.json"
with open(input_file, encoding="utf8") as f:
data = json.load(f)
count = 0
testpath = "tst.jpg"
for row in data:
image_url = row['url']
try:
response = requests.get(image_url, stream = True)
if ... | Lewington-pitsos/clip-download | download.py | download.py | py | 1,131 | python | en | code | 7 | github-code | 13 |
28065695396 | import requests
import os
# Your OpenAI API Keys - replace with your own keys
api_keys = ["your-api-key1", "your-api-key2", "your-api-key3", "your-api-key4"]
# Define the name and project for your prompt
name = "人文学"
project = "接力赛跑"
# The text prompt you want to generate a response
prompt = f"你是一名阳光积极向上的{name}院学生,你... | RwandanMtGorilla/txtMP | main.py | main.py | py | 1,941 | python | en | code | 6 | github-code | 13 |
27837548418 | from typing import Dict
import cv2 as cv
import logging
import numpy as np
from matplotlib.image import AxesImage
from ghostwriter.paths import DATA_DIR
from ghostwriter.utils import default_arguments, set_up_logging
from ghostwriter.camera.gamma import GammaCorrector
from ghostwriter.camera.keymap import KEY_UP, KEY... | mbmccoy/ghostwriter | ghostwriter/camera/examples/smile_detector.py | smile_detector.py | py | 4,803 | python | en | code | 1 | github-code | 13 |
10108907048 | import sys
from unittest import TestCase
from vending_machine import VendingMachine
from io import StringIO
import pytest
class TestVendingMachine(object):
def setup_method(self, method):
print('method{}'.format(method.__name__))
self.vm = VendingMachine()
self.captor = StringIO()
... | ki4070ma/vending-machine | test_vending_machine.py | test_vending_machine.py | py | 916 | python | en | code | 0 | github-code | 13 |
74667749457 | from PIL import Image
from IPython.display import display
filepath = ''
# load an image
img = Image.open(filepath)
img = img.convert('L')
w, h = img.size
# create the intensity matrix
img_data = img.getdata()
Img = [[img_data[x + w * y] / 255.0 for x in range(w)] for y in range(h)]
# matrices convolution
def convol... | dananas/Convolutions | convolution.py | convolution.py | py | 1,681 | python | en | code | 0 | github-code | 13 |
8841820208 | import os
from decimal import Decimal
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.files.storage import default_storage
from django.test import override_settings
from django.test import TestCase
from helpers.seed import get_or_create_default_image
from product.model... | vasilistotskas/grooveshop-django-api | tests/integration/product/category/test_model_product_category.py | test_model_product_category.py | py | 11,197 | python | en | code | 4 | github-code | 13 |
74134928019 | from copy import deepcopy
from profession import PROFESSION_LIST
import json
class Player:
def __init__(self, name):
self.name = name
self.profession = PROFESSION_LIST["None"]
self.attributes = None
self.ready = False
self.statuses = []
self.is_alive = True
... | forsytheda/tiny-pyrpg | src/server/player.py | player.py | py | 2,896 | python | en | code | 1 | github-code | 13 |
38910422425 | command = input()
coffees = 0
actions = ['coding', 'dog', 'cat', 'movie']
while command != 'END':
command_low = command.lower()
if command_low in actions:
if command.isupper():
coffees += 2
else:
coffees +=1
command = input()
if coffees <= 5:
print(coffees)
else:... | chomarliga/python-fundamentals | Python_Fundamentals/01_Basic_syntax_ex/coffee_need.py | coffee_need.py | py | 355 | python | en | code | 0 | github-code | 13 |
74324377616 |
import requests
from bs4 import BeautifulSoup
import xml.etree.ElementTree as ET
def _make_request(market: str, symbol: str, page_size=10, start=0):
""" Make request to Google """
params = {
'q': '{market}:{symbol}'.format(market=market, symbol=symbol),
'num': page_size,
'start': star... | bjornstromeqt/lambda-finance | src/google_finance/company_news.py | company_news.py | py | 1,527 | python | en | code | 0 | github-code | 13 |
39750635854 | #!/usr/bin/env python3
import os
import socket
import threading
import json
import jigly.cache
testlist = {
"nier": [
"../expers/nier1.mp3",
"../expers/nier2.mp3",
]
}
files = [
"expers/nier1.mp3",
"expers/nier2.mp3",
]
chunksize = 2048
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("... | mirmik/jigly | jigly/__main__.py | __main__.py | py | 868 | python | en | code | 0 | github-code | 13 |
73754997459 | # -problem3_6.py *- coding: utf-8 -*-
import sys
txtfile = sys.argv[1]
ctfile = sys.argv[2]
text = open(txtfile)
ct = open(ctfile, 'w')
for line in text:
line = line.strip("\n")
ct.write(str(len(line))+"\n")
text.close()
ct.close()
| xianan2/Python-Programming-A-Concise-Intro | Week 3/problem3_6.py | problem3_6.py | py | 249 | python | en | code | 0 | github-code | 13 |
40999129415 |
# Plotting Function -----------------------------------------------------------------------
def clustering_plot(X, labels=[], centers=[], title=None, figsize='auto', alpha=1,
xscale='linear', yscale='linear'):
import itertools
combination_set = list(itertools.combinations(X.columns,2))
... | kimds929/DS_Library | DS_Clustering.py | DS_Clustering.py | py | 3,710 | python | en | code | 0 | github-code | 13 |
11665895191 | import json
import logging
import os
from queue import Queue
import pymssql
import pandas as pd
import numpy as np
import requests
from src.config.config import *
from src.model.head import HeadModel
from src.model.lr_model import LRModel
from src.model.tail import TailModel
from src.utils.util import read_config, sav... | Ferrair/qingdao | src/manager/model_manager.py | model_manager.py | py | 14,618 | python | en | code | 0 | github-code | 13 |
14819761483 | import gradio as gr
import numpy as np
import torch
import transformers
from diffusers import StableDiffusionInpaintPipeline
from PIL import Image
from segment_anything import sam_model_registry, SamPredictor
import matplotlib.pyplot as plt
from datetime import datetime
import os
import json
sam_checkpoint = "sam_vit... | Myangsun/Streetview-app | backend/gradioapp.py | gradioapp.py | py | 7,554 | python | en | code | 0 | github-code | 13 |
73292674896 | import yaml
from heat2arm.parser.common.exceptions import TemplateDataException
from heat2arm.parser.cfn import FUNCTIONS as cfn_functions
from heat2arm.parser.cfn import RESOURCE_CLASS as cfn_resource_class
from heat2arm.parser.cfn import CFN_TEMPLATE_FIELDS as cfn_template_fields
from heat2arm.parser.hot import FUNC... | cloudbase/heat2arm | heat2arm/parser/template.py | template.py | py | 7,112 | python | en | code | 7 | github-code | 13 |
24490023845 | """Write a Python program for department library which has N books, write functions for
following:
a) Delete the duplicate entries
b) Display books in ascending order based on cost of books
c) Count number of books with cost more than 500.
d) Copy books in a new list which has cost less than 500."""
library = {}
books... | AditiMooley/BasicLearning | library_books.py | library_books.py | py | 2,149 | python | en | code | 0 | github-code | 13 |
44813293762 | from selenium import webdriver
from lib import random_num, random_date, save_image, scroll_down, croll_data_to_csv
from PIL import Image
import csv
import time
import re
category_ids = ["100571", "100610", "100615"]
def app():
input_prod_id = 1
error_count = 0
chrome_options = webdriver.ChromeOptions()
... | parkyeomyeong/HyeoDai_tohome_crolling | main_app.py | main_app.py | py | 5,191 | python | en | code | 0 | github-code | 13 |
19093595824 | #!/usr/local/bin/python3
from weakref import WeakKeyDictionary
class Grade(object):
def __init__(self):
self._values = WeakKeyDictionary()
def __get__(self, instance, instance_type):
print("__get__: %r, %r" % (instance, instance_type))
# print("Before: ", self.__dict__)
if ins... | jkaria/coding-practice | python3/grade_descriptor.py | grade_descriptor.py | py | 1,909 | python | en | code | 0 | github-code | 13 |
28596131220 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 3 16:01:17 2020
@author: Xuheng Ding
You can skip this step if the QSO stamp, noise level and the PSF is ready.
"""
#photutils in version 0.7.2
#astropy in version astropy-4.0.1
import numpy as np
import matplotlib.pyplot as plt
import astropy.i... | dartoon/my_code | package_code/galight_example/data_prep_example.py | data_prep_example.py | py | 3,956 | python | en | code | 0 | github-code | 13 |
30626459827 | hist = [] #list to hold the chars we have counted already
two_char = 0 # number of ids that contain 2 of the same letter
three_char = 0 # number of ids that contain 3 of the same letter
for line in open("box_list.txt"): # loop through each line in the file
# 2 bools to hold the stats of the count
two = False
... | Negative-Feedback/AOC_2018 | Day2/Day_Two_P1.py | Day_Two_P1.py | py | 997 | python | en | code | 0 | github-code | 13 |
10902470603 | from __future__ import annotations
import copy
import typing
from enum import Enum
from typing import Iterator, List, Optional
Position3D = typing.Tuple[float, float, float]
Velocity3D = typing.Tuple[float, float, float]
TimeStamps = typing.List[float]
LaunchParameter = typing.Tuple[float, ...]
PositionTrajectory =... | intelligent-soft-robots/aimy_target_shooting | aimy_target_shooting/custom_types.py | custom_types.py | py | 9,510 | python | en | code | 0 | github-code | 13 |
32384191902 | class LoggerNames:
"""
A "enum" class fot the available logger names.
"""
CONTROLLER_C = "Controller_Component"
EXPERIMENT_C = "Experiment_Component"
INPUT_C = "Input_Component"
CONFIGINPUT_C = "ConfigInput_Component"
LOGGER_C = "Logger_Component"
Output_C = "Logger_Component" | BonifazStuhr/CSNN | LoggerNames.py | LoggerNames.py | py | 313 | python | en | code | 7 | github-code | 13 |
42016605861 | from typing import Dict, Tuple, Sequence, Any, Union
import numpy as np
import torch
from torch.utils.data import Dataset, TensorDataset, DataLoader
from ._force2d import force2d
DataTuple = None
def split_x_or_u(
x_or_u: torch.Tensor,
dim_x: int
) -> Tuple[torch.Tensor, torch.Tensor]:
selec... | i-yamane/mediated_uncoupled_learning | mu_learning/utils/_make_and_split.py | _make_and_split.py | py | 2,601 | python | en | code | 2 | github-code | 13 |
31237000954 | from discord.ext import commands, tasks
import discord
import json
from loguru import logger
import asyncio
from bs4 import BeautifulSoup
import aiohttp
import sys
from utils.utils import *
from utils.data import *
import math
import datetime
with open('data/server.json') as d:
server = json.load... | amymainyc/raider-bot-public | cogs/game.py | game.py | py | 28,887 | python | en | code | 0 | github-code | 13 |
2887443531 | import os
import time
import shutil
import time
import json
import random
import time
import argparse
import numpy as np
## torch packages
import torch
import torch.nn.functional as F
from torch.autograd import Variable
from torch.utils.tensorboard import SummaryWriter
import torch.nn as nn
from transformers import ge... | varsha33/Fine-Grained-Emotion-Recognition | train_mutlilabel.py | train_mutlilabel.py | py | 6,794 | python | en | code | 6 | github-code | 13 |
71814578898 | from sqlalchemy import create_engine
from sqlalchemy import and_
from sqlalchemy.orm import sessionmaker
from models import Color, State, Team, Player
engine = create_engine(
'postgresql://postgres:passw0rd@localhost:5432/ACC_BBALL')
session = sessionmaker(bind=engine)()
def query1(
use_mpg, min_mpg, max_mp... | YUME-FF/Database_Programming | extraCredit/query_funcs.py | query_funcs.py | py | 3,265 | python | en | code | 0 | github-code | 13 |
17112410926 | import discord
from discord import app_commands
from discord.ext import commands
import random
# import our global settings file
import settings
class Chat(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command(name="flip")
async def flip(self, interaction: discord.Intera... | stapler8/Cadence | src/chat.py | chat.py | py | 2,169 | python | en | code | 0 | github-code | 13 |
37562915348 | import pymongo
import tkinter as tk
from tkinter import messagebox
#variables & mongodb connect
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["enrollmentsystem"]
mycol = mydb["teachers"]
lst = [['ID' , 'Name', 'Dept' , 'Contact']]
#assign to table
def callback(event):
li=[]
li=... | miggydai/PythonEnrollmentSystem_wTkinterandMongodb | funda/TeachersForm.py | TeachersForm.py | py | 7,125 | python | en | code | 1 | github-code | 13 |
480506770 | import ipaddress
async def handle_subnet(ip: str, mask: str):
network = ipaddress.ip_network(f"{ip}/{mask}", strict=False)
net_addr = str(network.network_address)
broadcast_addr = str(network.broadcast_address)
usable_range = f"{str(network[1])} - {str(network[-2])}"
host_count = network.num_addres... | CyberSentinels/discord-cyber-scenario-bot | features/subnet/handle_subnet.py | handle_subnet.py | py | 557 | python | en | code | 4 | github-code | 13 |
1690769944 | from flask_app.config.mysqlconnection import MySQLConnection, connectToMySQL
class Dojo:
def __init__(self, data):
self.id = data['id']
self.name = data['name']
self.created_at = data['created_at']
self.updated_at = data['updated_at']
# define a class method which ... | code-Brian/Dojos_and_Ninjas | flask_app/models/dojo.py | dojo.py | py | 2,387 | python | en | code | 0 | github-code | 13 |
17052905524 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class InputInvoiceOrderRequest(object):
def __init__(self):
self._buyer_inst_id = None
self._currency_code = None
self._exclude_tax_invoice_amt = None
self._invoice_amt ... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/InputInvoiceOrderRequest.py | InputInvoiceOrderRequest.py | py | 11,181 | python | en | code | 241 | github-code | 13 |
32336667678 | """
Project Euler Problem 24
========================
A permutation is an ordered arrangement of objects. For example, 3124 is
one possible permutation of the digits 1, 2, 3 and 4. If all of the
permutations are listed numerically or alphabetically, we call it
lexicographic order. The lexicographic permutations of 0, ... | mseibt/ProjectEuler | 024.py | 024.py | py | 1,124 | python | en | code | 1 | github-code | 13 |
12125888071 | #arr is array of (val, key) pairs
import math
import time
import random
def merge(arr1, arr2):
sortedArr = []
i = 0
j = 0
while i < len(arr1) or j < len(arr2):
if i >= len(arr1):
sortedArr.append(arr2[j])
j += 1
elif j >= len(arr2):
sortedArr.append... | Zaverot/CS120-2021-Fall | ps1/ps1.py | ps1.py | py | 2,252 | python | en | code | null | github-code | 13 |
41458320379 | from photoprism.Session import Session
from photoprism.Photo import Photo
pp_session = Session("admin", "changethis", "demo.photoprism.app")
pp_session.create()
p = Photo(pp_session)
data = p.search(query="original:*", count=1)
p.download_file(data[0]["Hash"])
data = p.list_albums(count=1)
p.download_album(uid=data... | mvlnetdev/photoprism_client | examples/download_files.py | download_files.py | py | 389 | python | en | code | 13 | github-code | 13 |
71350165459 | from torchvision.models.resnet import ResNet as _ResNet
from .extractor import Extractor
class ResNetExtractor(Extractor, _ResNet):
out_channels = [512, 256, 128, 64]
def _forward_impl(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
ou... | cafeal/SIGNATE_AIEdge2 | src/CenterNet/models/extractors/resnet.py | resnet.py | py | 633 | python | en | code | 3 | github-code | 13 |
7372857135 | import logging, os
from email.utils import formatdate
from operator import itemgetter
from time import time
from filerockclient.databases.sqlite import SQLiteDB
fst = itemgetter(0)
snd = itemgetter(1)
def compose(g, f):
return lambda x: g(f(x))
LASTACCEPTEDSTATEKEY = 'LastAcceptedState'
class MetadataDB(object)... | alvinlai/FileRock-Client | filerockclient/databases/metadata.py | metadata.py | py | 7,951 | python | en | code | null | github-code | 13 |
42442707245 | # Создайте программу для игры с конфетами человек против человека.
# Условие задачи: На столе лежит 2021 конфета. Играют два игрока делая ход друг после друга.
# Первый ход определяется жеребьёвкой.
# За один ход можно забрать не более чем 28 конфет.
# Все конфеты оппонента достаются сделавшему последний ход.
# Ск... | OlgaSuslova/starting_python | 12.01/2.py | 2.py | py | 1,784 | python | ru | code | 0 | github-code | 13 |
19670509364 | """ Timeseries driver for Landsat timeseries with meteorological data
"""
import datetime as dt
import logging
import os
from .timeseries_yatsm import YATSMTimeSeries
from ..ts_utils import ConfigItem, find_files
from ..series import Series
from ...logger import qgis_log
logger = logging.getLogger('tstools')
class ... | ceholden/TSTools | tstools/src/ts_driver/drivers/timeseries_yatsm_met.py | timeseries_yatsm_met.py | py | 2,936 | python | en | code | 52 | github-code | 13 |
184496373 | from django.shortcuts import render
from django.contrib.auth.models import User
from UserAuthsAPP.models import UserProfile
from ShopAPP.models import Product, WhishList
# Create your views here.
def Index(request):
if request.user.is_authenticated:
productsWithWish = list()
#get the current log... | donregulus/Teferet | TeferetPROJECT/CoreAPP/views.py | views.py | py | 1,920 | python | en | code | 0 | github-code | 13 |
25105261723 | # -*- coding: utf-8 -*-
import cv2
import numpy as np
import sys
# ============================================================================
# ============================================================================
class PolygonDrawer(object):
def __init__(self, file_name):
self.window_name = ... | ISCAS007/demo | areadetection/image_draw.py | image_draw.py | py | 4,205 | python | en | code | 0 | github-code | 13 |
36635427448 | import datetime
from app.shared import schema
from app.shared.data import delete, load, store
from app.shared.handler import lambda_handler
from app.shared.utils import convert_timestamp, is_expired
SCHEMA = schema.Schema(
prompt_user_hash=schema.HASH | schema.REQUIRED,
)
@lambda_handler(SCHEMA)
async def handl... | require-id/core | app/src/app/endpoints/user/poll.py | poll.py | py | 1,962 | python | en | code | 2 | github-code | 13 |
31971395163 | #!/usr/bin/env python
# coding: utf-8
import argparse
import sys
from collections import defaultdict
from Bio import SeqIO, AlignIO
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
from collections import Counter
from contextlib import redirect_stdout
def _get_args():
parser = argparse.ArgumentParser... | satoshikawato/bio_small_scripts | msa_to_txt.py | msa_to_txt.py | py | 7,873 | python | en | code | 2 | github-code | 13 |
13014037112 | import os
import collections
import yaml
import numpy as np
import torch
import gtn
from mathtools import utils, metrics, torchutils
from seqtools import fstutils_gtn as libfst
def sampleGT(transition_probs, initial_probs):
cur_state = np.random.choice(initial_probs.shape[0], p=initial_probs)
gt_seq = [cur_... | jd-jones/seqtools | tests/test_gtn.py | test_gtn.py | py | 8,491 | python | en | code | 1 | github-code | 13 |
74377288337 | import subprocess
import time
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
import os
import stat
import shutil
import mimetypes
import sys
if __name__ == "__main__":
patterns = ["*"]
ignore_patterns = None
ignore_directories = False
case_sensitive = Tr... | kartoza/hugo-watcher | hugo_watcher.py | hugo_watcher.py | py | 7,648 | python | en | code | 0 | github-code | 13 |
19180055305 | import pandas as pd
# Crear un DataFrame de ejemplo
data = {'Nombre': ['Juan', 'María', 'Pedro'],
'Edad': [25, 30, 35],
'Ciudad': ['Madrid', 'Barcelona', 'Sevilla']}
df = pd.DataFrame(data)
# Escribir el DataFrame en formato Parquet
df.to_parquet(r'C:\Users\migumart\OneDrive - Nokia\Archivos personale... | Nezzu14/Automatizaciones | Timo Project/Formato a Parquet.py | Formato a Parquet.py | py | 388 | python | es | code | 0 | github-code | 13 |
39859715441 | from unittest.mock import Mock
from brownie import network,accounts,config,FundMe,MockV3Aggregator
from scripts.helper_scripts import getAccount,deploy_mocks,LOCAL_DEVELOPMENT_ENVIRONMENTS
def fund_me_deploy():
account = getAccount()
if(network.show_active() not in LOCAL_DEVELOPMENT_ENVIRONMENTS):
pr... | prathamesh1301/Fund-Me-App | scripts/deploy.py | deploy.py | py | 720 | python | en | code | 0 | github-code | 13 |
72212589779 | salary=[]
total_hours=0
extra_hours=0
for i in range(7):
inp=int(input())
total_hours+=inp
salary.append(inp)
if inp>8:
extra_hours+=inp-8
extra=0
sunday_extra_salary=0
if salary[0]>0:
sunday_extra_salary+=(salary[0]*100)//2
saturday_extra_salary=0
if salary[6]>0:
saturday_extra_salary+=... | Shreesaraan/salary_calculator | salary_calculator.py | salary_calculator.py | py | 501 | python | en | code | 0 | github-code | 13 |
733259250 | #!/usr/bin/python3
""" Rectangle Class """
from models.base import Base
class Rectangle(Base):
""" Define the Rectangle class that inhirite from the Base class """
def __init__(self, width, height, x=0, y=0, id=None):
""" initialize instance of rectangle """
self.width = width
self.hei... | Aksaim-mohamed-amin/alx-higher_level_programming | 0x0C-python-almost_a_circle/models/rectangle.py | rectangle.py | py | 4,559 | python | en | code | 1 | github-code | 13 |
74267599059 | import math
from common import problem_data
def crabs(input_data):
return [int(c, base=10) for c in next(input_data).split(",")]
def fuel_cost(crabs, position):
cost = 0
for crab in crabs:
cost += abs(crab - position)
return cost
def find_lowest_cost(crabs):
max_crab = max(crabs)
lo... | firesock/advent-of-code | 2021/day7.py | day7.py | py | 1,343 | python | en | code | 0 | github-code | 13 |
5213671955 | #coding=utf-8
#Version: python3.6.0
#Tools: Pycharm 2017.3.2
_author_ = ' Hermione'
x,y,z=map(int,input().split())
numlist=[]
numlist.append(x)
numlist.append(y)
numlist.append(z)
numlist2=sorted(numlist)
print("{}->{}->{}".format(numlist2[0],numlist2[1],numlist2[2]))
#灵活运用python中自带的排序函数
#列表的append方法只能一个一个添加
| Harryotter/zhedaPTApython | ZheDapython/z2/z2.9.py | z2.9.py | py | 363 | python | zh | code | 1 | github-code | 13 |
26431488301 | with open("./input.txt") as f:
start, end = [int(n.strip()) for n in f.read().strip().split("-")]
def valid(num):
if not (start < num < end):
return False
dig = list(str(num))
double = False
for idx in range(len(dig) - 1):
if dig[idx] > dig[idx+1]:
return False
... | korylprince/adventofcode | 2019/04/main.py | main.py | py | 936 | python | en | code | 1 | github-code | 13 |
20653680157 | """
This script makes a cross section plot of the density quintiles.
"""
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from astropy.io import fits
from densitysplit.pipeline import DensitySplit
def get_data_positions(data_fn, split='z', los='z'):
"""
Re... | jgmorawetz/multitracer_densitysplit | scripts/cross_sections.py | cross_sections.py | py | 10,317 | python | en | code | 0 | github-code | 13 |
73546687057 | import itertools
import copy
n = 12
x = 4
lst = [2**i for i in range(n)]
base_groups = [[] for i in itertools.repeat(None, x)]
base_num = [0 for i in itertools.repeat(None, n)]
def split_to_groups(mask):
groups = copy.deepcopy(base_groups)
for i, digit in enumerate(mask):
groups[digit]... | BigB00st/ctf-solutions | rgbCTF/misc/creative-algo/solve.py | solve.py | py | 861 | python | en | code | 2 | github-code | 13 |
31565622110 | import math
def taxi_distance(n):
# find "taxi distance" of point on spiral to center 1
# round square root to next odd number ~ rotation
if n == 1:
return 0
c = math.ceil(math.sqrt(n))
if c % 2 == 0:
c += 1
r = (c - 1) / 2
lr = c ** 2
cp = lr - n
ep = cp % (2... | galgeek/advent2017 | 3-1.py | 3-1.py | py | 511 | python | en | code | 0 | github-code | 13 |
8668121724 | #!/usr/bin/env python
import scapy.all as scapy
def scan(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast / arp_request
answered_list = scapy.srp(arp_request_broadcast, verbose=False, timeout=10)[0]
client_list = []
for ... | alr0cks/alsploit-mitm-toolkit | networkscan/netscan.py | netscan.py | py | 834 | python | en | code | 0 | github-code | 13 |
73498352977 | script_create_table_especiais = lambda dados = {} : """
DROP TABLE IF EXISTS Especiais;
CREATE TABLE Especiais (
id int NOT NULL PRIMARY KEY,
nome text NOT NULL,
idioma INTEGER NOT NULL,
ref int NOT NULL,
FOREIGN KEY (idioma)
REFERENCES Idiomas(id)
);
""... | LeandroLFE/capmon | db/default_data/dados_especiais.py | dados_especiais.py | py | 830 | python | pt | code | 0 | github-code | 13 |
31321394322 | # coding=utf-8
__author__ = "AstroPrint Product Team <product@astroprint.com>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2017 3DaGoGo, Inc - Released under terms of the AGPLv3 License"
# singleton
_instance = None
def printerProfileManager()... | AstroPrint/AstroBox | src/astroprint/printerprofile/__init__.py | __init__.py | py | 7,896 | python | en | code | 158 | github-code | 13 |
22376124812 | def isPrime(n):
"""Returns True if n is prime."""
if n == 2:
return True
if n == 3:
return True
if n % 2 == 0:
return False
if n % 3 == 0:
return False
i = 5
w = 2
while i * i <= n:
if n % i == 0:
return False
... | ZacJoffe/competitive-programming | Python/Project Euler/sum_of_primes.py | sum_of_primes.py | py | 503 | python | en | code | 0 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.