seq_id
stringlengths
7
11
text
stringlengths
156
1.7M
repo_name
stringlengths
7
125
sub_path
stringlengths
4
132
file_name
stringlengths
4
77
file_ext
stringclasses
6 values
file_size_in_byte
int64
156
1.7M
program_lang
stringclasses
1 value
lang
stringclasses
38 values
doc_type
stringclasses
1 value
stars
int64
0
24.2k
dataset
stringclasses
1 value
pt
stringclasses
1 value
29486183593
# Exercise 5: This program records the domain name (instead of the address) # where the message was sent from instead of who the mail came from (i.e., # the whole email address). At the end of the program, print out the contents # of your dictionary. # python schoolcount.py # Enter a file name: mbox-short.txt # {'m...
tuyojr/pythonUdacity
exercises/dictVIII.py
dictVIII.py
py
915
python
en
code
0
github-code
6
25418252680
from sys import stdin nums = list(map(int, stdin.readline().split())) n = nums[0] m = nums[1] board = [] for _ in range(n): board.append(list(map(int, stdin.readline().rstrip()))) dist = [[-1] * m for _ in range(n)] dir = [(0, 1), (1, 0), (0, -1), (-1, 0)] queue = [] dist[0][0] = 0 queue.append((0, 0)) while l...
jaehui327/Algo
백준/Silver/2178. 미로 탐색/미로 탐색.py
미로 탐색.py
py
701
python
en
code
0
github-code
6
7663203620
import numpy as np import sounddevice as sd from scipy.io.wavfile import write from isort import file from tools import get_device_number # 録音の設定 fs = 48000 # サンプリング周波数 duration = 5 # 録音時間(秒) channels = 7 device_num = get_device_number("Azure Kinect") # マイクロフォンアレイのデバイス番号 # マイクロフォンアレイからの録音 print("録音開始...") audio_dat...
fkfk21/Enjoy_Azure_Kinect
scripts/record_audio.py
record_audio.py
py
1,024
python
ja
code
0
github-code
6
1381693048
from decimal import Decimal array = [1, 2, 3, 4, 5] # define function for find min in array for elements than 64 bits def min_array(arr): min_value = Decimal("Infinity") for element in arr: if element < min_value: min_value = element return min_value # define function for find max i...
chituenguyen/review_test_algorithms
minMaxFind.py
minMaxFind.py
py
1,383
python
en
code
0
github-code
6
71315302907
import requests,sys import requests from requests.structures import CaseInsensitiveDict sys.path.insert(1,".") from config import TODIST_API_KEY #Rate Limit: 1 per 2 seconds. headers = CaseInsensitiveDict() headers["Accept"] = "application/json" headers["Authorization"] = "Bearer " + str(TODIST_API_KEY) #This function...
leekycauldron/statusAPI
TodoistApps/createTask.py
createTask.py
py
937
python
en
code
0
github-code
6
32129407183
import json import bitarray from find_recipes_simple import process_recipe import time import sys PROCESS_SIZE = 50000000 def execute_find_recipe(item_str, recipe_data): if not item_str: return 0, 0 hp_crit, hp, price = process_recipe(recipe_data, item_str) # crit increases hp by 12, we just ne...
iTNTPiston/botw-recipe
dump/dump.py
dump.py
py
4,729
python
en
code
1
github-code
6
28808365461
import socket class Network: def __init__(self): self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server = socket.gethostname() self.port = 5555 self.addr = (self.server, self.port) self.connect() def getPlayer(self): return ...
yuvayt/PythonPixelGame
network.py
network.py
py
986
python
en
code
0
github-code
6
72355972669
#!/usr/bin/python3 """Module insert a line to a file""" def append_after(filename="", search_string="", new_string=""): """Initialization of inserting a line of text to a file after each line containing a specific string. Args: filename (str): file name search_string (str): text to seach ...
MrZooM001/alx-higher_level_programming
0x0B-python-input_output/100-append_after.py
100-append_after.py
py
689
python
en
code
0
github-code
6
30884940545
from zope.event import notify from zope.component import adapts, queryUtility from zope.interface import implements, alsoProvides from getpaid.core.interfaces import ILineItemFactory, IShoppingCart from getpaid.core.item import PayableLineItem, RecurringLineItem from pfg.donationform.interfaces import IDonationFieldSet...
collective/pfg.donationform
pfg/donationform/cart.py
cart.py
py
2,366
python
en
code
0
github-code
6
28173684280
# importing all libraries import cadquery as cq from cadquery import exporters import pyaudio import json from vosk import Model, KaldiRecognizer import pyttsx3 from tkinter import * from PIL import ImageTk, Image import tkinter.font as TkFont import os from word2number import w2n #loading vosk ml audio recognition m...
N3dal/YourFirstContribution
Python/interactivedesign.py
interactivedesign.py
py
9,411
python
en
code
null
github-code
6
20001859716
from nltk.stem import WordNetLemmatizer import re from nltk.tokenize import word_tokenize, sent_tokenize def myTokenizer(readFileDir, saveFileDir, stopwords, lim): readFile = open(readFileDir, "r", encoding="UTF8") saveFile = open(saveFileDir, "w", encoding="UTF8") preprocessed = [] lemmatizer = WordNe...
jkjan/NLP
Word2VecSkip-Gram/myTokenizer.py
myTokenizer.py
py
1,370
python
en
code
0
github-code
6
26495796671
from django.contrib import admin,messages from .models import * from inline_actions.admin import InlineActionsModelAdminMixin from commun.util import Util from django.utils.translation import ugettext_lazy as _ from django.conf import settings media_root = settings.MEDIA_ROOT admin.site.site_header = "Administration E...
bofilio/erp-backend
couriers/admin.py
admin.py
py
2,740
python
en
code
0
github-code
6
14777796282
N, K = list(map(int, input().split())) W = [] for i in range(N): W.append(int(input())) def is_enough(P): track_index = 0 w_index = 0 while track_index < K and w_index < N: # トラックの数を超える or Wを全て載せ終わる tmp_sum = 0 while w_index < N and tmp_sum + W[w_index] <= P: tmp_sum += W[w_index] w_index +...
kokoakuma/algorithm_practice
AOJ/Part5_Search/allocation.py
allocation.py
py
664
python
en
code
0
github-code
6
40702687414
#coding: utf-8 from . import BaseSuite class AcceptanceSuite(BaseSuite): def acceptance_from_mail(self, invoice_id, pointsale_id, date, items): """ /acceptance/pointsale/<int:point_id>/invoice/<int:invoice_id> """ data = { 'data': {'items': items, 'date': unicode(date)...
StasEvseev/buy_api
tests/suits/acceptance.py
acceptance.py
py
1,224
python
en
code
0
github-code
6
779154686
from typing import Annotated from fastapi import APIRouter, Depends, status from fastapi.encoders import jsonable_encoder from fastapi.responses import JSONResponse from pydantic_core import ValidationError from readconnect.shared.domain.dtos.error_response_dto import ErrorResponse from readconnect.shared.domain.exce...
YeisonKirax/readconnect-back
src/readconnect/auth/infrastructure/routes/auth_routes.py
auth_routes.py
py
3,939
python
en
code
0
github-code
6
7795341803
import json from random import randint import ideas.utils as utils IDEA_PATH = './ideas/ideas.json' class Generator: def __init__(self, context='general', keys=[]): self.idea_path = IDEA_PATH self.context = context self.rand_items = [] with open(self.idea_path, 'r') as json_fil...
kjbyleni/My_Art_tools
ideas/generator.py
generator.py
py
1,757
python
en
code
0
github-code
6
32119109971
from rest_framework.routers import DefaultRouter from apps.home.views import FeatureView, HomeView, I18nViewSet, SitemapView router = DefaultRouter() router.register("", HomeView) router.register("sitemap", SitemapView, basename="sitemap") router.register("i18n", I18nViewSet, basename="i18n") router.register("feature...
OVINC-CN/iWikiAPI
apps/home/urls.py
urls.py
py
384
python
en
code
0
github-code
6
14752733594
from flask import Flask,render_template, request, session, redirect, url_for from threading import Thread def createApp(): app = Flask( __name__, template_folder=r"templates", static_folder=r"static" ) return app app = createApp() @app.route("/") def home(): return render_template("./in...
SentientPlatypus/Self-Driving-Car-Simulation
services/main.py
main.py
py
485
python
en
code
1
github-code
6
71550269628
from pathlib import Path import typer from meteor import IdentityStage from meteor import Language from meteor import StemmingStage from meteor import meteor_macro_avg def cli( hypotheses_file: Path = typer.Option( ..., "-h", "--hypotheses", help="utf-8 encoded file with system o...
wbwseeker/meteor
meteor/cli.py
cli.py
py
1,909
python
en
code
1
github-code
6
38116610119
num = int(input("Enter the value num =")) factorial = 1 if num <0: print("Factorial does not exist for negative numbers") elif num == 0: print("factorial of 0 is 1") else: for i in range(1,num+1): factorial=factorial*i print("The factorial of",num,"is",factorial) #using recursion method # ...
3Sangeetha3/python
factorial.py
factorial.py
py
698
python
en
code
1
github-code
6
29918439800
#Tarea 20, para lenguajes de programacion import matplotlib.pyplot as plt import numpy as np print ("Minimos cuadrados") print ("Este programa calcula la pendiente (m), la intercepcion(b) y el coeficiente de relacion(r) de una regresion lineal") print ("¿Cuantos datos (en pares (x1,y1) se considera 1) desea evaluar? (m...
EdmundoD3/Ejercicios-de-Python
programas python parte 2/T20_Minimos_cuadrados.py
T20_Minimos_cuadrados.py
py
2,290
python
es
code
0
github-code
6
42913447777
import numpy as np import matplotlib import matplotlib.pyplot as plt import matplotlib.animation as animation import matplotlib.cm as cm import matplotlib.patches as mpatches import json import sys from helpers.helpers_visualisation import get_colors from scipy.misc import imread import matplotlib.image as mpimg ...
elbuco1/AttentionMechanismsTrajectoryPrediction
src/visualization/classes/animation.py
animation.py
py
7,151
python
en
code
49
github-code
6
39660675563
from ..libs import * from . import SubResultUI class ResultTableUI(QWidget): def __init__(self): super().__init__() self.init_ui() self.results = None self.results_ui = {} def init_ui(self): self.layout = QHBoxLayout() self.table = QTableWidget() self....
jingshenSN2/CrystalTool
crystalsearchgui/output/result_table_ui.py
result_table_ui.py
py
2,788
python
en
code
1
github-code
6
31851011006
n1 = float(input()) n2 = float(input()) n3 = float(input()) media = (n1 + n2 + n3) / 3 if media >= 9: conceito = "Ótimo" elif media >= 7.5: conceito = "Bom" elif media >= 6: conceito = "Satisfatório" else: conceito = "Insuficiente" print(conceito)
CaioPinho9/poo
scr/selecao/conceito.py
conceito.py
py
268
python
pt
code
0
github-code
6
29510369443
import pandas as pd import numpy as np from sklearn.base import BaseEstimator, TransformerMixin from sklearn.model_selection import cross_val_predict from sklearn.metrics import classification_report data = pd.read_csv('./ner_dataset.csv', encoding='latin1') data = data.fillna(method="ffill") # ffill前值填充,pfill后值填充 ...
jiangq195/tanxin
starter_code1/NER/majority_voting.py
majority_voting.py
py
1,532
python
en
code
0
github-code
6
74558105146
import pandas as pd #data process train1=pd.read_csv('taijing/df_affinity_train.csv') train2=pd.read_csv('taijing/df_molecule.csv') test=pd.read_csv('taijing/df_affinity_test_toBePredicted.csv') train1=pd.DataFrame(train1) train2=pd.DataFrame(train2) test=pd.DataFrame(test) test.columns = ['Protein_ID','Molecule_ID',...
xiaoqian19940510/python-
game/DataCastle/Drug_screening/combine.py
combine.py
py
1,348
python
en
code
9
github-code
6
12237739567
import tensorflow as tf import numpy as np tf.enable_eager_execution() # Dataset import tensorflow_datasets as tfds # Constants to eventually parameterise LOGDIR = './logs/autoencoder_gg/' # Activation function to use for layers act_func = tf.nn.tanh # Enable or disable GPU SESS_CONFIG = tf.ConfigProto(device_coun...
bfakhri/TensorflowEager
autoencoder.py
autoencoder.py
py
7,158
python
en
code
3
github-code
6
37370928668
import torch import torchvision # post-processing def handle_preds(preds, device, conf_thresh=0.25, nms_thresh=0.45): total_bboxes, output_bboxes = [], [] # 将特征图转换为检测框的坐标 N, C, H, W = preds.shape bboxes = torch.zeros((N, H, W, 6)) pred = preds.permute(0, 2, 3, 1) # 前背景分类分支 pobj = pred[:, ...
Zhefan-Xu/onboard_detector
scripts/yolo_detector/utils/tool.py
tool.py
py
2,179
python
en
code
9
github-code
6
15169976693
from typing import List from fastapi_utils.inferring_router import InferringRouter from sqlalchemy.ext.asyncio import AsyncSession from fastapi import Depends, Request from admins.models import Category from crud_handler import BaseHandler from database import get_async_session from fastapi_utils.cbv import cbv from ...
AlexeyShakov/helpdesk_fast_api
src/staff/endpoints.py
endpoints.py
py
3,364
python
en
code
0
github-code
6
6484230311
import os import shutil import subprocess from pathlib import Path import numpy as np from PIL import Image, ImageOps from lib import BruteForce, database from .utils import timeit MAX_RATIO = 0.90 # 0.60 MIN_RATIO = 0 # PARAM FOR THE RADIOMETRIC APPROACH # Try to normalize respect mean and std to reject static fr...
franioli/COLMAP_SLAM
lib/static_rejection.py
static_rejection.py
py
11,514
python
en
code
0
github-code
6
6634246233
def solve(length, nums, sumnum): # method1 hmap = {} for i in range(length): cnum = nums[i] if cnum not in hmap.keys(): hmap[cnum] = i target = sumnum - cnum if target in hmap.keys(): return [i, hmap[target]] return [-1, -1] length = int(inp...
rh01/gofiles
lcode1-99/ex64/solve copy.py
solve copy.py
py
467
python
en
code
0
github-code
6
648044037
import time import h5py from affogato.segmentation import InteractiveMWS def debug(): z = 0 path = '/home/pape/Work/data/ilastik/mulastik/data/data.h5' with h5py.File(path, 'r') as f: # raw = f['raw'][z] affs = f['prediction'][:, z] strides = [4, 4] offsets = [[-1, 0], [0, -1], [-...
constantinpape/affogato
example/interactive/debug.py
debug.py
py
1,168
python
en
code
9
github-code
6
32644440027
"""Shifters Rig Main class.""" import datetime import getpass import os.path import sys import json # Maya import pymel.core as pm from pymel.core import datatypes from pymel import versions # mgear import mgear import mgear.core.utils from . import guide, component from mgear.core import primitive, attribute, skin,...
mgear-dev/mgear4
release/scripts/mgear/shifter/__init__.py
__init__.py
py
31,325
python
en
code
209
github-code
6
75126804667
from mock import Mock import pytest import json from datetime import date, datetime from src.smallquery.functions.run_query import app @pytest.fixture() def run_query_event(): """ Generates Run Query event """ return { 'query': 'select * from unit/test.parquet', 'limit': 10, } ...
nxn128/serverless-query
test/test_run_query.py
test_run_query.py
py
1,290
python
en
code
0
github-code
6
71184254909
#!/usr/bin/python class podcasts(object): __tablename__ = 'podcasts' def __init__(self): self.castid = 0 self.castname = '' self.feedurl = '' self.pcenabled = 1 self.lastupdate = 0 self.lastattempt = 0 self.failedattempts = 0 class episodes(object):...
ddboline/programming_tests
sqlalchemy/hpodder.py
hpodder.py
py
679
python
en
code
0
github-code
6
43633170723
from __future__ import absolute_import import logging import math #typing import torch import torch.nn.functional as F #overrides from allennlp.data import Vocabulary from allennlp.models.model import Model from allennlp.modules.token_embedders import Embedding from allennlp.modules import FeedForward from allennlp....
plasticityai/magnitude
pymagnitude/third_party/allennlp/models/coreference_resolution/coref.py
coref.py
py
32,507
python
en
code
1,607
github-code
6
33639465646
import concurrent.futures import time def do_something(seconds): print (f'休眠{seconds}秒') time.sleep(seconds) return 'test' start_time = time.perf_counter() with concurrent.futures.ThreadPoolExecutor() as executor: #用list comprehension创建10个future objects并运行,到这里10个并发任务就完成了,下面调用results()的代码为可...
nnzmj/ParryWang
Multi_Threading/多线程演示(ThreadPoolExecutor-2).py
多线程演示(ThreadPoolExecutor-2).py
py
744
python
en
code
0
github-code
6
17168418038
import json import re from urllib import request import requests from panopto_oauth2 import PanoptoOAuth2 server = "sph.hosted.panopto.com" client_id = "29bd20b2-fd78-4bdd-9c40-af7a0133c139" client_secret = "oZVXzyYlRQun/+xrxaItsdSDm1n7Np6rNqlmjHjgcyQ=" def read_coursera_to_time_sentence(input_path, video_id): w...
Zhou-Xun/panopto_video_extraction
convert_caption_url.py
convert_caption_url.py
py
4,773
python
en
code
1
github-code
6
6015616240
#!/usr/bin/env python #coding: utf-8 import asyncio import yaml import sys from NetDevices import DeviceHandler from git import Repo import time FILEPATH = "/root/device_cfg/" async def get_config(device): hostname = device.get("hostname") conn = DeviceHandler(device) conn.connect() await conn.login()...
netdevops-engineer/newbie_book
Chapter13/Chapter13/Device.asyncio/Device6.py
Device6.py
py
989
python
en
code
36
github-code
6
15317442487
#!/usr/local/bin/python -tt import sys import os import random from copy import deepcopy class Blackjack(): def __init__(self,coins): self.player_coins = coins self.player = 'challenger' self.player_cards = 0 self.dealer_cards = 0 self.cards = [] self.hands = [] ...
Pankaj-Ra/Basic_Python_programs
google-python-exercises/blackjack.py
blackjack.py
py
4,643
python
en
code
1
github-code
6
34075662644
import random import sys from UI import Ui_MainWindow from PyQt5.QtCore import QPoint, QRect from PyQt5.QtGui import QPainter, QColor from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow MAX_X = MAX_Y = 400 class MyWidget(QMainWindow, Ui_MainWindow): def __init__(self): super().__init__() ...
Orisphera/random-circles
main.py
main.py
py
1,188
python
en
code
0
github-code
6
3081253994
# -*- coding: utf-8 -* """Input .. module:: input :synopsis: Module for processing input """ import resoncalc.output as output import resoncalc.detection as detection from argparse import ArgumentParser from os import path from json import load, JSONDecodeError def process_command(): """Process command ...
hydratk/resoncalc
src/resoncalc/input.py
input.py
py
3,159
python
en
code
0
github-code
6
28616374779
def main(): # establish connections to IO files input_file = open('test2.txt', 'r') output_file = open('output2.txt', 'w') # initialize variables average = 0 count = 0 # compute average for line in input_file: # int ignores whitespace and \n's average = average + int(l...
MasterNobikan/First_Python_Scripts
Read_Calculate.py
Read_Calculate.py
py
506
python
en
code
0
github-code
6
7318961586
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^modules/$', views.modules, name='modules'), url(r'^module/(?P<module>\w+)/list$', views.module_list, name='module_list'), url(r'^module/(?P<module>\w+)/detail/(?P<id>[\w-]+)/$', v...
sanchezfauste/bPortal
portal/urls.py
urls.py
py
2,424
python
en
code
1
github-code
6
8926398030
def cpn(a): x=2 while x<a: if a%x==0: break else: x+=1 if x==a-1: print(a) def main(): c=1 n=int(input('ENTER NO. TILL WHICH YOU WANT PRIME NOS. : ')) while c<=n: cpn(c) c+=1 print('done') input() m...
adarsh2818/beginningwithpy
primenos list.py
primenos list.py
py
339
python
en
code
0
github-code
6
28978147496
import tkinter as tk import pygubu import cv2 import copy import numpy as np class Application: def __init__(self, master): self.master = master #create builder self.builder = builder = pygubu.Builder() #load ui file builder.add_from_file('hw1.ui') #create a widget self.mainwindow = builder.get_object...
F74036378/IMAGE_DEAL1
hw1.py
hw1.py
py
4,397
python
en
code
0
github-code
6
27262011000
from database import DBHelper from photo_filter import PhotoFilter from photo_dao import PhotoDao def task_gen_photo_meta(root, query, do_save_meta): print('generating photo meta for %s'%(query)); filter = PhotoFilter(); dbHelper = DBHelper(); dbHelper.init(root); photos = filter.get_photo_with_tag_and_unique(que...
Asperado/iconic
data_collection/database_builder/core/task_gen_photo_meta.py
task_gen_photo_meta.py
py
708
python
en
code
0
github-code
6
29047649100
import atexit import os import re import shutil import subprocess import sys import tempfile def usage(): sys.stderr.write('Usage: {} [-h] -d <directory> [-b <bitrate>]\n'.format(sys.argv[0])) sys.stderr.write(' -h display help\n') sys.stderr.write(' -b bitrate [32-320, default 192]\n') sys.stderr...
eskaton/py-ripcd
ripcd.py
ripcd.py
py
3,527
python
en
code
0
github-code
6
43987707276
# test CurlypivSetup """ Notes about program """ # 1.0 import modules import numpy as np # plotting import matplotlib.pyplot as plt import matplotlib from matplotlib import colors import matplotlib.image as mgimg from matplotlib import animation from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar mat...
sean-mackenzie/curlypiv
curlypiv/CurlypivPIVSetup.py
CurlypivPIVSetup.py
py
7,120
python
en
code
0
github-code
6
38299570465
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: if not head or not head.next or k == 0: return head co...
nanup/Data-Structures-And-Algorithms
61-rotate-list/61-rotate-list.py
61-rotate-list.py
py
811
python
en
code
0
github-code
6
4592746162
__all__ = [ 'Canceled', 'DuplicateDestinationError', 'Record', 'get_download_manager', ] import os import dbus import logging from collections import namedtuple from io import StringIO from pprint import pformat try: import pycurl except ImportError: # pragma:...
ubports/system-image
systemimage/download.py
download.py
py
9,745
python
en
code
2
github-code
6
43848174354
import warnings from threading import Lock from queue import Queue, PriorityQueue, Empty class PubSubBase(): """ Internal base class should not be instanced, Please use classes PubSub and PubSubPriority The algorithms for thread safe functionnalities were designed by Zhen Wang : congratulation to...
Thierry46/pubsub
pubsub.py
pubsub.py
py
12,494
python
en
code
5
github-code
6
73928144189
import django_rq import logging from datetime import datetime, timedelta import time from django.core.management.base import BaseCommand from django_rq import job from reviews.models import Review #@job def get_count_reviews(): logger = logging.getLogger('counter') count = Review.objects.count() time.sle...
idesu/review_moderation_lite
reviews/management/commands/log.py
log.py
py
881
python
en
code
0
github-code
6
42542599040
while True: try: rows, columns = [int(w) for w in input().strip().split(" ")] matrix = [] for _ in range(rows): matrix.append([int(w) for w in input().strip().split(" ")]) initial_position = () pokemon_position = () for idx_row, row in enumerate(matrix): for idx_column, elem...
Trypion/aula_OOP
modulo7/ultimo_analogimon.py
ultimo_analogimon.py
py
679
python
en
code
1
github-code
6
31440178142
from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('',views.login,name='loginform'), # path('OTP/',views.otp,name="otp"), path('verifyotp/',views.verifyotp,name='verifyotp'), path('multiform/',views.multiform,name='multiform'), path("payme...
HIRAPARANAYAN/verni-by-s
authentication/urls.py
urls.py
py
490
python
en
code
0
github-code
6
39312594943
import os import requests from bs4 import BeautifulSoup, Tag from collections import Counter import re import string import nltk from nltk.corpus import stopwords from nltk.corpus import words from nltk.tokenize import word_tokenize from gensim.models import Word2Vec import pandas as pd import matplotlib.pyplot as plt ...
PhiloSolares/seo_analysis
seo_analysis_tool.py
seo_analysis_tool.py
py
18,812
python
en
code
0
github-code
6
73931877949
#!python """ The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145: 1! + 4! + 5! = 1 + 24 + 120 = 145 Perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169; it turns out that there are only three such loops that exist...
DanMayhem/project_euler
074.py
074.py
py
1,242
python
en
code
0
github-code
6
15018836415
import tkinter as tk import customtkinter as ctk from customtkinter import ThemeManager from View.GUI.CustomWidgets.NotebookCloseableTabs import NotebookCloseableTabs from View.GUI.Windows.ResultWindow.ComputationStatusBoard import ComputationStatusBoard from View.Observer import Observer class ComputationNotebook(...
Moni5656/npba
View/GUI/Windows/ResultWindow/ComputationNotebook.py
ComputationNotebook.py
py
2,306
python
en
code
0
github-code
6
39287970735
def bub(l1: list): n = len(l1) for i in range(n): flag = True for j in range(n-1-i): if l1[j] > l1[j+1]: l1[j], l1[j+1] = l1[j+1], l1[j] flag = False if flag: break return l1 if __name__ == "__main__": l = ['12', '34', '...
biswajeetpadhi/Data_structure_Algorithm
practice.py
practice.py
py
549
python
en
code
0
github-code
6
20571972816
from ply.lex import LexToken from windyquery.validator import ValidationError from ._base import Base TOKEN = 'SCHEMA' class SchemaToken(LexToken): def __init__(self, value): self.type = TOKEN self.value = value self.lineno = 0 self.lexpos = 0 class Schema(Base): def schema...
bluerelay/windyquery
windyquery/collector/schema.py
schema.py
py
540
python
en
code
68
github-code
6
27082652563
import time from datetime import timedelta import requests from celery import Celery from celery.utils.log import get_task_logger app = Celery('parsing') app.conf.update(broker_url='amqp://guest:guest@rabbitmq:5672', broker_connection_retry_on_startup=True) app.conf.beat_schedule = { 'add-every-monday-morning': {...
puplishe/testproject
fastapi1/celery/celery.py
celery.py
py
654
python
en
code
0
github-code
6
28797169675
""" Programma per la determinazione delle tautologie """ L = ["&","%",">","-","!"] #And, Or, Implica, Se e solo se (bicondizionale), Negazione F = [] semF = {"&" : [ [False,True],[True,False], [False,False] ], "%" : [ [False,False] ], ">" : [ [True,False] ], "-" : [ [False,True],[True,F...
dariochiaiese/tautologies
tautologie 4.0.py
tautologie 4.0.py
py
11,567
python
it
code
1
github-code
6
18187153319
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D t = np.linspace(0, 2*np.pi, 20) p = np.linspace(0, np.pi, 10) theta,phi = np.meshgrid(t,p) x = np.cos(theta)*np.sin(phi) y = np.sin(theta)*np.sin(phi) z = np.cos(phi) fig = plt.figure(figsize=(10,4)) ax1 = fig.add_subplot(1...
notmatthancock/notmatthancock.github.io
code/py/sphere-sampling/sphere-uniform-theta-phi.py
sphere-uniform-theta-phi.py
py
524
python
en
code
0
github-code
6
39184026326
# ---------------------------------------------------------------------- # | # | Setup_custom.py # | # | David Brownell <db@DavidBrownell.com> # | 2022-10-14 12:37:50 # | # ---------------------------------------------------------------------- # | # | Copyright David Brownell 2022 # | Distributed und...
davidbrownell/v4-Common_LLVM
Setup_custom.py
Setup_custom.py
py
15,433
python
en
code
0
github-code
6
39672847864
import fileinput from typing import List from number import Number def solve(input_file): n = Number.parse(input_file.readline().strip()) for line in input_file: n += Number.parse(line.strip()) n.reduce() return n.magnitude if __name__ == "__main__": print(solve(fileinput.FileInput(...
cmatsuoka/aoc
2021 - submarine/18 - snailfish numbers/solution1.py
solution1.py
py
324
python
en
code
0
github-code
6
71740452349
#/usr/bin/env python import yaml import os, sys, re import subprocess import argparse ## Arguments parser = argparse.ArgumentParser(description='Create a shared cuda.yml for docker-compose') parser.add_argument('--gpu', '-g', action='append', dest='gpus', default=[]) parser.add_argument('--verbose', action='stor...
auser/docker-tensorflow-ipython-celery-rest-server
shared/create_cuda.py
create_cuda.py
py
4,297
python
en
code
7
github-code
6
16539466565
# -*- coding: utf-8 -*- """Главный и единственный модуль в игре. Игра специально написана в минималистичном стиле, мне хотелось воплотить текстовый движок настолько лаконично, насколько это вообще возможно. Подкладывая этому скрипту различные json с метаданными, можно запускать произвольные текстовые истории. """ im...
IgorZyktin/BGCGame
game/__main__.py
__main__.py
py
6,720
python
ru
code
0
github-code
6
38858291652
""" Place to register all blueprints """ def customize_social_auth(): """ Customize certain routes of social auth """ from datetime import datetime from flask import Blueprint, current_app, g from flask_user import login_required, signals from social_core.actions import do_auth, do_comple...
Vixx-X/ati-project
src/backend/blueprints.py
blueprints.py
py
2,801
python
en
code
0
github-code
6
17509932483
def perm(s, k): n = len(s) def perm_helper(a=None, stamploc=0, used=None): if a is None: a = [None] * k if used is None: used = [False] * n if stamploc == k-1: for i in range(n): if not used[i]: a[stamploc] = s[i] ...
soji-omiwade/cs
dsa/before_rubrik/perm_nk_notset.py
perm_nk_notset.py
py
817
python
en
code
0
github-code
6
72478434747
import re def isValidEmail(email): regex = re.compile( r"([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+" ) if re.fullmatch(regex, email): return True else: return False def isValidPhone(phone): regex = re.compile(r"^\+?[0-9]{10,}$") if re.fullmatch(r...
lucas-kaminski/mvp-bot-telegram
src/utils/validation.py
validation.py
py
385
python
en
code
0
github-code
6
25550775532
i=0 Fib = [1,1] n = int(input("Welche Fibonaccizahl willst du?=")) while i < n: fib = Fib[i]+Fib[i+1] Fib.append(fib) i=i+1 print(f"Die Fibonacci Zahl F_{i+1} ist = {Fib[i]}") print(Fib) a=1 b=1 fibo=0 i=0 while i < n: fibo=a+b a=b b=fibo i=i+1 print(fibo) def f(p): if p==1: retu...
tobibrosch/mathematischeprogrammierung
Gruppenphase/Blatt03/nowakbrosch_Blatt03_rekursion.py
nowakbrosch_Blatt03_rekursion.py
py
381
python
en
code
0
github-code
6
9499182379
import torch from torch import nn from torch.utils.data import DataLoader from torchvision import datasets from torchvision.transforms import ToTensor # 공개 데이터셋에서 학습 데이터를 내려받습니다. training_data = datasets.FashionMNIST( root="Fashion_MNIST_Data", train=True, download=True, transform=ToTensor(), ) # 공개 데이터셋에서 테스...
hotsoycandy/learn-pytorch
train.py
train.py
py
2,907
python
en
code
1
github-code
6
5544798991
from common import execute_sh from retry import retry import os import logging import json """ Issue kubectl commands on the running linode cluster """ WEATHER_API_TOKEN = os.environ.get("WEATHER_API_TOKEN") KUBERNETES_NODE_COUNT = "2" @retry(tries=60, delay=30) def get_nodes(): # Verify kubectl is communicatin...
HarrisKirk/blue-green-dreams
gwa-deploy/kubectl.py
kubectl.py
py
2,558
python
en
code
2
github-code
6
74313290747
from .keywords import K_SET_1 class Program: def __init__(self, inputLines): self.inputLines = inputLines self.comment = False self.indent = 0 self.brackets = [] self.programlines = [] def __repr__(self): return '\n'.join(self.programlines) def gene...
ShriramShagri/Transpiler
src/core/program.py
program.py
py
3,519
python
en
code
2
github-code
6
42295145901
import geopy bairros_list = [ "Boa Vista", "Bom Pastor", "Centro", "Granbery", "Jardim Glória", "Santa Helena", "São Mateus", "Teixeiras", "Bairu", "Bonfim", "Botanágua", "Centenário", "Cesário Alvim", "Graj...
igortitoneli/Api_Vitrine
bairro_location.py
bairro_location.py
py
2,455
python
is
code
0
github-code
6
8385196931
from __future__ import print_function from __future__ import absolute_import import socket import struct import sys import warnings from . import constants as tc from .exceptions import TraCIException, FatalTraCIError from .domain import _defaultDomains from .storage import Storage from .step import StepManager _DEBU...
ngctnnnn/DRL_Traffic-Signal-Control
sumo-rl/sumo/tools/traci/connection.py
connection.py
py
14,818
python
en
code
17
github-code
6
25457066690
import telegram from twilio.rest import Client from twilio.base.exceptions import TwilioRestException import threading class MessageSender: def __init__(self, config): self.lock = threading.Lock() self.telegram_bot = None if config["telegram"] is not None: self.telegram_chat_id ...
wanmeihuali/Agressive-Store-Bots
MessageSender.py
MessageSender.py
py
1,434
python
en
code
null
github-code
6
73816585466
from collections import defaultdict from typing import ClassVar, Self from discord import Message, Thread from discord.errors import HTTPException from pydis_core.utils import scheduling from pydis_core.utils.logging import get_logger import bot from bot.constants import Channels from bot.exts.filtering._filter_conte...
python-discord/bot
bot/exts/filtering/_settings_types/actions/remove_context.py
remove_context.py
py
5,173
python
en
code
1,206
github-code
6
5187889784
def maxProfit(prices): """ :type prices: List[int] :rtype: int """ total = 0 for i in range(len(prices) - 1): total += max(prices[i + 1] - prices[i], 0) return total Input = [7,1,5,3,6,4] print(maxProfit(Input)) # Output: 7 # Explanation: Buy on day 2 (price = 1) and se...
IshGill/DSA-Guides
Array Problems/Buy_sell_stock.py
Buy_sell_stock.py
py
936
python
en
code
9
github-code
6
32966110161
# -*- coding: utf-8 -*- """ Created on Mon Mar 16 08:45:54 2020 @author: rishav """ minPer = 100 dict = {'Krishna':[67,68,69] ,'Arjun':[45,98,63] ,'Malika':[52,56,60]} for i in dict: x=sum(dict[i])/3 if(x<minPer): minPer=x index = i print(index)
rishavrajj/my-python-codes
finding_percent.py
finding_percent.py
py
286
python
en
code
0
github-code
6
10899943389
import cv2 import numpy as np from keras.models import load_model image = cv2 .imread("Bore2.jpg",0) image = cv2.resize(image, (48, 48)) image = image[..., np.newaxis] # dst = np.expand_dims(image, axis=1) print(image.shape) # exit() model = load_model("model_v6_23.hdf5") predicted_class = np.argmax(model.predict(i...
hassanahmed95/My_True_Face
ML_training/test_file.py
test_file.py
py
1,134
python
en
code
1
github-code
6
75061852026
import numpy as np import p3.pad import p3.config as c from p3.agent import Agent from p3.state import ActionState class Fox: def __init__(self): self.agent = 0 # individual agent number self.agents = [] # list of agents self.generation = 0 # generation number def reset(se...
gabriel-richardson/NSGA-Smash-AI
p3/fox.py
fox.py
py
2,122
python
en
code
2
github-code
6
42926685316
def Solve(ln_0, ln_1, ln_s): if ln_s == "-": result = ln_0 - ln_1 if ln_s == "+": result = ln_0 + ln_1 if ln_s == "*": result = ln_0 * ln_1 return result while True: try: T = int(input().strip()) #print(n, m) for i in range(T): k...
ppalantir/axjingWorks
algorithm_note/anExams/tencent3exp4.py
tencent3exp4.py
py
588
python
en
code
1
github-code
6
25968013406
import argparse import time from threading import Thread import requests class RequestThread(Thread): def __init__(self, url): self.url = url super(RequestThread, self).__init__(target=self.make_request) def make_request(self): requests.get(self.url) class Worker(object): def _...
wgaggioli/elk-example
threaded_requests.py
threaded_requests.py
py
1,602
python
en
code
6
github-code
6
11047387601
from astropy.wcs.utils import wcs_to_celestial_frame as wcs from astropy.coordinates import SkyCoord import astropy.units as u from scipy import ndimage import numpy as np import math as m __author__ = "Norbert Gyenge" __email__ = "n.g.gyenge@sheffield.ac.uk" def Sunspot_coord(photosphere_full, dx, dy, spot): ''...
gyengen/SheffieldSolarCatalog
engine/ssc/sunspot/coordinates.py
coordinates.py
py
2,040
python
en
code
1
github-code
6
4756037188
"""This module provides the CLI for the wrangle-ukds-trade-directories app.""" from . import __app_name__ import argparse from pathlib import Path def typecast_args(args): args.input = Path(args.input) args.output = Path(args.output) return args def test_args(args): if not Path(args.input).is_dir(...
Living-with-machines/wrangle-ukds-trade-directories
wrangle_ukds_trade_directories/argparse.py
argparse.py
py
1,285
python
en
code
0
github-code
6
26423979164
import numpy as np import torch import time from torch.autograd import Variable import torchvision.transforms as transforms import torchvision.datasets as dsets import collections import torch.utils.data as data class Model(torch.nn.Module): def __init__(self, input_dim=784, output_dim=10): ...
WENLIXIAO-CS/FL-IoT-Demo
Fed-IoT-demo-lightly/Pytorch_Model.py
Pytorch_Model.py
py
5,470
python
en
code
1
github-code
6
34540300851
import configparser import argparse import json import boto3 import utility from collections import OrderedDict global emr_configuration, emr_applications, cluster_config, optional_instance_config emr_configuration = "emr_cluster.config" emr_applications = ["Hadoop", "Spark", "Ganglia"] cluster_config = "source/cluste...
VCCRI/Falco
launch_cluster.py
launch_cluster.py
py
7,234
python
en
code
37
github-code
6
41744376400
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 16 14:43:47 2021 For plotting: COM data structure is [RGB,YX,FRAME], so if you want the X coordinate of the red float on the 69th frame, you type COM[0,1,69] @author: miles """ import glob import os """directories and data info""" data_dir='switc...
Faaborg/float_tracker
COM_concat.py
COM_concat.py
py
601
python
en
code
1
github-code
6
72764469628
from sklearn.feature_extraction.text import TfidfVectorizer from wordcloud import WordCloud import numpy as np def get_wordcloud(data, stop_words): vectorizer = TfidfVectorizer( use_idf=False, stop_words=stop_words, ngram_range=(2, 2)) vectors = vectorizer.fit_transform(data) counts = np.array(ve...
Amayas29/review-analysis
src/iads/nlp/visualisation.py
visualisation.py
py
607
python
en
code
0
github-code
6
12168811050
# import requests module import requests import logging import time # Setting up Logging logging.basicConfig(level = logging.INFO) logger = logging.getLogger() # URL url = "https://google.com" # Make request method def make_request(url): logging.info("Fetching URL") try: response = requests.get(url...
tolkiger/terraform-ecs-fargate-cicd-pipeline
monitoring.py
monitoring.py
py
891
python
en
code
0
github-code
6
3708389787
import re import redis import pickle import requests from bs4 import BeautifulSoup from dateutil.parser import parse import errors red = redis.StrictRedis(host='redis', port=6379, db=0) try: red.get('test') except ConnectionError: red = None _POST_COMMENT_URL = \ 'https://telopeapark.managebac.com/group...
samdroid-apps/ManageBacToTheFuture
lib/message.py
message.py
py
6,140
python
en
code
1
github-code
6
36093046858
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import unittest import mock from napixd.exceptions import InternalRequestFailed from napixd.application import Napixd from napixd.services.contexts import NapixdContext from napixd.loader.loader import Loader, Load from napixd.http...
napix/NapixServer
tests/test_application.py
test_application.py
py
4,444
python
en
code
1
github-code
6
3728793373
groupA=0 groupB=0 groupC=0 groupD=0 n=int(input("ponga # estudiantes: ")) i=0 while i < n: alt=int(input("altura estudiantes: ")) if alt<=150: groupA +=1 print("Hay", groupA,"alumnos en grupoA") elif 150<alt<=165: groupB +=1 print("Hay", groupB,"alumnos en grupoB") eli...
caroortegaa/Semestre-1
Ejercicios/Estudiantes.py
Estudiantes.py
py
545
python
es
code
0
github-code
6
31994054521
#coding: utf-8 import json, random, os import hashlib import requests from flask_babel import _ from webapp import app #利用百度翻译API提供文本翻译 def translate(text, source_language, dest_language): if 'BD_TRANSLATOR_KEY' not in app.config or not app.config['BD_TRANSLATOR_KEY']: return _('Error: the translation ser...
huawenjin1995/Microblog
webapp/translate.py
translate.py
py
1,421
python
en
code
0
github-code
6
8779322237
class Node: def __init__(self,value) : self.value = value self.next = None class LinkedList: def __init__(self) : self.head = None def add_node(self,value): node = Node(value) if self.head is None: self.head = node ...
ashwin275/DSA
linkedList/linkedlist.py
linkedlist.py
py
2,807
python
en
code
2
github-code
6
21341146103
#!/usr/bin/env python # -*- coding:utf-8 -*- # author: KrianJ # datetime:2022/5/8 21:32 # software: PyCharm-WideDeep import tensorflow as tf from tensorflow.keras.layers import Embedding from tensorflow.keras import Model from models_tf2.base_layer import LR_Layer, DenseLayer class WideDeep(Model): ...
KrianJ/CtrEstimate
models_tf2/WideDeep.py
WideDeep.py
py
2,715
python
en
code
0
github-code
6
22218976546
import os import math from director import robotsystem from director.consoleapp import ConsoleApp from director import ioUtils from director import segmentation from director import applogic from director import visualization as vis from director import continuouswalkingdemo from director import objectmodel as om from ...
RobotLocomotion/director
src/python/tests/testContinuousWalking.py
testContinuousWalking.py
py
3,324
python
en
code
176
github-code
6
71082571387
from ride import Ride def read_input(file): input = open(file, "r") content = input.readlines() input.close() #first line elems = content[0].strip().split(" ") R = int(elems[0]) C = int(elems[1]) F = int(elems[2]) N = int(elems[3]) B = int(elems[4]) T = int(elems[5]) ...
bjoukovs/HashCode2K18
read.py
read.py
py
683
python
en
code
0
github-code
6
70945127228
# remote DB 연동 import MySQLdb import pandas as pd import numpy as np import ast import csv """ config = { 'host':'127.0.0.1', 'user':'root', 'password':'123', 'database':'test', 'port':3306, 'charset':'utf8', 'use_unicode':True } """ try: # db 읽는 방법 with open("mar...
kangmihee/EX_python
py_pandas_db/pack/pandas_db2.py
pandas_db2.py
py
3,238
python
en
code
0
github-code
6