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
32029539658
import torch.nn as nn import torch import torch.nn.functional as F from src.models.dropblock import DropBlock from torch.autograd import Variable import math import numpy as np import torch.nn.functional as F from torch.nn.utils.weight_norm import WeightNorm from collections import defaultdict class ConvBlock(nn.Mod...
OscarcarLi/meta-analysis-classification
src/models/shallow_conv.py
shallow_conv.py
py
4,066
python
en
code
1
github-code
1
24710122363
from typing import List, Tuple STUDENT_START = -1 STUDENT_END = 1 def get_students_count(events: List[Tuple[int, int, int]], students_count: int) -> Tuple[int, List[int]]: """ Функция которая вычисляет необходимое количество билетов и вариант раздачи билетов. :param events: список событий в котором ука...
OkhotnikovFN/Yandex-Algorithms
trainings_1.0/hw_7/task_c/c.py
c.py
py
2,007
python
ru
code
1
github-code
1
702450714
from selenium.webdriver.common.action_chains import ActionChains from pymouse import PyMouse from pykeyboard import PyKeyboard from random import choice import time from utomarket.skip_util import * from utomarket.util import * from utomarket.settings import Settings def upload_avatar_o(browser): upload_btns ...
guzhijun369/test3
utomarket/personal_center_util.py
personal_center_util.py
py
11,035
python
en
code
0
github-code
1
6637185126
''' <문제> - 도현이 집 n개. 좌표 x1, x2, x3, ... - 집에 공유기 c개 설치 - 가장 인접한 공유기 사이 거리 최대 -> 최댓값 출력 ''' n,c = map(int,input().split()) house = [] for _ in range(n): x = int(input()) house.append(x) house.sort() # 좌표값의 최소값 start = 1 # 가장 높은 좌표와 가장 낮은 좌표의 차이 end = house[-1] - house[0] result = 0 while (start <= end): ...
dsc-sookmyung/2022-02-CodingTest-Study
Week5_Binary Search/suah/공유기 설치.py
공유기 설치.py
py
746
python
ko
code
2
github-code
1
28934137825
#!/usr/bin/env python3 import sys # Simple script to manage brightness of the display. # Min brightness (to not turn out monitor completely) MIN_BRIGHTNESS = 1 # Max brightness supported by the monitor on the target machine MAX_BRIGHTNESS = 512 # Path to the current brightness file BRIGHTNESS_FILE_PATH = "/sys/class/...
popzxc/dotfiles
.config/brightness.py
brightness.py
py
741
python
en
code
0
github-code
1
6749597437
from tool_share_app import models, forms from django.http import HttpResponseRedirect from django.contrib import messages from django.shortcuts import render from tool_share_app.forms.date_form import RequestDate, ReturnDate from tool_share_app.views import add_context_extra_data from django.views.decorators.csrf...
ibrr1/ToolShare
ToolShareVE/toolshare/toolshare/tool_share_app/views/tool_request.py
tool_request.py
py
6,095
python
en
code
0
github-code
1
4345568828
import time import pygame import threading from opening import screen # atak = 'first' from קבועים import rto, xx atak_1 = [100, 300, True] atak_2 = [200,200,True] def bose_atak(atak,a,x,y,live ): time = pygame.time.get_ticks() if time > 5000 and time < 7000: image = pygame.image.load(rto) ...
noamelul1234567890/DIYproject
bose_atak.py
bose_atak.py
py
860
python
en
code
0
github-code
1
34308053041
from random import randint import pygame class Colone: def __init__(self): self.x = 10 self.vitesse = 3 self.trou = randint(1,399) self.taille_trou = 100 self.rectUp = pygame.Rect((round(500*(self.x/10)), 0), (50, self.trou)) self.rectDown = pygame.Rect((round(500*(s...
SamTiq/fappy-bird-algog-n-
colone.py
colone.py
py
407
python
en
code
0
github-code
1
22995621098
import time from pyspark.sql import SparkSession from pyspark.sql import Window from pyspark.sql.functions import col, to_timestamp, rank, desc spark = (SparkSession .builder .appName("SparkEj1") .getOrCreate()) csv_trade = "trade_details.csv" csv_trade_snap = "trade_details_snapshot.csv"...
StefanoNapo/Big-Data-Bosonit
SparkEj1/SparkEj1.py
SparkEj1.py
py
1,762
python
en
code
0
github-code
1
14154096911
var1 = "" var2 = "" while not var1.replace('.', '', 1).isdigit(): var1 = input('Введите первое число: ') while not var2.replace('.', '', 1).isdigit(): var2 = input('Введите второе число: ') if var1.find('.') != -1: var1 = float(var1) else: var1 = int(var1) if var2.find('.') != -1: var2 = float(var2) else: ...
AleXeY1123/PythonLessons
Lesson2/task1_math.py
task1_math.py
py
1,002
python
ru
code
0
github-code
1
9946805104
# -*- coding: utf-8 -*- import subprocess import os import sys import socket import logging import dns.resolver #pip install dnspython dominio = raw_input(str('Digite o nome do seu dominio: ')) # Path's amavis_novalistadeverificacao = '/tmp/amavis_novalistadeverificacao' amavis_novalistadeverificacaoip = '/tmp/amavi...
danieljones0028/addAmavisBlacklistZimbra
addBlacklist.py
addBlacklist.py
py
8,545
python
pt
code
1
github-code
1
11531556819
import sqlite3 from aiocryptopay import AioCryptoPay, Networks from config import cryptobot_test_net, cryptobot_main_net from database.db_keys import user_table, k_user_id, k_locate, k_login, k_key, k_addres cp = AioCryptoPay(token=cryptobot_main_net, network=Networks.MAIN_NET) sql_create_users_table = f""" CREATE ...
stifhaks/testbot
database/db_helper.py
db_helper.py
py
8,967
python
en
code
0
github-code
1
43242842310
# -*- coding: utf-8 -*- """ Resources for handball models. TODO: Use ApiKeyAuthentication for models that need authentication. Implement custom authorization based on handball graph. """ from tastypie.resources import ModelResource, ALL_WITH_RELATIONS, ALL from tastypie import fields from handball.models impo...
Engaginglab/scoreit-handball
api.py
api.py
py
20,144
python
en
code
1
github-code
1
21343589977
import sys import time import traceback import discord from os import getenv from discord import Game, File from discord.ext import commands from discord.utils import get import logging import re from urllib.parse import urlparse from collections import defaultdict from sqlalchemy import create_engine, func, update, sq...
skydemmon/registerbotv3
registerbot.py
registerbot.py
py
15,418
python
en
code
0
github-code
1
9371102148
#pythonlists thislist = ["apple","banana","cherry"] print(thislist) #lists allow duplicate values thislist = ["apple","banana","cherry","apple","cherry"] print(thislist) #to print the number of items in ths list we use len() function thislist = ["apple","banana","cherry"] print(len(thislist)) list1 = ["apple"...
Sandra-Rosa/introduction-to-python
pythonlists.py
pythonlists.py
py
6,907
python
en
code
4
github-code
1
34013586724
''' Brute Force would be for each index, multiply the numbers at all other index. Time Complexity: O(n^2) This improve this, how can we store information as we calculate the product of numbers? Sliding window We can do 2 passes of the array: 1. Left to right - For each index, calculate the product of all nums to the...
kjingers/Leetcode
Problems/ProductOfArrayExceptSelf/ProductOfArrayExceptSelf.py
ProductOfArrayExceptSelf.py
py
1,548
python
en
code
0
github-code
1
38863371576
T = int(input()) for t in range(0,T): a,b,c = map(int, input().split()) lowerBound = a numOfDigit = len(str(lowerBound)) upperBound = 10**numOfDigit - 1 currentNumberCount = int((upperBound - lowerBound) / b) + 1; currentDigitCount = currentNumberCount * numOfDigit while currentDig...
einzeric/lge_competitive_coding
lge_codejam/2021_online_round2/problem_D.py
problem_D.py
py
829
python
en
code
0
github-code
1
5811938756
import pandas as pd, numpy as np import os os.chdir(os.path.dirname(os.path.abspath(__file__))) def parseInput(filename): file = open(filename) start = True prev_f = "" values = [] board = [] for f in file: if start: values.append(f[:-2]) start = False ...
utkimchi/Advent_Code
Advent_Code_Python/advent4.py
advent4.py
py
2,984
python
en
code
0
github-code
1
25472718455
# this is a really slow network scanner. # the idea is that it will slowly poke around and check who's up and whos not # over the course of a while, ideally without being discoverd or tripping over # network detection systems. who knows if it works import socket as s import netifaces import arprequest import argparse ...
BingoChado/NetMapper
scanner.py
scanner.py
py
5,776
python
en
code
0
github-code
1
15500406943
largura = int(input("Digite a largura: ")) altura = int(input("Digite a altura: ")) auxl = largura auxa = altura while altura > 0: while largura > 0: if altura == auxa or altura == 1: print('#', end = "") else: if largura == auxl or largura == 1: print('#', ...
synara/estudospy
imprime_retangulo_vazado.py
imprime_retangulo_vazado.py
py
483
python
pt
code
0
github-code
1
71400569633
# 1. С клавиатуры вводится 7 значное число. Если четных цифр в нем больше, чем # нечетных, то найти сумму всех его цифр, если нечетных больше, то найти # произведение 1 3 и 6 цифры. s = int(input("Введите 7ми значное число: ")) a = 0 # счетчик четных b = 0 # счетчик нечетных t = 0 # счетчик для суммы #p = 1 # сче...
12jf14MY/Obychenie1
8-9exzam1/1ex.py
1ex.py
py
1,193
python
ru
code
0
github-code
1
71505625634
import cv2 as cv import numpy as np import matplotlib.pyplot as plt img = cv.imread('tower.jpg', cv.IMREAD_GRAYSCALE) img_data = [] rows, cols = img.shape img_data.append(str(rows%256)) img_data.append(str(rows//256)) img_data.append(str(cols%256)) img_data.append(str(cols//256)) for row in range(rows): for col in...
Kaveesha-98/065-538-720-GNC
CPU/test_benches/textUpdate.py
textUpdate.py
py
782
python
en
code
0
github-code
1
32392455707
dados = dict() gols = list() dados['Nome'] = str(input('NOME DO JOGADOR: ')).strip().title() p = int(input(f'QUANTAS PARTIDAS {dados["Nome"]} JOGOU? ')) cont = 0 for c1 in range(1, p+1): p = int(input(f'QUANTOS GOLS {dados["Nome"]} FEZ NA {c1}ª PARTIDA? ')) gols.append(p) cont += p dados['gols'] = gols d...
Lucas-Winicius/estudo
Python/Curso de Python/Exercicios/ex093.py
ex093.py
py
583
python
pt
code
0
github-code
1
7564949893
import numpy as np from lime import lime_tabular from ...base import Explainer class LimeExplainer(Explainer): def __init__(self, train_ds, labels, *args, meta_prefix=None, **kwargs) -> None: super().__init__(*args, meta_prefix=meta_prefix, **kwargs) data = np.array([item["item"] for item in tra...
Oxid15/xai-benchmark
xaib/explainers/feature_importance/lime_explainer.py
lime_explainer.py
py
1,215
python
en
code
3
github-code
1
36580274522
from matplotlib.colors import ListedColormap from sklearn.metrics import accuracy_score import matplotlib.pyplot as plt import numpy as np def plot_decision_regions(X, y, classifier, test_idx = None, resolution = 0.02): labels = np.unique(y) markers = ('s', 'x', 'o', '^', 'v') colors = ('red', 'blue', 'lig...
zackcd/Machine-Learning-Projects
utilities.py
utilities.py
py
1,584
python
en
code
0
github-code
1
3156473153
#%% import re import pandas as pd import nltk import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity import plotly.express as px from termcolor import colored from DataUtility impor...
porterbmoody/Wilford-Woodruff-Papers
deprecated/scripts/WoodruffPapers.py
WoodruffPapers.py
py
8,270
python
en
code
0
github-code
1
33880439793
from utils import timeit @timeit def get_data(): data = [] with open('input.txt') as input_file: for line in input_file: value = line.strip() data.append(value) return data @timeit def part_1(data): key_pad = [[i*3+j+1 for j in range(3)] for i in range(3)] x, y = ...
bdaene/advent-of-code
2016/day02/solve.py
solve.py
py
1,755
python
en
code
1
github-code
1
18679758196
import re print("Rate, woran ich denke:") for i in 1, 2, 3, 4, 5, 6, 7: z = input() if re.findall("[Ll]uhmann", z): # finds "L/luhmann" print("Du kannst ja Gedanken lesen!") break else: print("Nö.") print("Luhmann, du Eule.")
IriniStivi/Ratespiel
ratespiel.py
ratespiel.py
py
273
python
de
code
0
github-code
1
41489742414
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2020-11-26 16:07 import glob import json import re from urllib.error import HTTPError import os from hanlp_common.io import load_json from elit.datasets.srl.ontonotes4 import ONTONOTES4_TASKS_HOME, ONTONOTES4_HOME from elit.datasets.srl.ontonotes5._utils import convert_...
emorynlp/seq2seq-corenlp
elit/datasets/srl/ontonotes4/chinese.py
chinese.py
py
7,307
python
en
code
13
github-code
1
71238790753
import numpy as np import pandas as pd import os import matplotlib.pyplot as plt import pandas as pd from scipy.stats import hmean from productiecapaciteit.src.capaciteit_strang import strangWeerstand import numpy as np from scipy.optimize import least_squares from scipy import linalg from dawacotools import get_daw_ts...
bdestombe/python-pwn-productiecapaciteit-infiltratiegebieden
productiecapaciteit/src/wvp_transient.py
wvp_transient.py
py
4,472
python
en
code
0
github-code
1
27090992766
with open('day4/input.txt') as input: lines = input.readlines() total_part1 = 0 total_part2 = 0 def intersection(lst1, lst2): return list(set(lst1) & set(lst2)) for line in lines: pair = line.split(',') first_elf_section, second_elf_section = pair[0].split('-'), pair[1].spl...
swimtrunks/AdventOfCode
day4/day4.py
day4.py
py
1,073
python
en
code
1
github-code
1
11483892621
from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split import pandas as pd import matplotlib.pyplot as plt import numpy as np df = pd.read_csv('/home/filip/Desktop/MachineLearning/dataset.csv') #df.drop('date',axis=1) y = df['deaths'] X = df[['cases','date']] benchmark ...
filipboucek/MachineLearning-filip_boucek
MachineLearning-filip_boucek/machineLeanrning.py
machineLeanrning.py
py
1,287
python
en
code
0
github-code
1
5328715406
# ****************************************************************************** ## GLOBIO - https://www.globio.info ## PBL Netherlands Environmental Assessment Agency - https://www.pbl.nl. ## Reuse permitted under Gnu Public License, GPL v3. # ***************************************************************************...
GLOBIO4/GlobioModelPublic
Calculations/GLOBIO_CalcAquaticRiverFRHLUMSA.py
GLOBIO_CalcAquaticRiverFRHLUMSA.py
py
5,364
python
en
code
17
github-code
1
28676451867
from fastai.vision.all import * from fastai.vision.all import cnn_learner #imports relevant libraries to create a CNN model from fastaudio.core.all import * from fastaudio.augment.all import * from fastaudio.ci import skip_if_ci #imports relevant libraries to prepare audio data from pandas.api.types impo...
kmcshane811/AutoML
autoMl/source(Commented code)/train_cnn.py
train_cnn.py
py
2,983
python
en
code
1
github-code
1
74843330274
from django.http import HttpResponse from django.shortcuts import render, redirect from myapp.models import * from django.contrib import messages def show_about_page(request): print("requesting show about page") name="Channel name is Learn Code with Durgesh" link="https://www.youtube.com/watch?v=697_0UGxD...
AbdulQadir8/Imagebazzar.github.io
imagebazar/views.py
views.py
py
1,487
python
en
code
0
github-code
1
8020600920
import random from PyQt6.QtWidgets import QPushButton, QApplication, QMainWindow, QWidget, QGridLayout, QLabel from PyQt6.QtGui import QAction, QIcon from PyQt6.QtMultimedia import QSoundEffect from PyQt6.QtCore import QSize, Qt, QCoreApplication, QPoint, QPropertyAnimation, QUrl from PyQt6 import QtCore class MainWin...
ArthurDubovik/Minesweeper
Minisweeper_Qt6.py
Minisweeper_Qt6.py
py
15,854
python
en
code
0
github-code
1
2303554777
import socket def main(): # 1. 创建一个 udp 套接字 udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 2. 绑定本地信息 如果一个网络程序不绑定,则系统会随机分配 local_addr = ("", 10789) # ip地址和端口号,ip一般不用写,表示本机的任何一个ip udp_socket.bind(local_addr) # 3. 发送信息 send_msg = input("请输入发送的消息:") send_addr = ("192.168.0...
sunhx0914/PythonTips
udp_send_and_recv.py
udp_send_and_recv.py
py
844
python
zh
code
0
github-code
1
4536994522
import scrapy class CompaniesSpider(scrapy.Spider): name = "companies" def start_requests(self): urls = [ 'https://www.nse.co.ke/market-statistics.html' ] for url in urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): ...
wcyn/nse
nse/spiders/companies_spider.py
companies_spider.py
py
808
python
en
code
0
github-code
1
7730126747
# Python program to handle simple runtime error #https://www.geeksforgeeks.org/try-except-python/ n1=10 n2=0 try: res= n1/n2 print("result = ", res) except ZeroDivisionError: print("An error occurred") else: print("No exception") finally: print("in final")
murali-kotakonda/PythonProgs
PythonBasics1/exception1/TestEx111.py
TestEx111.py
py
282
python
en
code
0
github-code
1
40089766883
from rest_framework import serializers from s2016.models import Doctor, LANGUAGE_CHOICES, STYLE_CHOICES class DoctorSerializer(serializers.Serializer): pk = serializers.IntegerField(read_only=True) name = serializers.CharField(max_length=100) education = serializers.CharField(max_length=100) specialty = serial...
ksj1993/s2016
s2016/serializers.py
serializers.py
py
995
python
en
code
0
github-code
1
24154787834
revision = '044' down_revision = '043' from alembic import op import sqlalchemy as sa from sqlalchemy.sql.expression import table MYSQL_ENGINE = 'InnoDB' MYSQL_CHARSET = 'utf8' def upgrade(active_plugins=None, options=None): op.create_table( 'story_types', sa.Column('id', sa.Integer(), nullable=...
pombredanne/storyboard
storyboard/db/migration/alembic_migrations/versions/044_story_types.py
044_story_types.py
py
1,855
python
en
code
null
github-code
1
29846376006
import numpy as np class AntColonyOptimizer: def __init__(self, num_ants, num_iterations, evaporation_rate=0.5, alpha=1.0, beta=1.0): self.num_ants = num_ants self.num_iterations = num_iterations self.evaporation_rate = evaporation_rate self.alpha = alpha self.beta = beta ...
mialtra/ant-colony-RMS-PELNI
AntColonyOptimizer.py
AntColonyOptimizer.py
py
4,084
python
en
code
0
github-code
1
32917331194
#Given an array of integers, find the one that appears an odd number of times. #[1,2,2,3,3,3,4,3,3,3,2,2,1] should return 4, because it appears 1 time #(which is odd). def find_oddint(arr): for i in arr: if arr.count(i) % 2 != 0: result = i else: continue return result f...
MannyVenegas/my-python-katas
findtheoddint.py
findtheoddint.py
py
358
python
en
code
0
github-code
1
26816860426
n = int(input()) list1 = [] list2 = [] for i in range(0,n): min,max1 = list(map(int,input().split())) for j in range(min,max1): list1.append(j) for i in range(0,n): min,max1 = list(map(int,input().split())) for j in range(min,max1): list2.append(j) m = max(list1[-1],list2[-1])+1 count = ...
jianjiachenghub/PythonClass
CCF/201809/买菜.py
买菜.py
py
432
python
en
code
0
github-code
1
34872538868
import numpy as np from deep_sort.utils.parser import get_config from deep_sort.deep_sort import DeepSort class DeepSortTracker: """ DeepSort object tracker. """ def init(self, reid_model_path, max_dist=0.2, min_confidence=0.3, nms_max_overlap=1.0, max_iou_distance=0.7, max_age=70, n_ini...
strikerPro818/strikerBot
Xavier_NX/personDetection.py
personDetection.py
py
1,215
python
en
code
0
github-code
1
11336816782
# -*- coding: utf-8 -*- """Test s3 class.""" import pytest from unittest.mock import Mock, patch from s3_client import s3_client from conftest import BUCKET_NAME def test_download_object(s3, s3_bucket, tmpdir): """Test object download.""" s3_client.log = Mock() obj_name = "my_object" obj_body = "Te...
thobiast/s3_client
tests/test_s3_class_download_object.py
test_s3_class_download_object.py
py
1,302
python
en
code
3
github-code
1
6328047635
# json keys from original data are bad... see data: # http://data.sfgov.org/resource/w969-5mn4.json class Result: def __init__(self, result): self.priority = 0 self.address = result['yr_inst'] self.location = result['addr_num'] self.longitude = float(result['latitude']['longitude']) self.latitude = float...
cheniel/sf-bike-parking
sf_bike_parking/parkfinder/result.py
result.py
py
918
python
en
code
3
github-code
1
1218277044
""" Populate database command module """ import os import json from django.core.management.base import BaseCommand from core.settings import BASE_DIR from schemas.models.cities import City from schemas.models.countries import Country class Command(BaseCommand): help = "Populate the databse with multiple count...
alexeipopov95/drf-practice
tools/management/commands/populate_database.py
populate_database.py
py
1,906
python
en
code
0
github-code
1
74143407712
import unittest from kerlescan import profile_parser from kerlescan.exceptions import UnparsableNEVRAError class PackageParserTests(unittest.TestCase): def test_package_parsing(self): tests = { "0:bluejeans-1.37.22-1": ("bluejeans", "1.37.22-1"), "0:brscan4-0.4.7-1": ("brscan4", ...
beav/kerlescan
tests/test_info_parser.py
test_info_parser.py
py
5,022
python
en
code
2
github-code
1
34842461890
# Basic Calculator: https://leetcode.com/problems/basic-calculator/ # Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation. # Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, suc...
KevinKnott/Coding-Review
Month 02/Week 04/Day 02/b.py
b.py
py
1,678
python
en
code
0
github-code
1
21065158917
from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import os import time from absl import flags import absl.logging as _logging # pylint: disable=unused-import import tensorflow as tf import imagenet_input import resnet_model from tensorflow.contr...
ProjectSidewalk/sidewalk-cv-assets19
old/tf_resnet_tutorial/tpu/models/experimental/resnet_bfloat16/resnet_main.py
resnet_main.py
py
18,959
python
en
code
4
github-code
1
72426162273
#!/usr/bin/python # https://code.google.com/codejam/contest/2933486/dashboard # application of insertion sort N = int(input().strip()) for i in range(N): M = int(input().strip()) deck = [] count = 0 for j in range(M): deck.append(input().strip()) p = 0 for k in range(len(deck)): if k > 0 and deck[k]...
binkoni/algo-practice
codejam/moist/solve.py
solve.py
py
406
python
en
code
0
github-code
1
6722675922
from classes import * cart = Cart() user = User(cart) login = False while(login == False): username = input("\nEnter your username: ") #checks login credentials password = input("Enter your password: ") print("\n") try: #catch login error if(user.login(username, password)): ...
jsburrell97/SWArch
main.py
main.py
py
9,668
python
en
code
0
github-code
1
17716181461
import os import unittest import dosma from dosma.defaults import preferences from dosma.utils import env class TestEnv(unittest.TestCase): def test_package_available(self): assert env.package_available("dosma") assert not env.package_available("blah") def test_get_version(self): ass...
ad12/DOSMA
tests/utils/test_env.py
test_env.py
py
639
python
en
code
49
github-code
1
20181232988
""" radixsort string sortowanie pozycyjne Complexity O(d*n) gdzie: d - ilość znaków w każdym słowie n - liczba słów """ def SortOnPosString(A, pos): # sortuje A, ktora jest 2-wym, pos to index wg którego sortujemy n = len(A) dig = [0] * (58) # bo ord('z') - ord('A')=57 więc potrzebuję indeksy od 0 do...
wlgs/algorithms-and-data-structures-course
sorts/radixsort_string.py
radixsort_string.py
py
1,620
python
pl
code
0
github-code
1
27662200815
# coding: utf-8 from .base import MongoBase from .index import MongoIndex, MongoReIndex from .topic import MongoTopic, MongoReTopic from .comment import MongoComment from .feedback import MongoFeedback from .ossfile import OssFile from .local import LocalFile __all__ = [ 'MongoWeb', ] class MongoWeb(MongoBase): d...
endsh/haoku-open
kread/read/db/web.py
web.py
py
895
python
en
code
6
github-code
1
31192285305
import re import sys vowels = "[ауоыиэяюёе]" not_vowels = "[бвгджзйклмнпрстфхцчшщьъ]" perfect_gerund_endings = r'(вшись|вши|в)$' perfect_gerund_endings_for_search = '(а|я)' + perfect_gerund_endings perfect_gerund_endings2 = r'(ившись|ывшись|ивши|ывши|ив|ыв)$' reflexive = r'(сь|ся)$' adjective = r'(ыми|ими|его|ого|ем...
YauheniSuvitau/stemming
main.py
main.py
py
3,529
python
en
code
0
github-code
1
2946911396
# Авторизоваться на сайте https://fix-online.sbis.ru/ # Перейти в реестр Контакты # Отправить сообщение самому себе # Убедиться, что сообщение появилось в реестре # Удалить это сообщение и убедиться, что удалили # Для сдачи задания пришлите код и запись с экрана прохождения теста from selenium import webdriver from se...
AnnaBlem/AT_course
hw11/task_2.py
task_2.py
py
3,467
python
ru
code
0
github-code
1
42769197778
#!/usr/bin/python # __author__ = 'jasonsheh' # -*- coding:utf-8 -*- import sys import requests import threading import queue import time from database.database import Database class Sendir: def __init__(self, targets, id=''): self.targets = targets self.id = id self.q = queue.Queue(0) ...
euphrat1ca/SiteScan
lib/sendir.py
sendir.py
py
3,854
python
en
code
1
github-code
1
25467462275
__author__ = 'jcgregorio@google.com (Joe Gregorio)' import unittest from oauth2client import xsrfutil # Jan 17 2008, 5:40PM TEST_KEY = 'test key' TEST_TIME = 1200609642081230 TEST_USER_ID_1 = 123832983 TEST_USER_ID_2 = 938297432 TEST_ACTION_ID_1 = 'some_action' TEST_ACTION_ID_2 = 'some_other_action' TEST_EXTRA_INFO_...
hanpfei/chromium-net
third_party/catapult/third_party/gsutil/third_party/oauth2client/tests/test_xsrfutil.py
test_xsrfutil.py
py
3,932
python
en
code
289
github-code
1
14592464595
from rest_framework import serializers from .models import RegisterInvitation from django.core.mail import send_mail from django.conf import settings import datetime class RegisterInvitationSerializer(serializers.ModelSerializer): class Meta: model = RegisterInvitation fields = '__all__' de...
benhchoi/coursemanager
coursemanager/invitations/serializers.py
serializers.py
py
950
python
en
code
0
github-code
1
2269945821
import os import torchvision as tv import numpy as np from PIL import Image def get_dataset(args, transform_train, transform_test): cifar_train = Cifar100Train(args, train=True, transform=transform_train, download = args.download) testset = tv.datasets.CIFAR100(root='./data', train=False, download=False, tran...
EricArazo/ImportanceSampling
dataset/cifar100_dataset.py
cifar100_dataset.py
py
1,531
python
en
code
10
github-code
1
6953518270
import json from django.shortcuts import render, get_object_or_404, render_to_response from django.template import loader from django.http import HttpResponse, HttpResponseRedirect from .models import Libro from .models import Autor, Editor from .forms import AutorForm, EditorForm from django.views.generic import List...
JokerBerlin/python
biblioteca/views.py
views.py
py
7,569
python
en
code
0
github-code
1
17811259423
#!/usr/bin/env python3 import numpy as np import h5py import glob import matplotlib import matplotlib.pyplot as plt import argparse import csv def get_dataset_keys(f): keys = [] f.visit(lambda key : keys.append(key) if isinstance(f[key], h5py.Dataset) else None) return keys if __name__ == '__main__': ...
MichaelSt98/milupHPC
postprocessing/PlotBB.py
PlotBB.py
py
2,384
python
en
code
6
github-code
1
31808609856
# encoding: utf-8 import re import time import json import datetime from aliyun.log import * from prometheus_client import CollectorRegistry, push_to_gateway, Gauge, write_to_textfile endpoint = '' # 选择与上面步骤创建Project所属区域匹配的Endpoint accessKeyId = '' # 使用你的阿里云访问密钥AccessKeyId accessKey = '' # 使用你的阿里云访问密钥Acc...
amendge/OpsSricpts
getlogfromaliyun.py
getlogfromaliyun.py
py
1,943
python
en
code
5
github-code
1
13496397373
import logging import logging.handlers import sys import datetime LOGGING_LEVEL = logging.DEBUG LOGGING_BASE = '/tmp' SUMMON_API_HOST = 'api.summon.serialssolutions.com' # Google credentials GOOGLE_CRED_JSON_FILE = '' # Summon Credentials SUMMON_ACCESS_ID = '' SUMMON_API_KEY = '' supported_languages = { 'Afri...
summon/translated-search
translatedsearch/settings.py
settings.py
py
2,042
python
en
code
2
github-code
1
10651942871
#imports import json import pandas as pd from tqdm import * import pickle import networkx as nx # Extraindo dados dos json e colocando em dataframe pandas contador = 0 lista_slices = [] # Quantidade de slices que serão utilizados, 1 slice são 1000 playlists pegar_quant_slices = 1 while(True): with open("data\mpd...
Carlos1999/Network_Analysis_Spotify_Playlists
Cria_grafo.py
Cria_grafo.py
py
2,942
python
pt
code
0
github-code
1
23885346763
import numpy as np from numpy.testing import assert_array_almost_equal from reservoirpy.nodes import Reservoir, Ridge def test_ridge_init(): node = Ridge(10, ridge=1e-8) data = np.ones((1, 100)) res = node(data) assert node.Wout.shape == (100, 10) assert node.bias.shape == (1, 10) assert n...
reservoirpy/reservoirpy
reservoirpy/nodes/tests/test_ridge.py
test_ridge.py
py
2,922
python
en
code
296
github-code
1
74574230112
def deltat (popT,Tc,a): delta = a*(popT**2)*(1 - (Tc/popT)) return delta def deltaA (popA,Ac,k): delta = k*(popA**2)*(1 - (Ac/popA)) return delta def deltaV (popV,Vc,l): delta = l*(popV**2)*(1 - (Vc/popV)) return delta def Tf(popA,Ap,popT): tubarao_fome=popA/Ap-popT return tubarao_fome def A...
Leobhering/projeto1-modsim
Projeto 1/projeto1.py
projeto1.py
py
1,851
python
pt
code
0
github-code
1
39727612180
#!/usr/bin/python3 #part 1 f = open('02_input.txt') coordinates = [0,0] #forward, depth path = [] count = 0 for i in f.readlines(): path.append(i[:-1]) #-1 to not copy the newline character for a in path: if a[0] == "f": coordinates[0] += int(a[-1]) elif a[0] == "u": coordinates[1] -= ...
derwaro/2021AdventOfCode
02.py
02.py
py
864
python
en
code
0
github-code
1
1931622003
""" This module contains a Flask application that uses OpenAI's GPT-4 model to chat with users. """ import os import markdown from flask import Flask, request, jsonify, render_template from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from flask_bootstrap import Bootstrap from gunicorn.app.ba...
hooman130/gpt4-gui
main.py
main.py
py
3,003
python
en
code
0
github-code
1
42157120652
# from django.http import JsonResponse, HttpResponse from rest_framework.status import HTTP_201_CREATED, HTTP_404_NOT_FOUND, HTTP_400_BAD_REQUEST, HTTP_200_OK from .serializers import * from .models import * from .exceptions import * from rest_framework.response import Response from rest_framework.views import APIVie...
Ellanity/sweets-from-all-misfortunes
server/delivery/views.py
views.py
py
16,143
python
en
code
1
github-code
1
6370764918
import json import tweepy import socket ACCESS_TOKEN = '311893922-jasoBxDymbqR4OxLBoDLw9Ab0pkPqUX2AVxFoYuy' ACCESS_SECRET = 'wa87QvHapxNOh3AxDy5bPL1vh9GrfqDA5kKuasbn8unhl' CONSUMER_KEY = 'UiDazJWIu3SvHSxltmO7mtN6b' CONSUMER_SECRET = 'YDI2mHOyWXfjUupr1CpUNVpAD6oin6YQ2u03RpWUtPbFeaXn4H' auth = tweepy.OAuthHandler(CON...
Sharayu2554/Big-Data
HW3/RoughWork/tweetApi.py
tweetApi.py
py
1,319
python
en
code
0
github-code
1
7799926770
class Car(object): """A simple attempt to represent a car""" def __init__(self,make,model,year): """Initialize attributes to describe a car""" self.make=make self.model=model self.year=year self.odometer_reading=0 def get_descriptive_name(self): """Return a ...
rishabhchopra1096/Python_Crash_Course_Code
Chapter_9_Classes/Class_car.py
Class_car.py
py
1,762
python
en
code
0
github-code
1
75189377633
# Test file def countNegatives(grid): n_count = 0 row_length = len(grid[0]) for an_item in grid: for i in range(row_length): if an_item[i] < 0: n_count = n_count+(row_length-i) break return n_count countNegatives([[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-...
MallikarjunHS/leetcode
0000_playground.py
0000_playground.py
py
333
python
en
code
0
github-code
1
74830203233
from numpy import arange, dot, ones, append, savetxt, zeros, asarray, exp from numpy.random import RandomState def create_phenotype(covariates, covariances): nsamples = covariates.shape[0] y = zeros(nsamples) random = RandomState(0) y += dot(covariates, random.randn(covariates.shape[1])) for K i...
limix/ggp-poisson-example
create_example.py
create_example.py
py
1,240
python
en
code
0
github-code
1
10048401104
""" Search a 2D Matrix II Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. Example: Consider the following matrix: [ ...
okaysidd/Interview_material
Extras/Search a 2D Matrix II.py
Search a 2D Matrix II.py
py
1,167
python
en
code
0
github-code
1
2697335806
from math import lcm def main() -> None: with open("input.txt") as f: # Parsing input for monkey class constructor for monkey in [el.splitlines() for el in f.read().split("\n\n")]: items = [int(el) for el in monkey[1].removeprefix( " Starting items: ").split(", ")] ...
Gutek8134/AdventOfCode2022
Day 11/main.py
main.py
py
4,879
python
en
code
0
github-code
1
21232958424
import numpy as np import copy import pickle import torch import torch.nn as nn from torch.utils.data import TensorDataset, DataLoader from sklearn.metrics import f1_score import feature_engineer from catboost import CatBoostClassifier from xgboost import XGBClassifier from mlp import MLP class EnsembleRNN(nn.Modul...
hjc18/sml_project
ensemble.py
ensemble.py
py
6,012
python
en
code
1
github-code
1
1918040195
#!/usr/bin/env python # coding=utf-8 """ TBW """ from __future__ import absolute_import from __future__ import print_function import os from ipapy.ipastring import IPAString from wiktts import write_file from wiktts.cleanedpronunciationlexicon import CleanedPronunciationLexicon from wiktts.commandlinetool import Com...
pettarin/wiktts
wiktts/lexcleaner/lexcleaner.py
lexcleaner.py
py
9,712
python
en
code
5
github-code
1
35916070388
# -*- coding: utf-8 -*- from typing import Dict, List, Tuple import json import requests import re from enum import Enum from bs4 import BeautifulSoup import configparser import logging import pickle # 创建日志记录器 logger = logging.getLogger('my_logger') logger.setLevel(logging.DEBUG) file_logger = logging.getLogger('my...
supersonictan/astro_web
util.py
util.py
py
9,394
python
en
code
0
github-code
1
71903777953
# List (for in) # // # If Statement # Variables # Maak drie variables aan. Een die de prijs van het gekozen product vasthoud, een die het betaalde bedrag vasthoud en de derde die het verschil tussen die twee variables vasthoud. # Maak zes variables aan die de Integers van de munteenheid kunnen vasthouden. # Maa...
ZekoTheDev/Python
vendingMachine.py
vendingMachine.py
py
2,578
python
nl
code
0
github-code
1
8275354682
import argparse parser = argparse.ArgumentParser( description="Save baselines and klambda conversions to CSV." ) parser.add_argument("outfile", help="Destination to save CSV table.") args = parser.parse_args() import csv import numpy as np from mpol.constants import c_ms header = ["baseline", "100 GHz (Band 3)...
shawn194/MPoL
docs/_static/baselines/src/print_conversions.py
print_conversions.py
py
1,298
python
en
code
null
github-code
1
2889270077
import sys readline = sys.stdin.buffer.readline map_readline = lambda: map(int, readline().split()) sreadline = lambda: readline().decode("utf-8").rstrip() if __name__ == "__main__": N = int(readline()) S = sreadline() pins = [None] * 1000 for i in range(1000): num = str(i) pins[i] = ("...
Kumamoto-Hamachi/atcoder_pr
others/archives_abc_selection/SUMITRUST2019/d/d.py
d.py
py
711
python
en
code
1
github-code
1
40249437213
n = int(input()) points = [] for _ in range(n): p = float(input()) points.append(p) def quick_sort(lists, left, right): # quick sort if left >= right: return lists key = lists[left] low = left high = right while left < right: while left < right and lists[right] >= key: ...
nummy/exec
conqure/q1/a1.py
a1.py
py
725
python
en
code
0
github-code
1
24893230486
# -*- coding: utf-8 -*- import scrapy from scrapy import Request from lxml import etree from WaiBaoSpider.utils.csvWriter import CSVDumper from WaiBaoSpider.utils.base import unicode_body, deal_ntr import os class ChuzhouSpider(scrapy.Spider): name = 'chuzhou' base_url = "http://www.chuzhou.gov.cn/content/col...
jamesfyp/WaiBaoSpider
WaiBaoSpider/spiders/chuzhou.py
chuzhou.py
py
3,885
python
en
code
1
github-code
1
31056112122
"""M345SC Homework 2, part 1 Jimmy Yeung 01203261 """ def count_days(task_id): days = dict() if task_id in days: return days[task_id] if not L[task_id]: days[task_id]=0 return 0 md = max([count_days(t) for t in L[task_id]]) days[task_id] = md + 1 return days[task_id] def ...
jyeung205/University-Projects
M3SC-Scientific-Computation/hw2/p1.py
p1.py
py
6,689
python
en
code
0
github-code
1
15247482287
import socketserver import socket import threading import functools from webserver.casseroleWebServerImpl import CasseroleWebServerImpl, dashboardWidgetList, WEB_ROOT from utils.singleton import Singleton # A threaded TCP server starts up new python threads for each client request, which allows # complex reque...
RobotCasserole1736/firstRoboPy
webserver/webserver.py
webserver.py
py
2,100
python
en
code
1
github-code
1
37785348874
import pandas as pd #import nltk #from nltk.corpus import wordnet #from nltk.stem.lancaster import LancasterStemmer #from nltk.stem import WordNetLemmatizer #import spacy #from spacy.matcher import Matcher from thefuzz import fuzz, process import sys sys.setrecursionlimit(10**6) # lists to create pandas dataframes ...
runo-hr/NLP-vocabulary-matching
draft/draft.py
draft.py
py
2,601
python
en
code
0
github-code
1
8872246940
class return_value(object): def __init__(self, plaintext, description, certainty): self.plaintext = plaintext self.description = description self.certainty = certainty with open("dictionary.txt", "r") as dict_file: dictionary = dict_file.read().split("\n") with open("dict_oxford.txt", "r") as dict_file: ...
spook-dev/ciphersolver
CipherSolverIncludes.py
CipherSolverIncludes.py
py
1,727
python
en
code
1
github-code
1
74962288673
import os import threading import time import tkinter.messagebox from tkinter import * from tkinter import filedialog import pyglet from tkinter import ttk from ttkthemes import themed_tk as tk from mutagen.mp3 import MP3 from pygame import mixer class Media: def musicPlayer(self, music_player, window): ...
Dkarya846/PaiBot
ExtraFiles/MediaPlayer.py
MediaPlayer.py
py
6,714
python
en
code
1
github-code
1
19031150212
import numpy as np import pandas as pd class BiasVarianceCovariance: @classmethod def get_bvc(cls, y_hat: pd.DataFrame, y: np.ndarray): return cls.avg_sqr_bias(y_hat, y), cls.avg_var(y_hat), cls.avg_cov(y_hat) @staticmethod def avg_sqr_bias(y_hat: pd.DataFrame, y: np.ndarray): """ ...
vcerqueira/blog
src/ensembles/bvc.py
bvc.py
py
970
python
en
code
15
github-code
1
70839054753
q = int(input()) for _ in range(q): lst = list(map(int, input().split())) a, b = lst[0], lst[1] if a == b: print(0) elif a < b: if (b-a) % 2 == 0: # 짝수 차이면 print(2) else: # 홀수 차이면 print(1) elif a > b: if (a-b) % 2 == 1: # 홀수 차이면 ...
ckdfh0917/Algorithm
CodeForces/Div. 3/#624/A.py
A.py
py
395
python
ko
code
0
github-code
1
31002519252
import numpy as np import pandas as pd import pyarrow as pa import pyarrow.parquet as pq import os import gc array_length = 2**20 num_arrays = 10 filename = "test.parquet" # Only run this if the data file hasn't been already generated if(not os.path.isfile(filename)): # Generate arrays and write them to a datafr...
Hugo-loio/lasap
test/parquet_read_bug.py
parquet_read_bug.py
py
2,055
python
en
code
0
github-code
1
2736703863
''' https://www.codewars.com/kata/520b9d2ad5c005041100000f/python ''' from curses.ascii import isalpha def pig_it1(text:str): content = [] txt_lst = text.split() for txt in txt_lst: if not isalpha(txt[0]): content.append(txt) continue first_letter = txt[0] ...
SzybkiRabarbar/CodeWars
2022-03/2022-03-29Simple Pig Latin.py
2022-03-29Simple Pig Latin.py
py
625
python
en
code
0
github-code
1
6080209867
import gym from gym import spaces import numpy as np import matplotlib.pyplot as plt from scipy.optimize import minimize class PortfolioManagementEnv(gym.Env): """ Portfolio Management Env """ def __init__(self, seed=0): # self.simulator = BlackScholes(num_stocks=3, # ...
JinyangJiangAI/Quantile-based-Policy-Optimization
portfolio_management/envs/portfolio_management.py
portfolio_management.py
py
9,366
python
en
code
6
github-code
1
43104630194
from Assignment1 import human class Emp(human) : def emply(self): desg = input("enter designation") exp = input("enter expierence") sal = input("enter salary") hike = "10000" if desg.lower() >= "PM" else "8000" if desg.lower() >= "TL" else "5000" print("HIkE : ",hi...
Pooja5573/DS-Pragms
emp.py
emp.py
py
444
python
en
code
0
github-code
1
7555774390
T = int(input()) for i in range(T): s = input() arr = list(s) result = True for j in range(len(arr)//2): if arr[j] != arr[-1-j]: result = False break if result: print(f"#{i+1} 1") else: print(f"#{i+1} 0")
seriokim/SW-Expert-Academy
sw_1989.py
sw_1989.py
py
278
python
en
code
0
github-code
1
29963253724
import random from W_Main_File.Data import HpEntity def calculate_damage(damage, elements, target: HpEntity.HpEntity): from W_Main_File.Data.Item import DamageType if elements & (DamageType.Any_Elemental & ~DamageType.Void_Elemental): elemental_damage = damage * 0.2 elif elements & DamageType.Voi...
jackshotgamer/Adventure-Mini-Visual-Game
W_Main_File/Utilities/Damage_Calc.py
Damage_Calc.py
py
625
python
en
code
1
github-code
1
33706405037
import random def is_prime(n): """ :param n: :type n: :return: :rtype: """ assert n >= 2 if n == 2: return True if n % 2 == 0: return False # for n < 2^64, these a are sufficient for a in {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}: if not rabin_...
liamlundy/rsa
utils/rabin_miller.py
rabin_miller.py
py
990
python
en
code
0
github-code
1