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
4223512763
import numpy as np import pandas as pd import imageio as io from skimage.measure import label, regionprops from skimage.color import label2rgb,gray2rgb from skimage.segmentation import watershed import cv2 import os import scipy.ndimage as ndi def watershedSegStack(seg_stack,num_lesions,postprocess_dir,cam_num): ...
mattposka/PDPS
postprocess.py
postprocess.py
py
7,502
python
en
code
0
github-code
1
1311232607
"""Module containing class for collection of cases""" from typing import Union, List, Dict from sumo.wrapper import SumoClient from fmu.sumo.explorer.objects._document_collection import DocumentCollection from fmu.sumo.explorer.objects.case import Case from fmu.sumo.explorer.pit import Pit _CASE_FIELDS = [ "_id", ...
equinor/fmu-sumo
src/fmu/sumo/explorer/objects/case_collection.py
case_collection.py
py
4,117
python
en
code
0
github-code
1
15552243241
import glob import os def createExe(fileName): exeFileName = fileName masmPath = "C:\\masm\\8086\\" os.system(masmPath+"masm "+exeFileName+", , ;\n") os.system(masmPath+"link "+exeFileName+", , ;\n") os.system("del *.OBJ \n") # clean up unnecessary remnants os.system("del *.LST \n") os.system("del *.MAP \n") d...
Tvashta/HMM
Exe/Experiment 2/makeExes.py
makeExes.py
py
504
python
en
code
0
github-code
1
38819126631
from flask import Flask, render_template, request import jsonify import requests import pickle import numpy as np import sklearn app = Flask(__name__) model = pickle.load(open('insurance_rf.pkl', 'rb')) @app.route('/') def home(): return render_template('index.html') @app.route("/predict", methods=['POST']) def ...
helloraghav1305/Medical-Insurance-Forecast
app.py
app.py
py
1,540
python
en
code
1
github-code
1
24295593369
from itertools import combinations def isPrime(number): if number < 2: return False else: for num in range(2, number): if number % num == 0: return False return True def Prime(n): prime_num = [] for num in range(n): if isPrime(num): ...
HyunSung-Na/TIL-algorism
알고리즘/3주 모의고사 소수.py
3주 모의고사 소수.py
py
646
python
en
code
0
github-code
1
19979055197
"""This module contains a function for loading and processing the distributed representations for the dataset in question. Then generating a BatchGenerator that is compatible with the modified pipeline. The modified pipeline will then train the specified model with the input distributed representations along with its ...
paulmorio/DrugPairScoringDR
train_dr_model.py
train_dr_model.py
py
8,143
python
en
code
5
github-code
1
37453131182
import numpy as np from qiskit import Aer, QuantumCircuit from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit.opflow import StateFn, PauliSumOp,AerPauliExpectation,ListOp,Gradient from qiskit.utils import QuantumInstance,algorithm_globals algorithm_globals...
Rin-The-QT-Bunny/quantum_networks
basic_qnns.py
basic_qnns.py
py
1,572
python
en
code
0
github-code
1
71547921315
import subprocess as sp from collections import defaultdict import numpy as np import pandas as pd import argparse import pickle import os import re ''' This script creates feature matrix from VCF files for downstream ML analysis ''' parser=argparse.ArgumentParser(description='Append MIC phenotype to MIC dataframe') ...
SSID08/ML_thesis
Scripts/Append_MIC_Phenotype.py
Append_MIC_Phenotype.py
py
1,205
python
en
code
0
github-code
1
18718545308
import logging import sys from pathlib import Path from typing import Union import datetime import discord.ext.commands from discord import Message from discord.ext.commands.bot import Bot from google.cloud import firestore from discord.ext import commands from discord_slash import SlashCommand, SlashContext from .an...
suhail339/Discord-Dictionary-Bot
discord_dictionary_bot/discord_bot_client.py
discord_bot_client.py
py
4,500
python
en
code
null
github-code
1
10756180376
import operator OPERATIONS = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv} class Node: def __init__(self): self.data = None self.left: Node = None self.right: Node = None self.root: Node = self def getLeftChild(self): if self.left i...
vabic/HP-35
service/eval_service.py
eval_service.py
py
2,790
python
en
code
0
github-code
1
33091871668
import solution class Solution(solution.Solution): def solve(self, test_input=None): nums, pos = test_input nums = nums.copy() index = 0 curr = head = ListNode(nums.pop(0)) node = None while nums: if index == pos: node = curr ...
QuBenhao/LeetCode
problems/141/solution.py
solution.py
py
993
python
en
code
8
github-code
1
35805656748
#!/usr/bin/env python import turtle import sys import tkinter as tk #s = turtle.getscreen() t = turtle.Turtle() #color('red', 'yellow') while True: t.forward(200) t.left(150) if abs(t.pos()) < 1: break #t.circle(60) t.end_fill() sys.exit()
StoneNLD/python-projects
graphics_and_multimedia/turtle_graphics.py
turtle_graphics.py
py
272
python
en
code
0
github-code
1
73839828832
''' 拖动控件之间的边界:QSplitter ''' import sys,math from PyQt5.QtWidgets import * from PyQt5.QtCore import * class Splitter(QWidget): def __init__(self): super(Splitter,self).__init__() self.initUI() def initUI(self): layout=QHBoxLayout(self) self.setWindowTitle('QSplitter例子') s...
puhaoran12/pyqt5_note
104.拖动控件之间的边界.py
104.拖动控件之间的边界.py
py
1,356
python
en
code
0
github-code
1
4699497508
import os import sys import json import requests from dotenv import load_dotenv load_dotenv() try: path = sys.argv[1] except IndexError: path = input('Path to .md file:\n') with open(path, 'r') as file: md_text = file.read() TOKEN = os.getenv('TOKEN') URL = 'https://api.github.com/markdown' HEADERS = {...
eo-uk/markdown-to-html-converter
main.py
main.py
py
1,302
python
en
code
0
github-code
1
727123219
from RadialBasisFunction import * import numpy as np from sklearn import datasets C=3 F=2 X,Y = datasets.make_classification( n_features=C, n_classes=F, n_samples=200, n_redundant=0, n_clusters_per_class=1 ) X=X.T Y=np.array([Y]) RBF =RadialBasisFunction(C,4) RBF.Train(X,Y,5,100)
dani2442/DeepLearning
RadialBasisFunction/test.py
test.py
py
305
python
en
code
2
github-code
1
16098184030
import pygame import datetime pygame.init() WIDTH=1080 HEIGHT=720 screen = pygame.display.set_mode((WIDTH, HEIGHT)) clock=pygame.image.load("images/main-clock.png").convert() scale_clock = pygame.transform.scale( clock, (clock.get_width() // 2, clock.get_height() // 2)) clockr=scale_clock.get_rect(ce...
aminazhumabayeva/PP2
lab7/1clock.py
1clock.py
py
1,400
python
en
code
0
github-code
1
41612546375
import os import shutil from typing import List, Tuple import pytest from src.models.running_token import RunningToken from src.models.token import Token # folder names and paths of all test files test_files_folder_name = 'test_files' xml_files_folder_name = 'xml' temp_xml_files_folder_name = 'temp_xml' def pytes...
rathaustreppe/bpmn-analyser
test/conftest.py
conftest.py
py
3,398
python
en
code
3
github-code
1
36977463862
sklad = { "1N4148": 250, "BAV21": 54, "KC147": 147, "2N7002": 97, "BC547C": 10 } kod=input("Zadej kód součástky: ") mnozstvi=int(input("Zadej množství součástek: ")) # je/není skladem if kod in sklad: print(f'Součástka {kod} je skladem.') else: print((f'Součástka {kod} není skladem.')) exit() # ...
BarboraVojackova/kurz-python-jaro-23
ukol2.py
ukol2.py
py
734
python
cs
code
0
github-code
1
15279122161
from collections import Node # Definition for a Node. """" class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right """ class Solution: def treeToDoublyList(self, root: 'Node') -> 'Node': # first analyze BST ppties #...
onyxolu/DSA
Facebook/Top 100/ConvertBinarySearchTreeToSortedDoublyLinkedList.py
ConvertBinarySearchTreeToSortedDoublyLinkedList.py
py
1,282
python
en
code
0
github-code
1
25845095235
# Creating a Bouncing Ball Screensaver using OpenCV-Python # Task- Create a Window that we can write text on. If we don’t write for 5 seconds screensaver will start. import cv2 import numpy as np def screensaver(): img = np.zeros((480,640,3),dtype='uint8') dx,dy =1,1 x,y = 100,100 while True: ...
aryaniiit002/Computer-Vision
Basic Programs/screensaver.py
screensaver.py
py
1,769
python
en
code
2
github-code
1
4246358935
import pandas as pd import re from utils import ANALYTICS_DATASET, ENVIRONMENT_SHORT_NAME def get_data_archiving(sql_file): """Run SQL query and save data in a dataframe.""" params = {"{{ANALYTICS_DATASET}}": ANALYTICS_DATASET} file = open(sql_file, "r") sql = file.read() for param, table_name ...
pass-culture/data-gcp
jobs/etl_jobs/external/metabase-archiving/archiving.py
archiving.py
py
6,570
python
en
code
2
github-code
1
70802571555
from sys import platform import pandas as pd import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.metrics.pairwise import cosine_similarity from tabulate import tabulate import string import settings df = pd.read_csv("Cleaned_dataset.csv") df = df.iloc[0:10000,:] features = ['N...
kusai99/Game-Recommendation-system
GameRec.py
GameRec.py
py
3,958
python
en
code
0
github-code
1
74945788513
import os def file_tree(Path, file_filter=None, num_of_space=0): for element in os.listdir(Path): NewPath = Path + '/' + element if os.path.isdir(NewPath): print(num_of_space * '\t' + element) file_tree(NewPath, file_filter, num_of_space=(num_of_space + 1)) elif file...
georgygospodinov/dm_intro
hw1/FileTree.py
FileTree.py
py
505
python
en
code
0
github-code
1
41600008105
# -*- coding:utf-8 -*- # C Style a = 0b10111011 b = 0xc5f print('Binary is %d, hex is %d' % (a, b)) print('==========================================') # Python3 Style a = 1234.5678 formatted = format(a, ',.2f') # ","で3桁で区切る print(formatted) b = 'my string' formatted = format(b, '^20s') # "^" でセンタリング print('*', ...
shomrkm/python_study
effective_python/1_pythonic_thinking/str_format.py
str_format.py
py
1,176
python
en
code
0
github-code
1
6874429677
from functools import reduce numeros = input("ingrese numeros:") numerosEnList = sorted(numeros) print(numerosEnList) numerosImpares = [] for i in numerosEnList: if int(i) % 2 != 0: numerosImpares.append(int(i)) print(numerosImpares) def suma(a, b): return a + b resultado = reduce(suma, num...
Guido564/open-bootcamp-fullstack
Python/Modulo 9/tarea2.py
tarea2.py
py
352
python
pt
code
0
github-code
1
41285122264
from __future__ import unicode_literals import json import datetime from django.template.defaultfilters import escape from program.models import Program from notification.models import Notif from ourjseditor import api from .models import Comment # /program/PRO_ID/comment/new @api.StandardAPIErrors("POST") @api.lo...
OurJSEditor/OurJSEditor
django_code/comment/api.py
api.py
py
5,876
python
en
code
29
github-code
1
23770066721
import sys import os import gui.button from argument_parser import ArgumentParser from data_extraction.collect_data import CollectData from data_extraction.request_handler import RequestHandler from data_extraction.url_collector import UrlCollector from data_storage.data_holder import DataHolder if os.getcwd() not in ...
VenziVi/WebScraper
main.py
main.py
py
1,327
python
en
code
0
github-code
1
25587263944
from flask import Flask, request, render_template import numpy as np import tensorflow as tf from tensorflow.keras.preprocessing import image import os app = Flask(__name__) # Get the absolute path to your application's directory #app_directory = os.path.dirname(os.path.abspath(__file__)) # Construct the absolute pa...
Aravind0510/plant_disease
app.py
app.py
py
2,650
python
en
code
0
github-code
1
33721705752
import sys, os def indice(liste,element): return liste.index(element) if __name__ == '__main__': commande = [] for i in range(1,len(sys.argv)): if '-' in sys.argv[i] : pass else: args = [] if i != len(sys.argv) - 1 and '-' not in sys.argv[i+1]: args.append(sys.argv[i]) for j in range(i+1,len...
gando537/L2-Systeme-Python
rendu_1/Mouhamed_Gando_Diallo/myif.py
myif.py
py
1,583
python
en
code
0
github-code
1
4384202526
''' RESPONSE WITH HTML CONTENTS Let's response with our first web page written in HTML. We know nothing about HTML. It is the language used for the creating web pages,that describes the structure of the document. Web browsers receive HTML documents from a web server or from local storage and render the documents int...
helenyaben/2018-19-PNE-practices
PNE-Session11/HTML_response.py
HTML_response.py
py
3,059
python
en
code
0
github-code
1
14929220320
"""Defines hyperparameters and runtime settings for the Deep Q-Network.""" # The network learning rate. LEARNING_RATE = 1e-6 # Initial probability of the learner taking a random action. # This probability decays over time as the learner experiences the world. EXPLORATION_START_RATE = 1 # Final probability of the lea...
evandez/mqrio
learner/config.py
config.py
py
2,126
python
en
code
2
github-code
1
31325561176
import glob import os import corner import matplotlib.pyplot as plt import numpy as np import pandas as pd import scipy.stats import matplotlib.lines as mlines VIOLET_COLOR = "#8E44AD" BILBY_BLUE_COLOR = '#0072C1' PARAMS = dict( # chi_eff=dict(l=r"$\chi_{eff}$", r=(-1, 1)), # chi_p=dict(l=r"$\chi_{p}$", r=(...
avivajpeyi/bh_getting_kicks
creating_an_agn_prior/add_agn_spins_to_samples.py
add_agn_spins_to_samples.py
py
3,970
python
en
code
0
github-code
1
9058951679
from __future__ import annotations from typing import List, Tuple, Optional import re import os from .basic import Unit from .pattern import PatternLoader class VplParser: @staticmethod def finish(text): return text if text.endswith("\n") else text + "\n" @staticmethod def unwrap(text): ...
senapk/tko
src/tko/loader.py
loader.py
py
8,186
python
en
code
2
github-code
1
2733857930
import requests from bs4 import BeautifulSoup import os #os.chdir('~/crawl') from selenium import webdriver from selenium.webdriver import FirefoxOptions from selenium.webdriver.common.by import By opts = FirefoxOptions() opts.add_argument("--headless") browser = webdriver.Firefox(firefox_options=opts) #browser = webd...
elSomewhere/AnalyticsTextGen_DL
crawl_SKA.py
crawl_SKA.py
py
1,701
python
en
code
0
github-code
1
73681599393
''' Access Point Test Copyright (c) 2009 Jouni Miettunen http://jouni.miettunen.googlepages.com/ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENS...
aurzola/s60
tel/t_ap.py
t_ap.py
py
3,445
python
en
code
1
github-code
1
16386355754
# -*- coding: utf-8 -*- """ Created on Mon Sep 6 22:36:08 2021 @author: user """ import random import numpy as np def medir_temp(n): mu = 0 sigma = 0.2 temp_normal = 37.5 mediciones = [] for i in range(n): mediciones.append(temp_normal + random.normalvariate(mu,sigma)) ...
MarcosMartilotta/Curso_Python_UNSAM
Entrega_clase_5/termometro.py
termometro.py
py
1,024
python
es
code
0
github-code
1
16805215564
import multiprocessing as mp from parallel_data_processing.parallel_join.hash_join import hash_join def range_partition(data, range_indices): result = [] new_data = data[:] new_data=sorted(new_data,key=lambda new_data:new_data[1]) # Calculate the number of bins range_index = len(range_indices) ...
OceanicSix/Python_program
parallel_data_processing/parallel_join/disjoint.py
disjoint.py
py
2,271
python
en
code
1
github-code
1
703924834
#!/usr/bin/env python3 """ module """ import tensorflow as tf sdp_attention = __import__('5-sdp_attention').sdp_attention class MultiHeadAttention(tf.keras.layers.Layer): """ multiheadattention """ def __init__(self, dm, h): """ init """ if type(dm) is not int: raise TypeEr...
GuzhiRegem/holbertonschool-machine_learning
supervised_learning/0x11-attention/6-multihead_attention.py
6-multihead_attention.py
py
1,643
python
en
code
0
github-code
1
38202371506
from datetime import datetime, timedelta import requests import json import eel @eel.expose def ten_newest_question(tag): url = "http://api.stackexchange.com/2.2/search?order=desc&sort=creation&tagged=" + tag + \ "&site=stackoverflow&filter=withbody&pagesize=10" data = requests.get(url).js...
Taichi-Pink/Android-related-questions-Stackoverflow
Web.py
Web.py
py
954
python
en
code
0
github-code
1
40888320190
from tkinter import simpledialog import math import pygame pygame.init() tamanho = (850, 560) tela = pygame.display.set_mode(tamanho) pygame.display.set_caption("Space Marker") # Definir o ícone da janela icone = pygame.image.load("space.png") pygame.display.set_icon(icone) fundo = pygame.image.load("bg.jpg") pygame...
biecoski/spacemaker
main.py
main.py
py
4,644
python
pt
code
0
github-code
1
29520479895
import pytest import requests @pytest.fixture def api_base_address(): return "http://localhost:5000" @pytest.fixture def pq_data(): return [(0, 4), (1, 7)] @pytest.fixture def pq_get_data(): return {"highest": {"index": 1, "key": 7}, "content": [ {"index": 1, "key": 7}, {"index": 0, "key": 4} ...
AlanKev117/demo-restful-api
test/test_api.py
test_api.py
py
2,189
python
en
code
0
github-code
1
17145944405
import json import random import re import string import sys from json import JSONDecodeError from entities import ConfigEntity, UserEntity from network import exponential_backoff_request API_URL = 'http://127.0.0.1:8000' API_METHOD_SIGNUP = '/api/signup' API_METHOD_SIGNIN = '/api/token/' API_METHOD_CREATE_POST = '/a...
Omkommersind/drf_template_bot
bot.py
bot.py
py
3,957
python
en
code
0
github-code
1
31509541216
from django.db import models from django.shortcuts import reverse from django.utils import timezone from django.contrib.auth.models import User class Callout(models.Model): BWD = 'BWD' CCH = 'CCH' HND = 'HND' SYO = 'SYO' FACILITY = ( (BWD, 'BWD'), (CCH, 'CCH'), (HND, 'HND')...
Megaprotas/work_project
my_app/models.py
models.py
py
2,445
python
en
code
0
github-code
1
15111556685
import argparse import zipfile import io from lxml import etree namespace = "{http://schemas.microsoft.com/3dmanufacturing/core/2015/02}" if __name__ == "__main__": parser = argparse.ArgumentParser(description='Strip metadata from 3MF files') parser.add_argument('source', metavar='source', type=str, nargs='...
nallath/3MFMetadataStripper
stripMetadata.py
stripMetadata.py
py
1,789
python
en
code
1
github-code
1
6912998800
#!/usr/bin/env python3 import collections import os import subprocess DATE = "2022-01-01" BRANCH = 'main' print("Statistics on the %s branch after %s" % (BRANCH, DATE)) print("cwd: %s" % os.getcwd()) proc = subprocess.run(['git', 'log', '--after=%s' % DATE, BRANCH], stdout=subprocess.PIPE, ...
vstinner/misc
python/git_commit_stats.py
git_commit_stats.py
py
657
python
en
code
22
github-code
1
39631632894
import os from pathlib import Path from unittest.mock import patch import pytest import pytest_check as check import yaml from msticpy.config.comp_edit import CompEditStatusMixin from msticpy.config.ce_azure_sentinel import CEAzureSentinel, _validate_ws from msticpy.config.ce_common import get_def_tenant_id from mstic...
sh9369/msticpy
tests/config/test_item_editors.py
test_item_editors.py
py
12,896
python
en
code
null
github-code
1
2016504957
from __future__ import division import sys from math import* import numpy from numpy import* import random from matplotlib import pyplot as plt R=10**12 #cm Radius Tau=10 #Opacity Lambda=R/Tau #Mean Free Path c=3.0*10**9 #cm/s nph=10000 TimeS=numpy.empty(nph) for p in range(nph): i=1 ...
chatcher99/Cassandra_Hatcher
Finished Thesis Codes (Unused)/Timing Scattered Photons in Star.py
Timing Scattered Photons in Star.py
py
1,892
python
en
code
0
github-code
1
8787434018
worker={} n=int(input("Range:")) for x in range(n): na=input("Worker Name:") sal=int(input("Salary:")) print() worker[na]=sal print("WorkerName----->Salary") for y in worker: print(y,"------>",worker[y])
3110vaibhav2005/pythonPro
Worker Details 2.py
Worker Details 2.py
py
234
python
en
code
0
github-code
1
22525713243
from setuptools import setup with open("README.md") as f: readme = f.read() setup( name="dpr", version="1.0.0", description="Facebook AI Research Open Domain Q&A Toolkit", url="https://github.com/facebookresearch/DPR/", classifiers=[ "Intended Audience :: Science/Research", "Li...
microsoft/LMOps
uprise/DPR/setup.py
setup.py
py
930
python
en
code
2,623
github-code
1
41146694685
import multiprocessing """ result = [] def Calculate_Square(numbers): for i in numbers: print("Square :", i * i) result.append(i * i) print("Inside Function :", result) if __name__ == "__main__": list = [1, 2, 3, 4, 5] p1 = multiprocessing.Process(target = Cal...
naveedeveloper/operating-system
sharingData.py
sharingData.py
py
1,414
python
en
code
0
github-code
1
24606051474
#!/usr/bin/env python # coding: utf-8 # In[40]: ''' 세 정수가 입력으로 주어진다. 순서대로 년도, 월, 일 이다. 년도 - 월 + 일의 마지막 숫자가 0이면 "대박"을 , 그렇지 않으면 "그럭저럭"을 출력하시오. ''' a,b,c=input().strip().split(' ') a=int(a) b=int(b) c=int(c) d=a-b+c d=str(d) e=d[-1] if e=='0': print("대박") else: print("그럭저럭") # In[ ]:
smilesunho/practice-for-codeup
1162.py
1162.py
py
422
python
ko
code
0
github-code
1
10879724088
import pyb CMD_MEASURE_TEMP = 0xF3 CMD_MEASURE_HUM = 0xF5 CMD_READ_TEMP = 0xE0 CMD_RESET = 0xFE CMD_READ_USER = 0xE6 CMD_FIRMWARE_V = b'\x84\xb8' CMD_READ_SERIAL1 = b'\xFA\x0F' CMD_READ_SERIAL2 = b'\xFC\xC9' class SI7021: def __init__(self, i2c): self.i2c=i2c self.addr=64 def exec_cmd(self, c...
aquell/micropython-driver
si7021/si7021.py
si7021.py
py
879
python
en
code
0
github-code
1
24875016673
import hashlib import os import pathlib import random import re import string import uuid from datetime import datetime, timedelta from typing import List, NamedTuple, Optional, Tuple import astropy.units as u from astropy.units import Quantity from dateutil import tz from faker import Faker from ssda.observation imp...
saltastroops/data-archive-database
src/ssda/util/dummy.py
dummy.py
py
14,081
python
en
code
0
github-code
1
17159878700
from .models import Coleccion, Autor, Libro from django.core.cache import cache from django.conf import settings from django.contrib.sites.models import Site def colecciones(request): return { 'colecciones': Coleccion.objects.filter(orden__lt=9).order_by("orden"), "DEBUG": settings.DEBUG, ...
ignacionf/cuenco
home/context_processors.py
context_processors.py
py
757
python
en
code
0
github-code
1
4190657104
################################# # Your name:Yonatan Gertskin ################################# # Please import and use stuff only from the packages numpy, sklearn, matplotlib import numpy as np import matplotlib.pyplot as plt import numpy.random from sklearn.datasets import fetch_mldata from scipy.io import loadmat...
Maltmark/hello-world
perceptron - Copy.py
perceptron - Copy.py
py
4,050
python
en
code
0
github-code
1
7830366989
# 4) Make two files, cats.txt and dogs.txt. # Store at least three names of cats in the first file and three names of dogs in the second file. # Write a program that tries to read these files and print the contents of the file to the screen. # Wrap your code in a try-except block to catch the FileNotFound error, and...
CharlesMontgomery2/Python-Class-Exercises
Files and Exceptions/pet_names.py
pet_names.py
py
898
python
en
code
0
github-code
1
12171462089
import torch import torch.nn as nn from attention import MultiHeadedAttention class FeedForward(nn.Module): def __init__(self, input_dim: int, dim: int = 2048, dropout: float = 0.1) -> None: super(FeedForward, self).__init__() self.feed_forward = nn.Sequential( nn.Linear(input_dim, dim...
VashishtMadhavan/transformers-scratch
blocks.py
blocks.py
py
2,597
python
en
code
1
github-code
1
26661553275
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html from pymongo import MongoClient from crop_spiders.items import CropItem, PestItem, PestItem2 class CropPipeline(object): ...
jllan/spiders_mess
crop_spiders/crop_spiders/pipelines.py
pipelines.py
py
899
python
en
code
0
github-code
1
73645659875
#!/usr/bin/env python3 import unittest try: from packaging.version import Version as LV except ImportError: from distutils.version import LooseVersion as LV print('WARNING: using distutils version check, not packaging!') import os nvidia = False # if running within NVIDIA container nvidia_skip = False m...
CSCfi/puhti-ml
tests/pytorch.py
pytorch.py
py
9,647
python
en
code
0
github-code
1
75256457633
class Solution(object): def islandPerimeter(self, grid): """ :type grid: List[List[int]] :rtype: int """ recount=0 sum=0 n=len(grid) m=len(grid[0]) for i in range(len(grid)): for j in range(len(grid[i])): if grid[i]...
HawkinYap/Leetcode
leetcode463.py
leetcode463.py
py
899
python
en
code
0
github-code
1
1424320107
num1= 30 num2= 40 num3 = num2 + num1 # print ("hello world" , num3) print("bitwise shift by 2 =" , num1 >> 1) print("bitwise shift by 2 =" , num2 >> 2) string1="python" string2="kundan" # print("addming string =", string1+string2) # print("repeating string", string1*4) # print("string slicing", string1[2:4]) # ...
kundankumarmourya/pythonpractice
test.py
test.py
py
677
python
en
code
0
github-code
1
40475531621
import cv2 import numpy as np import os import torch from torch.utils.data import Dataset class MaskDataset(Dataset): def __init__(self, data_dir, img_transform, msk_transform, img_resize=(256, 256), msk_resize=(32, 32)): self.image_paths = [] self.masks_paths = [] self.img_transform = img...
OYMiss/ssdd-net
ssdd/dataset.py
dataset.py
py
1,693
python
en
code
1
github-code
1
29244918906
# postpone and is in UTC # If program re-run, no job but present in db # postpone the next day's class # postponing on sat and sun shouldnt be allowed # add cancel button to postpone, cancel and events from replit import db import credentials as crd from apscheduler.schedulers.background import BackgroundScheduler f...
Tibin-Saji/ClassAssistant_TeleBot
main.py
main.py
py
18,095
python
en
code
0
github-code
1
10255584826
from core.utils.osutils import join from core.utils.osutils import exists from core.utils.osutils import isdir from core.utils.osutils import mkdir_p from core.utils.osutils import dirname from shutil import copyfile OBJECT_NAME = "tissue" DATA_ROOT = "D:\\Code\\Project\\NeuralTexture_gan\\data" TARGET_PATH = join(DAT...
xuxmin/NeuralTexture_gan
copy_data.py
copy_data.py
py
1,408
python
en
code
1
github-code
1
45021048063
import os import cv2 global i global coordinates def on_event(event, x, y, flags, img): global i global coordinates if i < 4: if event == cv2.EVENT_LBUTTONDOWN: xy = "%d,%d" % (x, y) coordinates[i][0] = int(x) coordinates[i][1] = int(y) cv2.circle(...
INFWOLAD/OCR_BookPages
assistant/mark.py
mark.py
py
1,272
python
en
code
0
github-code
1
20741853198
import json import unittest.mock from typing import List import pytest from pytest_httpx import HTTPXMock from world_boss.app.data_provider import DATA_PROVIDER_URLS from world_boss.app.enums import NetworkType from world_boss.app.kms import MINER_URLS, signer from world_boss.app.models import Transaction, WorldBossR...
planetarium/world-boss-service
tests/tasks_test.py
tasks_test.py
py
10,833
python
en
code
2
github-code
1
70702971555
from machine import Pin, PWM from time import sleep import math #143.76 steps per inch INCH = 143.76 DEGREE = 14.4 class Driving_control: def __init__(self): self.leftPWM = PWM(Pin(15)) self.rightPWM = PWM(Pin(19)) self.leftDir = Pin(14, Pin.OUT) self.rightDir = Pin(18, Pin.OUT) ...
jdc13/Farm_Roomba
Test Files/adjust_function_for_pico_main.py
adjust_function_for_pico_main.py
py
6,854
python
en
code
0
github-code
1
42174288140
import numpy as np import json as j def get_counts(json_anno, size=(100,70,100)): count = np.zeros(size, dtype=np.int) for img_name in json_anno: for relation in json_anno[img_name]: sub = relation['subject']['category'] pred = relation['predicate'] obj = relation['o...
econser/active_refer
vrd_analysis.py
vrd_analysis.py
py
793
python
en
code
0
github-code
1
45870824361
from numpy import linspace from sympy import symbols from math import * # Definição da variável em uso -> f(x): x x = symbols('x') def Simpson(f, a, b, e): #Um numero muito pequeno d = 0.0001 #Vetor de m pontos cobrindo o intervalo [a,b] xd = [] yd = [] for i in linspace(a,b,round((b-...
iOsnaaente/Faculdade_ECA-UFSM
Metodos Numericos/Integrais/integral_Simpson.py
integral_Simpson.py
py
2,772
python
pt
code
0
github-code
1
74934250594
from generic_scripts.tools import ToolsCmd, ssh_cli from generic_scripts.global_var import logger, console, dbaas from nginx import set_nginx import time import re import random import inspect import os def login_mysql(inst_info): norms = {1: 'master', 2: 'slave', 3: 'logger'} console.print('************** 请输...
xxyhhd/my_scripts
new/db_scripts/mysql.py
mysql.py
py
11,543
python
en
code
0
github-code
1
13589234475
from django import forms from django.utils.translation import gettext_lazy as _ from django.contrib.auth import get_user_model from .models import Blog class BlogForm(forms.ModelForm): class Meta: model = Blog fields = ['title', 'slug', 'content', 'categories', 'cover', 'is_vip', 'status', 'autho...
Adler-KZ/AKLog
blogs/forms.py
forms.py
py
1,164
python
en
code
0
github-code
1
27801962557
from list_node import ListNode from test_framework import generic_test def merge_two_sorted_lists(L1, L2): placeholder = ListNode() pointer = placeholder while L1 and L2: if L1.data < L2.data: pointer.next= L1 L1 = L1.next else: pointer.next = L2 ...
garciamilord/Elements-of-Programming-Interviews
epi_judge_python_solutions/sorted_lists_merge.py
sorted_lists_merge.py
py
658
python
en
code
null
github-code
1
27756401926
import sys, os, json, types, unittest for i in ["/task", "/workspace", "/program"]: sys.path.append(os.path.dirname(os.path.realpath(__file__)) + i) import taskManager as TM, workspaceManager as WM, programManager as PM commands = WM.commands + TM.commands + PM.commands class Commands(unittest.TestCase): de...
legit-programming/Todo-App
tests.py
tests.py
py
1,860
python
en
code
3
github-code
1
410373120
from __future__ import absolute_import from tests import util import transitfeed class ShapeValidationTestCase(util.ValidationTestCase): def ExpectFailedAdd(self, shape, lat, lon, dist, column_name, value): self.ExpectInvalidValueInClosure( column_name, value, lambda: shape.AddPoint(lat, lon, d...
google/transitfeed
tests/transitfeed/testshapepoint.py
testshapepoint.py
py
4,365
python
en
code
670
github-code
1
10147080980
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import time import magic import datetime import logging from pastefile import utils from jsondb import JsonDB from flask import send_from_directory, abort from werkzeug import secure_filename LOG = logging.getLogger(__name__) def get_infos_file_from_md5(md5, db...
guits/pastefile
pastefile/controller.py
controller.py
py
8,324
python
en
code
7
github-code
1
25266075341
from discord.ext import commands import traceback class ErrorHandler(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_command_error(self, ctx, error): print(error) def setup(bot): bot.add_cog(ErrorHandler(bot))
jamesreprise/dante-lite
src/cogs/errorhandler.py
errorhandler.py
py
291
python
en
code
0
github-code
1
41054626746
from unittest.mock import MagicMock from botocore.exceptions import ClientError import pytest class MockManager: def __init__(self, stub_runner, scenario_data, input_mocker): self.scenario_data = scenario_data self.instance_id = "test-instance" self.scenario_data.scenario.inst_wrapper.inst...
awsdocs/aws-doc-sdk-examples
python/example_code/ec2/test/test_stop_and_start_instance.py
test_stop_and_start_instance.py
py
2,740
python
en
code
8,378
github-code
1
18266456013
import sys import optparse from os import stat from os.path import exists, join as pathjoin from eventlet import wsgi, listen from swift.common.exceptions import LockTimeout from swift.common.utils import split_path, readconf, lock_parent_directory from srm.utils import Daemon, get_md5sum, get_file_logger class FileI...
pandemicsyn/swift-ring-master
srm/ringmasterwsgi.py
ringmasterwsgi.py
py
6,717
python
en
code
11
github-code
1
39956940067
from models.yolo import * from models.ssd import * from util import * from collections import defaultdict import argparse import time import pickle as pkl import random import pdb import os.path as osp #Path vars dirname = os.path.dirname(__file__) CLASS_NAMES_PATH = os.path.join(dirname, 'data/image/coco/coco.names')...
RaedShabbir/Object-Detection
main.py
main.py
py
15,219
python
en
code
0
github-code
1
22419684025
#!/usr/bin/python2.7 import os # We'll render HTML templates and access data sent by POST # using the request object from flask. Redirect and url_for # will be used to redirect the user once the upload is done # and send_from_directory will help us to send/show on the # browser the file that the user just uploaded from...
pkraison/Resize
app.py
app.py
py
6,779
python
en
code
4
github-code
1
18163845793
from sys import argv, stderr from json import load json_fname = argv[1] # load json with open(json_fname) as f: j = load(f) # create list of existing input-output pairs pairs_list = [] for e in j: for f in e['flows']: if 'inputPort' in f and 'outputPort' in f: pair = (f['inputPort'], f['outputPort']) ...
giditre/unibo-agh_monitoring
old_stuff_2018/sflowtest/pp_avgDatarate.py
pp_avgDatarate.py
py
1,076
python
en
code
0
github-code
1
22462482103
import pyautogui from tkinter import * import pyperclip3 as pc import keyboard janela = Tk() janela.title("Collor Micker") janela.geometry('250x58') janela.configure(bg='#FFFFFF') janela.iconbitmap("icon.ico") global pixelColorHEX def atualizar_cor(): x, y = pyautogui.position() print(f"x:{x} y:{y}") pi...
mayconvs/color_micker
color_micker.py
color_micker.py
py
1,387
python
en
code
1
github-code
1
3723395858
#对整数的二进制表示取反(0 变 1 ,1 变 0)后,再转换为十进制表示,可以得到这个整数的补数。 #例如,整数 5 的二进制表示是 "101" ,取反后得到 "010" ,再转回十进制表示得到补数 2 。 #给你一个整数 num ,输出它的补数。 #示例 1: #输入:num = 5 #输出:2 #解释:5 的二进制表示为 101(没有前导零位),其补数为 010。所以你需要输出 2 。 #示例 2: #输入:num = 1 #输出:0 #解释:1 的二进制表示为 1(没有前导零位),其补数为 0。所以你需要输出 0 。 class Solution: def findComplement(self, num: int)...
YuLili-git/leedcode_daily
476. 数字的补数.py
476. 数字的补数.py
py
895
python
zh
code
0
github-code
1
73295405474
fname = input("Enter file name: ") try: fh = open(fname) except: print('File cannot be opened:',fname) quit() count = 0 total_dspam_confidence = 0 for line in fh: # Confidence rate in each line if not line.startswith("X-DSPAM-Confidence:"): continue # Count of lines where X-DSPAM conf...
codesydney/citizendev
py4e/chapter07/eduardo/ex_07_02.py
ex_07_02.py
py
772
python
en
code
2
github-code
1
3849699527
N = abs(int(input('Enter count of elements A: '))) A_entered = input("Enter list elements separated by a space: ").split() A_num = list(map(int, A_entered)) if len(A_num) != N or N == 0: print('No match!') else: X = int(input('Enter X, to compare the elements of the list: ')) min = abs(X - A_num[0]) ind...
Gulnoza-PM/python
hw3-2.py
hw3-2.py
py
585
python
en
code
0
github-code
1
22235661224
from flask import Blueprint, jsonify from backend.app import db from backend.models.listings import Listings from backend.models.staff import Staff from backend.models.staffapplication import StaffApplication updateStaffApplicationBP = Blueprint("updateStaffApplication", __name__) @updateStaffApplicationBP.route("/ap...
darylcwx/skillbasedroleportal
backend/routes/post/updateStaffApplication.py
updateStaffApplication.py
py
1,492
python
en
code
0
github-code
1
27089629037
n = int(input()) a = list(map(int, input().split())) a.sort(reverse=True) if n == 2: print(*a) exit() l = a[0] if l % 2 == 1: desirable = l//2 + 1 r = a[0] for item in a: if abs(item - desirable) < abs(r - desirable): r = item print(l, r) else: desirable = l//2 ...
Intel-out-side/AtCoder
DiffUme/BinomialCoefficients.py
BinomialCoefficients.py
py
442
python
en
code
0
github-code
1
42999706569
''' Problem 107 | Binary Tree Level Order Traversal II https://leetcode.com/problems/binary-tree-level-order-traversal-ii/ ''' class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def levelOrderBottom(sel...
davijit868/Programming-Solutions
Data Structures/Trees/Binary Tree Level Order Traversal II.py
Binary Tree Level Order Traversal II.py
py
832
python
en
code
2
github-code
1
19841378208
import random import string import urllib2 import json import time import csv from PIL import ImageDraw from PIL import Image from PIL import ImageFont def createImage(): name = raw_input("What is your name?\n") size = (240,280) color = "#%06x" % random.randint(0, 0xFFFFFF) font = ImageFont.truetype("Arial.ttf",2...
reispedro/CS1122
hw02.py
hw02.py
py
2,162
python
en
code
0
github-code
1
29732225856
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup def get_version(): """Gets the repository version.""" import subprocess proc = subprocess.Popen('hg log -r tip --template "{latesttagdistance}"', shell=True, stdout=subproce...
iamFIREcracker/strappon
setup.py
setup.py
py
574
python
en
code
0
github-code
1
1914844296
# import necessary packages from __future__ import print_function import sys import os sys.path.append('../web') from sense_hat import SenseHat from app.doctor.doctor_services import DoctorService import aiy.assistant.auth_helpers from aiy.assistant.library import Assistant import aiy.audio import aiy.voicehat from goo...
jasonshere/MAPS
maps_assis/assistant.py
assistant.py
py
4,775
python
en
code
0
github-code
1
36038885033
def getHint(secret, guess): """ :type secret: str :type guess: str :rtype: str """ A, B = 0, 0 secret_cnt = {} guess_cnt = {} for i in range(len(secret)): if secret[i] == guess[i]: A += 1 else: if secret[i] in secret_cnt: secr...
zhaoxy92/leetcode
299_bulls_cows.py
299_bulls_cows.py
py
827
python
en
code
0
github-code
1
73034193633
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Rahul Handay <rahulha@saltstack.com>` ''' # Import Python libs from __future__ import absolute_import # Import Salt Libs from salt.states import http # Import Salt Testing Libs from salttesting import skipIf, TestCase from salttesting.helpers import ensure_in_syspa...
shineforever/ops
salt/tests/unit/states/http_test.py
http_test.py
py
1,499
python
en
code
9
github-code
1
72775535074
def cipher(text, shift, encrypt=True): """ Conducts the traditional caesar cipher on the string text. Parameters ---------- text: Any python string value shift: Any python integer value encrypt: Default value is left shift, but setting it to False will create a right...
QMSS-G5072-2020/cipher_patel_pooja
cipher_pvp2108/cipher_pvp2108.py
cipher_pvp2108.py
py
975
python
en
code
0
github-code
1
17591144969
import streamlit as st import streamlit.components.v1 as components import pandas as pd import plotly.express as px import webbrowser # Page configuration st.set_page_config(page_title='Archdaily Statistics') st.title('Archdaily Statistics') st.markdown('This app is showing various statistics of projects on ArchDaily....
mariovalkovic/archdaily_statistics
app.py
app.py
py
1,647
python
en
code
0
github-code
1
14617540959
import os import sys import time sys.path.append(os.getcwd()) from main_folder.smpc_addition.experiments.distances.BoxPlotMaker import BoxPlotMaker from main_folder.smpc_addition.PickleFileUtils import ( read_in_pickle_file, write_to_pickle_file, ) # load af dataset complete_data_set = read_in_pic...
mswartz2/Secure-Multiparty-Computation-Main-Code
main_folder/smpc_addition/experiments/distances/calculate_distances.py
calculate_distances.py
py
1,836
python
en
code
0
github-code
1
34000502655
# 20200704 from heapq import * class HeapQueue: def __init__(self, l=[], key=lambda x:x): self.key = key self.l = [(self.key(l_i), l_i) for l_i in l] heapify(self.l) def push(self, v): heappush(self.l, (self.key(v), v)) def pop(self): if self.l: ...
yojiyama7/python_competitive_programming
atcoder/abc/abc020/c_.py
c_.py
py
4,079
python
en
code
0
github-code
1
32486140161
from collections import deque def bfs(r, c): visited[r][c] = 1 s = 1 queue.append((r, c)) while queue: i, j = queue.popleft() if visited[i][j] == L: return s for k in range(4): ni = i + drc[k][0] nj = j + drc[k][1] cur = grid[i][j...
CrimsonTheLegoBuilder/MyBaekjoonSolve
hw/sw1953_2.py
sw1953_2.py
py
1,163
python
en
code
0
github-code
1
12429395250
#! /usr/bin/env python3 import sys import argparse import expand def go(args): expander = expand.Expander() if args['bundles']: print('Querying bundles') print(expander.getGeneBounds(args['compressed'], args['chrom'], args['start'], args['end'])) if args['coverage']: print('Querying...
jpritt/boiler
query.py
query.py
py
1,734
python
en
code
13
github-code
1
22291648102
from typing import Any, Dict, List, Type, TypeVar, Union import attr from ..models.aml_record import AMLRecord from ..models.taa_acceptance import TAAAcceptance from ..models.taa_record import TAARecord from ..types import UNSET, Unset T = TypeVar("T", bound="TAAInfo") @attr.s(auto_attribs=True) class TAAInfo: ...
Indicio-tech/acapy-client
acapy_client/models/taa_info.py
taa_info.py
py
3,665
python
en
code
6
github-code
1