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
16181058653
import numpy as np import cv2 import os import sys import matplotlib.pyplot as plt def detect_feature_and_keypoints(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # detect and extract features from the image sift = cv2.xfeatures2d.SIFT_create() keypoints, features = sift.detectAndComp...
Jackkuoo/CV
HW3/CV_HW3_3_309505018/stitch.py
stitch.py
py
8,361
python
en
code
0
github-code
50
26526685783
from flask import jsonify, request from controller import app, db from service.authenticate import jwt_required from model.valid_database_model import ValidDatabase, valid_databases_share_schema @ app.route('/getValidDatabases', methods=['GET']) @ jwt_required def getValidDatabases(current_user): try: re...
FRIDA-LACNIC-UECE/back-end
api/controller/valid_database_controller.py
valid_database_controller.py
py
1,024
python
en
code
0
github-code
50
39333877966
#!/usr/bin/python2 """ JSON Tokens ============== """ from setuptools import setup, find_packages import unittest def get_test_suite(): test_loader = unittest.TestLoader() test_suite = test_loader.discover('.', pattern='unit_tests.py') return test_suite setup( name='jsontokens', version='0.0.4',...
blockstack-packages/jsontokens-py
setup.py
setup.py
py
1,113
python
en
code
9
github-code
50
34355928097
from unittest.mock import MagicMock from entrypoint import DynDNS import pytest @pytest.fixture def main_obj(): obj = DynDNS() obj.r53 = MagicMock() return obj def test_get_hosted_zone(main_obj): main_obj.r53.list_hosted_zones.return_value={ "HostedZones": [{ "Id": "boston", ...
ktruckenmiller/aws-docker-dynamic-dns
test_entrypoint.py
test_entrypoint.py
py
990
python
en
code
0
github-code
50
23188207488
import pickle import generating_descriptors as gd import Profile def load_db(pathname): """ returns the stored database from a pickle file Parameters ---------- pathname: string Returns ------- database: dictionary mapping names to profiles """ with open(pathname...
armaan-v924/computer-vision-capstone
database_functions.py
database_functions.py
py
1,787
python
en
code
1
github-code
50
24076526190
import tensorflow as tf import numpy as np import traceback import torch import os class Logger(object): """ Общее описание класса """ def __init__(self, log_dir, save_weight): """ Create a summary writer logging to log_dir :param log_dir: str: папка для местоположения логов ...
NikitaKoltok/sonar_sig
src/utils/logger.py
logger.py
py
3,061
python
ru
code
0
github-code
50
31761205091
from torch import nn import torch # 在模型结构中需要体现α class DepthwiseSeparableConv(nn.Module): def __init__(self,in_channel,out_channel,stride=1,alpha=1.): super(DepthwiseSeparableConv, self).__init__() # stride作用与深度可分离卷积的depth-wise模块中 in_channel = int(alpha * in_channel) out_chann...
hu12jiangtao/-
mobilenet v11/mobilenet_v1理解/model.py
model.py
py
5,469
python
en
code
0
github-code
50
1937713173
''' 'PYTHON CODE SIMILARITY ANALYZER' Created for the course of Artificial Intelligence, taught by Sir Sikandar Khan at SZABIST. Authors: Esha Rashid CS-1812262 Hamza Hussain CS-1812264 ''' import ast import astor import math import json import re from difflib import SequenceMatcher from difflib import unified_d...
hamzahussyn/SimilarityAnalyser
SimilarityAnalyzer.py
SimilarityAnalyzer.py
py
11,828
python
en
code
1
github-code
50
32178668998
#!/usr/bin/env python3 import sys n = int(sys.argv[1]) total_lines = [] unique_lines = set() for line in sys.stdin: line = " ".join(line.lower().split()) total_lines.append(line) unique_lines.add(line) if len(unique_lines) >= n: print(f"{n} distinct lines seen after {len(total_lines)} lines re...
Syyre/COMP2041
test09/distinct_lines.py
distinct_lines.py
py
444
python
en
code
1
github-code
50
44196669020
from logging import getLogger from hornet import models from .common import ClientCommand logger = getLogger(__name__) class Command(ClientCommand): def add_arguments(self, parser): parser.add_argument("member_id", type=int) parser.add_argument("text") def handle(self, member_id, text, *ar...
namezys/mandilka
hornet/management/commands/hornet_send_message.py
hornet_send_message.py
py
567
python
en
code
0
github-code
50
42243755878
import sys E_HITS, E_D = [int(line.split(': ')[1]) for line in sys.stdin.readlines()] M_HITS, MANA = 50, 500 SPELLS = [ # cost, dmg, heal, arm, mana, delay (53, 4, 0, 0, 0, 0), (73, 2, 2, 0, 0, 0), (113, 0, 0, 7, 0, 6), (173, 3, 0, 0, 0, 6), (229, 0, 0, 0, 101, 5) ] def run(hard): min_cos...
ShuP1/AoC
src/2015/22.py
22.py
py
1,546
python
en
code
0
github-code
50
23321370519
import random # A list of words that potential_words = ["code", "sisterhood", "program", "empower", "team", "atom", "technology", "notebook", "marker"] word = random.choice(potential_words) # Use to test your code: #print(word) # Converts the word to lowercase word = word.lower() # Make it a list of letters for so...
gomezquinteroD/GWC2019
Python/GuessWord.py
GuessWord.py
py
1,262
python
en
code
0
github-code
50
37945910633
#-----Las biblotecas de uso------------ from tkinter import * from PIL import ImageTk, Image #importar imagen from tkinter import messagebox import os import subprocess #-------------------------------------------Metodos para llmar otros proyectos-------------------------- def animales(): # Ruta al archivo del pro...
Genesis-BQ/Crucigrama-
Juego cucigrama.py
Juego cucigrama.py
py
7,093
python
es
code
0
github-code
50
20611233178
#! /usr/bin/env python3 ''' This modules list the files to install/copy. Used by both nao_sync and createArchive ''' CHMOD_GO_NONE = 'go= ' ''' Lists, in order, files to install. Array order determines the order of copying. Element descriptions description: Description of the element src: File in Git repo to copy r...
rmit-computing-technologies/redbackbots-coderelease
Make/Common/rbbpython/install.py
install.py
py
2,439
python
en
code
0
github-code
50
43329466705
#!/usr/bin/env python # this program convolves a time function with an mseed file # John Vidale 6/2019 def pro2_convstf(eq_num, conv_file): from obspy import UTCDateTime from obspy import Stream, Trace from obspy import read # from obspy.signal import correlate_template import os import time ...
JohnVidale/Array_codes
Process/pro2_con_stfs.py
pro2_con_stfs.py
py
3,254
python
en
code
2
github-code
50
32081040709
import os import json import requests import tarfile # Directory where you want to extract the contents output_directory = "output" def fetch_IANA_time_zone_database(output_directory): # API URL for downloading the latest database database_api_url = "https://data.iana.org/time-zones/tzdata-latest.tar.gz" ...
shan-shaji/country-code-from-timezone
refresh.py
refresh.py
py
3,196
python
en
code
0
github-code
50
70816688477
import pytest import uuid from os.path import exists, join from src.report_generator import ReportGenerator from tests import utils as test_utils @pytest.fixture def rep_gen(tmp_path): temp_reports = tmp_path / 'reports' temp_reports.mkdir() _rep_gen=ReportGenerator(reports_folder=temp_reports, temps_fol...
d2gex/py-rep-to-pdf_xml
tests/test_report_generator.py
test_report_generator.py
py
1,449
python
en
code
0
github-code
50
14202375433
"""Api - Puzzle api Usage: api run [--config <file>] api serve [--config <file>] api --help api --version Options: -h --help Show this screen. --config <file> Set config file. [default: site.cfg] Subcommands: run - Start the web server in the foreground. Don't use for produ...
jkenlooper/puzzle-massive
api/api/script.py
script.py
py
1,993
python
en
code
31
github-code
50
70740650077
from scipy.optimize import minimize import numpy as np import pandas as pd import datetime as dt import copy import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression import sklearn import time import math import plotly.express as px import plotly.graph_objects as go from cvxpy import * from sci...
LusoNX/LongShort-Cointegration-Pairwise-Strategy
Long_SHORT_GIT_HUB/price_data.py
price_data.py
py
5,762
python
en
code
0
github-code
50
73034668955
# -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in: # http://doc.scrapy.org/en/latest/topics/spider-middleware.html import json import logging import requests from requests.exceptions import ConnectionError from scrapy.exceptions import IgnoreRequest class CookiesMid...
XiMuYouZi/Python-crawler-demo
Crawler/Weibo/weibo/middlewares.py
middlewares.py
py
2,644
python
en
code
0
github-code
50
32592221413
import sys arr=[] def push(n): arr.append(n) def pop(): if len(arr)==0: print(-1) else: print(arr.pop(-1)) def size(): print(len(arr)) def empty(): if len(arr)==0: print(1) else: print(0) def top(): if len(arr)==0: print(-1) else: print(arr[-1]) n=int(sys.stdin....
san9w9n/2020_WINTER_ALGO
10828.py
10828.py
py
598
python
en
code
0
github-code
50
40099699490
from __future__ import print_function from __future__ import absolute_import import os,sys import glob import logging import argparse import subprocess import time, datetime import urllib2 import json from . import tools from .CLIHelper import CLIHelper from .CrabHelper import CrabHelper import FWCore.ParameterSet.Con...
cms-sw/cmssw
CalibMuon/DTCalibration/python/Workflow/DTWorkflow.py
DTWorkflow.py
py
17,966
python
en
code
985
github-code
50
70082183197
class Node: def __init__(self, d): self.data = d self.children = [] class Directory: def __init__(self, root = None): self.root = root def search(self, data): return self.searchAux(self.root, data) def searchAux(self, node, data): if node == None: ...
amchp/ST0245-001
laboratorios/lab04/codigo/Directorios.py
Directorios.py
py
1,531
python
en
code
0
github-code
50
26500205426
#!/usr/bin/python import optparse, os, sys, ConfigParser, getpass, re, urlparse, time VERSION = '0.3' def get_directories(config, dir_type): """ Get read or write directories and return formatted list """ if config.has_option('Directories', dir_type) and config.get('Directories', dir_type) != '': dir...
DHTC-Tools/UC3
skeleton_key/scripts/skeleton_key.py
skeleton_key.py
py
7,715
python
en
code
0
github-code
50
8004784936
#!/usr/bin/env python3.4 salario = int(input("Salario? ")) imposto = 27 while imposto > 0: imposto = input("Imposto em % (ex: 27.5)? ") if not imposto: imposto = 27 elif imposto == "s": break else: imposto = float(imposto) print("Valor real: {}".format(salario - (salario *...
josejnra/python
python-basics/lacos_funcoes_recursos_etc/while.py
while.py
py
379
python
pt
code
3
github-code
50
18525434076
from util import * import json from bs4 import BeautifulSoup import time def load_city(): f = open('./files/city.json', 'r') city_data = json.load(f) return city_data def get_city_hall(province_code, city_code): url = 'http://iservice.10010.com/e3/static/life/listHallByPropertyNew?provinceCode={}&ci...
19js/Nyspider
iservice.10010.com/iservice.py
iservice.py
py
2,126
python
en
code
16
github-code
50
38021585718
""" *packageName : * fileName : 2910_빈도 정렬_S3 * author : jihye94 * date : 2022-07-23 * description : * =========================================================== * DATE AUTHOR NOTE * ----------------------------------------------------------- * 2022-07-2...
guqtls14/python-algorism-study
박상준/정렬/2910_백준_빈도 정렬_S3.py
2910_백준_빈도 정렬_S3.py
py
629
python
en
code
0
github-code
50
39879369616
import tkinter as tk def create_checkbox_dict(): category_dict = {'Культура': '1000000', 'Правосудие': '2000000', 'Происшествия и конфликты': '3000000', 'Экономика и бизнес': '4000000', 'Образование': '5000000', 'Экология': '6000000', 'Медицина': '7000000', 'Светская жизн...
pavlinbl4/KSP_selenium_new
KSP_shoot_create/checkbox_output.py
checkbox_output.py
py
1,724
python
en
code
0
github-code
50
25156254416
from pathlib import Path import ai from ai.examples.alphazero import AlphaZeroMLP def run(cfg, game, model): model.init().train().to(cfg.device) player = ai.game.MctsPlayer(cfg.player, game, model) task = ai.task.GameTask(game, player, cfg.task.n_matches) trial = ai.Trial(cfg.outpath, task=task, clea...
calvinpelletier/ai
examples/alphazero/main.py
main.py
py
872
python
en
code
0
github-code
50
72056400476
#!/usr/bin/env python from __future__ import division, print_function import numpy as np import matplotlib.pyplot as plt from rvseg import opts, patient, dataset, models def save_image(figname, image, mask_true, mask_pred, alpha=0.3): cmap = plt.cm.gray plt.figure(figsize=(12, 3.75)) plt.subplot(1, 3, ...
chuckyee/cardiac-segmentation
scripts/eval.py
eval.py
py
5,232
python
en
code
274
github-code
50
33744741148
import tensorflow as tf import joblib import sklearn # from tensorflow.keras.preprocessing import image import numpy as np import matplotlib as plt import gzip class_names = ['Lesion', 'Normal'] IMAGE_SHAPE = (224, 224) def load_and_prep_image(filename, img_shape=224, scale=True): """ Reads in an...
prathameshparit/Lesion-Detection
predictions.py
predictions.py
py
2,560
python
en
code
0
github-code
50
5304829131
import datetime, time import parsedatetime.parsedatetime as pdt import parsedatetime.parsedatetime_consts as pdc from django.template import Library from django.template.defaultfilters import stringfilter from taskmanager.framework.utilities import parsedt register = Library() @register.filter(name='parse_date') @...
falquaddoomi/cens_dev
taskmanager/templatetags/parse_date.py
parse_date.py
py
2,322
python
en
code
0
github-code
50
70069960155
from sklearn import svm import numpy as np path = "currentStateFinal.txt" f = open('data.txt','w') dataFile = open(path, 'r') n = 0 # Magic numbers occupiedSet = [[22, 19, 37], [22, 39, 36], [24, 5, 15], [25, 19, 21], [25, 24, 14]] emptySet = [[22, 38, 6], [23, 41, 58], [25, 18, 45], [25, 20, 19], [25, 26, 5]] svmDa...
jackalsin/Python
AIS_Project2016/MachineLearning.py
MachineLearning.py
py
1,879
python
en
code
1
github-code
50
70249628314
import random import time from random import choice import os def carta1(): carta = { "tipo": "", "palo": "", "valor": "", } tipos = [1, 2, 3, 4, 5, 6, 7, "Sota", "Caballo", "Rey"] palos = ["Oro", "Basto", "Copa", "Espadas"] lista_cartas = [] for palo in palos: ...
XxEduBoss/ejerciciospython
7ymedio.py
7ymedio.py
py
3,737
python
es
code
0
github-code
50
30945998017
import turtle turtle.setup(800, 600, 0, 0) wn = turtle.Screen() wn.bgcolor('white') leonardo = turtle.Pen() leonardo.color('blue') leonardo.speed(0) for x in range(200): leonardo.width(x/100 + 1) leonardo.forward(x) leonardo.left(59) turtle.exitonclick()
mentecatoDev/intermezzo
docs/eje_la_tortuga_que_dibuja/eje0202.py
eje0202.py
py
271
python
en
code
1
github-code
50
35721310194
import streamlit as st import numpy as np import onnxruntime as rt import mediapipe as mp import os import cv2 import av from typing import List from streamlit_webrtc import webrtc_streamer, WebRtcMode from twilio.rest import Client from skimage.transform import SimilarityTransform from types import SimpleNamespace fro...
Martlgap/livefaceidapp
main.py
main.py
py
11,160
python
en
code
19
github-code
50
22417525136
# Libraries ######################################################################################################################## import numpy as np import cv2 as cv import matplotlib.pyplot as plt ##################################################################################################################...
Royal00Blood/Poliolim-OpenCV-Detect
FindandDetect.py
FindandDetect.py
py
8,796
python
en
code
0
github-code
50
11609777638
from database.methods.get import get_all_students, get_student_by_vk_id, get_students_with_admin from vkbottle import Keyboard, KeyboardButtonColor, Text from vkbottle.bot import Message, Blueprint import logging bp = Blueprint('admin_panel')# Объявляем команду bp.on.vbml_ignore_case = True # Игнорируем регистр ...
nickname123456/BotNetSchool
vk_bot/commands/admin/admin_panel.py
admin_panel.py
py
1,865
python
ru
code
6
github-code
50
38616522140
# В генеалогическом древе у каждого человека, кроме родоначальника, # есть ровно один родитель. Каждом элементу дерева сопоставляется целое # неотрицательное число, называемое высотой. У родоначальника высота равна 0, # у любого другого элемента высота на 1 больше, чем у его родителя. # Вам дано генеалогическое древо, ...
AnnaSmelova/Python_programming_basics_course
week7/24_genealogy.py
24_genealogy.py
py
1,042
python
ru
code
1
github-code
50
30614528108
import os import errno import pandas as pd import re def mkdir_p(path): """Create a directory if not exist""" try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise return def clean_sentence(sentence): """Get rid of trace characters""" cl...
dharakyu/wh-questions-lm
utils.py
utils.py
py
2,073
python
en
code
0
github-code
50
17149404851
import sys sys.path.append("..") from box_coder import DefaultBoxes, Encoder import torch def dboxes300_coco(): figsize = 300 feat_size = [38, 19, 10, 5, 3, 1] steps = [8, 16, 32, 64, 100, 300] # use the scales here: https://github.com/amdegroot/ssd.pytorch/blob/master/data/config.py scales = [21...
Deep-Spark/DeepSparkHub
cv/detection/ssd/pytorch/base/test/box_coder_test.py
box_coder_test.py
py
1,345
python
en
code
28
github-code
50
31168514697
import random import math class Deck(): def __init__(self, deck_array=None): """ Deck can either be the game deck to be dealt out or can be the hand a Player has, based on whether we set deck_array in the initialization if not set, we create a full deck if not, we want the Player's hand to have the...
voidiker66/PyHearts
Deck.py
Deck.py
py
3,668
python
en
code
1
github-code
50
70485352157
from ship import Ship from square import Square class Ocean(): width = 10 height = 10 def __init__(self, owner): self.board = [] self.ships = [] self.owner = owner for y in range(self.height): row = [] for x in range(self.width): ...
SebastianHalinski/Battleship
ocean.py
ocean.py
py
2,748
python
en
code
0
github-code
50
37701303517
class Solution: def maxArea(self, height): """ :type height: List[int] :rtype: int Idea: lower a horizontal line with width n down the array. In each iteration keep track of the lowest and highest indices of elements that reach to the line or beyond....
NikolaiT/incolumitas
content/Interview/src/water6.py
water6.py
py
1,435
python
en
code
17
github-code
50
7014122383
#Jonathan Dang | PP2.16 | Assignment 1 #I Jonathan Dang do hereby certify that I have derived no assistance for this project or examination from any sources whatever, whether oral, written, or in print #except from explicit descrestion from the source material itself. #PP2.16 Write a program that reads a five-digit ...
Jonathan-Dang/CS3C
Assignment1/PP2-16.py
PP2-16.py
py
959
python
en
code
0
github-code
50
38682123289
import sys from pathlib import Path from timeit import default_timer as timer from . import http SCRIPT_PATH = Path(sys.argv[0]) SCRIPT_DIR = SCRIPT_PATH.parent ROOT_DIR = SCRIPT_DIR.parent.parent PUZZLE_DAY = SCRIPT_DIR.name PUZZLE_YEAR = SCRIPT_DIR.parent.name CHALLENGE_COUNT = 0 TOTAL_TIME = 0 def get_input(de...
DismissedGuy/AdventOfCode
aoc/__init__.py
__init__.py
py
2,327
python
en
code
1
github-code
50
39856574480
""" Given a 2D integer array matrix, return the transpose of matrix. The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. Example 1: Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]] Example 2: Input: matrix = [[1,2,3],[...
ramogi4960/Leetcode-problems
easy/Transpose Matrix.py
Transpose Matrix.py
py
828
python
en
code
0
github-code
50
13073056978
#!/usr/bin/env python3 import os for i in range(5000,10000,10): os.system("python3 longList.py " + str(i)) os.system("TIMEFORMAT=%R") time = os.system("time java SortsRunner list.txt") f = open("selection.txt", "a+") f.write(str(time)) if i == 5020: break
smjaques/Java
asgn1/runTimes.py
runTimes.py
py
290
python
en
code
0
github-code
50
29331952171
import cv2 import numpy as np from .ocr_redaction import OCR from .speech_filter import hate_speech_detection import pytesseract pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' def content_filtering(image = '../relay/img/screen.png'): east = 'text/data/frozen_east_text_detec...
greaseuniverse/greaseterminator
interventions/text/text_filter.py
text_filter.py
py
2,942
python
en
code
1
github-code
50
26255921148
"""Create a ChatVectorDBChain for question/answering.""" from langchain.callbacks.base import AsyncCallbackManager from langchain.callbacks.tracers import LangChainTracer from langchain.chains import ChatVectorDBChain from langchain.chains.chat_vector_db.prompts import (CONDENSE_QUESTION_PROMPT, ...
kpister/prompt-linter
data/scraping/repos/iFixit~chat/query_data.py
query_data.py
py
3,228
python
en
code
0
github-code
50
42725712340
import os import time import datetime import pandas as pd from sklearn.tree import DecisionTreeClassifier # Compute the number of transactions per day, fraudulent transactions per day and fraudulent cards per day def get_tx_stats(transactions_df, start_date_df="2020-04-01"): # Number of transactions per day ...
redhat-partner-ecosystem/fsi-fraud-detection
notebooks/simulator/training.py
training.py
py
5,086
python
en
code
0
github-code
50
24327575818
lines = int(input()) table = [input().split() for i in range(lines)] rot90 = [[0 for j in range(lines)] for i in range(lines)] rot180 = [[0 for j in range(lines)] for i in range(lines)] rot270 = [[0 for j in range(lines)] for i in range(lines)] testList = [] testTwo = [] correctNow = True correct270 = True correct180 =...
vishnupsatish/CCC-practice
2018/J4/J4.py
J4.py
py
3,620
python
en
code
1
github-code
50
18727794630
from django.conf.urls import url from .views import event, login, profile, friends urlpatterns = [ url(r'^api/event', event, name='event'), url(r'^api/login', login, name='login'), url(r'^api/profile', profile, name='profile'), url(r'^api/friends', friends, name='friends') ]
stanislavBozhanov/hello
hello_back_end/helloers/urls.py
urls.py
py
295
python
en
code
0
github-code
50
29473290269
__author__ = 'srkiyengar' import os import logging.handlers scriptname = os.path.basename(__file__) LOG_LEVEL = logging.INFO # Set up a logger with output level set to debug; Add the handler to the logger my_logger = logging.getLogger("UR5_Logger") my_dir = "../trials" class match: def __init__(self,dname): ...
srkiyengar/ur5_client
src/match.py
match.py
py
1,410
python
en
code
1
github-code
50
36795359974
import sigrokdecode as srd import binascii import struct import traceback from .handlers import * # ... RX = 0 TX = 1 # these reflect the implicit IDs for the 'annotations' variable defined below. # if you renumber 'annotations', you'll have to change these to match. ANN_MESSAGE = 0 ANN_ERROR = 1 ANN_BYTES = 2 clas...
dracode/sigrok-lego-boost
boost/pd.py
pd.py
py
3,482
python
en
code
3
github-code
50
22006232249
#.CSV(Comma Seperated Values file) #is atype of plain text file that uses specific structuring to arrange tabular data #because its a plain text file, it can contain only actual text data(printable ASCII or Unicode) characters. #.CSV file uses a comma to separate each specifc data value #CSV files are created by progra...
DENNIS-CODES/Python-csvFiles
file.py
file.py
py
1,573
python
en
code
1
github-code
50
23393766489
from torch import nn import torch.nn.functional as F from torch_geometric.nn import SAGEConv from key_info_extraction.utils import ID2LABEL class SageNet(nn.Module): def __init__(self, in_channels, n_classes=len(ID2LABEL.keys()), dropout_rate=0.2, bert_model='vinai/phobert-base', device='cuda'): ...
manhph2211/MC-OCR
key_info_extraction/models/phobert_sage.py
phobert_sage.py
py
1,228
python
en
code
26
github-code
50
37344733255
''' Crie um programa que leia o nome de uma cidade diga se ela começa ou não com o nome "SANTO". ''' cidade=str(input('Digite o nome de uma cidade: ')) cidade2=cidade.upper() ini=cidade2.find('SANTO') print(ini) if ini==0: print('\nO primeiro nome da cidade é Santo') elif ini==-1: print('\nPalavra não exis...
igorbalbino/Estudos-Python
VerificandoLetrasDoTexto.py
VerificandoLetrasDoTexto.py
py
390
python
pt
code
0
github-code
50
73799333915
#!/usr/bin/env python2 # reference: CTP/OSCE # author: greyshell # description: identify good and bad chars in HPNNM-B.07.53 # dependency: python version: 2.7.x, pyenv-win==1.2.2, pywin32==218, WMI==1.4.9, pydbg # 1) download the `dependency.zip` file. # 2) extract the `pydbg.zip` inside your python `lib\site-package...
bigb0sss/OSCE
hp_nnm7.5/bad_char.py
bad_char.py
py
10,022
python
en
code
74
github-code
50
42577913058
from queue import PriorityQueue import bisect import sys class Solution: def coinChange(self, coins, amount): q = PriorityQueue() q.put((0, (0,0))) if amount in coins: return 1 while not q.empty(): sys.stdout.write(f"L-> {q.qsize()}... ") ...
RamonRomeroQro/ProgrammingPractice
code/generating-paths.py
generating-paths.py
py
821
python
en
code
1
github-code
50
29775654337
# ID-Fits # Copyright (c) 2015 Institut National de l'Audiovisuel, INA, All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 3.0 of the License, ...
ina-foss/ID-Fits
lib/scores_accumulator.py
scores_accumulator.py
py
2,297
python
en
code
7
github-code
50
2936876007
from time import sleep from threading import Thread from unicodedata import numeric import requests import uuid from threading import Barrier import creds import webbrowser import telebot from telebot import types from telebot.types import InlineKeyboardButton, InlineKeyboardMarkup import os import re import urllib fr...
lorenzopiro/GeronimoBot
functions.py
functions.py
py
11,817
python
it
code
1
github-code
50
4591513762
from colour_palette.colour import Colour def test_complementary_colour(): black = Colour(0, 0, 0) white = Colour(255, 255, 255) complementary_to_black = black.complementary_colour() complementary_to_white = white.complementary_colour() assert black == complementary_to_white assert white == com...
anishpatelwork/colour-palette-calculator
tests/test_colour.py
test_colour.py
py
2,961
python
en
code
0
github-code
50
24005442897
''' BEGIN GPL LICENSE BLOCK This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it wi...
JT-a/blenderpython279
scripts/addons_extern/tp_arch_tool_v000.py
tp_arch_tool_v000.py
py
18,451
python
en
code
5
github-code
50
45730463859
from __future__ import division, print_function from sklearn import preprocessing from sklearn.tree import DecisionTreeClassifier, export_graphviz from sklearn.externals.six import StringIO import numpy as np import random import json # Takes a dictionary of players as keys and weapons as values # Returns the key of...
daniel-lovell/Paper-Rock-Scissors
rps.py
rps.py
py
6,914
python
en
code
0
github-code
50
70551213276
from Simplex import * class BranchAndBound: def __init__(self, a, b, c, minimize=True): # self.BaseA = a # self.BaseB = b self.A = a self.B = b self.C = c self.Minimize = minimize self.Solutions = [] self.Values = [] self.Nodes = [] s...
TheMatrix2/OptimizationMethods
Branch&BoundMethod/BranchAndBound.py
BranchAndBound.py
py
2,746
python
en
code
0
github-code
50
8141213629
import sqlite3 from django.shortcuts import render, redirect, reverse from django.contrib.auth.decorators import login_required from capstoneapp.models import Business, BusinessType, Customer from .business_details import get_business def get_business_types(): return BusinessType.objects.all() @login_required d...
castlesmadeofcode/Stay-Safr
capstoneapp/views/businesses/business_form.py
business_form.py
py
1,202
python
en
code
0
github-code
50
19594321641
import re from gringotts.middleware import base UUID_RE = r"([0-9a-f]{32}|[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12})" API_VERSION = r"(v1|v2)" RESOURCE_RE = r"(images)" class GlanceBillingProtocol(base.BillingProtocol): def __init__(self, app, conf): super(GlanceBillingProtocol, self...
gbraad/ustack-gringotts
gringotts/middleware/glance.py
glance.py
py
906
python
en
code
null
github-code
50
17313809663
from fastapi import FastAPI from mythril_script import * import json app = FastAPI() @app.get('/') def default(): return "Server is running! The API is ready" @app.get("/output/{contract_name}") async def show(contract_name: str): analyze_mythril(contract_name) file_json = contract_name.replace(".sol", ...
NavyanshMahlaMarsh/mythril-api
mythril_api.py
mythril_api.py
py
507
python
en
code
0
github-code
50
41099265715
########################################### # Book "Python Crash course" - Eric Matthes # Chapter 8: Functions ########################################### ########################################### # print a greeting # the str() is needed if someones's name is a number def greeting(name): """ simple greeting """ ...
aschiedermeier/Python_Crash_course
8_1_Functions.py
8_1_Functions.py
py
935
python
en
code
0
github-code
50
8339732859
"""Sengled Bulb Integration.""" import asyncio import logging _LOGGER = logging.getLogger(__name__) class Switch: def __init__( self, api, device_mac, friendly_name, state, device_model, accesstoken, country, ): _LOGGER.debug("SengledAp...
jfarmer08/ha-sengledapi
custom_components/sengledapi/sengledapi/devices/switch.py
switch.py
py
2,753
python
en
code
97
github-code
50
30755941328
from category import Category from customer import Customer from email import Email from phone import Phone from goods import Goods from base import Base from order import Order from base import Base, Session, engine import psycopg2 import query_parser def iterator(mes): for i in range(10): mes += "chr(tr...
filenkoB/databases
lab3/model.py
model.py
py
9,396
python
en
code
0
github-code
50
2354781570
from Compilador.Entorno import entorno from Compilador.Entorno.simbolo import Simbolo from Compilador.Expresiones.llamada_funcion_exp import Llamada_funcion_exp from Compilador.Interfaces.nodo import Nodo from Compilador import generador from Compilador.TablaSimbolo.tipo import tipo class Declaracion(Nodo): def _...
JASAdrian1/OLC2_Proyecto2_201901704
Compilador/Instrucciones/declaracion.py
declaracion.py
py
3,415
python
es
code
0
github-code
50
21670622468
"""Some things never change.""" import typer from ee_cli.settings import Settings settings = Settings() EXIT_HOTWORDS = {"end", "exit", "done", "quit", "q"} RESET_HOTWORDS = {"clear", "restart", "c"} DROP_HOTWORDS = {"drop", "remove", "rm", "d"} TOGGLE_INDEX_HOTWORDS = {"index", "idx", "indexes", "i"} HELP_HOTWORDS ...
ainsleymcgrath/epoch-echo
ee_cli/constants.py
constants.py
py
2,012
python
en
code
2
github-code
50
74343895835
#!/usr/bin/env python #-*- coding:utf-8 -*- #author: Jiang Liu<jiang.liu@yottaa.com> #date: 2014-3-27 try: import json except ImportError: import simplejson as json import os,commands from zabbix_socket_sender import Zabbix data = {} def dns_health(): status = commands.getstatusoutput('dig +time=3 +t...
canshen-yottaa/shencan
ansible/zabbix/roles/install/files/zabbix_tmu.py
zabbix_tmu.py
py
703
python
en
code
0
github-code
50
11272726020
import torch import random from agents.RandomAgent import RandomAgent from agents.DeepCFR.DeepCFRAgent import DeepCFRAgent from agents.DeepCFR.StrategyMemory import StrategyMemory from copy import deepcopy from statistics import mean """ Two randomization techniques we are using for avoiding local minima are: 1) ...
prateekstark/matrix-game
CFRRunner.py
CFRRunner.py
py
7,595
python
en
code
0
github-code
50
15830134815
import mock import six from tvrenamer.core import formatter from tvrenamer.tests import base class FormatterTest(base.BaseTest): def test_replace_series_name(self): self.CONF.set_override('input_series_replacements', dict()) name = 'Reign' self.assertEqual( formatter._replace...
shad7/tvrenamer
tvrenamer/tests/core/test_formatter.py
test_formatter.py
py
11,698
python
en
code
0
github-code
50
32677128650
#!/usr/bin/python3 # -*- coding: utf-8 -*- # ------------------------------------------- # Name: YOUR NAME # Version: 0.1 # Notes: ADD UPDATES HERE # ------------------------------------------- # Imports import sys, logging # Path to DBConnect sys.path.append("../") # Import DBConnect import DBConnect...
JarekCode/Boru
scripts/scriptTemplate.py
scriptTemplate.py
py
3,064
python
en
code
0
github-code
50
32538776490
# -*- coding: utf-8 -*- # © 2015 Elico corp (www.elico-corp.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from urllib import urlencode from openerp.osv import fields, osv class AccountAccount(osv.osv): _inherit = 'account.invoice' def _edi_paypal_url(self, cr, uid, ids, field, a...
Elico-Corp/odoo-addons
payment_utf8/invoice.py
invoice.py
py
1,457
python
en
code
45
github-code
50
21119618969
""" Plots figure 2A, boxplot of reported times. """ import pickle import os import numpy as np from matplotlib import pyplot as plt import importlib.util from fna.tools.visualization.helper import set_global_rcParams from fna.tools.utils import logger from fna.tools.utils.data_handling import set_storage_locations f...
zbarni/re_modular_seqlearn
src/cone_shouval_2021/experiments/plot_fig2_a.py
plot_fig2_a.py
py
4,089
python
en
code
1
github-code
50
1150928520
from profile.profile import Profile from paths.circle import Circle import kinematics import numpy as np ################################################### # Tests a circular path in the profiler. # Generates the profile, transforms it into # configuration space, then tests each of the # configuration space points a...
lessthantrue/RobotProjects
double_joint_arm/profile_test.py
profile_test.py
py
1,738
python
en
code
3
github-code
50
20068340110
from operator import itemgetter import os import json import re import flatland as fl from flatland.validation import IsEmail, Converted, Validator import database def _load_json(name): with open(os.path.join(os.path.dirname(__file__), name), "rb") as f: return json.load(f) class EnumValue(Validator): ...
dincamihai/cites-meetings
cites/schema.py
schema.py
py
11,640
python
en
code
1
github-code
50
10838901651
import os import sys def extract_txt(folder): folder_list = [os.path.join(folder, file) for file in os.listdir(folder)] for folder in folder_list: if len(folder.split('.')) == 1: file_list = [file for file in os.listdir(folder) if file.split('.')[1]=='txt'] with open(folder + '...
realtimshady1/Koalafinder
utils/extract_txt.py
extract_txt.py
py
1,159
python
en
code
1
github-code
50
30211999203
# coding: utf-8 # In[56]: # package imports #basics import numpy as np import pandas as pd import ast #misc import gc import time import warnings #viz import matplotlib.pyplot as plt import seaborn as sns import matplotlib.gridspec as gridspec import matplotlib.gridspec as gridspec #settings start_time=time....
shayan113/Yelp-Data-Exploration
Yelp Dataset Exploration2.py
Yelp Dataset Exploration2.py
py
17,612
python
en
code
0
github-code
50
74571782556
from flask import Flask, request import re import os import sys import time import json import requests debug = True covid_cache = {} def fetch_status(id): global covid_cache try: if id in covid_cache.keys(): if time.time()-covid_cache[id]['timestamp'] < 3600: if debug: pr...
jordiprats/python-covidcache
covidcache.py
covidcache.py
py
2,818
python
en
code
0
github-code
50
25604701736
import csv from typing import Dict from pathlib import Path import xml.etree.ElementTree as ET def get_namespace(root: ET.Element) -> Dict[str, str]: return {"page": root.tag.split('}')[0].strip('{')} def export_stats(stats: dict, output_dir: Path): csv_header = ["Project", "Lines of ground truth"] try:...
maxnth/GTCounter
src/utils.py
utils.py
py
2,222
python
en
code
1
github-code
50
601544481
import numpy as np import matplotlib.pyplot as plt import pandas as pd import re # Load the data df = pd.read_csv("moore.csv", header = None, sep='\t') #df.info() # <class 'pandas.core.frame.DataFrame'> # RangeIndex: 102 entries, 0 to 101 # Data columns (total 6 columns): # 0 102 non-null object # 1 102 non-nul...
YasirHabib/linear-regression-in-python
Section2/moore_law.py
moore_law.py
py
4,421
python
en
code
0
github-code
50
30072993488
# from symbol import term import matplotlib.pyplot as plt import numpy as np import sys import operator import argparse import copy from nltk.corpus import stopwords import gensim from gensim import corpora, models # from textblob import TextBlob from bs4 import BeautifulSoup import pickle def main(): word_freq("...
joelmathew003/Gmail-Mail-Tagging
py scripts/tf_idf_scripts/tf_idf_attempt2.py
tf_idf_attempt2.py
py
4,219
python
en
code
0
github-code
50
45620765778
def steps(number): if number <= 0: raise ValueError("Only positive integers are allowed") cont = 0 while number > 1: cont += 1 if (number % 2) == 0: number //= 2 else: number = (number*3) + 1 return cont print(steps(16))
Japarraes/Python_Exercism
Numbers/collatz_conjeture.py
collatz_conjeture.py
py
317
python
en
code
0
github-code
50
44705708478
from app.main.model.models import Book, Users from flask_restful import Resource from flask import jsonify, request, make_response import datetime import jwt from flask import Blueprint from functools import wraps from werkzeug.security import check_password_hash, generate_password_hash from bson.objectid import Object...
YaroslavYaryk/Programming
Python/FlaskApp/app/main/controller/auth_api.py
auth_api.py
py
5,135
python
en
code
0
github-code
50
24311435778
from .models import Order from .form import OrderForm def sort_orders(queryset): new_sorted = {} i = 0 for item in queryset: i += 1 urgency_weight = (int(item.urgency) * 0.7) position_weight = (len(queryset) - (i))*0.3 name = item.name new_sorted[name] = urgency_w...
lukejamestyler/Bungee
src/CommunitySupport/need/sort.py
sort.py
py
814
python
en
code
0
github-code
50
3195056829
from flask import jsonify, request from flask_restful import abort, Resource from db import DBConn def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d class UserController(Resource): def get(self, id): conn = DBConn() ...
bmw2621/workPresentation
backend/python/users.py
users.py
py
1,650
python
en
code
0
github-code
50
38750788230
# Configurations dependent on the sample type. import sys import FWCore.ParameterSet.Config as cms import os if sys.version_info.major < 3: from sets import Set as set mcSampleTypes = set([ 'MC_16', 'MC_UL16', 'MC_UL16APV', 'MC_17', 'MC_UL17', 'MC_18', 'MC_UL18', 'Emb_16', 'Emb_17', 'Emb_18ABC', 'Emb_18D', 'MC_P...
dimaykerby/DisTauMLTools
Production/python/sampleConfig.py
sampleConfig.py
py
5,075
python
en
code
0
github-code
50
41154480733
import tensorflow as tf W = tf.Variable([.3], tf.float32, name='weight') b = tf.Variable([-.3], tf.float32, name='bias') x = tf.placeholder(tf.float32) linear_model = W * x + b init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) print(sess.run(linear_model, {x: [1, 2, 3, 4]}))
shirakiya/practice-tensorflow
get_started/variable.py
variable.py
py
320
python
en
code
0
github-code
50
70082184477
class Node: def __init__(self, data): self.left = None self.right = None self.data = data def TreeSumming(node, sum, val):#O(2^h) left = False right = False if node.left == None and node.right == None: return sum == val if node.left != None: left = TreeSummin...
amchp/ST0245-001
laboratorios/lab04/ejercicioEnLinea/TreeSumming.py
TreeSumming.py
py
746
python
en
code
0
github-code
50
709736238
from django.shortcuts import render from django.core import serializers from django.http import JsonResponse from django.core.serializers.json import DjangoJSONEncoder from mesineapp.models import * import json # Create your views here. def social_network_type(request): social_network = نوع_شبکه_اجتماعی.objects.f...
HosseinKeramati/mesine
mesineapp/controllers/social_network.py
social_network.py
py
1,605
python
en
code
0
github-code
50
70578895835
# card_no = "5610591081018250" # Declarations odd_sum = 0 even_sum = 0 double_list = [] # Checking card number while True: card_num = input("Please input your card number(There should be up to 16 digits):") if len(card_num) == 16: break else: continue number = list(card_num) for (idx, val...
bitmap357/Credit_Card_Validator
Validator App.py
Validator App.py
py
833
python
en
code
0
github-code
50
6399540886
from rest_framework import serializers from .models import Message, ChatRoom from collections import OrderedDict class MessageSerializer(serializers.ModelSerializer): image = serializers.ImageField(allow_null=True) def to_representation(self, instance): # this function will remove keys that have None...
Aron-S-G-H/django-chat-application
chat_app/serializer.py
serializer.py
py
731
python
en
code
6
github-code
50
70579004635
import sys sys.path.append(".") from dao.daoRRHH import daoRRHH from modelo.personal import Personal class daoJRRHH(daoRRHH): def getRegistrosFiltro(self, Personal): sql_filtrarNomina = """SELECT `personalRut`, `personalNombre`, `personalGenero`, `cargoNombre`, `areaNombre`, `departamentoNomb...
bluuscript/app
dao/daoJRRHH.py
daoJRRHH.py
py
956
python
es
code
0
github-code
50
4553730026
import local_secrets as secrets from openai import AsyncOpenAI import openai import logging #from openai.embeddings_utils import get_embedding as openai_get_embedding OPENAI_API_KEY = secrets.OPENAI_API_KEY #COMPLETION_MODEL = 'gpt-3.5-turbo' #COMPLETION_MODEL = 'gpt-4-32k' COMPLETION_MODEL = 'gpt-4-1106-preview' EMB...
cliff-rosen/datatrove
openai_wrapper.py
openai_wrapper.py
py
2,293
python
en
code
0
github-code
50