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
42558176076
#!/usr/bin/env python3 ## Estimates errors using Monte Carlo sampling # Hamish Silverwood, GRAPPA, UvA, 23 February 2015 import numpy as np import gl_helper as gh import pdb import pickle import sys import numpy.random as rand import matplotlib.pyplot as plt #TEST this will eventually go outside def ErSamp_gauss_l...
PascalSteger/gravimage
programs/gi_mc_errors.py
gi_mc_errors.py
py
2,025
python
en
code
0
github-code
36
17156680991
import torch import numpy as np from transformers import AutoTokenizer from tqdm import tqdm def get_lm_embeddings(mapper_model, test_df, trained_model_name, use_first_token_only = False): mapper_model.set_parameters() # Load pre-trained model tokenizer (vocabulary) tokenizer = AutoTokenizer.from_pretrain...
Peter-Devine/Feedback-Mapping
utils/bert_utils.py
bert_utils.py
py
2,182
python
en
code
0
github-code
36
4123119834
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import pandas as pd import matplotlib.pyplot as plt # In[2]: dataset = pd.read_csv(r'E:\Udemy corurse\[DesireCourse.Net] Udemy - Machine Learning A-Z™ Hands-On Python & R In Data Science\1.Machine Learning A-Z New\Part 2 - Regression\Section 4 - S...
Rizwan-khan-7/Machine-Learning
Regression_Analysis_Part I.py
Regression_Analysis_Part I.py
py
1,045
python
en
code
0
github-code
36
14130664964
""" The Morse code encodes every character as a sequence of "dots" and "dashes". For example, the letter A is coded as ·−, letter Q is coded as −−·−, and digit 1 is coded as ·−−−−. The Morse code is case-insensitive, traditionally capital letters are used. When the message is written in Morse code, a single space is ...
adrikosm/interview_questions
Codewars/6kyu/Morse_Decoder.py
Morse_Decoder.py
py
2,460
python
en
code
0
github-code
36
25718178961
# This exports all networks and their base attributes from an organization to a file # and then imports them to another organization. # # You need to have Python 3 and the Requests module installed. You # can download the module here: https://github.com/kennethreitz/requests # or install it using pip. # # To ...
meraki/automation-scripts
copynetworks.py
copynetworks.py
py
8,232
python
en
code
361
github-code
36
20338749336
import cv2 import numpy as np # VARIABLES # True while mouse button down, False while mouse button up drawing = False ix,iy = -1,-1 # FUNCTION def draw_rectangle(event, x,y, flags, param): global ix,iy,drawing if event == cv2.EVENT_LBUTTONDOWN: drawing = True ix,iy = x,y elif event == cv2.EVEN...
eliottjohnson/VS_code
draw_circle_with_mouse.py
draw_circle_with_mouse.py
py
798
python
en
code
0
github-code
36
19029066252
import logging import requests import time import json from cifsdk.exceptions import AuthError, TimeoutError, NotFound, SubmissionFailed, InvalidSearch, CIFBusy from cifsdk.constants import VERSION, PYVERSION, TOKEN from pprint import pprint from base64 import b64decode from cifsdk.client.plugin import Client import os...
csirtgadgets/cifsdk-py-v3
cifsdk/client/http.py
http.py
py
8,165
python
en
code
8
github-code
36
15184343497
"""Advent of Code - Day 1.""" from pathlib import Path from typing import List FILE_PATH = Path(__file__).parent.parent / "data" / "day_1.txt" def find_elves_most_calories(calories: List, n: int) -> int: """Fat elf detection. Find the elf carrying the most calories. Args: calories: Calorie list...
albutz/aoc-2022
src/day_1.py
day_1.py
py
1,360
python
en
code
0
github-code
36
13170391452
# this file exists to help tune the parameters of the stressor functions that put learners in different states # it doesn't make sense to put the same load on a Jetson Nano as on a raspberry pi. What would moderately inconvenience the Nano would completely cripple the pi # for this reason, we need to tune stressor para...
DuncanMays/multi_orchestrator_pl
tests/tune_stressors.py
tune_stressors.py
py
1,205
python
en
code
0
github-code
36
30771483937
import mysql.connector def search_item(table_name, records): config = { "host": "localhost", "user": "hr_manager", "password": "hrpass", "database": "hr_department" } try: conn = mysql.connector.connect(**config) cursor = conn.cursor() filtered_rec...
sacheex/Employee-Management-System
dbconnector/search.py
search.py
py
903
python
en
code
0
github-code
36
42578862241
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import importlib importlib.reload(sys) import time import requests import csv url = "https://rdap.registro.br/domain/" domains = ['stz.com.br', 'viasullogistica.com', 'eletronor.com', 'intelbras.com.br', 'bmlog.com.br', 'blueticket.com.br', ...
fiilipeneto/pandorasbox
Busca CNPJ.py
Busca CNPJ.py
py
1,758
python
en
code
0
github-code
36
9360611864
''' <sample input> 4 2 1 3 1 4 5 750 466 <sample output> 2 3 0 1 ''' def less_mod(a, s): return a // s def test01(): line_cnt = int(input('input count of line:')) numbers = [] for i in range(line_cnt): input_string = input('input two number (a, s):') numbers.append( input_string.spli...
maxmin93/my-pythons
coding_test/exam10.py
exam10.py
py
536
python
en
code
0
github-code
36
14696977373
import json import os.path as osp from typing import Union class Prompter(object): __slots__ = ("template", "_verbose") def __init__(self, template_name: str = "", verbose: bool = False): self._verbose = verbose if not template_name: template_name = "KoRAE_template" file_n...
gauss5930/KoRAE
finetuning/utils/prompter.py
prompter.py
py
1,553
python
en
code
0
github-code
36
938216382
import inspect import sys from chimpsetup.dependencies import InstallDependenciesCommand, TestDependenciesCommand from chimpsetup.versions import VersionsCommand def add_extra_tasks(): main_module = sys.modules['__main__'] setup_func = next((obj for name, obj in inspect.getmembers(main_module) if name == 'se...
chimpler/chimpsetup
chimpsetup/__init__.py
__init__.py
py
893
python
en
code
0
github-code
36
20219566108
import os from . import utils import ipywidgets as widgets from IPython.display import display, clear_output, Javascript class FileBrowser(object): def __init__(self, funcName): self.path = os.getcwd() self._update_files() self._chosenFileName = None self.funcName = funcName @p...
gudasergey/pyFitIt
pyfitit/fileBrowser.py
fileBrowser.py
py
2,642
python
en
code
28
github-code
36
44539221196
from flask import Flask, request, jsonify from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow import uuid app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///employees.db' db = SQLAlchemy(app) ma = Marshmallow(app) # Модель данных для сотрудника class Employee(db.M...
InKarno27/CRUD_on_Python
main.py
main.py
py
3,267
python
en
code
0
github-code
36
43724221141
class Card: number = "0000 0000 0000" validDate = "12/2025" holder = "unknown" def __init__(self, number, date, holder): self.number = number self.validDate = date self.holder = holder def pay(self, amount): print("С карты", self.number, "списано", amount)
ol557/skypro-aqa-homework
Lesson3_1/card.py
card.py
py
324
python
en
code
0
github-code
36
34356444247
# -*- coding: utf-8 -*- """ EE 511 Final Project """ import pandas as pd import numpy as np from numpy.random import default_rng """ # # https://towardsdatascience.com/3-simple-ways-to-handle-large-data-with-pandas-d9164a3c02c1 columns = ['Unnamed: 0', 'Unnamed: 0.1', 'date', 'year', 'month', 'day', 'author', 'titl...
Brandon-Yee/article-publisher-classifier
classifier.py
classifier.py
py
7,205
python
en
code
0
github-code
36
2863809841
import requests import lxml.etree import re session = requests.Session() response = session.get('http://www.baidu.com') content = response.content.decode() # print(content) # -------------解析 doc = lxml.etree.HTML(content) tree = doc.getroottree() nodes = tree.xpath('//title/text()') for i in nodes: print(i)
XiaJune/A-small
miller_cre/baidu.py
baidu.py
py
323
python
en
code
0
github-code
36
22861904779
import pandas as pd import datetime as dt from sodapy import Socrata from airflow.hooks.base_hook import BaseHook class Extract: chicago_crime_portal = "https://data.cityofchicago.org/resource/ijzp-q8t2.json" def __init__(self, start_time , end_time ) -> None: self.start_time = start_time self...
prabha-git/airflow
dags/chicago_crime_etl/extract.py
extract.py
py
1,041
python
en
code
0
github-code
36
73349162343
import pygame pygame.init() screen = pygame.display.set_mode((720, 480)) clock = pygame.time.Clock() FPS = 60 BLACK = (0, 0, 0) WHITE = (255, 255, 255) ballsurface = pygame.Surface((50,50)) ballsurface.set_colorkey((0,0,0)) pygame.draw.circle(ballsurface, (255,0,0), (25,25),25) ballsurface...
Tevvur/lab8
lab8(1).py
lab8(1).py
py
1,257
python
en
code
0
github-code
36
25863118859
import numpy as np import sys ITERATION_LIMIT = 100000 n = int(input('Ведите количество уравнений: ')) a =[] #print(a) b = [] e = float(input('Введите точность'))*10e-22 #rounding = len(e)-1 #n = int(input('Ведите количество уравнений: ')) for row in range(n): #for column in range(n): #aa = float(input('введ...
DeathNapalm/Courseach
nseidel.py
nseidel.py
py
1,850
python
ru
code
0
github-code
36
5953172719
try: from grove import grove_temperature_humidity_aht20 from grove.adc import ADC from gpiozero import DigitalOutputDevice import chainable_rgb_direct except: grove_temperature_humidity_aht20 = None ADC = None DigitalOutputDevice = None chainable_rgb_direct = None import random class Plant: def __ini...
Xermax3/ContainerFarm
Hardware/plant.py
plant.py
py
2,790
python
en
code
0
github-code
36
39783045715
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="diss-iamhectorotero", version="0.0.1", author="Hector Otero", author_email="7hector2@gmail.com", description="A package to train RNN in physical microworlds in a supervised or RL manner", ...
iamhectorotero/learning-physical-properties-with-rnns
libraries/setup.py
setup.py
py
702
python
en
code
4
github-code
36
6486766341
#ecret = 'pantofel' #haslo = 'tralala' #print "Secret -> "+ secret #print "haslo -> "+ haslo #for i in range (1, len(haslo) -1): print('podaj haslo: ') haslo = input() gwiazdki = (len(haslo) - 2) * "*" if len(haslo) == 0: print ('nie podano hasla') elif len(haslo) < 3: print ('za krotkie haslo') else: ...
koziolaga/nauka-pythona
haslo.py
haslo.py
py
517
python
en
code
0
github-code
36
30545491503
class WidgetBase: def __init__(self, sky_map_engine, alloc_space_spec): self.engine = sky_map_engine self.alloc_space_spec = alloc_space_spec self.x, self.y = None, None self.width, self.height = None, None def get_rect(self): return self.x, self.y, self.width, self.heig...
skybber/fchart3
fchart3/widget_base.py
widget_base.py
py
1,087
python
en
code
9
github-code
36
20858190937
#https://leetcode.com/problems/search-suggestions-system/ class Solution: def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]: ans=[] for i in range(0,len(searchWord)): x=searchWord[0:i+1] #print(x) ...
manu-karenite/Problem-Solving
Strings/searchSuggestionsSytem.py
searchSuggestionsSytem.py
py
706
python
en
code
0
github-code
36
3460979087
import pickle import os from bs4 import BeautifulSoup from numpy import vectorize import spacy import unidecode from word2number import w2n import os import pickle #import contractions nlp = spacy.load('en_core_web_lg') # exclude words from spacy stopwords list deselect_stop_words = ['no', 'not'] for w in deselect_st...
abde0103/H-index-prediction
Code/PreprocessingAndGetIndices.py
PreprocessingAndGetIndices.py
py
4,195
python
en
code
0
github-code
36
74330392745
# How to detect specific color inside python # from cv2 import getTrackbarPos import numpy as np import cv2 as cv # img=cv.imread("resources/image.png") # Convert in HSV (Hue, Saturation, Value) # hue_img=cv.cvtColor(img,cv.COLOR_BGR2HSV)#rang barangi sakal my chla gye ga jb show kary gye def slider(): ...
amirasghar123/Opencv-vision
20_chptr.py
20_chptr.py
py
1,970
python
en
code
0
github-code
36
32065161333
import random from django.shortcuts import render , redirect , get_object_or_404 from django.http import HttpResponse from django.contrib.auth.models import User , auth from django.contrib import messages from .models import Profile, Post, Likepost, FollowersCount , Notification , Comment from django.contrib.auth.decor...
ahmedradwan21/ATR_Social
core/views.py
views.py
py
13,622
python
en
code
2
github-code
36
1243434549
""" uncertainty_analysis.py ========================================= Python script that performs uncertainty analysis on profile estimation. """ import time import pandas as pd import numpy as np from src.instance import Instance from src.optimization_profile_time import ProfileOptTime from scipy.stats import dirichl...
carolinetjes/CFRrecruitment
uncertainty_analysis.py
uncertainty_analysis.py
py
4,391
python
en
code
0
github-code
36
36635713373
""" Practice of implementing Linked Lists in Python. Creates a Singly Linked List with following properties and functions: LinkedList has one property "head" which points to the head of the list Node has two properties, "data" which stores the data in the node, and "next" which points to the next node in the linked li...
subratacharya99/Data-Structures
linkedlist.py
linkedlist.py
py
6,903
python
en
code
0
github-code
36
12382043913
from math import sin def sin_calculator(x): return sin(x) / x def main(): for i in [x / 2 for x in range(-6, 7, 1)]: try: print(sin_calculator(i)) except: print('>>>>>>>>>>>Pas possible avec 0.0') if __name__ == '__main__': main()
laiduy98/prog-av-tp
TP3/sintest.py
sintest.py
py
289
python
en
code
0
github-code
36
43300161534
"""Implements the core parts of flow graph creation. """ import sys import collections import types import __builtin__ from rpython.tool.error import source_lines from rpython.rlib import rstackovf from rpython.flowspace.argument import CallSpec from rpython.flowspace.model import (Constant, Variable, Block, Link, ...
mozillazg/pypy
rpython/flowspace/flowcontext.py
flowcontext.py
py
45,650
python
en
code
430
github-code
36
36956014429
from helper_tiered import TieredConfigMixin, gen_tiered_storage_sources from wtscenario import make_scenarios import errno, filecmp, os, time, shutil, wiredtiger, wttest # Return a boolean string that is acceptable for WT configuration. def wt_boolean(b): if b: return "true" else: return "false...
mongodb/mongo
src/third_party/wiredtiger/test/suite/test_tiered20.py
test_tiered20.py
py
8,178
python
en
code
24,670
github-code
36
29588206743
#coding:utf-8 import unittest class SelfConfigDict(dict): def __init__(self,*args,**kwargs): self._meta={} self._onchange=lambda key,value:None if args or kwargs: self.update(*args,**kwargs) def update(self,*args,**kwargs): if args: try_prefix=args[...
chen19901225/SimplePyCode
SimpleCode/SelfImplement/ceshi-file.py
ceshi-file.py
py
3,587
python
en
code
0
github-code
36
13990583368
""" While the previous DFS approach works, it can potentially traverse long sections of the graph without a real need. In order to improve further, we can leverage the previously ignored properties of the similar relation: it is an equivalence relation. Equivalence relations bring a natural partition to the set, where...
dariomx/topcoder-srm
leetcode/zero-pass/google/sentence-similarity-ii/Solution1.py
Solution1.py
py
2,622
python
en
code
0
github-code
36
17092858056
''' Cosmic1 will be equipped with High Tech COM hardware and use modern protocols to transfer Audio and video. If Emergency occurs will be fallback to traditional low energy, low tech Simplex Radio communication with Morse Code via terminal in hexadecimal codes 00-ff. !!! WARNING RUN THRU TERMINAL PROGRAM NOT PYCHAR...
fortisauris/Cosmic1
comms/EMERGENCY_Morse_HEXCode.py
EMERGENCY_Morse_HEXCode.py
py
2,254
python
en
code
0
github-code
36
18207798589
from math import sqrt, asin, atan, pi, inf, radians, sin, cos, atan2 A = 6378137 B = 6356752.314245 e2 = 1 - B * B / (A * A) f = 1 - B / A def cart2lle(x, y, z): r = sqrt(x ** 2 + y ** 2 + z ** 2) lon = atan(y / x if x != 0 else inf) if x < 0 and y >= 0: lon += pi if x < 0 and y < 0: ...
jonathanblade/gampy
gampy/utils/coord.py
coord.py
py
1,256
python
en
code
1
github-code
36
22755402141
import privateConfig from selenium.webdriver.chrome.options import Options URL_PISOS = "https://www.pisos.com" URL_PLACE = "/venta/pisos-esparreguera/" URL_LOG_IN = "https://www.pisos.com/Login" USER_PISOS = "informe.casas@gmail.com" PW_PISOS = "17InformeCasas" USER_MAIL = "informe.casas@gmail.com" PW_MAIL = "17Info...
paucampana/pisosScrapper
app/src/config.py
config.py
py
1,095
python
en
code
1
github-code
36
26946887509
import numpy as np import rogues import scipy.linalg as sl def condex(n, k=4, theta=100): """ CONDEX `Counterexamples' to matrix condition number estimators. CONDEX(N, K, THETA) is a `counterexample' matrix to a condition estimator. It has order N and scalar parameter THETA (default 100)....
macd/rogues
rogues/matrices/condex.py
condex.py
py
2,556
python
en
code
16
github-code
36
6172682101
import time from turtle import Screen from player import Player from car_manager import CarManager from scoreboard import Scoreboard screen = Screen() screen.setup(width=600, height=600) screen.tracer(0) tim = Player() car = CarManager() score = Scoreboard() screen.listen() screen.onkeypress(tim.move,"Up") make_car...
qkrwldns/turtle_crossing
turtle-crossing-start/main.py
main.py
py
795
python
en
code
0
github-code
36
74267315625
# -*- coding: utf-8 -*- # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
line/line-bot-sdk-python
linebot/models/recipient.py
recipient.py
py
2,083
python
en
code
1,739
github-code
36
995230871
# Authors: Antoine Ginies <aginies@suse.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distri...
aginies/virt-scenario
src/virtscenario/configuration.py
configuration.py
py
22,528
python
en
code
5
github-code
36
12813950306
# 연구소 import sys from itertools import combinations from collections import deque import copy input = sys.stdin.readline N,M = map(int,input().split()) board = [] for i in range(N): board.append(list(map(int,input().split()))) virus = [] comb = [] for i in range(N): for j in range(M): if board[i][j] =...
Girin7716/PythonCoding
Etc/PS/Q16.py
Q16.py
py
1,217
python
en
code
1
github-code
36
74642998183
# -*- coding: utf-8 -*- """ @author: Florian Koch @license: All rights reserved """ import pandas as pd import json with open('../../data/city_of_zurich/aussichtspunkt.json') as data_file: data = json.load(data_file) df = pd.io.json.json_normalize(data, ['features', ['geometry', 'coordinates']],['name', ['features...
limo1996/ETH-DataScience
src/preprocess/aussichtspunkt.py
aussichtspunkt.py
py
646
python
en
code
0
github-code
36
31541638918
import os from setuptools import setup def read_project_file(path): proj_dir = os.path.dirname(__file__) path = os.path.join(proj_dir, path) with open(path, 'r') as f: return f.read() setup( name = 'pyronic', version = '0.1.1', description = 'Suppress command output on success', lo...
JonathonReinhart/pyronic
setup.py
setup.py
py
936
python
en
code
0
github-code
36
38716436502
#!/usr/bin/env python3 import re from collections import defaultdict from pprint import pprint allergen_sets = defaultdict(list) # allergen => list of sets of foods with open('input.txt', 'r') as infile: line_re = re.compile(r'((\w+\s+)+)\(contains(.*)\)') for line in infile: m = line_re.match(line) ...
lvaughn/advent
2020/21/food_list_2.py
food_list_2.py
py
1,264
python
en
code
1
github-code
36
17849208142
import torch import torch.nn as nn from prodict import Prodict class ODEFunc(nn.Module): def __init__(self, dims: Prodict, device: str = torch.device("cpu")): """The Neural ODE decoder Module of TDNODE. Neural network function that considers as input a tumor state and p-dimensional parameter encod...
jameslu01/TDNODE
src/model/SLD/ode_func.py
ode_func.py
py
3,303
python
en
code
0
github-code
36
25970215922
from tkinter import * # Creates a colored Button in containerWidget, at position (row, column) of the Grid with sticky option # and returns the reference to that button: def create_coloredbutton_grid(containerwidget, row, column, color, sticky): button = Button(containerwidget, bg=color) button.grid(row=row, ...
Povaz/MHWIceborneCalculator
utils.py
utils.py
py
1,941
python
en
code
1
github-code
36
70955301864
"""Add description for 15 puzzle Revision ID: bdeb38c37fg1 Revises: 05923bad79cf Create Date: 2020-10-23 14:23:00.123969 """ from sqlalchemy.sql import table, column from sqlalchemy import String from alembic import op # revision identifiers, used by Alembic. revision = 'bdeb38c37fg1' down_revision = '05923bad79cf' ...
euphwes/cubers.io
migrations/versions/047_bdeb38c37fg1_add_desc_to_15_puzzle.py
047_bdeb38c37fg1_add_desc_to_15_puzzle.py
py
1,041
python
en
code
27
github-code
36
32413559312
import abc from typing import Callable, Dict, List, Optional, Union import torch import torchmetrics from pytorch_lightning import LightningModule, Trainer from pytorch_lightning.loggers.logger import Logger from torch.utils.data import DataLoader, Dataset from renate import defaults from renate.data.datasets import ...
awslabs/Renate
src/renate/evaluation/evaluator.py
evaluator.py
py
7,525
python
en
code
251
github-code
36
3110630730
""" Creator: Dhruuv Agarwal Github: Dhr11 """ import os import numpy as np import torch import torch.nn as nn from torch.utils import data from tqdm import tqdm from Voc_loader import VOCLoader from Unet_model import Unet from metrics import custom_conf_matrix def train(): device = torch.device("cuda" if tor...
Dhr11/Semantic_Segmentation
Main_src.py
Main_src.py
py
3,992
python
en
code
2
github-code
36
16969152957
# -*- coding: utf-8 -*- from jsonfield.fields import JSONField from natasha import ( Segmenter, MorphVocab, MoneyExtractor, NamesExtractor, NewsEmbedding, NewsMorphTagger, NewsSyntaxParser, NewsNERTagger, PER, LOC, ORG ) from natasha.grammars.date import Date, MONTHS, MO...
infolabs/django-edw
backend/edw/models/mixins/nlp/ner.py
ner.py
py
9,781
python
ru
code
6
github-code
36
24614073845
import requests # for api calls import time # for converting epoch to timedate format import pprint as pp # for debugging def convert_epoch_to_datetime(epoch): return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(epoch)) def get_news(ticker, startDate, endDate): """ Purpose: Get a list of news ur...
ajsalagundi/Stock_Intelligence
data_application/web_scrapers/news_articles_retriever.py
news_articles_retriever.py
py
1,137
python
en
code
0
github-code
36
40805356005
from analyzer.Builds import Build from analyzer.Repository.TestRepo import TestRepo def test_constructor(): empty_dirs = [ "directory/", "path/to/directory/" ] existing_paths = [ "path/to/file", "path/to/other/file" ] other_repo_type = 'other' path = "usernam...
FreekDS/CIAN
tests/Repository/test_TestRepo.py
test_TestRepo.py
py
2,015
python
en
code
1
github-code
36
8436688323
import time def timer(func): def wrapper(*args, **kwargs): start_time = time.time() val = func(*args, **kwargs) print(time.time()-start_time) return val return wrapper def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) def fib2(n): if dp[n] != -1...
kashyapa/coding-problems
april-22/dp.py
dp.py
py
6,462
python
en
code
0
github-code
36
40027566811
import cv2 import os import imutils import time import numpy as np from matplotlib import pyplot as plt MODEL_MEAN_VALUES = (78.4263377603, 87.7689143744, 114.895847746) age_list = [ '(0, 2)', '(4, 6)', '(8, 12)', '(15, 20)', '(25, 32)', '(38, 43)', '(48, 53)', '(60, 100)' ] gender_list = ['Male', 'Female'] ...
cNille/Agender
prediction.py
prediction.py
py
2,143
python
en
code
0
github-code
36
73969955624
import torch from torch import nn import torch.nn.functional as F from onerl.networks.norm_layer import normalization_layer class PreactResBlock(nn.Module): def __init__(self, in_channels: int, out_channels: int, stride: int, norm_type: str, ...
imoneoi/onerl
onerl/networks/resnet.py
resnet.py
py
2,604
python
en
code
16
github-code
36
43090387357
import sys def func(a): ret = 0 if a == 1: ret = a else: ret = a + func(a - 1) return ret if __name__ == "__main__": result = func(int(sys.argv[1])) print(result)
kensakamoto/playground
C/SystemProgramming/stack_overflow.py
stack_overflow.py
py
207
python
en
code
0
github-code
36
12829616868
import tkinter as tk from tkinter.ttk import Progressbar from tkinter import ttk root = tk.Tk() root.title("Progressbar") root.geometry('300x200') style = ttk.Style() style.theme_use('default') style.configure("black.Horizontal.TProgressbar", background='green') bar = Progressbar(root, length=220, style='black.Horizont...
WHATSINYOURMIND/1nothing
Python Qb/tkinter/q_34.py
q_34.py
py
398
python
en
code
0
github-code
36
18831138683
# Representation du fonctionnement du T9 comme on peut trouver dans les anciens portables t9="22233344455566677778889999" # abcdefghijklmnopqrstuvwxyz les corresppondances # conversion d'une lettre dans le chiffre associe def lettre_to_chiffre(x): # On verifie que c'est bien une lettre definie dans le codage ...
AntoineCanda/Python_and_algo
chaine_caracteres/t9.py
t9.py
py
1,666
python
fr
code
0
github-code
36
24492496700
# This problem was asked by Uber. # Given an array of integers, return a new array such that each element at index i of the new array # is the product of all the numbers in the original array except the one at i. # For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. # I...
tanucdi/dailycodingproblem
5DaysCodingProblem/Problem#2 return new array in which product of all the numbers in the original array except the one at i.py
Problem#2 return new array in which product of all the numbers in the original array except the one at i.py
py
586
python
en
code
1
github-code
36
13987172448
class Solution: def partition(self, head: ListNode, x: int) -> ListNode: lt_head = ListNode(None) lt_tail = lt_head ge_head = ListNode(None) ge_tail = ge_head node = head while node: if node.val < x: lt_tail.next = node lt_t...
dariomx/topcoder-srm
leetcode/first-pass/amazon/partition-list/Solution.py
Solution.py
py
560
python
en
code
0
github-code
36
16164485348
# Created on 2022/10/13 # By Suman Regmi # Syntax of for loop in Python # for i in range (Initial value,final balue,size) # range(X) denotes initial value as 0 and ending vaulue as X. sum = 0 number = int(input("Enter the number\n")) # Here initial value is 0 and final value is value of number. for i in ra...
LimitlessPlaying/PYTHON
08_Sum_of_Digits_of_given_number.py
08_Sum_of_Digits_of_given_number.py
py
455
python
en
code
0
github-code
36
19836728090
def days_to_units(num_of_days, conversion_unit): if conversion_unit == "hours": return f"{num_of_days} days are {num_of_days * 24} hours" elif conversion_unit == "minutes": return f"{num_of_days} days are {num_of_days * 24 * 60} minutes" else: return "Unsupported unit" def validate_...
JClishe/code-snips
Python/Python Tutorial - TechWorld with Nana/ModulesHelper.py
ModulesHelper.py
py
1,112
python
en
code
0
github-code
36
938560702
import json import jieba import os import argparse frequency = {} word2id = {"PAD": 0, "UNK": 1} min_freq = 10 def cut(s): arr = list(jieba.cut(s)) for word in arr: if word not in frequency: frequency[word] = 0 frequency[word] += 1 return arr if __name__ == "__main__": ...
china-ai-law-challenge/CAIL2020
sfks/baseline/utils/cutter.py
cutter.py
py
1,406
python
en
code
150
github-code
36
4480053305
import pandas as pd raw_data = pd.read_csv("2018_Central_Park_Squirrel_Census_-_Squirrel_Data.csv") new_data = raw_data["Primary Fur Color"].value_counts().rename_axis('Fur Color').reset_index(name='Quantity') new_data.to_csv("squirrels_colors_count.csv") print(new_data) # # # data = pd.read_csv("weather_data.csv") ...
montekrist0/PythonBootCamp
day25/main.py
main.py
py
1,037
python
en
code
0
github-code
36
4965329236
from settings.database import get_all_resumes, add, clear_table from settings.config import ProfessionStep, ResumeGroup from settings.tools import group_steps_to_resume import locale from typing import NamedTuple from operator import attrgetter from datetime import datetime, date from rich.progress import track ...
SalomanYu/Trajectory
test.py
test.py
py
3,493
python
ru
code
1
github-code
36
19416762509
from check_your_heuristic.dataset.ReCoRDDataset import ReCoRDDataset from check_your_heuristic.heuristics.Heuristic import BaseHeuristicSolver from typing import Dict, Any, List import pandas as pd import string import numpy as np import logging class ReCoRDHeuristics(BaseHeuristicSolver): def __init__(self, conf...
tatiana-iazykova/check_your_heuristic
check_your_heuristic/heuristics/ReCoRDHeuristics.py
ReCoRDHeuristics.py
py
7,723
python
en
code
0
github-code
36
8201792049
import tkinter import pandas import random import time BACKGROUND_COLOR = "#B1DDC6" def change_card(): global new_card new_card = random.choice(revision_dict) canvas.itemconfig(image, image=card_front_image) canvas.itemconfig(language, text="French", fill="black") canvas.itemconfig(word, text=ne...
TheoMullen/Flashcard-application
main.py
main.py
py
2,062
python
en
code
0
github-code
36
19698435188
import numpy as np from numpy import ma import matplotlib.pyplot as plt import matplotlib.patches as mp from matplotlib.collections import PatchCollection m_s = 4 m_e = 1 x_s, y_s = 0, 0 x_e, y_e = 2, 0 x_c, y_c = (m_s*x_s+m_e*x_e)/(m_s+m_e), (m_s*y_s+m_e*y_e)/(m_s+m_e) gamma = 1.0 x = np.linspace(-2.5, 4, 1000) y = ...
JakeI/PlaneteSimulator
LagrangePoints/lagrangePoints.py
lagrangePoints.py
py
2,767
python
en
code
1
github-code
36
11025748669
"""user token nonce Revision ID: 71503b29c05a Revises: aac9a548d9f5 Create Date: 2018-05-04 13:42:42.222974 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '71503b29c05a' down_revision = 'aac9a548d9f5' branch_labels = None depends_on = None def upgrade(): ...
akahard2dj/Blackberry
migrations/versions/71503b29c05a_user_token_nonce.py
71503b29c05a_user_token_nonce.py
py
661
python
en
code
0
github-code
36
25916668621
# review last week # operators # logical # variable names - no spaces! # who did math homework? # quiz: apples cost $1 and oranges cost $1.50 # create a variable for apples and one for oranges # calculate the cost of 5 apples and 3 oranges # how many oranges can you buy for $9? for $10? ## New print("Hello world") #...
dlebauer/intro-python
lesson_2.py
lesson_2.py
py
1,340
python
en
code
1
github-code
36
73391053864
from gym import spaces from gym import Env import numpy as np from pathlib import Path from PIL import Image from gym.utils import seeding from spg.view import TopDownView import arcade from spg.playground import Playground, Room from spg.playground.collision_handlers import get_colliding_entities from spg.utils.defi...
aomerCS/IN3007
gym_env/envs/perturbation_world.py
perturbation_world.py
py
6,057
python
en
code
0
github-code
36
27252447369
#!/usr/bin/python """ Adam Kavka and Levi Melnick December 2014 This runs the SVM program (a third party C program) on the features sets that script.py and testGensim.py wrote to disk. """ import utility as u import os from permute import permute m=u.getUndisputedFederalistMatrix() d=u.getDisputedFederalistMatr...
akavka/federalistPapers
runsvm.py
runsvm.py
py
758
python
en
code
0
github-code
36
29264153109
from threading import Thread, Lock import random from time import sleep posti_liberi = 12#posti liberi nel parcheggio mutex = Lock()#dichiaro il mutex class auto(Thread):#classe del thread dell'auto def __init__(self, id): Thread.__init__(self)#iniziaizzo il thread self.id = id#ogni ma...
albiserra/TPSIT_python
serra_parcheggio_1.py
serra_parcheggio_1.py
py
1,502
python
it
code
0
github-code
36
31063781935
from ..utils import Object class MessageForwardInfo(Object): """ Contains information about a forwarded message Attributes: ID (:obj:`str`): ``MessageForwardInfo`` Args: origin (:class:`telegram.api.types.MessageForwardOrigin`): Origin of a forwarded message dat...
iTeam-co/pytglib
pytglib/api/types/message_forward_info.py
message_forward_info.py
py
2,080
python
en
code
20
github-code
36
23992985122
''' 542. 01 Matrix https://leetcode.com/problems/01-matrix/ ''' from collections import defaultdict, deque from typing import List # Approach 1: BFS from '1' columns to '0' # The problem is we do BFS for 1, which is sub-optimal class Solution: def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]: ...
asset311/leetcode
bfs/01_matrix.py
01_matrix.py
py
2,531
python
en
code
0
github-code
36
22057061997
import pandas as pd import helper import weaviate # initiate the Weaviate client client = weaviate.Client("http://localhost:8080") client.timeout_config = (3, 200) # empty schema and create new schema client.schema.delete_all() schema = { "classes": [ { "class": "Wine", "properties...
weaviate/weaviate-examples
semanticsearch-transformers-wines/import.py
import.py
py
2,091
python
en
code
253
github-code
36
34412858831
from turtle import Turtle, Screen turtle = Turtle() screen = Screen() screen.colormode(255) turtle.speed(0) turtle.width(5) R = 255 G = 1 B = 1 screen.bgcolor((255, 255, 255)) for i in range(5000): G += 0.5 B += 0.5 #R -= 1 turtle.color((int(R % 255), int(G % 255), int(B % 255))) turtle.forward(i) turt...
denorlov/turtle
08_spirals_color/color_increase.py
color_increase.py
py
332
python
en
code
0
github-code
36
24582436849
from system.core.controller import * import time, requests from math import * class Events(Controller): def __init__(self, action): super(Events, self).__init__(action) self.load_model('User') self.load_model('Location') self.load_model('Event') self.db = self._app.db ...
MoralesJohn/rumbler_chasers
app/controllers/Events.py
Events.py
py
2,381
python
en
code
0
github-code
36
6862212397
# Utilities ############################################################################ # Imports from sklearn.metrics.pairwise import cosine_similarity import numpy as np import pickle ############################################################################ # Function to read the embedding_dataset from...
TuvalZit/Capstone-Project-23-1-R-18
GUI/Backend/GetEmbedding.py
GetEmbedding.py
py
1,878
python
en
code
0
github-code
36
36033282554
""" Utility functions Some of them will probably be useless """ import numpy as np def pascal_triangle(n): # Returns the pascal triangle, T[n,k] is n choose k T = np.zeros((n + 1, n + 1), dtype=np.int64) T[0, 0] = 1 for i in range(1, n + 1): T[i, 0] = 1 T[i, i] = 1 for j in ra...
HugoPasse/PI-Kimono
src/utils/proba_utils.py
proba_utils.py
py
1,312
python
en
code
0
github-code
36
26285045448
from functools import wraps from . import database as db from .reddit import user_exists, subreddit_exists from sqlalchemy.exc import IntegrityError from . import constants as c from .template import get_template from .utils import message_url from sqlalchemy.orm import joinedload _COMMANDS = {} _MENTION_COMMANDS = {...
necessary129/InformsYouBot
InformsYouBot/commands.py
commands.py
py
6,941
python
en
code
0
github-code
36
18736574490
from django import forms from ..contrib.sysdate import dateFromLocal class DateBigInput(forms.DateInput): def value_from_datadict(self, data, files, name): valData = super().value_from_datadict(data, files, name) return dateFromLocal(valData) def get_context(self, name, value, attrs): ...
MindKafuu/demo
demoWeb/extends/formext.py
formext.py
py
4,630
python
en
code
0
github-code
36
36127494424
from fastapi import FastAPI, Path from typing import Optional from pydantic import BaseModel class Item(BaseModel): name: str price: float color: Optional[str] = None inventory = { 1: { 'name': 'Milk', 'price': 3.99, 'color': 'white' } } app = FastAPI() @app.get('/') asy...
Kelvingandhi/kafka_sample
test_main.py
test_main.py
py
761
python
en
code
2
github-code
36
22565259557
class TrieNode: def __init__(self): self.is_end = False self.count = 0 self.children = {} class Solution: def __init__(self): self.root = TrieNode() def insert(self, word: str) -> None: current = self.root for char in word: if char not in curren...
miedan/competetive-programming
sum-of-prefix-scores-of-strings.py
sum-of-prefix-scores-of-strings.py
py
1,072
python
en
code
0
github-code
36
69846477224
import logging from random import randint from time import sleep from typing import List import pandas as pd import requests # type: ignore from models.auction import Lot, Lots from models.item import Item, Items from models.media import Media, Medias from scrape.item_scraper import ItemScraper from scrape.lot_scrape...
lassebenni/scraper-wow-auctionhouse
scrape/auction_scraper.py
auction_scraper.py
py
4,503
python
en
code
0
github-code
36
20614874987
#!/usr/bin/env python # coding: utf-8 # # Computer Science Refresher Project 1 # # ## Description # # The problem given was the following : we want to set up an indoor location system, like an indoor GPS. In this project we will focus on computing the error of detection of the position of a moving object. Thus, we h...
nzotto/CSRefresh_Project
trajectory_error/solution.py
solution.py
py
13,482
python
en
code
0
github-code
36
70631472744
from unittest import TestCase from reverse_linked_list_ii import * class TestSolution(TestCase): def test_reverse_between(self): ln1 = list_to_node([1, 2, 3, 4, 5]) ln2 = list_to_node([3, 5]) inputs = ((ln1, 2, 4), (ln2, 1, 1)) outs = ([1, 4, 3, 2, 5], [3, 5]) for inp, out...
sswest/leetcode
92_reverse_linked_list_ii/test_reverse_linked_list_ii.py
test_reverse_linked_list_ii.py
py
452
python
en
code
0
github-code
36
43506809963
import numpy as np import csv import os import cv2 import matplotlib.pyplot as plt from xml.etree import ElementTree as ET import argparse parser = argparse.ArgumentParser(description='compare mediapipe and kinect skeleton data', epilog = 'Enjoy the program! :)') parser.add_argument('--inputfile', default =...
elma1294/Neuroinformatic
Mediapipe/3Dto2D.py
3Dto2D.py
py
5,279
python
en
code
1
github-code
36
29981196912
# Example: echo server, using StreamServer import logging import argparse from gruvi import get_hub, util from gruvi.stream import StreamServer logging.basicConfig() parser = argparse.ArgumentParser() parser.add_argument('port', type=int) args = parser.parse_args() def echo_handler(stream, protocol, client): p...
cocagne/gruvi
examples/echoserver1.py
echoserver1.py
py
667
python
en
code
null
github-code
36
14505653809
import os import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader import torchvision as tv from time import time from src.model.madry_model import WideResNet from src.attack import FastGradientSignUntargeted from src.utils import makedirs, create_logger, tensor2cuda,...
ylsung/pytorch-adversarial-training
cifar-10/main.py
main.py
py
9,835
python
en
code
230
github-code
36
3315546924
import nltk def nouns_transform(sentence): tokenized = nltk.word_tokenize(sentence) def is_noun (pos): return pos[:2] == 'NN' return [word for (word, pos) in nltk.pos_tag(tokenized) if is_noun(pos)] def render_template(template_name='html pages/home.html', context={}): html_str = "" wit...
valya007/junior_technical_test
webapp.py
webapp.py
py
1,171
python
en
code
0
github-code
36
75174472104
# task 2.1 import numpy as np # 1.Write a NumPy program to convert a list of numeric values into a one-dimensional NumPy array. l = [6.3, -3.45, 10542, 39.3] arr = np.array(l) print(arr) # 2.Write a NumPy program to create a NumPy array with values ranging from 2 to 10. arr = np.arange(2, 11) print(arr) # 3.Write ...
ArmineHovhannisyan/Python-Introduction-to-Data-Science
src/second_month/task_2_1.py
task_2_1.py
py
721
python
en
code
0
github-code
36
28700017158
#aoc20150101 import pathlib import sys def parse(path): return list(pathlib.Path(path).read_text()) def solve(puzzleInput): finalFloor = 0 for datum in puzzleInput: if datum == '(': finalFloor += 1 else: finalFloor -= 1 return finalFloor if __name__ == "__main__": for path in sys.ar...
dbm19/aoc2015
aoc201501/aoc20150101.py
aoc20150101.py
py
401
python
en
code
0
github-code
36
71713008103
import os import time from dotenv import dotenv_values from selenium import webdriver from selenium.webdriver import Chrome from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.service import Service from utilities.commons.exceptions import DriverSetupFailedException from utilities.co...
HarshDevSingh/python-behave
environment.py
environment.py
py
4,291
python
en
code
0
github-code
36
9173707874
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ from the month of edge deletion, find the SR before, at the time and after """ from collections import defaultdict import codecs import os import json import numpy as np IN_DIR = "../../../DATA/General/MO_MENT_networks" os.chdir(IN_DIR) F_IN = "mention_edges_monthly_...
sanja7s/SR_Twitter
src_graph/create_MO_MENT_networks.py
create_MO_MENT_networks.py
py
1,146
python
en
code
0
github-code
36
33092752191
from match.models import Match # Yes, I'm aware this isn't really the best way of doing this. class Gateway: def update_match(self, id, payload): try: match = Match.objects.get(pk=id) match_fields = [f.name for f in Match._meta._get_fields()] for field, value in payload...
KarlaRocha/evient-edu-back
use_cases/update_match/gateway.py
gateway.py
py
554
python
en
code
0
github-code
36