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
15815820289
from odoo import fields, models, api class AccountReconciliation(models.AbstractModel): _inherit = 'account.reconciliation.widget' @api.model def _process_move_lines(self, move_line_ids, new_mv_line_dicts): """ Create new move lines from new_mv_line_dicts (if not empty) then call reconcile_partia...
telenocodoo/indeal-sa
tn_hr_payslip/models/account_recocnile.py
account_recocnile.py
py
1,889
python
en
code
0
github-code
1
21430393588
import os, queue def compute_score(line): score = 0 for bracket in line: score = score * 5 + scores[bracket] return score opposing_brackets = {"(": ")", "[": "]", "{": "}", "<": ">"} scores = {")": 1, "]": 2, "}": 3, ">": 4} with open(os.path.join(os.path.dirname(__file__), "input.txt"), 'r') a...
borisbarath/advent-of-code-21
10/brackets.py
brackets.py
py
1,237
python
en
code
0
github-code
1
7696267710
import requests as requests from API.base_api import BaseApi class WeWork(BaseApi): corpid = "wwf55a566b6d1c6bd3" contact_secret = "lsgkRCZorU9MLTU7h-f7s0NsC_AJYoc9z7jWzwW2JlQ" token = dict() token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken" @classmethod def get_token(cls, secret=co...
shadingyu96/apiautotest
API/wework.py
wework.py
py
724
python
en
code
0
github-code
1
13352323669
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import json import logging import numpy as np import os import uuid from pycocotools.cocoeval import COCOeval from pycocotools import mask as COCOmask from core.config ...
Min-Sheng/CA_FSIS_Cell
lib/datasets/fis_cell_evaluator.py
fis_cell_evaluator.py
py
23,521
python
en
code
0
github-code
1
43467564915
from bs4 import BeautifulSoup import re import pandas as pd import time def getCarInfo(pagina): doc = BeautifulSoup(pagina, "html.parser") year_td = doc.find_all(["td"], bgcolor="#ffffff") for td in year_td: print(td.get_text()) '''year = year_td.find_next_sibling('td').get_...
Sankhay/Estudos
Python/selenium/getCarInfo.py
getCarInfo.py
py
23,229
python
pt
code
0
github-code
1
1093280636
import pandas as pd import warnings warnings.filterwarnings('ignore') ## import os ## print(os.getcwd()) import tkinter as ttk app = ttk.Tk() app.title('Movie Reccomendor System') app.geometry("800x700") #Reading the Data Files cols = ['user_id', 'movie_id', 'rating', 'ts'] df = pd.read_csv('u.data', sep = '\t', name...
dhupianishant/JECRC_MachineLearning
movielens recc/movie_recc_gui.py
movie_recc_gui.py
py
2,236
python
en
code
3
github-code
1
7535284663
import json from database import get_cart_by_id, set_cart_to_user import logging log = logging.getLogger(__name__) class Cart: def __init__(self, chat_id): self.chat_id = chat_id self.items = self.get_items_by_id() def add_item(self, item): item = list(item) item_id = str(ite...
1mpossible-code/avarice
classes/cart.py
cart.py
py
1,256
python
en
code
23
github-code
1
25888659781
import datetime from typing import Any, Optional, Union from django.db import models dt_format = "%Y-%m-%d %H:%M:%S.%f" class TimestampField(models.CharField): def __init__(self, *args: Optional[Any], **kwargs: Optional[Any]): kwargs['max_length'] = 50 super(TimestampField, self).__init__(*args,...
ruler501/multipoll
multipoll/models/fields/timestamp.py
timestamp.py
py
1,802
python
en
code
0
github-code
1
71874354595
# -*- coding: utf-8 -*- """ @author: Stefan Mejlgaard """ import itertools import math def num_digits(number: int) -> int: """Return the number of digits in `number`""" return int(math.log10(number) + 1) def find_digits(positions: list[int]) -> list[int]: positions_iter = iter(positions) position =...
connesy/ProjectEuler
python/problem040/problem040.py
problem040.py
py
960
python
en
code
0
github-code
1
31475727911
from bs4 import BeautifulSoup import lxml import requests res = requests.get("https://web.archive.org/web/20200518073855/https://www.empireonline.com/movies/features/best-movies-2/") res.raise_for_status() soup = BeautifulSoup(res.text, "lxml") titles = soup.select(selector="h3[class='title']") titles_text = "" for...
csukel/100_days_of_code
Day45/top-100-movies/main.py
main.py
py
489
python
en
code
0
github-code
1
11177776005
import os from selenium import webdriver import random import time from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.act...
dr11m/steamSkins
ScriptsForDiffPlatforms/steamMakeOrders.py
steamMakeOrders.py
py
30,363
python
en
code
2
github-code
1
20175691500
# try: # a = int(input("请输入一个被除数:")) # b = int(input("请输入一个除数:")) # print(a / b) # except ZeroDivisionError: # print("除数不能为0!他妈的错了") # except ValueError: # print("需要输入数值型整数") # except: # print("这是一个异常!") # else: # print("执行完毕") # finally: # print("无论是否发生异常,都会有此提示") # x=10 # if x>5: # ...
zhoukunxiaozhi/Python_TestProject
test_file3.py
test_file3.py
py
618
python
en
code
0
github-code
1
71096893793
from linebot import ( LineBotApi, WebhookHandler ) from linebot.exceptions import ( InvalidSignatureError ) from linebot.models import (ButtonsTemplate, PostbackAction, TemplateSendMessage) import shutil import testcount line_bot_api = LineBotApi('g40p1VQDlWGVMHyMd7pL2kZXGj/Qxx0g35zTCf7+NhIN/cUm/...
AliesFY/LALALA
pythonfile/recipi.py
recipi.py
py
5,306
python
en
code
0
github-code
1
13760565958
# nombres de variables nombre = "Max" food_today = "Tacos" favorite_videogame = "Resident Evil 2 Remake" # nombres de constantes PESO_DLRS = 20.00 PI = 3.1416 SECONDS_PER_HOUR = 3600 # Diferencia entre variables con el mismo nombre pero variando algún caracter Nombre = "otro nombre" print(nombre) # "Max" print(Nombr...
MaxCazares/Bootcamp-Python
section-2-variables-const/2-names-variables-constants.py
2-names-variables-constants.py
py
621
python
es
code
0
github-code
1
27818070176
import time import struct import pickle import random import socket import builtins from copy import deepcopy from threading import Thread, Lock import queue from utils import NoSocketCreated, ConnectionNotEstablished, HandshakeFailure, CONNECTION_STATES, MESSAGE_TYPES class Packet: def __init__(self, message_ty...
karthikrangasai/MONKE-Protocol
monke/monke.py
monke.py
py
11,197
python
en
code
0
github-code
1
31779738261
#remainder for your need # imports from turtle import title from win10toast import ToastNotifier #win10toast module import time # for timer toaster = ToastNotifier() title = input("\nTitle of Remainder: ") msg = input("Message: ") minutes = float(input("How Many Minutes: ")) seconds = minutes * 15 print("\nRemaind...
raviteja9010/-Set-Remainder
remainder.py
remainder.py
py
480
python
en
code
0
github-code
1
74319923552
# Witness my jank! import awakened as aw; import delve_Class as dc; import skill as sk; import item as eq; import accolade as ac; # Example usage t = aw.Awakened(name='Teston Lautts',attributes = [10, 10, 200, 70, 10, 10, 10, 10], level = 25, character_class = dc.shieldwielding_defender) t.add_experience(2000) # Set ...
TheOneJohiah/DelveManager
testing.py
testing.py
py
1,372
python
en
code
0
github-code
1
43647649737
def find_min_index(array): min_val = array[0] index = 0 for i in range(len(array)): if min_val > array[i]: index = i min_val = array[i] else: pass return index def find_max_index(array): max_val = array[0] index = 0 for i in range(len(arr...
aratijadhav/Python
min_max_sum.py
min_max_sum.py
py
1,136
python
en
code
0
github-code
1
25393046114
def gcd(a, b) -> int: if b == 0: return a remain = a % b return gcd(b, remain) a, b = map(lambda x: int(x), input().split(" ")) res = gcd(a, b) print(res)
XaviPeiro/algorithms_toolbox_coursera
tasks/generic_algorithms/gcd.py
gcd.py
py
178
python
en
code
0
github-code
1
23152647258
import json import random from typing import Optional import discord from discord import app_commands from discord.ui import Button, View from pydantic import ValidationError from client import TextToImageClient from enums import ErrorMessage, ErrorTitle, ModelEnum, ResponseStatusEnum, SchedulerType, WarningMessages ...
ainize-team/TTI-Bot
src/bot.py
bot.py
py
22,255
python
en
code
3
github-code
1
29281970870
from collections import defaultdict import csv import gzip import itertools from pathlib import Path import tqdm from repodb.common import logger from repodb.classes.nodes.disorder import Disorder from repodb.classes.nodes.gene import Gene from repodb.classes.edges.gene_associated_with_disorder import ( GeneAssoc...
repotrial/nedrex
nedrex/parsers/disgenet.py
disgenet.py
py
2,920
python
en
code
0
github-code
1
26975726274
#!/usr/bin/python3 import sys import argparse import hmac import http import urllib from urllib import parse from http import client as httpclient parser = argparse.ArgumentParser() parser.add_argument('url') parser.add_argument('secret') args = parser.parse_args() payload = sys.stdin.read().encode() secret = args.s...
lexbailey/isabelle-theory-build-github-action
signed_post.py
signed_post.py
py
1,035
python
en
code
0
github-code
1
37462061907
import copy import re import time """ Usage: token_array = Prism.parse(code, lang_key, return_all, assign_mode) Return: A token list, like [ { 'type': 'assign-left', # order number of the tokens 'no': 2, # the start position in the c...
linb/prism-python
PrismParser/Prism.py
Prism.py
py
19,231
python
en
code
0
github-code
1
40133928515
#1. 주어진 리스트를 통해 뒤 숫자가 나올 수 있는지 확인(A,B or 숫자) #2. 숫자가 나올 수 있는 리스트라면 a,b 구하기 #3. (앞 수 * a + b)=뒷 수 => nlist[1]=nlist[0]*a+b import sys n=int(sys.stdin.readline()) nlist=list(map(int,sys.stdin.readline().split())) if n==1: #1개면 뒤에 숫자 예측 불가 -> 무조건 A print('A') elif n==2: if nlist[0]==nlist[1]: print(nl...
Woojung0618/Goldrush_Algorithm_Study
브루트포스/IQ TEST/sunhee.py
sunhee.py
py
1,306
python
ko
code
0
github-code
1
71131672033
import sys def dynamicProgramming(): maxNum = 0 dp = [[0] * m for _ in range(n)] # dp[i][j]는 i, j까지 이동했을 때 얻을 수 있는 가장 많은 금광값 dp[0][0] = array[0][0] dp[1][0] = array[1][0] dp[2][0] = array[2][0] for i in range(1, m): # 첫번째 열부터 비교 for j in range(n): # 첫번째 행부터 비교 if j == 0:...
cookie-god/algorithm
dongbin/dynamic-programming/examination/1.py
1.py
py
1,493
python
ko
code
0
github-code
1
23531939947
""" +===============================+ ╦ ╦ ╔═╗ ╔╗╔ ╔═╗ ╔═╗ ╔╦╗ ╠═╣ ║ ║ ║║║ ║╣ ╚═╗ ║ ╩ ╩ ╚═╝ ╝╚╝ ╚═╝ ╚═╝ ╩ MARKET - PEGGED - ASSETS +===============================+ called by pricefeed_final.py to upload data matrix for HONEST MPA's to jsonbin.io if you run this script solo it will create a...
litepresence/Honest-MPA-Price-Feeds
honest/jsonbin.py
jsonbin.py
py
2,994
python
en
code
8
github-code
1
3230238257
import tkinter def split_by_chapter(book_file): chapter_split = book_file.split('Chapter ') # Obviously not perfect, but works in many cases return chapter_split def write_chapters_to_files(chapter_split): chap_num = 0 for i in chapter_split: with open('ch' + str(chap_num) + '.txt', 'w') as...
ChemiKyle/Novel-heatmap
split_book_to_chapters.py
split_book_to_chapters.py
py
647
python
en
code
6
github-code
1
25015472158
from typing import Optional, Dict, Any import pendulum from geopy.distance import distance as geopy_distance from src.data_models import Configuration def add_calculated_fields(*, current_item: Dict[str, Any], initial_status, current_statu...
krezac/tesla-race-analyzer
src/data_processor/calculated_fields_status.py
calculated_fields_status.py
py
2,822
python
en
code
1
github-code
1
27100580027
#!/usr/bin/env python3 from sys import argv def kvadrat(x): a = float(x) print(' При стороне квадрата: ', a) print(' Периметр квадрата: ', 4 * a) print(' Площадь квадрата: ', round(a * a, 5)) b = a * 2**(1/2) print(' Диагональ квадрата: ', round(b, 3)) if len(argv) > 1: kvadrat(argv[1]) ...
dmb0709/testPython
square.py
square.py
py
474
python
ru
code
0
github-code
1
12984950288
#!/usr/bin/env python import logging from urllib.parse import urljoin from atomic_utils import ( PYCON_TW_ROOT_URL, query_text, parse_out_href_gen, is_relative_href, is_visited_or_mark, ) # https://docs.python.org/3.6/library/logging.html#logrecord-attributes logging.basicConfig( format=( ...
moskytw/elegant-concurrency-lab
channel_operators.py
channel_operators.py
py
2,366
python
en
code
43
github-code
1
17244409261
import sys import shapefile from .utils import Command, FeatureLoader, create_connection, filename_to_table_name def shp_field_to_sql_type(field): if field[1] == "L": return "INTEGER" if field[1] == "F": return "FLOAT" if field[1] == "N": if field[3] == 0: return "INT...
chris48s/geometry-to-spatialite
geometry_to_spatialite/shapefile.py
shapefile.py
py
2,579
python
en
code
12
github-code
1
16874515340
#!/usr/bin/env python3 import csv import glob import warnings from typing import List, Tuple from KaSaAn.core import KappaSnapshot def find_snapshots(directory: str, prefix: str) -> List[str]: """Get the file names of snapshots in specified directory that fit the pattern [dir][prefix][number].ka""" if direct...
yarden/KaSaAn
KaSaAn/functions/prefixed_snapshot_analyzer.py
prefixed_snapshot_analyzer.py
py
4,996
python
en
code
null
github-code
1
3031853440
import matplotlib.pyplot as plt def plot_indicators_empirical_analysis(all_sorted_intervals): """ :param all_sorted_intervals: all created time intervals """ spam_x = [] spam_y = [] non_x = [] non_y = [] counter = 0 for interval in all_sorted_intervals: if ...
SandraSukarieh/SPRAP
SPRAP/plotting_functions.py
plotting_functions.py
py
700
python
en
code
0
github-code
1
15222580959
import numpy as np import pickle from abc import ABC from keras.layers import Input, Dense, TimeDistributed from keras.layers import LeakyReLU, Dropout, Bidirectional from keras.layers import GRU, LSTM from keras.models import Model from keras.models import load_model from modules.constants import Constants from modu...
chandraseta/paparazzi-id
modules/summarizer/models.py
models.py
py
8,605
python
en
code
2
github-code
1
15128086812
DIRECTIONS = [(0, 1), (1, 0), (0, -1), (-1, 0)] def exist(board, word): ROWS, COLS = len(board), len(board[0]) visited = [[False for _ in range(COLS)] for _ in range(ROWS)] def dfs(row, col, searchIdx): if searchIdx == len(word): return True if not 0 <= row < ROWS or not...
mmichalak-swe/Algo_Expert_Python
LeetCode/Word_Search/attempt_1.py
attempt_1.py
py
887
python
en
code
3
github-code
1
4825182294
import requests from flask import Flask, render_template from bs4 import BeautifulSoup file = "kari-sakib-lab-report.txt" url = "https://climate.nasa.gov/effects/" def convert_tag_to_str_list(lst): new_lst = [] for i in lst: new_lst.append(str(i)) return new_lst def scraper(url): r = requests...
karisakib/flask_project
app.py
app.py
py
1,194
python
en
code
0
github-code
1
43361748288
#coding:utf-8 from __future__ import print_function import os import sys # sys.path.append('../') import time import cv2 # import rospy import math import pickle import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib.animation as animation import matplotlib.image as m...
mkwork22/CarlaDataPreprocessor
output_sim_images.py
output_sim_images.py
py
15,170
python
en
code
0
github-code
1
71076018915
# # Create an app that supports multiple Shopping Lists. # # Each SHopping list will contain multiple items. # create_list = [] # import sys # from create_list import create_list # from add_item import add_item shopping_lists = { "Kroger": ["egg", "milk", "bread", "juice"], "Walmart": ["lightbu...
justinjtx/python101
Grocery_app.hw.py/grocery_app.py
grocery_app.py
py
1,928
python
en
code
0
github-code
1
29001113439
import sys, pygame, random class enemy(pygame.sprite.Sprite): def __init__(self, posX, posY): super().__init__() randomEntity = [] randomEntity = [pygame.image.load("../assets/spaceinvader1.png").convert_alpha(), pygame.image.load("../assets/spaceinvader2.png").convert_alpha(), pygame.ima...
wiltley/SpaceInvadersPyGame
scripts/enemy.py
enemy.py
py
1,874
python
en
code
0
github-code
1
36755304755
RES = WIDTH, HEIGHT = 1600, 900 FPS = 60 SCROLL_SPEED = 8 # bird BIRD_POS = WIDTH // 4, HEIGHT // 4 BIRD_SCALE = 1.5 BIRD_AN = 150 GRAVITY = 1 JUMP = -16 BIRD_ANGLE = 25 # ground GROUND_HEIGHT = HEIGHT // 12 GROUND_Y = HEIGHT - GROUND_HEIGHT # pipes PIPES_WIDTH = 150 PIPES_HEIGHT = HEIGHT DIST_BETWEEN_PIPES = 650 GA...
KrystofKr/Project_no.5
settings.py
settings.py
py
376
python
en
code
0
github-code
1
74448616352
# Создайте 2 экземпляра данного класса. У каждого # экземпляра вызовите оба параметра описанные в этом классе. # Для обоих экземпляров вызовите метод **climb** class Monkey: max_age = 12 loves_bananas = True def climb(self): print('I am climbing the tree') c = Monkey() p = Monkey() c.climb() prin...
Zhamshid2121/2.7
hw2.py
hw2.py
py
526
python
ru
code
0
github-code
1
34266333830
import torch import torch.nn as nn import torch.nn.functional as F import math import time def timeit(x, func, iter=10): torch.cuda.synchronize() start = time.time() for _ in range(iter): y = func(x) torch.cuda.synchronize() runtime = (time.time()-start)/iter return runtime class HOG...
YutingXiao/Amodal-Segmentation-Based-on-Visible-Region-Segmentation-and-Shape-Prior
hoglayer.py
hoglayer.py
py
5,424
python
en
code
40
github-code
1
42744794274
#!/usr/bin/env python # coding: utf-8 # In[1]: import tensorflow as tf from tensorflow.keras.datasets import imdb (train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000) # In[27]: class myCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs={}): if(...
shahmeerrajput/WorkOnTensorflowNmpyPandas
IMDB DATASET.py
IMDB DATASET.py
py
2,624
python
en
code
0
github-code
1
16567540614
#coding:utf8 from flask import Flask,make_response,request app = Flask(__name__) @app.route('/cookie') def set_cookie(): response = make_response('cookie设置成功') response.set_cookie("name", 'zhang') return response if __name__ == '__main__': app.run(debug=True)
1071183139/biji
2_框架/1_flask框架/1_flask的基本使用/10_设置cookie.py
10_设置cookie.py
py
288
python
en
code
0
github-code
1
18941046142
from django.shortcuts import render from accounts.models import Team # Create your views here. def dashboard(request): context = { } return render(request, 'accounts/dashboard.html', context) def create_team(request): if request.POST: name = request.POST['name'] members = request.POST['...
jabguru/interswitch-mind
accounts/views.py
views.py
py
588
python
en
code
0
github-code
1
71717091875
import sys import math sys.path.insert(0, "../..") # LEXING math_reserved = { 'sin': 'SIN', 'cos': 'COS', 'tg': 'TAN', 'ctg': 'COT', 'sqrt': 'SQRT', 'log': 'LOG', 'exp': 'EXP', 'asin': 'ASIN', 'acos': 'ACOS', 'atg': 'ATAN', 'actg': 'ACOT' } reserved = { **math_reserv...
slawomirgicala/compilers_project
ex2/calc.py
calc.py
py
11,416
python
en
code
0
github-code
1
14751220428
''' A set of utility methods that are used in different parts of the framework. ''' import logging # Set of bots read from a bot tsv file bots = None filterBots = False def setFilterBots(fb,botfile): global filterBots,bots if fb: try: bots = set(long(bot) for bot in open(botfile,'r')...
declerambaul/WikiPride
src/utils.py
utils.py
py
6,973
python
en
code
9
github-code
1
3292374645
import os import os.path as osp import argparse import numpy as np import pandas as pd from tqdm import tqdm from sklearn import metrics import torch from dataset import create_data_loader, preprocess_df from model import ClassificationModel from utils import set_seeds, load_config, str2bool def inference(model, te...
DeepVisionStudy/dacon_breast_cancer
infer.py
infer.py
py
5,359
python
en
code
0
github-code
1
14283289627
import requests from tests.helpers import NetworkTest import time CONTROLLER = '127.0.0.1' KYTOS_API = 'http://%s:8181/api' % CONTROLLER class TestE2ESDNTraceInvertedCircuit: net = None circuit = None @staticmethod def setup_class(cls): """run at the beginning for all tests""" cls.net ...
Alsn2200/tests-kytos-
tests/test_e2e_200_sdntrace.py
test_e2e_200_sdntrace.py
py
4,307
python
en
code
0
github-code
1
24667117253
from forta_agent import Finding, FindingType, FindingSeverity, Network from src.detectors import processContract import rlp from datetime import datetime, timedelta from web3 import Web3 cache = [] def calc_contract_address(address, nonce): address_bytes = bytes.fromhex(address[2:].lower()) return Web3.toChe...
Sapo-Dorado/FortaKnight
src/agent.py
agent.py
py
1,747
python
en
code
2
github-code
1
965185620
import openpyxl VOLUNTEER_NUMBER = 1 VOLUNTEER_FIRST_NAME= 2 VOLUNTEER_LAST_NAME= 3 VOLUNTEER_EMAIL = 4 VOLUNTEER_HOUR= 5 VOLUNTEER_POSITION = 6 VOLUNTEER_COMMENT = 7 VOLUNTEER_CERT_LOC = 8 class VolunteerExcelFile: """ VolunteerExcelFile Class """ def __init__(self, filename:...
jasonwei0224/Volunteer_Certificate_Generator
ca/jason/pdfgenerator/VolunteerExcelFile.py
VolunteerExcelFile.py
py
2,223
python
en
code
0
github-code
1
38924501928
st=0 board=[] b = input("").split(",") Dies = list( map( int, input("").split(",") ) ) for i in b: c = i.split(":") a = [int(c[0]) , int(c[1])] board.append(a) data = dict(board) for i in Dies: die = i st =st+ die for i in data: if(i == st): st = data.get(i) ...
DeepR19/Snake_Ladder
Snake_ladder/snake and ladder 2.py
snake and ladder 2.py
py
433
python
en
code
0
github-code
1
5594298933
t = int(input()) for l in range(t): n = int(input()) c = 0 temp = n ds = 0 while temp != 0: # print(temp, ds) ds += (temp % 10) temp = temp//10 # print(ds) if ds%10==0: digit = 0 else: digit = 10 - ds%10 # print(digit) ans = int(str(n) ...
mayank-kumar-giri/Competitive-Coding
JuneLong19/guddu.py
guddu.py
py
348
python
en
code
0
github-code
1
35131155384
''' The following codes are from https://github.com/d-li14/mobilenetv2.pytorch ''' import os import torch import numpy as np from torchvision import datasets from torchvision import transforms DATA_BACKEND_CHOICES = ['pytorch'] try: from nvidia.dali.plugin.pytorch import DALIClassificationIterator from nvidia...
snudm-starlab/FALCON2
src/imagenetutils/dataloaders.py
dataloaders.py
py
14,404
python
en
code
40
github-code
1
40930647516
from django.db import models ###################################################################################################################### class Status(models.Model): id = models.AutoField( primary_key=True, ) title = models.CharField( verbose_name='Название стадии', max_...
joinc/SupportCenter
Contract/models.py
models.py
py
4,741
python
en
code
0
github-code
1
72563162595
from tensorflow.examples.tutorials.mnist import input_data mnist=input_data.read_data_sets("MNIST_data/",one_hot=True) import tensorflow as tf # implement variables x= tf.placeholder(tf.float32, [None,784]) #note None allows any length W= tf.Variable(tf.zeros([784,10])) b=tf.Variable(tf.zeros([10])) #implement model y=...
leobrowning92/tf_edu
mnist_beginner.py
mnist_beginner.py
py
1,236
python
en
code
0
github-code
1
34470262730
# 변수 선언 및 입력: n = int(input()) arr = list(map(int, input().split())) freq = {} # 각 수가 몇 번씩 나왔는지 기록합니다. for elem in arr: freq[elem] = freq.get(elem, 0) + 1 # 정확히 1번만 나온 수 중 # 등장한 최초 위치를 구해줍니다. ans = -1 for i in range(n - 1, -1, -1): # 최초로 나왔다면 답을 갱신합니다. if freq[arr[i]] == 1: ans = arr[i] print(an...
yeafla530/algorithms
코드트리/모의고사/네카라쿠배2/2_오직한번만주어진수.py
2_오직한번만주어진수.py
py
438
python
ko
code
0
github-code
1
36690204065
# daily challenge mar. 14 # simply path class Solution(object): def simplifyPath(self, path): """ :type path: str :rtype: str """ stack = [] for portion in path.split("/"): if portion == "..": if stack: stack.pop() ...
lingerxu/leetcode-solutions
simply_path.py
simply_path.py
py
610
python
en
code
0
github-code
1
41746201635
height = [4,2,0,3,2,5] # height = [0,1,0,2,1,0,1,3,2,1,2,1] all_trapped = 0 for i in range(1,len(height)-1): trapped = 0 water_level= min(max(height[:i]),max(height[i:])) if water_level > 0 and trapped >= 0: trapped = water_level - height[i] if trapped > 0: all_trapped+=trapped prin...
aniketwattamwar/Leetcode
trap_42.py
trap_42.py
py
336
python
en
code
0
github-code
1
40133379850
# suggestions.py # Code to handle submitting and reviewing suggestions. # Author: wHo#6933 # Plans: # 1. Submit suggestion command # 2. List pending suggestions command # 3. Accept/Decline suggestions command # Json format: # { # "id" (int): { # "user": userId (int), # "suggestion": suggestion (str) # ...
notbowen/CTSSBot
cogs/Suggestions/suggestions.py
suggestions.py
py
6,644
python
en
code
0
github-code
1
11163242013
a=[1, 3, 2, 5, 2, 2, 3, 1, 1, 6] print(len(a)) result=[] for i in range(len(a)): start = i -a[i] end = i + a[i] if start < 0 : start = 0 if end > len(a): end = len(a) result.append(sum(a[start:end+1])) print(result)
ahrtz/study
혼자하는거/기초_예제7번.py
기초_예제7번.py
py
255
python
en
code
0
github-code
1
18176472651
import os import shutil import pickle import pandas as pd from sklearn.cluster import KMeans #pd.set_option('display.max_colwidth', -1) DATA_PATH = "../ML_data" target = os.path.join(DATA_PATH, "target.csv") fp = os.path.join(DATA_PATH, "fp_folded.csv") y = pd.read_csv(target, index_col = "index") y = y.loc[(y[...
paulzierep/NP_epitope_predictor
tool/scripts/helper.py
helper.py
py
4,423
python
en
code
0
github-code
1
25072147771
import os from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait class scrapebook(): ...
Husseinmdarman/BookContentToYoutubeVideos
secondary.py
secondary.py
py
1,995
python
en
code
0
github-code
1
34013495264
''' Always want to combine the two sticks with the smallest lengths to minimize cost. Can use minHeap to get the two sticks with lowest cost. One we combine sticks. We put back into heap Time: heapify: O(n) + O(nlog(n)) ''' from heapq import * class Solution: def connectSticks(self, sticks: List[int]) -> int: ...
kjingers/Leetcode
Problems/MinimumCostToConnectSticks/MinimumCostToConnectSticks.py
MinimumCostToConnectSticks.py
py
595
python
en
code
0
github-code
1
2065842249
"""Module for ingesting quotes from PDF files.""" import os import subprocess from typing import List import tempfile from .IngestorInterface import IngestorInterface from .QuoteModel import QuoteModel class PDFIngestor(IngestorInterface): """Ingestor for parsing quotes from PDF files. This c...
NgoDuyVu1993/Advance_Python_Udacity_Ass2
QuoteEngine/PDFIngestor.py
PDFIngestor.py
py
1,945
python
en
code
0
github-code
1
20158053259
import math from torch.optim.lr_scheduler import _LRScheduler class CosineAnnealingWarmUpRestarts(_LRScheduler): r"""Set the learning rate of each parameter group using a cosine annealing schedule, where :math:`\eta_{max}` is set to the initial lr, :math:`T_{cur}` is the number of epochs since the last res...
SangHunHan92/2K2K
utils/scheduler.py
scheduler.py
py
6,051
python
en
code
170
github-code
1
35947567604
# -*- coding: utf-8 -*- import os import csv import matplotlib.pyplot as plt """ This script is for plotting each data (force/RMSE & TC(300K) diff from 112.1) with classified color by normalized distance """ if __name__ == '__main__': root=os.getcwd() tdata=["40"] node=["50","100","200","300","500"] ...
s-okugawa/HDNNP-tools
tools/Lmps-MD/plotRMSETCdata-d20L.py
plotRMSETCdata-d20L.py
py
2,726
python
en
code
0
github-code
1
34469512220
n = int(input()) a = [tuple(input().split()) for _ in range(n)] d = {} # print(a) for i in range(n): command = a[i][0] k = int(a[i][1]) if command == "add": d[k] = int(a[i][2]) elif command == "remove": d.pop(k) else: # print(k, d) if k in d: print(d[k...
yeafla530/algorithms
코드트리/IM/중급자료구조/HashMap/hashmap기본.py
hashmap기본.py
py
364
python
en
code
0
github-code
1
2819034093
# py -m pip install pygame # py -m pip install pywin32 import pygame, sys, random import win32api import win32con import win32gui def hide_console(): window = win32gui.GetForegroundWindow() win32gui.ShowWindow(window, win32con.SW_HIDE) if __name__ == "__main__": hide_console() pygame.init() c...
SicerBrito/Scripts
Etica/bb/ssss.py
ssss.py
py
1,028
python
es
code
13
github-code
1
28480361634
import math x, y, w, h = map(int, input().split()) ''' 직사각형 (0,0)~(w,h) 한수 (x,y) 안에 위치할 경우 : 점 사방면의 거리를 체크하여 가장 짧은 위치 출력 밖에 위치할 경우 : case1: x>w and y<=h case2: x<=w and y>h case3: x>w and y>h ''' if x<=w and y<=h: check = [] check.append(w-x) check.append(x) check.append(h-y...
sujeengim/problem-solving
baekjoon/class2/1085.py
1085.py
py
579
python
ko
code
0
github-code
1
38256631414
import cv2 import face_recognition from django.conf import settings from .faceRecognition import findEncodings import os, numpy as np from .attendance import mark_attendance, get_Remarks from .models import Schedule import time class VideoCamera(object): t = Schedule.objects.get(is_active=True) def __init__(se...
coder-val/AMSFR
amsfr/employees/camera.py
camera.py
py
3,616
python
en
code
1
github-code
1
74390609314
import numpy as np import torch from torch import nn from torch.utils import data # 生成数据集 def synthetic_data(w, b, num_examples): """生成 y = Xw + b + 噪声。""" X = torch.normal(0, 1, (num_examples, len(w))) y = torch.matmul(X, w) + b y += torch.normal(0, 0.01, y.shape) return X, y.reshape((-1, 1)) i...
hello2mao/Learn-MachineLearning
DeepLearning/DiveIntoDeepLearning/3.LinearNetwork/3.3.LinearRegressionConcise.py
3.3.LinearRegressionConcise.py
py
1,623
python
en
code
1
github-code
1
13255316883
## program that asks users for sandwich preferences and display total cost import pyinputplus as pyip # bread type bread_type = pyip.inputMenu( ['wheat', 'white', 'sourdough'], prompt = 'Choose your bread type:\n', numbered = True) print(f'You have selected {bread_type}.') # protein type protein_type =...
simink/py_automatetheboringstuff
code/sandwichMaker.py
sandwichMaker.py
py
1,542
python
en
code
1
github-code
1
165943487
# Read the introduction about garden path sentences and study a few of the examples on Wikipedia. # Create a new Python file called garden.py. # Find at least 2 garden path sentences from the web or create them. # Store the sentences you have identified or created in a list called gardenpathSentences # Add the followin...
marianklo/natural_language_processing
garden.py
garden.py
py
2,916
python
en
code
0
github-code
1
10277790770
import csv_reader from datetime import datetime, timedelta import time class Bus: def __init__(self, route_id, direction, trip_id): bus_id = f"bus-{route_id}-{direction}-{trip_id}" self.bus_id = bus_id self.route_id = route_id self.direction = direction self.trip_id = trip_i...
jovanovicm/genetic-bus-charging-network
Testing/bus_integration_v1.py
bus_integration_v1.py
py
3,987
python
en
code
0
github-code
1
20996429330
# Даны две строки. Эти строки отличаются друг от друга только одним символом. # Т.е. вторая строка получена добавлением случайного символа в случайную # позицию первой строки. Найти этот символ, вывести его и его индекс в строке. someString_1 = input() someString_2 = input() length = len(someString_1) cnt = 0 if len(...
astrogurvik/Homework_while
Homework_005_string_two exercises/main.py
main.py
py
1,859
python
ru
code
0
github-code
1
29389482192
from flask import Flask from flask import render_template, request, make_response, redirect, url_for import requests import random import json app = Flask(__name__) @app.route("/") def hello_world(): #retun 'hello' + home return "<p>Hello, App!</p>" @app.route('/home', methods=['GET']) def getTicTacToe(): ...
nkitanand/tictactoe_FrontEnd
app.py
app.py
py
4,499
python
en
code
0
github-code
1
71187679394
from functools import lru_cache from typing import List, Dict import csv @lru_cache def read(path: str) -> List[Dict]: try: with open(path, encoding="utf-8") as file: fields, *jobs = csv.reader(file, delimiter=",", quotechar='"') list_jobs = [dict(zip(fields, job)) for job in jobs]...
FP-Coding/project-job-insights
src/insights/jobs.py
jobs.py
py
749
python
en
code
0
github-code
1
20732284781
# -*- coding: utf-8 -*- from odoo import fields, models, api, _ from odoo.exceptions import UserError class PalletLoading(models.TransientModel): _name = 'pallet.loading' _description = 'Pallet Loading' @api.model def default_get(self, fields): res = super(PalletLoading, self).default_get(fi...
ezt-togawa/rtw-custom
stock_move_pallet/wizard/stock_move_pallet_wizard.py
stock_move_pallet_wizard.py
py
2,118
python
en
code
0
github-code
1
21382837069
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on: 2021/06/28 17:51 @Author: Merc2 ''' import numpy as np from pathlib import Path import openml import torch from torch.utils.data import Dataset class OPML(Dataset): def __init__(self, task=None, cv=0, train=True):# volkert # _, self.CV_NUM, _ ...
mhh0318/KDRVFL
data/opml.py
opml.py
py
1,110
python
en
code
0
github-code
1
16385188379
from flask import jsonify from . import app from .models import DBManager ############## VISTAS API @app.route("/api/v1/movimientos") def listar_movimientos(): try: # db = DBManager(app.config.get("RUTA")) """ Hace excepcion para la configuracion tomar el dato en vez de con GET, s...
RamiroCovian/flask-api
balance/api.py
api.py
py
2,516
python
es
code
0
github-code
1
27821992297
import pytest from xapres import load import numpy # Test the loading of a single dat file from the google bucket def test_dat_file_loading(): directory='gs://ldeo-glaciology/GL_apres_2022/A101' fs = load.from_dats(max_range=1400) fs.load_all(directory, remote_load = True, ...
ldeo-glaciology/xapres_package
tests/test_dat_file_loading.py
test_dat_file_loading.py
py
456
python
en
code
3
github-code
1
12782326030
def combination_sum(candidates, target): result = [] def backtrack(index, stack, current_sum=0): # if current sum equals to the target, add the current combination to the result if current_sum == target: result.append(list(stack)) return # if current sum exceeds...
tranphibaochau/LeetCodeProgramming
Medium/combination_sum.py
combination_sum.py
py
805
python
en
code
0
github-code
1
71519254113
# Задача-1: У вас есть массив целых чисел, в котором каждое число, кроме одного, повторяется дважды. # Вам нужно найти это одиночное число. # __ # Пример: # Входной массив: [4, 3, 2, 4, 1, 3, 2] # Результат: 1 # В данной задаче вы должны найти способ найти одиночное число с использованием массивов и алгоритмов. def fi...
Pl0tter/paradigm
Seminar 01/HW02.py
HW02.py
py
1,136
python
ru
code
0
github-code
1
30092387341
import re ## finitesum simplify() and derive() and derived() are ready for testing. ## use: exp=finitesum('2x^3+4y^7+5x^3'), exp.derive('y') derives wrt y ## use: '' '' exp.derived('y') changes value of exp to exp.derive('y') ## goal here is Laurent polynomials class finitesum: __string=None def __init__(self,...
georgercarder/calculus
calculus/polynomial_1.py
polynomial_1.py
py
3,713
python
en
code
0
github-code
1
21657652759
def extract_from_zero_width(zero_width_text): extracted_text = "" binary_char = "" for char in zero_width_text: if char == "\u200C" or char == "\u200B": binary_char += "1" if char == "\u200C" else "0" if len(binary_char) == 16: extracted_text += chr(int...
RadhitAsmara/Text_Steganography
extract.py
extract.py
py
599
python
en
code
1
github-code
1
37699492063
from driver import Driver from packet import Packet from packet.types import RGB from zone import Fan from debug import validate_tuple from effects import Effect def toHex(value): return "".join("0x{:02X} ".format(c) for c in value) VENDOR_ID = 0x2516 PRODUCT_ID = 0x0051 usb = Driver(VENDOR_ID, PRODUCT_ID) # To ...
twifty/plasma
main.py
main.py
py
1,109
python
en
code
0
github-code
1
27394954701
# Create your views here. from django.contrib import messages from django.contrib.auth import authenticate from django.contrib.auth.decorators import login_required, permission_required from django.contrib.auth import login as auth_login from django.http import HttpResponseRedirect, HttpResponseForbidden from django.sh...
AliVillegas/Wisapp
Wisapp/app/views.py
views.py
py
23,656
python
en
code
0
github-code
1
34372206850
#!/usr/bin/python # coding:utf-8 import sys from futu import * quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111) # 创建行情对象 # 获取港股 HK.00700 的快照数据 code_list = ['HK.00700'] # 上证指数[000001]沪深实时行情 - 东方财富 code_list = ['SZ.399959'] ret, data = quote_ctx.get_market_snapshot(code_list) if ret == RET_OK: print(data...
shsun/i47
bak/test1.py
test1.py
py
889
python
zh
code
0
github-code
1
41921955381
import math from World.node import * import sys def dir_dist(node1, node2): """ Calculates the direct distance bewteen each points """ return math.sqrt(math.pow(node1.x - node2.x, 2) + math.pow(node1.y - node2.y, 2)) def shortest_dist(agent_pos, containers_pos, cont_goals): "...
BenBausch/Mapf-with-Blocking-Containers
Environment/Algorithms/heuristic.py
heuristic.py
py
1,338
python
en
code
3
github-code
1
13330534487
from collections import deque class Solution: def minJumps(self, arr: List[int]) -> int: N = len(arr) common_vals = defaultdict(list) for idx, val in enumerate(arr): common_vals[val].append(idx) q = deque([N - 1]) min_jumps = {N - 1: 0} ...
edorado93/leetadaykeepsrustaway
January-Challenge-2022/[Day-15] Jump Game IV/bfs_dp_solution.py
bfs_dp_solution.py
py
1,123
python
en
code
1
github-code
1
15959651810
from flask_app.config.mysqlconnection import connectToMySQL from flask_app import app from flask_app.models.user import User from flask import flash, session DB = "coding_dojo_wall" class Post: def __init__( self , data ): self.id = data['id'] self.user_id = data['user_id'] self.content = da...
tndodge/Python
coding_dojo_wall/flask_app/models/post.py
post.py
py
3,205
python
en
code
0
github-code
1
21646634617
import numpy as np import joblib from nltk.tokenize import RegexpTokenizer import tldextract import pandas as pd from urllib.parse import urlparse from typing import * # predict def predict(url): def parse_url(url: str) -> Optional[Dict[str, str]]: try: no_scheme = not u...
skiraz/cloud_project
predictor.py
predictor.py
py
2,848
python
en
code
0
github-code
1
8428176367
""" This script uses the classes implemented in make_tables.py to create the tables used in PISAM simulations. The data loaded to make the tables are in the form of fit parameters or data points for reactions rates and cross sections. The data is stored in the directory "Collision data for tables". I you add a reaction...
kristofferkvist/PISAM-HESEL
PISAM/make_tables_main.py
make_tables_main.py
py
7,111
python
en
code
0
github-code
1
74917146594
__author__ = "Domen Gorjup" import os import glob import cv2 import time import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from tqdm import tqdm, tqdm_notebook import tools # IZBIRA SLIK IN NAČINA REKONSTRUKCIJE ############################################################### p...
domengorjup/pySfM
SfM_test_run.py
SfM_test_run.py
py
4,597
python
en
code
0
github-code
1
17283492359
import os.path import shutil # path = r"C:\Users\yang\OneDrive - Thuyloi University\Images\apple\test\labels" def moveFile(currentPath, newPath): for i in range(622, 1000): if os.path.isfile(r"currentPath\apple_" + str(i) + ".txt"): shutil.move( r"currentPath\apple_" + str(i) ...
ruaruababa/FruitsDetectionYOLOv8
services/file_services.py
file_services.py
py
2,022
python
en
code
1
github-code
1
39840653963
import argparse import sys from constants import ( IMPL_DEP_FILE_STR, OUTPUT_FILE_STR, ) from parser import Parser def main(): arg_parser = argparse.ArgumentParser( description="Control module for tracking implicit dependencies" ) arg_parser.add_argument( "-f", "--file", default=IM...
illumos/illumos-gate
usr/src/tools/smatch/src/smatch_scripts/implicit_dependencies/main.py
main.py
py
1,051
python
en
code
1,466
github-code
1
19546605494
import json import requests from loguru import logger from wb.services.tools import get_date class JWTApiClient: """Get Marketplace Statistics.""" def __init__(self, new_api_key: str): self.token = new_api_key self.base = "https://suppliers-api.wildberries.ru/public/api/" def build_hea...
prog1ckg/wildberries-rest-api
wb/services/rest_client/jwt_client.py
jwt_client.py
py
3,451
python
en
code
null
github-code
1
33854572922
""" Taken from pyro tutorial """ import argparse from os.path import exists import numpy as np import torch import torch.nn as nn import pyro import pyro.distributions as dist import pyro.poutine as poutine from pyro.distributions import TransformedDistribution from pyro.distributions.transforms import affine_autore...
CJHJ/convolutional-neural-markov-model
models/convdmm.py
convdmm.py
py
25,613
python
en
code
1
github-code
1
10712107494
import numpy as np import matplotlib.pyplot as plt #extract values Jacobi1_10n,Jacobi2_10n,Jacobi3_10n,analytic1_10n,analytic2_10n,analytic3_10n = np.loadtxt("solution_10n.txt", usecols=(0,1,2,3,4,5), unpack=True) Jacobi1_100n,Jacobi2_100n,Jacobi3_100n,analytic1_100n,analytic2_100n,analytic3_100n = np.loadtxt("so...
raggsokker/fys3150
project2/solution.py
solution.py
py
2,800
python
en
code
0
github-code
1