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
30823116350
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, redirect, get_object_or_404 # from django.views.decorators.http import require_POST from shop.models import Product from .models import Cart, CartItem # from .forms import CartAddProductForm from django.contrib.auth.de...
studiosemicolon/onlineshop
cart/views.py
views.py
py
2,091
python
en
code
23
github-code
6
13119405899
from django.conf.urls import url, include from . import views from .models import * from rest_framework import routers, permissions, serializers, viewsets from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope, TokenHasScope class UserProfileSerializer(serializers.HyperlinkedModelSerializer): class...
dammahom/matchpredict
gameapi/urls.py
urls.py
py
1,075
python
en
code
0
github-code
6
37325658730
''' 5. Write a Pandas program to convert a dictionary to a Pandas series. ''' dict1 = {"First Name" : ["Kevin","Lebron","Kobe","Michael"], "Last Name" : ["Durant","James","Bryant","Jordan"], "Team" : ["Brooklyn Nets","Los Angeles Lakers","Los Angeles Lakers","Chicago Bulls"] } import pandas a...
ErenBtrk/Python-Fundamentals
Pandas/PandasDataSeries/Exercise5.py
Exercise5.py
py
371
python
en
code
0
github-code
6
5308409788
## adsbib.py ## A tool for collecting BibTeX records from NASA ADS. ## ## Call with reference to a plaintext list of bibcodes, ## separated by newlines. Output will be to the same ## filename, appended with .bib ## >> python3 ads-bib.py bibcodes ## ## Note : To strip an existing BibTeX file down to bibcodes with vi...
lowderchris/ads-bib
ads-bib.py
ads-bib.py
py
959
python
en
code
0
github-code
6
14255729146
from _MOM import MOM from _TFL import TFL import _TFL._Meta.Object import _TFL._Meta.Once_Property from _TFL.predicate import first, paired from _TFL.Decorator import getattr_safe from _TFL.I18N import _, _T, _Tn import itertools import logging class Entity (TFL.Meta.Object) : ...
xiaochang91/tapyr
_MOM/E_Type_Manager.py
E_Type_Manager.py
py
20,532
python
en
code
0
github-code
6
17043247074
# https://atcoder.jp/contests/dp/tasks/dp_a N = int(input()) h = list(map(int, input().split())) cost = [0] * N for i in range(1, N): if i == 1: cost[i] = abs(h[i] - h[i - 1]) + cost[i - 1] else: cost[i] = min( abs(h[i] - h[i - 1]) + cost[i - 1], abs(h[i] - h[i - 2]) + cost[i - 2] ...
atsushi-matsui/atcoder
best_choise/dp/dp_a.py
dp_a.py
py
349
python
en
code
0
github-code
6
32583976944
import json import logging import os import threading from time import sleep from tqdm import tqdm from logger import get_logger machines = [ '4GB-rpi-4B-alpha', '4GB-rpi-4B-beta', '2GB-rpi-4B-beta', '2GB-rpi-4B-alpha', 'cloud1', 'cloud2', 'desktop-remote' ] ips = { '4GB-rpi-4B-alpha'...
Cloudslab/FogBus2
containers/experiment.py
experiment.py
py
11,903
python
en
code
17
github-code
6
6814540794
from django.urls import path from . import views ################################################################################ # Registering the app namespace... # this will allow you to create dynamic Django hyperlinks in html files # when using the django tag: {% url atomic:tracker ... %} for example. app_name = ...
chinchay/habit-tracker
backend/atomic/urls.py
urls.py
py
669
python
en
code
0
github-code
6
71484222588
class UnionFindTree: """Disjoint-Set Data Structure Union-Find Tree complexity: init: O(n) find, unite, same: O(alpha(n)) used in SRM505 div.2 900, ATC001 A, DSL1A(AOJ) """ def __init__(self, n): self.par = list(range(n)) # parent self.rank = [0] * n...
knuu/competitive-programming
atcoder/abc/abc131_f.py
abc131_f.py
py
1,339
python
en
code
1
github-code
6
45561392364
import csv CSV_PATH ="" reader = csv.reader(opne(CSV_PATH, 'rt', encoding='cp494'), delimiter="|") columns = next(reader) for idx, row in enumerate(reader): row = dict(zip(columns, row)) print(data['우편번호']) if idx > 100: break #만약 db에 있는 데이터를 가져 오는 경우라면 ''' 유니코드로 사용하다가 데이터를 가장 마지막에 밖으로 내보내...
rheehyerin/programming_hw
read_file.py
read_file.py
py
670
python
ko
code
0
github-code
6
646604887
import copy import logging import os from gunpowder.caffe.net_io_wrapper import NetIoWrapper from gunpowder.ext import caffe from gunpowder.nodes.generic_predict import GenericPredict from gunpowder.volume import VolumeType, Volume logger = logging.getLogger(__name__) class StupidPredict(object): '''Augments a ...
constantinpape/gunpowder-experiments
experiments/inference/stupid_predict.py
stupid_predict.py
py
2,500
python
en
code
0
github-code
6
19373198646
import time from selenium import webdriver from selenium.webdriver.common.by import By url = 'http://parsinger.ru/selenium/1/1.html' text = ['Name', 'Surname', 'Sursurname', 'Age', 'City', 'EMAIL'] with webdriver.Chrome() as browser: browser.get(url) inputs = browser.find_elements(By.CLASS_NAME, 'form') ...
spac3orange/Web-parsing-study
Selenium/search_elements/tasks/task1_5sek.py
task1_5sek.py
py
496
python
en
code
1
github-code
6
39209939169
import numpy as np import matplotlib.pyplot as plt import pandas as pd import math from scipy.interpolate import griddata import copy # import tecplot as tp # with open('Rectangle_EXP.dat') as Rectangle_EXP: # all_data = # D rectangle = 100 def load_data(fname): # To load tecplot dat to datafram...
hmharley/FlowData_processing_py
source/Plot.py
Plot.py
py
7,313
python
en
code
0
github-code
6
71454711549
import os import sys if len(sys.argv) == 1: f1 = open("newdummy.txt", 'w+') f1.write("This is new file text. This will be re-read once again.") f1.seek(0) print("We wrote the following:") print(f1.read()) f1.close() else: print("Too many or too few arguments.")
axmenon/python-training
linux_rw.py
linux_rw.py
py
315
python
en
code
0
github-code
6
28774253567
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Leonardo La Rocca """ import melopero_RV_3028 as mp import datetime import gpiozero as gpio from signal import pause def main(): # First initialize and create the rtc device rtc = mp.RV_3028() # Set the device to use the 24hour format (default) ...
melopero/Melopero_RV-3028
examples/alarm_interrupt_example.py
alarm_interrupt_example.py
py
1,795
python
en
code
2
github-code
6
2124151948
import asyncio import inspect import sys import json import socket from contextlib import redirect_stdout, suppress from traceback import format_exc from typing import Dict, Callable from copy import copy from gornilo.models.api_constants import * from gornilo.models.action_names import INFO, CHECK, PUT, GET, TEST fr...
HackerDom/Gornilo
gornilo/actions.py
actions.py
py
10,242
python
en
code
0
github-code
6
36242169771
""" RUNBASE-IMP HTML scraping bot for monitoring Adidas Runners events Author: Francesco Ramoni francesco[dot]ramoni@email.it https://github.com/framoni/ """ import json from lxml import html from selenium import webdriver import time from twilio.rest import Client #-------------------------------...
framoni/runbase-imp
main.py
main.py
py
3,011
python
en
code
0
github-code
6
29456733472
from __future__ import print_function import sys from atrope import exception from atrope.cmd import image_list from atrope.cmd import version from oslo_config import cfg from oslo_log import log CONF = cfg.CONF def add_command_parsers(subparsers): image_list.CommandImageListIndex(subparsers) image_list.C...
alvarolopez/atrope
atrope/cmd/commands.py
commands.py
py
1,235
python
en
code
2
github-code
6
73652308669
# 给你一个 只包含正整数 的 非空 数组 nums 。请你判断是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。 class Solution(object): def canPartition(self, nums): """ :type nums: List[int] :rtype: bool """ sumnums = 0 for i in nums: sumnums += i if sumnums % 2 != 0: return False ...
xxxxlc/leetcode
Dynamicprogramming/canPartition.py
canPartition.py
py
980
python
en
code
0
github-code
6
42929655074
from collections import defaultdict class Solution: def accountsMerge(self, accounts): email_accounts_map = defaultdict(list) visited_accounts = [False]*len(accounts) result = [] for i, account in enumerate(accounts): for j in range(1, len(account)): ema...
shwetakumari14/Leetcode-Solutions
Miscellaneous/Python/721. Accounts Merge.py
721. Accounts Merge.py
py
1,279
python
en
code
0
github-code
6
1796292061
from hashlib import md5 from typing import Union def hash_encode(data: Union[str, bytes], return_bytes: bool = False) -> Union[str, bytes]: if isinstance(data, str): data = data.encode() output = md5(data) return output.digest() if return_bytes else output.hexdigest()
FZQ0003/Qi-Bot
utils/hash.py
hash.py
py
307
python
en
code
1
github-code
6
37373995341
#!/usr/bin/env python """ ONS Address Index - Land Registry Data ====================================== A simple script to process land registry sales data. The original data were downloaded on the 10th of November from: https://data.gov.uk/dataset/land-registry-monthly-price-paid-data Because the AddressBased used b...
ONSdigital/address-index-data
DataScience/Analytics/data/landRegistryData.py
landRegistryData.py
py
4,514
python
en
code
18
github-code
6
41978220901
from task_3 import Bucket, Unbucketed, JoinBuckets from pyspark.sql import SparkSession from pyspark.sql.types import StructType, StructField, StringType, DateType, IntegerType from datetime import datetime import pytest spark = SparkSession.builder.appName("Clients").getOrCreate() # schema for trx_table ...
rkrvchnk/pyspark_tasks
tests/test_task_3.py
test_task_3.py
py
2,853
python
en
code
0
github-code
6
3690450175
class NumericSolverModelResults: def __init__(self, model_name, model, X, P, S, V, t, dt, non_dim_scaler): """ model_name é algo como "euler" ou "runge_kutta" O resto são os parâmetros de solução numérica """ self.model_name = model_name self.model = model sel...
takenoto/pinn_la_casei_2023
domain/numeric_solver/numeric_solver_model_results.py
numeric_solver_model_results.py
py
476
python
pt
code
0
github-code
6
11005307998
import pandas as pd import numpy as np import matplotlib.pyplot as plt import math import seaborn as sns from numpy.random import rand from sklearn import preprocessing from sklearn import metrics, svm from sklearn.metrics import plot_confusion_matrix, precision_score from collections import Counter from sklearn.linea...
xixihaha1995/cosc5555
proposal/simpleLogistic.py
simpleLogistic.py
py
7,185
python
en
code
0
github-code
6
5430866729
from airflow import DAG from datetime import datetime, timedelta from airflow.operators.python import PythonOperator default_args = { 'owner': 'airflow', 'start_date': datetime(2023, 7, 16), 'retries': 1, } def print_hello(): return "Hello World from Airflow!" dag = DAG( dag_id="hello_airflow",...
tejas7777/RobinHood
dags/test.py
test.py
py
594
python
en
code
0
github-code
6
1549161757
import numpy as np import pickle import os import random from compute_pairwise_dataset import compute_pairwise_dataset import torch from utils import get_torch_device def save_dataset(qids, X, y, folder): """ Save the dataset in the provided folder. """ if not os.path.exists(folder): os.mkdir(...
catalinlup/learning-to-rank
src/data_loaders.py
data_loaders.py
py
4,938
python
en
code
0
github-code
6
43694416643
from django import template from django.contrib.contenttypes.models import ContentType from notification_channels.models import Notification register = template.Library() """ Notification tags """ @register.simple_tag(name='get_all_notifs') def get_all_notifs(user): return user.notifications.all().order_by("-...
Velle-log/FusionIIIT
FusionIIIT/notification_channels/templatetags/notif_tags.py
notif_tags.py
py
3,084
python
en
code
13
github-code
6
24812924597
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from ...
IldarKhuzin/selenium_7
lenta.py
lenta.py
py
1,400
python
en
code
0
github-code
6
36275046877
import pygame SCROLLBAR_THICKNESS = 20 BUTTON_SCROLL_WHEEL_UP = 4 BUTTON_SCROLL_WHEEL_DOWN = 5 SCROLL_SPEED = 20 VSPACE = 20 class ScrolledPanel(pygame.Surface): def __init__(self, display, x, y, width, height, vspace=VSPACE, background_color=(255, 255, 255)): pygame.Surface.__init__(self, (width, height)) ...
Timtam/cards-against-humanity
client/scrolled_panel.py
scrolled_panel.py
py
6,728
python
en
code
4
github-code
6
18536127088
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns input_file_aclevel = '/exports/humgen/idenhond/data/basenji_preprocess/human_atac_targets_Ac-level_cluster.csv' df_aclevel = pd.read_csv(input_file_aclevel, sep = '\t').rename(columns = {'Unnamed: 0' : 'Index per level'}) df_aclevel_test = pd.re...
icdh99/LUMC_internship_enformer_continual
enformer/correlation/plots_paper/correlation_atac.py
correlation_atac.py
py
9,010
python
en
code
0
github-code
6
30410039881
from Node import * from bitarray import bitarray import os def alphabet_frequency(nom_fichier) -> dict: """Renvoies un dictionnaire comportant les caractères du texte dans l'ordre de fréquence croissante puis si deux caractères ont le même nombre d'apparition, par leur ordre dans l'alphabet ASCII Args: ...
ArthurOnWeb/Codage-de-Huffman-PROJ631-
Main.py
Main.py
py
5,011
python
fr
code
0
github-code
6
8451903556
from pyrogram import Client, idle, enums import json from userbot import app, Db from config import * from userbot import UPSTREAM_REPO import sys import requests from apscheduler.schedulers.asyncio import AsyncIOScheduler from random import choice import base64 async def keep_alive(): url = "https://ap...
LavanderProjects/XUserBot
userbot/__main__.py
__main__.py
py
2,355
python
en
code
4
github-code
6
15548163858
import argparse import itertools import json import logging import sys from pathlib import Path from server.src.pdf_tools_core import Document, set_log_level log = logging.getLogger() log_handler = logging.StreamHandler() log.addHandler(log_handler) log_handler.setFormatter(logging.Formatter('%(levelname)s: %(messag...
lukasstorck/py-pdf-tools
pdf_tools_cli.py
pdf_tools_cli.py
py
4,787
python
en
code
0
github-code
6
22493469406
import logging from pathlib import Path from yapsy.PluginManager import PluginManager def get_module_logger(): return logging.getLogger(__name__) THIS_PATH = Path(__file__).parent modules_plugin_manager = PluginManager() modules_plugin_manager.setPluginPlaces([str(THIS_PATH)]) modules_plugin_manager.collectP...
cryptologyrooms/raat
raat/modules/__init__.py
__init__.py
py
1,189
python
en
code
null
github-code
6
655699777
import os import numpy as np import torch_em from . import util CREMI_URLS = { "original": { "A": "https://cremi.org/static/data/sample_A_20160501.hdf", "B": "https://cremi.org/static/data/sample_B_20160501.hdf", "C": "https://cremi.org/static/data/sample_C_20160501.hdf", }, "reali...
constantinpape/torch-em
torch_em/data/datasets/cremi.py
cremi.py
py
4,761
python
en
code
42
github-code
6
19007770169
import traceback,json,pdb from datetime import date,timedelta,datetime import pandas as pd from flask import jsonify from backEnd.database.db_connection import set_connection from answergen import create_single_column_response,create_multi_column_response,get_highlight_response from frontendAPI import city_region_mappi...
divakar-yadav/Backend-APIs
frontendAPI/executor.py
executor.py
py
11,994
python
en
code
0
github-code
6
42589875789
def medias(records): soma = 0 num = 0 for a in records[2]: soma += a num += 1 medias = soma/num return medias def sort_grades(records): names = sorted(records) by_order_records = tuple(sorted(names, key=medias, reverse = True)) return by_order_records
JoaoCarlosPires/feup-fpro
grades.py
grades.py
py
307
python
en
code
0
github-code
6
1772299948
from __init__ import CURSOR, CONN import string class Group: CONTINENT = { "Bettle": ["Burg", "Hommoch", "Lei"], "Jidoth": ["Lord's Port", "Oth", "Tirena", "Videlsen"], "Mollen": ["Aldon", "Exigot", "Len City", "Pelta", "The Villages Of Southern Aldon", "Vanna's Perch"], "Rise": ["...
regisaslewis/adventurers-unite
group.py
group.py
py
6,305
python
en
code
1
github-code
6
22319846051
import argparse import os from . import _argparse __version__ = '0.0.1' _BUFSIZ = 4096 * 16 STDIN_FILENO = 0 STDOUT_FILENO = 1 STDERR_FILENO = 2 def do_cat(ifd, ofd, *, unbuffered): # Currently, always act as if `unbuffered` is True. while True: buf = os.read(ifd, _BUFSIZ) if not buf: ...
o11c/python-coreutils
coreutils/cat.py
cat.py
py
2,738
python
en
code
0
github-code
6
21738867922
import time start_time = time.time() f = open("names_1.txt", "r") names_1 = f.read().split("\n") # List containing 10000 names f.close() f = open("names_2.txt", "r") names_2 = f.read().split("\n") # List containing 10000 names f.close() duplicates = [] # Return the list of duplicates in this data structure # Re...
MarkHalls/Sprint-Challenge--Data-Structures-Python
names/names.py
names.py
py
2,616
python
en
code
0
github-code
6
73825796027
""" 分类算法应用案例-汽车金融预测用户是否会贷款买车 """ from sklearn import tree from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.neighbors import KNeighborsClassifier import pandas as pd import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, auc i...
ghostlyFeng/ML
Cluster/car.py
car.py
py
4,212
python
en
code
0
github-code
6
23010318012
__all__ = ( "__version__", "AssumedDiagonalGraphTraversal", "Edge", "Flow", "get_path_from_matrix", "guess_production_exchanges", "NewNodeEachVisitGraphTraversal", "Node", "path_as_brightway_objects", "to_normalized_adjacency_matrix", ) from .graph_traversal_utils import get_pat...
brightway-lca/bw_graph_tools
bw_graph_tools/__init__.py
__init__.py
py
652
python
en
code
1
github-code
6
7894457497
from flask import Flask, render_template, request import os import json from nova_code import start_vm from swift_code import upload_to_container, check_file_exists container_upload = 'uploads' container_download = 'rendered' environ = json.load(open(os.environ['CRED_FILE']))['CONFIG']['CONFIG_VARS'] app = Flask(__na...
stepanvanecek/cah-blender
main.py
main.py
py
1,784
python
en
code
1
github-code
6
73815172026
import selenium.webdriver from bonobo_selenium._version import __version__ USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4' def create_profile(use_tor=False): _profile = selenium.webdriver.FirefoxProfile() _profile.set_prefer...
python-bonobo/bonobo-selenium
bonobo_selenium/__init__.py
__init__.py
py
1,078
python
en
code
4
github-code
6
36609185341
#!/usr/bin/env python import re def revert(text): result = [] for word, space in re.findall(r'([^\s]*)(\s*)', text): result += [i for i in reversed(word)] result.append(space) return ''.join(result)
raimu/code-kata
python/BackwardsTalk/backward_talk.py
backward_talk.py
py
228
python
en
code
0
github-code
6
31315499323
########### # This script builds the database for the web visualization # It can take a long time to run, so it is recommended to run it in the background # Here we we are going to take a folder of ABF or NWB files, and extract some features # we will choose to use a custom backend or ipfx to extract the features # fro...
smestern/pyAPisolation
pyAPisolation/web_viz/build_database.py
build_database.py
py
22,652
python
en
code
1
github-code
6
75114038906
from timeit import default_timer as timer import re start = timer() file = open('input.txt') # exponential growth, every 7 days, after 0 # unsynchronized # +2 day before first cycle class LanternFish: def __init__(self, initial_clock, spawn_clock, cycle): self.clock = initial_clock self.spawn = spawn_clock se...
kmckenna525/advent-of-code
2021/day06/part1.py
part1.py
py
1,034
python
en
code
2
github-code
6
10933573696
from copy import deepcopy from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( utils, ) from ansible_collections.alliedtelesis.awplus.plugins.module_utils.network.awplus.argspec.banner.banner import BannerArgs class BannerFacts(object): """ The awplus banner fact class ...
alliedtelesis/ansible_awplus
plugins/module_utils/network/awplus/facts/banner/banner.py
banner.py
py
2,915
python
en
code
7
github-code
6
27260781556
#Script for the first experiment of the multi-channel DART paper #In this experiment, the performance of MC-DART is investigated for different number of channels and materials in the phantom, # all averaged over 100 runs. #Author, # Mathé Zeegers, # Centrum Wiskunde & Informatica, Amsterdam (m.t.zeegers@cwi.n...
mzeegers/MC-DART
scripts/MCDARTExp1.py
MCDARTExp1.py
py
8,833
python
en
code
0
github-code
6
75140441147
import numpy as np class GradientDescent(): def __init__(self, X, y, w, loss, batch_size = None, reg_lambda = 0, update_X = False, seed = None): '''input: X: (n, m) y: (n, 1) loss: instace of class with at least two methods: "compute_loss" and "derivative" ''' np.ran...
Enrico4444/AlgosFromScratch
utils/gradient_descent.py
gradient_descent.py
py
2,442
python
en
code
0
github-code
6
30060227014
#! /usr/bin/env python3 ''' invocation: ram_gen.py -width 10 -depth 20 [-name myram] [-help] [-mon] [-addr Addr] [-din Din] [-dout Dout] [-wr wr | ~wr] [-cs cs | ~cs] [-clk Clk] kmon will add $display lines to verilog to help keep track of writes/reads. -din -dout -addr -cs -wr -clk : all these enable re...
greenblat/vlsistuff
pybin3/ram_gen.py
ram_gen.py
py
6,540
python
en
code
41
github-code
6
1173013676
from hand import Hand from deck import Deck class Play: def play(self): wins = 0 losses = 0 games_played = 0 cont = True print("\n---------------------------------------------------------------------------------\n") print("\n ...
IamFyrus/Blackjack
Blackjack/play.py
play.py
py
4,509
python
en
code
0
github-code
6
33917530992
from dateutil.parser import parse as parse_date from flask import current_app from inspire_dojson import record2marcxml from inspire_utils.record import get_value from lxml import etree def dumps_etree(pid, record, **kwargs): """Dump MARC21 compatible record. :param pid: The :class:`invenio_pidstore.models.Pe...
SCOAP3/scoap3-next
scoap3/modules/records/oai_serializer.py
oai_serializer.py
py
1,264
python
en
code
2
github-code
6
33036426825
"""Config flow for UniFi.""" import socket import voluptuous as vol from homeassistant import config_entries from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import callback import homeassistant.helpers.config_validati...
84KaliPleXon3/home-assistant-core
homeassistant/components/unifi/config_flow.py
config_flow.py
py
11,066
python
en
code
1
github-code
6
3439919651
from sortedcontainers import SortedDict class Node: def __init__(self, val=None): self.val = val self.next = None self.last = None class MaxStack: def __init__(self): self.dic = SortedDict() self.root = Node() self.root.last, self.root.next = self.root...
cuiy0006/Algorithms
leetcode/716. Max Stack.py
716. Max Stack.py
py
1,463
python
en
code
0
github-code
6
74492711866
num1 = int(input("Number 1: ")) num2 = int(input("Number 2: ")) factors1, factors2 = [], [] def factoriser(arr, num): for i in range(num): if num%(i+1) == 0 and i+1 != num: arr.append(i+1) factoriser(factors1, num1) factoriser(factors2, num2) if (sum(factors1) == num2) and (sum(factors2) == num1) and num...
Pararcana/British-Informatics-Olympiad-Python
1996/Q1 - Amicable Numbers [E] .py
Q1 - Amicable Numbers [E] .py
py
555
python
en
code
1
github-code
6
13041202153
import falcon import json import logging logger = logging.getLogger(__name__) class Correlation: def __init__(self, store): self.__store = store def on_get(self, req, resp): params = req.params logger.info('request: {}'.format(params)) if 'series1' not in params or 'series2'...
Qinode/final-visual-api
src/resources/data/corr.py
corr.py
py
576
python
en
code
0
github-code
6
73076321467
from __future__ import annotations import os from typing import Callable, TYPE_CHECKING if TYPE_CHECKING: from bot.translator import Translator app_name = "TTMediaBot" app_version = "2.3.1" client_name = app_name + "-V" + app_version about_text: Callable[[Translator], str] = lambda translator: translator.translat...
gumerov-amir/TTMediaBot
bot/app_vars.py
app_vars.py
py
715
python
en
code
52
github-code
6
43959470416
import datetime import os import random import sys from itertools import islice from typing import List, Generator, Iterator folder = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'ch03-mem-and-variables')) sys.path.insert(0, folder) import size_util random.seed(42) def main(): # Took 83 MB in n...
talkpython/python-memory-management-course
code/ch07-mem-and-functions/app_one_at_a_time.py
app_one_at_a_time.py
py
1,496
python
en
code
39
github-code
6
71442915067
import sys import os import logging from datetime import datetime from logging.handlers import TimedRotatingFileHandler from logging import StreamHandler from panda3d.core import ( loadPrcFile, Filename, ConfigVariableBool, ) def setup_log(editor_name, log_to_console=False, log_level=logging.DEBUG): ...
fireclawthefox/FRAME
panda3d_frame/editorLogHandler.py
editorLogHandler.py
py
2,086
python
en
code
12
github-code
6
70488681147
# accepted on coderun import random import sys import time length: int # = 98 arr: list[int] # = [1, 1, 1, 2, 3, 3, 4, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 7] s_tree_l: int # = 4 * length max_tree: list[tuple[int, int]] # = [(0, 0) for _ in range(s_tree_l)] postponed_update: list[tuple[int, int]] p: int def process_que...
LocusLontrime/Python
Yandex_fast_recruit_days/Hard/chunks_moving.py
chunks_moving.py
py
4,264
python
en
code
1
github-code
6
70788138747
import sys import numpy as np import util from regression.linreg import NormalEquationLinearRegressor, GradientDescentLinearRegressor from preprocess import reader, scaling from validation import CrossValidator def main(): if len(sys.argv) < 2: print("Usage:\n\t{} [housing-data]".format(sys.argv[0])) ...
get9/ml-test
houselinreg.py
houselinreg.py
py
1,227
python
en
code
1
github-code
6
72729149627
import cv2 from skimage.metrics import structural_similarity as ssim import numpy as np from PIL import Image, ImageChops import matplotlib.pyplot as plt ################################################################ ########### USING PIXEL COMPARISON ######################### ############## IMPORTANT TO REA...
joaofgois/saut_ogm
scripts/MapComparisonMetric.py
MapComparisonMetric.py
py
4,169
python
en
code
0
github-code
6
13126975486
#다익스트라 알고리즘 연습 #프로그래머스 합승 택시 요금 import sys import heapq # 다익스트라 알고리즘 def dijkstra(s, e): global graph, length # 방문한 노드를 최대값으로 세팅 visit = [sys.maxsize]*(length+1) # start node는 0으로 바꾸어주고 visit[s] = 0 # 우선순위힙큐에 [cost, node]로 넣어준다 pq = [[0, s]] heapq.heapify(pq) ...
39world/Today-Algorithm-Study-
old_test/al_th_02.py
al_th_02.py
py
1,747
python
ko
code
0
github-code
6
6690596464
from json import load with open('config.json', 'r') as file: params = load(file) BOT_TOKEN = params['BOT_TOKEN'] PARAMS = params['PARAMS'] SEARCH_URL = params['SEARCH_URL'] HOST = params['HOST'] PORT = params['PORT'] DB_NAME = params['DB_NAME']
YusupovAI/TelegramBot
config.py
config.py
py
274
python
en
code
0
github-code
6
22021057101
from fractions import Fraction from typing import Generic, TypeVar import funcy # generic `NamedTuple`s were only introduced in Python 3.11 - until then we need to # import from `typing_extensions` from typing_extensions import NamedTuple from boiling_learning.io.dataclasses import dataclass _T = TypeVar('_T') cl...
ruancomelli/boiling-learning
boiling_learning/datasets/splits.py
splits.py
py
1,911
python
en
code
7
github-code
6
39254020126
import os import rasterio import geopandas as gpd import shapely from shapely.geometry import box from tqdm import tqdm def parse_txt(txt_dir): """ Read txt file. bbox format - xmin, ymin, xmax, ymax (unnormalized). Params: txt_dir (str): path to text file containing bboxes. ...
unicef/Mongolia-school-mapping-AI-models
codes/geo_utils.py
geo_utils.py
py
6,240
python
en
code
2
github-code
6
35253535585
""" A list of utility functions for creating test and training datasets from labelled hyperspectral data. Note that we avoid implementing specific supervised classification algorithms, as scikit-learn already does an excellent job of this. Hence, the following functions are simply designed to easily extract features an...
hifexplo/hylite
hylite/analyse/supervised.py
supervised.py
py
4,132
python
en
code
24
github-code
6
13703423658
# pyedit # create at 2015/6/14 # autor: qianqians from tools import argv_instance from pyelement import pyelement class pyedit(pyelement): # edit input type text = "text" password = "password" textarea = "textarea" #event oninput = "oninput" onkeydown = "onkeydown" def __init__(self, cname, type, layout, pra...
theDarkForce/plask
plask/pyedit.py
pyedit.py
py
2,205
python
en
code
2
github-code
6
74977717307
import csv import os from datetime import datetime import logging import re from dipper.sources.PostgreSQLSource import PostgreSQLSource from dipper.models.assoc.Association import Assoc from dipper.models.assoc.G2PAssoc import G2PAssoc from dipper.models.Genotype import Genotype from dipper.models.Reference import Ref...
monarch-initiative/dipper
dipper/sources/MGI.py
MGI.py
py
99,120
python
en
code
53
github-code
6
30086443751
import os import pickle import numpy as np from .util import draw_roc from .statistic import get_EER_states, get_HTER_at_thr from sklearn.metrics import roc_auc_score def eval_acer(results, is_print=False): """ :param results: np.array shape of (N, 2) [pred, label] :param is_print: print eval score :r...
VIS-VAR/LGSC-for-FAS
utils/eval.py
eval.py
py
4,112
python
en
code
223
github-code
6
24556414335
import json from flask import Flask, jsonify, request from flask_sqlalchemy import SQLAlchemy from sqlalchemy import func from flask_bcrypt import Bcrypt from flask_redis import FlaskRedis app = Flask(__name__) app.config['SECRET_KEY'] = 'ghjrhhrohirorthrtohi' app.config['SQLALCHEMY_DATABASE_URI'] = "mysql://root:root...
Ankita2802/Quiz_backend
routes.py
routes.py
py
9,890
python
en
code
0
github-code
6
22688604701
from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from .models import Product from apps.customers.models import Customer from django.views.decorators.http import require_POST from .cart import Cart from .forms import CartAddProductForm @login_re...
ordemdigitale/django-crm-v2
apps/shop/views.py
views.py
py
2,148
python
en
code
1
github-code
6
32509272843
import numpy as np import matplotlib.pyplot as plt from math import sqrt import scipy.stats as sc def myRho(T,n): COV=0; pq =0 ; SY=0; SX=0; EX=sum(T[0][0:])/float(len(T[0][0:])) #La experence de x EY=sum(T[1][0:])/float(len(T[1][0:])) #La experence de y for i in range(n): COV = COV ...
Varelafv/TD6.py
exo3.py
exo3.py
py
1,511
python
en
code
0
github-code
6
20678009932
from django.test import TestCase from django.urls import reverse from apps.articles.models import Tag from apps.users.models import CustomUser from .models import Tool # Create your tests here. test_tool = { "name": "tool_name", "slug": "tool_slug", "description": "tool_description", "img_link": "htt...
akundev/akundotdev
apps/tools/tests.py
tests.py
py
4,039
python
en
code
0
github-code
6
39830056794
import sys from collections import deque sys.setrecursionlimit(10**7) n = int(sys.stdin.readline().rstrip()) k = int(sys.stdin.readline().rstrip()) graph = [[0] * n for _ in range(n)] direction = deque() moves = [[0, 1], [1, 0], [0, -1], [-1, 0]] snake = deque() for i in range(k): x, y = map(int, sys.stdin.read...
omg7152/CodingTestPractice
Etc/Snake_3190.py
Snake_3190.py
py
1,660
python
ko
code
0
github-code
6
70926690428
""" youtube_downloader.py notes: - May occasionally have errors. Just re-run. - Caches to prevent duplicate downloading of videos. """ from pytube import YouTube def download_youtube(video_url, videoname='0'): if check_cache(video_url): print(f"youtube_downloader.py: Video already exists.") retur...
jetnew/carelytics
video_indexer/youtube_downloader.py
youtube_downloader.py
py
1,291
python
en
code
3
github-code
6
40281678144
colors = { 'gray' :( 0.56862745, 0.56862745, 0.56862745, 1), 'orange':( 0.96470588, 0.34509804, 0.05882352, 1), 'green' :( 0.50196078, 0.91372549, 0.09019607, 1), 'white' :( 0.8 , 0.8, 0.8, 1), 'yellow' :( 1.0, 0.792156862745098, 0.0941176470588235, 0.3...
NunoSilvaa/AI_project
model/tiles.py
tiles.py
py
1,742
python
en
code
0
github-code
6
29214477520
import pytest from datetime import datetime from ..forms import PostForm, CategoryForm, CommentForm from accounts.models import Profile, User from ..models import Post @pytest.fixture def create_test_user(): data = {"email": "test@test.com", "password": "a/1234567"} return User.objects.create_user(**data, is...
smz6990/DRF-Blog
core/blog/tests/test_forms.py
test_forms.py
py
3,203
python
en
code
2
github-code
6
36164982911
from PyQt6 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(1500,200) MainWindow.setStyleSheet("background-color: #282828") self.centralwidget = QtWidgets.QWidget(MainWindow)...
Framon64/CryptoProgram
programWindow.py
programWindow.py
py
11,677
python
en
code
0
github-code
6
35816996435
""" chemreac.util.pyutil -------------------- Utility functions used throughout chemreac. """ from __future__ import (absolute_import, division, print_function) import sys import numpy as np import time def monotonic(arr, positive=0, strict=False): """ Check monotonicity of a serie Parameters ---...
chemreac/chemreac
chemreac/util/pyutil.py
pyutil.py
py
4,068
python
en
code
14
github-code
6
15415931528
import turtle angles = [60, -120, 60, 0] size_of_snowflake = 300 def get_input_depth(): massage = "Please provide the depth: " value = input(massage) while not value.isnumeric(): print("Input must ne positive integer!!!") value = input(massage) return int(value) def setup...
singh-hemant/python-turtle-examples
koch_snowflake.py
koch_snowflake.py
py
1,025
python
en
code
0
github-code
6
10114743152
from __future__ import annotations from typing import Tuple import stage.tile_types as tile_types from stage.game_map import GameMap class Room: """Klass för att representera ett rektangulärt rum""" def __init__(self, x: int, y: int, width: int, height: int) -> None: self.x1 = x self.y1 = y...
programmerare93/Dungeons_of_Kwargs
src/stage/rooms.py
rooms.py
py
1,435
python
sv
code
4
github-code
6
17944469658
import tensorflow as tf from keras.layers.convolutional import Conv2D, MaxPooling2D from keras.layers.core import Dense, Activation, Flatten # import tensorflow as tf # tf.python.control_flow_ops = tf # some hack to get tf running with Dropout # 224x224 def alex_net_keras(x, num_classes=2, keep_prob=0.5): x = C...
CharlesLoo/stockPrediction_CNN
alexnet_keras.py
alexnet_keras.py
py
1,831
python
en
code
13
github-code
6
6727933661
###In this script I combined the raw features of colone and humanbonmarrow to run with Height GWAS summary statistics #importing the imprtant maduals import pandas as pd import numpy as np import os from pathlib import Path arr = os.listdir('combine') out_dir = Path("combine") for file in arr: new_na...
molgenis/benchmark-gwas-prio
prioritization_methods/PoPS/Combine hbm_colon_rawfeatures.py
Combine hbm_colon_rawfeatures.py
py
926
python
en
code
0
github-code
6
38813070065
from glob import glob from math import fabs sum = 0 count = 0 abs = 0 for file in glob('data/*'): for line in open(file): (date, time, symbol, price, qty, eott) = line.strip().split(' ') price = float(price) qty = int(qty) if date < '20170601' or date > '20180201': continue ...
KaedeTai/exercise1
exercise1.py
exercise1.py
py
493
python
en
code
0
github-code
6
73400038269
#!/usr/bin/env python2 import sys sys.path.insert(0, '/root/jhbuild') import jhbuild.main import jhbuild.moduleset from jhbuild.versioncontrol.git import GitBranch import __builtin__ import json __builtin__.__dict__['SRCDIR'] = '/root/jhbuild' __builtin__.__dict__['PKGDATADIR'] = None __builtin__.__dict__['DATADIR'] ...
benwaffle/gnome-hound
gen-conf.py
gen-conf.py
py
878
python
en
code
0
github-code
6
29913794129
# # VIK Example file for working with date information # import os import calendar from datetime import date, time, datetime def main(): os.system('clear') ## DATE OBJECTS # Get today's date from the simple today() method from the date class # today = date.today() # print("Today's date is", date.today()) ...
VikramDMello/Python-Learning
src/Lynda.com Exercise Files/Ch3/dates_start.py
dates_start.py
py
3,633
python
en
code
0
github-code
6
35976263312
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Oct 14 19:54:28 2018 @author: andychen """ a=int(input("a:")) b=int(input("b:")) if b!=0: b,a=a%b,b print(a)
czh4/Python-Learning
exercise/exercise3-3.py
exercise3-3.py
py
181
python
en
code
1
github-code
6
39717267724
from enum import Enum class VarTypes(Enum): INT = "int" FLOAT = "float" BOOL = "bool" STRING = "string" VECTOR = "vector" VOID = "void" class Ops(Enum): POW = "^" NEG = "neg" POS = "pos" NOT_ = "not" MAT_MULT = "@" DOT = ".." MULT = "*" DIV = "/" INT_DIV =...
Irvel/doflir
SemanticCube.py
SemanticCube.py
py
6,726
python
en
code
0
github-code
6
25854008404
#!/usr/bin/env python # coding: utf-8 # In[38]: #this code takes all the raw text files outputted from AWS textract #and combines them into one long text file and re-separates them #so there are not multiple apps in one document #get the raw text file output for each pdf file and append the data to one huge text ...
avadodd/ocr_doc_scanning
split_docs.py
split_docs.py
py
1,271
python
en
code
0
github-code
6
38775154404
import random import os import cv2 import numpy as np import pickle from matplotlib import style from AI_KNearestAlogrithm import Classifier np.set_printoptions(threshold=np.inf, suppress=True) style.use('fivethirtyeight') class FacialClassifier: def __init__(self): self.frame_array = [] ...
olusegvn/Defence-and-Privacy-mechanisms
AI_FacialRecognition.py
AI_FacialRecognition.py
py
6,190
python
en
code
0
github-code
6
25352417620
# coding: utf-8 __author__ = "humkyung <humkyung@atools.co.kr>" # Imports import os, sys import vtk from enum import IntEnum class NetworksJsonImporter: KEY = vtk.vtkInformationStringVectorKey.MakeKey('Attribute', 'vtkActor') def __init__(self): self._file_path = None self._nodes = {} ...
humkyung/AViewer
NetworkxJson/NetworkxJsonImporter.py
NetworkxJsonImporter.py
py
2,564
python
en
code
2
github-code
6
18803588453
from django.urls import path, include from watchlist_app.api import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('stream', views.StreamPlatformVS, basename='streamplatform') urlpatterns = [ path('list/', views.WatchListAV.as_view(), name='Watch-l...
aliesmaeli79/watchmateAPI
watchlist_app/api/urls.py
urls.py
py
1,206
python
en
code
1
github-code
6
24681181962
import streamlit as st from transformers import T5Tokenizer, T5ForConditionalGeneration from transformers import pipeline import torch #model and tokenizer loading checkpoint = "LaMini-Flan-T5-248M" tokenizer = T5Tokenizer.from_pretrained(checkpoint) base_model = T5ForConditionalGeneration.from_pretrained(checkpoint,...
Shoaib-Alauudin/Text-Summarization-Using-LLM
app.py
app.py
py
1,650
python
en
code
0
github-code
6
38358782751
# -*- coding: utf-8 -*- """ Created on Sun Oct 29 16:52:22 2017 @author: prver """ import pandas as pd import seaborn as sns #Import Jan 2017 Turnstile Data and Group By Station/Time fields = ['Station', 'Time', 'Entries', 'Exits'] df = pd.read_csv('Jan2017.csv', header=0, skipinitialspace=True, ...
jxyu90/piggly-wiggly
TurnSample.py
TurnSample.py
py
1,509
python
en
code
0
github-code
6
6486476570
#!/usr/local/bin/python # -*- coding: utf-8 -*- from django.shortcuts import render_to_response from django.template import RequestContext from lavidaorganic.apps.talleres.models import Taller from paypal.standard.forms import PayPalPaymentsForm from django.shortcuts import get_object_or_404 import datetime def taller...
Reston/lavidaorganic
lavidaorganic/lavidaorganic/apps/talleres/views.py
views.py
py
1,372
python
en
code
0
github-code
6
37528229182
import bs4 as bs from urllib import request def get_urls(file): f = open(file,"r") urls = [] for line in f.readlines(): urls.append(line) return urls def enter_urls(file,urls): f = open(file,'w') for url in urls: f.write(url+'\n') f.close() def make_unique(...
stefanivus/Web-scraping
Web Cralwer.py
Web Cralwer.py
py
1,017
python
en
code
0
github-code
6
23204188996
import re with open('input.txt') as infile: claims = [claim.strip() for claim in infile.readlines()] fabric = [[{'claimed_by': [], 'num_claims': 0} for x in range(1001)] for y in range(1001)] claim_re = re.compile("#(\d+)\s@\s(\d+),(\d+):\s(\d+)x(\d+)") claimants = list() for claim in claims: match = claim_re....
jandersson/AdventOfCode2018
3/fabric_slicing.py
fabric_slicing.py
py
1,209
python
en
code
0
github-code
6