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
73819292265
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import enum import logging from logging import StreamHandler handler = StreamHandler() logger = logging.getLogger(__name__) class Level(enum.Enum): FATAL = logging.FATAL ERROR = logging.ERROR WARN = logging.WARN INFO = logging.INFO DEBUG = logging.D...
ujiro99/auto_logger
logger/log.py
log.py
py
2,655
python
en
code
0
github-code
36
40735068929
import numpy as np from plotfit import plotLineReg, plotPoints def approxD2(f, x_0, h): return (f(x_0+h) - 2*f(x_0) + f(x_0-h))/(h*h) def approxD2iter(f, x_0, h, tol, maxiters): iters = 0 err = 10*tol a = x_0 appxList = [] while(err>tol and iters<maxiters): b = approxD2(f, x_0, h) ...
DryToaster/ComputationalMath
src/derive.py
derive.py
py
852
python
en
code
0
github-code
36
15476854005
from __future__ import division, print_function, absolute_import import os import pytest import hypothesis from hypothesis.errors import InvalidArgument from hypothesis.database import ExampleDatabase from hypothesis._settings import settings, Verbosity def test_has_docstrings(): assert settings.verbosity.__do...
LyleH/hypothesis-python_1
tests/cover/test_settings.py
test_settings.py
py
4,182
python
en
code
1
github-code
36
16172861853
""" Сравнивает два списка. Возвращает в виде списка результаты сравнения элементов: 1 - если l1[n] и l1[n] - буквы одного регистра; 0 - если l1[n] и l1[n] - буквы разных регистра; -1 - если l1[n] или l1[n] - не бунвы """ def same(l1, l2): li = [] for i in range(0, len(l1)): if l1[i].isalpha() and l2[i...
genievy/codewars
same_case.py
same_case.py
py
743
python
ru
code
0
github-code
36
10140994218
from django.urls import reverse def reverse_querystring(view, urlconf=None, args=None, kwargs=None, current_app=None, query_kwargs=None): """Custom reverse to handle query strings. Usage: reverse_querystring('app.views.my_view', kwargs={'pk': 123}, query_kwargs={'search': 'Bob'}) for multival...
chiemerieezechukwu/django-api
core/utils/reverse_with_query_string.py
reverse_with_query_string.py
py
930
python
en
code
0
github-code
36
34754881507
N = int(input()) arr = [list(map(int, input().split())) for _ in range(N)] Max = 0 def dfs(day,total): global Max if day == N: Max = max(Max, total) return if day+arr[day][0]<=N: dfs(day+arr[day][0],total+arr[day][1]) dfs(day+1,total) for i in range(N): dfs(i,...
dwkim8155/Algorithm
Algorithm/DFS/[BOJ] 14501 Sliver3 퇴사.py
[BOJ] 14501 Sliver3 퇴사.py
py
333
python
en
code
1
github-code
36
37059041423
"""Function which calculates how positive a website's content is. Scores usually range between -10 and +10""" import requests from bs4 import BeautifulSoup as bs from afinn import Afinn from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer def sentiment_analyze(url): """calculates a website's posit...
mihailthebuilder/news-sentiment
sentiment.py
sentiment.py
py
4,072
python
en
code
0
github-code
36
20254710953
print("BMI calculator:-") h = input("What is your height in m : ") w = input("What is your weight in kg : ") h1 = float(h) w1 = float(w) bmi1 = w1/ h1**2 bmi2 = float(bmi1) bmi= round(bmi2, 2) if bmi <= 18 : print("you are under waeight",bmi) elif bmi <= 24: print("you are normal weight",bmi) elif bmi <= 30: ...
Mr-Pankuu/snoopy
Day_3/bmiindex.py
bmiindex.py
py
462
python
en
code
0
github-code
36
71683730983
import argparse import datetime import os import socket import sys from time import sleep # espa-processing imports import config import parameters import processor import settings import sensor import utilities from api_interface import APIServer from logging_tools import (EspaLogging, get_base_logger, get_stdout_h...
djzelenak/espa-worker
processing/main.py
main.py
py
8,666
python
en
code
0
github-code
36
40657010510
import tensorflow as tf import numpy as np import scipy import time import math import argparse import random import sys import os import matplotlib.pyplot as plt from termcolor import colored, cprint # from Kuhn_Munkres import KM # from BN16 import BatchNormalizationF16 from time import gmtime, strf...
betairylia/NNParticles
model_graph.py
model_graph.py
py
87,989
python
en
code
0
github-code
36
15593091597
# den här funktionen ger dig möjlighet att välja vilken biom du vill spela spelet i def biomer(): try: print(""" <-------------> 1.Mountain,N 2.Desert,S 3.Jungle,E 4.Plains,W <-------------> """) choosebiom=int(input("\nChoose a diracti...
xXwilson2005Xx/python-projekt
biom.py
biom.py
py
1,032
python
en
code
0
github-code
36
71952062185
def longestCommonPrefix(strs): s1 = '' s = strs[0] k=0 for i in range(len(s)): match = s[:k + 1] c = 1 for j in range(1, len(strs)): s2=strs[j] if match == s2[:k+1]: c += 1 if c == len(strs): s1=match ...
Exile404/LeetCode
LEETCODE_Longest-common-prefix.py
LEETCODE_Longest-common-prefix.py
py
415
python
en
code
2
github-code
36
30647725108
#! /usr/bin/python2 # coding=utf-8 import socket clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) hostName = clientSocket.getsockname() serverIP = "127.0.0.1" port = 8888 clientSocket.connect((serverIP, port)) while True: mess = "hello" # clientSocket.send(mess.encode()) #发送一条信息 python3 ...
Hsurpass/ElegantTest
test_python/python2/netProgramming/client.py
client.py
py
465
python
en
code
0
github-code
36
73123502184
from udb.controller.tests import WebCase class TestApp(WebCase): def test_index(self): # Given the application is started # When making a query to index page self.getPage('/') # Then an html page is returned self.assertStatus(303) self.assertHeaderItemValue("Locatio...
ikus060/udb
src/udb/controller/tests/test_index_page.py
test_index_page.py
py
354
python
en
code
0
github-code
36
6164265087
from random import Random, choice import math MAX_LEVELS = 4 HERIDITARY_WEIGHT = 0 MUTATED_WEIGHT = 1 random_negative = Random().randint(-1,1) ran = Random() def shouldMutate(random_num,mutate_range): (low,high) = mutate_range return low < random_num < high def genRandomBiotGene(): gene = { ...
elstupido/primlife
src/biots/genes.py
genes.py
py
5,842
python
en
code
4
github-code
36
74928715303
# Derived from https://github.com/greenelab/deep-review/blob/75f2dd8c61099a17235a4b8de0567b2364901e4d/build/randomize-authors.py # by Daniel Himmelstein under the CC0 1.0 license # https://github.com/greenelab/deep-review#license import argparse import pathlib import sys import yaml from manubot.util import read_seri...
greenelab/covid19-review
build/update-author-metadata.py
update-author-metadata.py
py
5,812
python
en
code
117
github-code
36
228949403
eps = 1e-4 n_generations = N_generations_max for i in range(N_generations_max-1): # print(i) SR_i = SR_all[i] metric_i = metric_all[i] if metric_i.min() == metric_i.max(): n_generations = i+1 break selected_inds = selection_tournament(-metric_i, N_population, 2, elitism=True) SR...
hhnam96/AstroGeo
ipython_cell_input.py
ipython_cell_input.py
py
932
python
en
code
0
github-code
36
323629396
"""Added paid to order model Revision ID: eb502f9a5410 Revises: 82df20a186ef Create Date: 2020-04-19 17:05:05.312230 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils # revision identifiers, used by Alembic. revision = 'eb502f9a5410' down_revision = '82df20a186ef' branch_labels = None depen...
Dsthdragon/kizito_bookstore
migrations/versions/eb502f9a5410_added_paid_to_order_model.py
eb502f9a5410_added_paid_to_order_model.py
py
682
python
en
code
0
github-code
36
30974355669
import importlib import shutil import uuid from typing import Dict, List, Tuple, Union from torch import Tensor, nn from torchdistill.common import module_util from pathlib import Path import torch import time import gc import os from logging import FileHandler, Formatter from torchdistill.common.file_util import che...
rezafuru/FrankenSplit
misc/util.py
util.py
py
20,533
python
en
code
9
github-code
36
35910502981
import os, discord, random, asyncio, json, time from discord.ext import commands class games(commands.Cog): def __init__(self,bot): self.coin_toss=0 self.bot=bot self.counter = 0 @commands.command(name="FLIP",aliases=['FLIP`']) async def coin_toss(self,ctx,choice): #choice ...
yassir56069/TSOE
cogs/games.py
games.py
py
4,574
python
en
code
0
github-code
36
72166330345
# Importing necessary libraries import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression # from sklearn.metrics import mean_squared_error, r2_score # Sample dataset of house prices and areas (replace this with your own dataset) mona =...
preyar/RealEstatePricePrediction
Prediction.py
Prediction.py
py
1,385
python
en
code
0
github-code
36
884569807
#driving 2 (add new usa) country = input('你的国家是? ') if country == 'taiwan' : age = input('请输入年龄? ') age = int(age) if age >= 18 : print('你已经',age,'岁了,可以考驾照') else : print('you`re not allowed to get liance!') elif country == 'usa' : age = input('请输入年龄? ') age = int(age) if age >= 16 : print('你已经',age,'岁了,可...
hugoming620/driving
driving2.py
driving2.py
py
475
python
zh
code
0
github-code
36
30176732849
import re with open("250-najbolj-znanih-filmov.html") as dat: vsebina = dat.read() vzorec = re.compile( r'<a href="/title/tt' r'(?P<id>\d+)' r'/\?ref_=adv_li_tt">(?P<naslov>.+?)</a>\s*' r'<span class="lister-item-year text-muted unbold">' r'(\([IVXLCDM]+\) )?' # če je več filmov v istem letu,...
matijapretnar/programiranje-1
01-regularni-izrazi/predavanja/preberi_filme.py
preberi_filme.py
py
502
python
sl
code
6
github-code
36
4799644228
from cadastro import Cadastro, Login from email_senha import EmailSenha import json, random, string login = False cadastro = False opcao = input("1. login\n2. cadastrar ") if opcao == "1": login = Login().autenticacao() tentativas = 0 while login == "senha incorreta": print("senha incorreta") ...
Bonbeck/Cadastro
main.py
main.py
py
2,800
python
pt
code
0
github-code
36
40148288536
def moveZeroes(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ pter_non_0 = 0 for i,num in enumerate(nums): if num != 0: nums[i] = nums[pter_non_0] pter_non_0 += 1 ...
Elmanou89/leetcode_daily_challenge
week1/movezeroes.py
movezeroes.py
py
327
python
en
code
0
github-code
36
12631299379
import cv2 import os # 비디오 파일 경로 설정 video_path = "차체 영상 1차.mp4" # 저장할 이미지 파일을 저장할 폴더 경로 설정 output_folder = "video" if not os.path.exists(output_folder): os.makedirs(output_folder) # 비디오 캡쳐 객체 생성 cap = cv2.VideoCapture(video_path) # 캡쳐가 올바르게 열렸는지 확인 if not cap.isOpened(): print("Error: Could not open video."...
TAEM1N2/kudos12_2023
data_setting/python_practice/video_cap.py
video_cap.py
py
971
python
ko
code
1
github-code
36
20052331496
__author__ = 'matsrichter' import numpy as np import AccountV2 as acc import time class Risk_Manager: # @param isBroke failure state. System has fatal error and stops functioning if this is True def __init__(self, account, risk_aversion_factor, max_draw_down): assert(isinstance(account, acc.Account))...
MLRichter/AutoBuffett
Layer2/Risk_Manager.py
Risk_Manager.py
py
1,976
python
en
code
8
github-code
36
20227289100
#!/usr/bin/python import sys, os import sets from Bio import SeqIO def make_location_set(l): return sets.Set([n for n in xrange(l.nofuzzy_start, l.nofuzzy_end)]) for rec in SeqIO.parse(sys.stdin, "genbank"): new_features = [] for feature in rec.features: add = 1 if feature.type == 'CDS': ...
nickloman/xbase
annotation/remove_overlaps_with_frameshifts.py
remove_overlaps_with_frameshifts.py
py
843
python
en
code
6
github-code
36
23410005730
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime class Migration(migrations.Migration): dependencies = [ ('bar', '0238_auto_20160817_1352'), ] operations = [ migrations.AddField( model_name='caja', ...
pmmrpy/SIGB
bar/migrations/0239_auto_20160817_1408.py
0239_auto_20160817_1408.py
py
1,747
python
es
code
0
github-code
36
74957373542
from __future__ import print_function, division import os import torch import torchtext import itertools from loss.loss import NLLLoss class Evaluator(object): def __init__(self, loss=NLLLoss(), batch_size=64): self.loss = loss self.batch_size = batch_size def evaluate(self, model, data): ...
hopemini/activity-clustering-multimodal-ml
autoencoder/seq2seq/evaluator/evaluator.py
evaluator.py
py
4,024
python
en
code
3
github-code
36
21546325152
#This python script reads a CSV formatted table of methylation sites #and attaches, depending on the coordinate, 1.5 kb flanking regions #numbers listed import csv # module to read CSV files import re # module to search for regular expressions in files; not in use now but will set up for sophisticated search ...
lanl/DNA_methylation_analysis
meth_site_flanking_seq.py
meth_site_flanking_seq.py
py
2,848
python
en
code
0
github-code
36
20294716631
import socket def main(): host = '127.0.0.1' port = 5001 server = (host, 5000) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((host, port)) message = input('->') while message != 'EXIT': s.sendto(bytes(message, encoding='utf-8'), server) data, addr = s.recvfr...
ijkilchenko/_socket_programming
udp_client.py
udp_client.py
py
495
python
en
code
0
github-code
36
14570907737
#importar librerias from ast import parse from wsgiref import headers import requests #peticion al servidor import lxml.html as html import pandas as pd from tqdm.auto import tqdm #barras de progreso from lxml.etree import ParseError from lxml.etree import ParserError import csv from fake_useragent import UserAgent ua...
joseorozco84/scraper
genres.py
genres.py
py
1,910
python
en
code
0
github-code
36
138291184
#!/usr/bin/env python3 from collections import deque class BinaryTreeNode: def __init__(self, value): self.value = value self.left = None self.right = None def create_tree(): root = BinaryTreeNode(1) root.left = BinaryTreeNode(2) root.right = BinaryTreeNode(3) root....
banginji/algorithms
misc/treebalance.py
treebalance.py
py
1,635
python
en
code
0
github-code
36
32088085449
from app.models import db, Portfolio, environment, SCHEMA def seed_portfolio(): tsla = Portfolio( symbol="TSLA", user_id=1, num_shares=10, average_price=187.85 ) # look up python docs for datetime nvda= Portfolio( symbol="NVDA", user_id=1, num_shares=15, average_price=162.60 ...
Dylluu/Ravenhood
app/seeds/portfolio.py
portfolio.py
py
1,466
python
en
code
5
github-code
36
406588995
# Run by typing python3 main.py # Import basics import re import os import pickle # Import stuff for our web server from flask import Flask, flash, request, redirect, url_for, render_template from flask import send_from_directory from flask import jsonify from utils import get_base_url, allowed_file, and_syntax # Im...
aashishyadavally/pick-up-line-generator
app/main.py
main.py
py
4,425
python
en
code
0
github-code
36
39013964049
# 1969 DNA import sys sys.stdin = open('DNA.txt', 'r') N, M = map(int, input().split()) # N: DNA의 수, M: 문자열의 길이 arr = [list(input()) for _ in range(N)] # 배열 초기화 print(arr) result = '' # 결과 값 result 초기화 ham_d = 0 # 해밍 거리 for j in range(M): # 가로열 고정 cnt = [0, 0, 0, 0] # DNA A, C, G, T 각 개수 초기화 for i in ran...
eomsteve/algo_study
johoh0/2nd_week/1969_DNA.py
1969_DNA.py
py
1,569
python
ko
code
0
github-code
36
20968448747
# 2. **********maria**********Создайте список, в который попадают числа, # описывающие возрастающую последовательность. # Порядок элементов менять нельзя from random import choices # функция ****choices**** # возвращает !!!!список!!! элементов длины k , # выбранных из последовательности (список- any_list или корт...
Nadzeya25/Python_GB
seminar5_Python/class_work5/task5_2.py
task5_2.py
py
2,355
python
ru
code
0
github-code
36
26297648004
from itertools import product def create_dice(sides): dice = [] for i in range(sides): dice.append( i+1 ) return dice number_of_dices = int(input("Mata in antalet tärningar:\n")) number_of_sides = int(input("Mata in antalet sidor för tärningarna:\n")) highest_sum = number_of_sides * number_of...
hadi-ansari/TDP002
gamla_tentor_tdp002/2018/uppgift2.py
uppgift2.py
py
730
python
en
code
0
github-code
36
34986315817
from flask import Flask, render_template, request, url_for, flash, redirect import sqlite3 from werkzeug.exceptions import abort from flask_socketio import SocketIO from engineio.payload import Payload Payload.max_decode_packets = 50 def get_db_connection(): conn = sqlite3.connect('database.db') conn.row_fact...
JeroenMX/LearningPython
main.py
main.py
py
3,952
python
en
code
0
github-code
36
24193842042
import pandas as pd from pathlib import Path from enum import Enum pd.options.mode.chained_assignment = None # default='warn' class Location(Enum): home = 1 visiting = 2 #not used atm def get_last_occurrence(team_id, location): data_folder = Path("../") all_game_file = data_folder / "_mlb_remerged_...
timucini/MLB-DeepLearning-Project
Verworfen/TeamIdMerge2.py
TeamIdMerge2.py
py
2,468
python
en
code
1
github-code
36
12466948381
import smbus #dit is een library om met de i2c bus te communiceren import time #op de pi instaleren: i2c-tools, python-smbus en zeker ook de i2c enablen in de raspi-config I2C_ADDR = 0x27 #i2cdetect -y 1 LCD_WIDTH = 20 #breedte van mijn scherm LCD_CHR = 1 #om data door te sturen LCD_CMD = 0 #om een command door te s...
VanbecelaereVincent/Speedometer
LCD.py
LCD.py
py
1,807
python
nl
code
2
github-code
36
5216604834
from dataclasses import dataclass from struct import Struct from .bytes import Bytes KEY_HASH = Struct("<HH") ENCRYPTED_MESSAGE = Struct("<BIIII16s16s") @dataclass class SignedMessage: """The cryptographic message portion of Session Offer.""" flags: int key_slot: int key_mask: int challenge: by...
vbe0201/wizproxy
wizproxy/proto/handshake.py
handshake.py
py
2,130
python
en
code
2
github-code
36
30461364600
# village_id, name, x, y, idx, pts, b import pdb import utils import numpy as np if __name__ == "__main__": files = utils.getLastFiles() villages = utils.read_villages(files["villages"]) coords = villages['coords'] pts = villages["points"] v_barb = (villages['player'] == 0) v_playe...
felipecadar/tw-scripts
plot_world.py
plot_world.py
py
1,374
python
en
code
1
github-code
36
35512006282
import trimesh import numpy as np from sklearn.neighbors import KDTree from trimesh.proximity import ProximityQuery def transform_mesh(mesh, trans_name, trans_params): if trans_name == 'preprocess': mesh = preprocess_mesh(mesh, **trans_params) elif trans_name == 'refine': mesh = refine_mesh(me...
amaleki2/graph_sdf
src/data_utils.py
data_utils.py
py
4,749
python
en
code
2
github-code
36
368888743
from datetime import datetime import re import string import pandas as pd import time from sympy import li class Model_Trace_Analysis: def __init__(self): timestr = time.strftime("%Y%m%d_%H%M%S") self.txt_path = './analysis/klm_bei_record/typing_log_'+str(timestr)+'.txt' self.result_path =...
TuringFallAsleep/Tinkerable-AAC-Keyboard
develop/model_trace_analysis.py
model_trace_analysis.py
py
25,662
python
en
code
0
github-code
36
73013290345
def main(): #Entrada x = int(input()) y = int(input()) somador = 0 #processamento if x > y : for i in range(y, x+1): if i%13 !=0: somador += i else: for i in range(x, y+1): if i%13 !=0: somador += i print(somador) if __name__ == '__main__': main()
DarknessRdg/URI
iniciante/1132.py
1132.py
py
277
python
en
code
2
github-code
36
947924592
pkgname = "zxing-cpp" pkgver = "2.1.0" pkgrel = 0 build_style = "cmake" configure_args = [ "-DBUILD_UNIT_TESTS=ON", "-DBUILD_EXAMPLES=OFF", "-DBUILD_BLACKBOX_TESTS=OFF", "-DBUILD_DEPENDENCIES=LOCAL", ] hostmakedepends = ["cmake", "ninja", "pkgconf"] checkdepends = ["gtest-devel"] pkgdesc = "Multi-format...
chimera-linux/cports
contrib/zxing-cpp/template.py
template.py
py
667
python
en
code
119
github-code
36
29014504899
import numpy as np import torch import torch.nn as nn import torch.optim as optim from penn_treebank_reader import * from dataset import DatasetReader from dataset import make_batch_iterator def get_offset_cache(length): offset_cache = {} ncells = int(length * (1 + length) / 2) for lvl in range(length):...
mrdrozdov/chart-parser
train.py
train.py
py
7,733
python
en
code
0
github-code
36
25452837300
"""Test whether the app increased LDs by comparing a 7-session total against a baseline week. """ import os import numpy as np import pandas as pd import pingouin as pg from scipy.stats import sem import utils #### Choose export paths. basename = "app_effect" export_dir = os.path.join(utils.Config.data_directory,...
remrama/lucidapp
analyze-app_effect.py
analyze-app_effect.py
py
3,437
python
en
code
0
github-code
36
39893499902
from django.urls import path from . import views # app_name = '' urlpatterns = [ #GET: 전체글조회, POST: 게시글 생성 path('', views.review_list), #GET: 단일 게시글 조회, DELETE: 해당 게시글 삭제, PUT: 해당 게시글 수정 path('<int:review_pk>/', views.review_update_delete), #GET: 댓글 전체를 조회 path('<int:review_pk>/comments/...
chomyoenggeun/linkedmovie
server/community/urls.py
urls.py
py
707
python
ko
code
0
github-code
36
13098646528
from io import BytesIO from pathlib import Path import random from flask import Blueprint, Flask from flask.wrappers import Response from loft.config import Config, DebugConfig from loft.util.id_map import IdMap from loft.web.blueprints.api import api rand = random.Random() rand.seed(24242424) def client(config:...
ucsb-cs148-s21/t7-local-network-file-transfer
test/web/blueprints/test_api.py
test_api.py
py
4,074
python
en
code
3
github-code
36
13933428778
import pytest from uceasy.ioutils import load_csv, dump_config_file @pytest.fixture def config_example(): config = { "adapters": { "i7": "AGATCGGAAGAGCACACGTCTGAACTCCAGTCAC*ATCTCGTATGCCGTCTTCTGCTTG", "i5": "AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGTAGATCTCGGTGGTCGCCGTATCATT", } ...
uceasy/uceasy
tests/test_ioutils.py
test_ioutils.py
py
1,048
python
en
code
8
github-code
36
30526669570
# augmentations for 2D and 2.5D import random import numpy as np import SimpleITK as sitk from src.utils.itk_tools import rotate_translate_scale2d # Now only support list or tuple class Compose(object): def __init__(self, augmentations): self._augmentations = augmentations def __call__(self, nda, nd...
eugeneyuan/test_rep
src/data/aug2d.py
aug2d.py
py
3,312
python
en
code
0
github-code
36
12133536334
# -*- coding: utf-8 -*- """ Created on Wed Aug 2 14:51:00 2017 @author: trevario Automatically plot TCSPC data using matplotlib.pyplot """ import glob, os import numpy as np import matplotlib.pyplot as plt import csv #%matplotlib inline print("what directory are the files in?") name = input() os.chdir('/home/tre...
trevhull/dataplot
tcspc.py
tcspc.py
py
2,065
python
en
code
0
github-code
36
2952639119
import visa import time from time import sleep rm = visa.ResourceManager() print('Connected VISA resources:') print(rm.list_resources()) dmm = rm.open_resource('USB0::0x1AB1::0x09C4::DM3R192701216::INSTR') print('Instrument ID (IDN:) = ', dmm.query('*IDN?')) #print("Volts DC = ", dmm.query(":MEASure:VOLTage:DC?")) ...
JohnRucker/Rigol-DM3058E
test.py
test.py
py
1,135
python
en
code
1
github-code
36
14203206189
import math from flask import render_template, request, redirect, url_for, session, jsonify from saleapp import app, login import utils import cloudinary.uploader from flask_login import login_user, logout_user, login_required from saleapp.admin import * from saleapp.models import UserRole @app.route("/") def index(...
duonghuuthanh/K19SaleApp
mysaleappv3/saleapp/index.py
index.py
py
5,712
python
en
code
0
github-code
36
27228057071
# Major League Baseball Statistical Analysis for Batters import csv def main(): batters = [] try: with open("/Users/jasonbarba/Projects/MLB_Statistics_Analysis/WhiteSox_Batting_2022.csv", 'r') as file: csvreader = csv.reader(file) for batter in csvreader: batters.append(batter) except: print("Could not...
jasonbarba19/MLB_Statistics_Analysis
batter_analyze.py
batter_analyze.py
py
422
python
en
code
0
github-code
36
1479958272
from datetime import date import numpy as np import pandas as pd from pandas.tseries.holiday import USFederalHolidayCalendar as calendar from app.features_extractors.numerical import make_harmonic_features def number_of_days_until_true(boolean_values: pd.Series, today: date) -> pd.Series: return (boolean_values[...
ahmediqtakehomes/TakeHomes
reformated_takehomes_old/doordash_1/example_submission/app/features_extractors/calendar.py
calendar.py
py
2,283
python
en
code
1
github-code
36
27601063298
import threading # def do_this(what): # whoami(what) # def whoami(what): # print("Thread %s says: %s" % (threading.current_thread(), what)) # if __name__ == '__main__': # whoami("I'm the main program") # for n in range(4): # p = threading.Thread(target=do_this, args=("I'm function %s" % n,)) # ...
AlexNavidu/BillLob
test_treading/2threading.py
2threading.py
py
637
python
en
code
0
github-code
36
19255593783
class GameStats(): """Seguir las estadisticas de Alien Invasion""" def __init__(self, ai_settings): """Inicializar las estadisticas""" self.ai_settings = ai_settings self.reset_stats() #Empezar Alien Invasion en un estado inactivo self.game_active = False #Puntua...
jGarciaGz/PythonCrashCourse_Proyecto1
game_stats.py
game_stats.py
py
568
python
es
code
0
github-code
36
16586177664
# -*- coding: UTF-8 -*- from flask import render_template, flash, redirect from sqlalchemy.orm import * from sqlalchemy import * from flask.ext.sqlalchemy import SQLAlchemy from flask import Flask from flask import * from forms import lyb #from flask.ext.bootstrap import Bootstrap app = Flask(__name__) app.config.f...
wjh1234/python-scripts
flasker/app/views.py
views.py
py
2,095
python
en
code
0
github-code
36
73605994665
class Solution(object): def flipAndInvertImage(self, image): """ :type image: List[List[int]] :rtype: List[List[int]] """ result = [] for row in image: new_row = [] for grid in row[::-1]: new_row.append(1 - grid) res...
yichenfromhyrule/LeetCode
#832_FlippingAnImage.py
#832_FlippingAnImage.py
py
362
python
en
code
0
github-code
36
31479728563
import pygame from constants import WHITE, SIZE_WALL, YELLOW, MARGIN class Food: def __init__(self, row, col, width, height, color): self.image = pygame.Surface([width, height]) self.image.fill(WHITE) self.image.set_colorkey(WHITE) pygame.draw.ellipse(self.image, color, ...
nxhawk/PacMan_AI
Source/Object/Food.py
Food.py
py
860
python
en
code
0
github-code
36
30490661295
#!/usr/bin/env python3 import os import sys import logging import json import requests import datetime import pyteamcity import http.server import validators from urllib.parse import urlparse config = {} tc = None logger = None def initializeLogger(): logger = logging.getLogger('teamcity_connector') logger.setL...
mrlov/hygieia_teamcity_collector
main.py
main.py
py
6,631
python
en
code
1
github-code
36
34058973132
from sklearn.preprocessing import Normalizer import numpy as np from utils import extract_face_roi_single from Database import addNewStudent import pickle import os from bson.binary import Binary import tensorflow as tf os.environ['CUDA_VISIBLE_DEVICES']='-1' Normaliser = Normalizer(norm='l2') global graph frozen_gr...
VikasOjha666/Attendance_API_optimized
prepare_embeddings.py
prepare_embeddings.py
py
2,065
python
en
code
0
github-code
36
12482854412
#!/usr/bin/env python # coding: utf-8 # !rm -r inference # !pip install -r requirements.txt import json import sys, os import requests import datetime import numpy as np import pickle import time import random import zstandard as zstd import tarfile import pandas as pd import boto3 import botocore from bo...
drivendataorg/nasa-airathon
no2/1st Place/RunFeatures.py
RunFeatures.py
py
25,953
python
en
code
12
github-code
36
28239507991
W = H = 480 SIZE = 180.0 IN_SIZE = 60.0 FPS = 20.0 D = 2.0 N_FRAMES = D * FPS N_SAMPLES = 4.0 WEIGHT = 3 MINE_COLOR = color(231, 231, 222) BLUR_COLOR = color(0, 0, 0) BG_COLOR = color(188, 184, 172) RECORD = False def polar2cart(r,theta): return r * cos(theta), r * sin(theta) def make_triangle(radius): retur...
letsgetcooking/Sketches
processing/2015/triangle.py
triangle.py
py
2,592
python
en
code
0
github-code
36
25743825361
__all__ = [ "Quantizer" ] from multiprocessing import Pool import numpy as np from ..base import Pipe from ..config import read_config from ..funcs import parse_marker config = read_config() D = config.get("jpeg2000", "D") QCD = config.get("jpeg2000", "QCD") delta_vb = config.get("jpeg2000", "delta_vb") reserve_b...
yetiansh/fpeg
fpeg/utils/quantify.py
quantify.py
py
6,831
python
en
code
1
github-code
36
15138053890
import sys import numpy as np import matplotlib.pyplot as plt import cuqipy_fenics import dolfin as dl import warnings import cuqi from cuqi.problem import BayesianProblem from cuqi.model import PDEModel from cuqi.distribution import Gaussian from cuqi.geometry import Geometry import dolfin as dl from .pde import Stead...
CUQI-DTU/CUQIpy-FEniCS
cuqipy_fenics/testproblem.py
testproblem.py
py
18,480
python
en
code
4
github-code
36
29178775126
from django.http import HttpResponse from django.core.paginator import Paginator from django.shortcuts import render from .operations_c import Company_O, Publication from django.http import QueryDict from home.operation_home import Home_O def Add_Publication(request): if request.method == 'POST': mutable_post_data ...
cdavid58/empleo
company/views.py
views.py
py
1,810
python
en
code
0
github-code
36
17872592313
# # author: Paul Galatic # # This program is JUST for drawing a rounded rectangle. # import pdb from PIL import Image, ImageDraw from extern import * def sub_rectangle(draw, xy, corner_radius=25, fill=(255, 255, 255)): ''' Source: https://stackoverflow.com/questions/7787375/python-imaging-library-pil-drawin...
pgalatic/zeitgeist
rectround.py
rectround.py
py
2,033
python
en
code
0
github-code
36
9587970567
from plugin import plugin from colorama import Fore @plugin("hex") def binary(jarvis, s): """ Converts an integer into a hexadecimal number """ if s == "": s = jarvis.input("What's your number? ") try: n = int(s) except ValueError: jarvis.say("That's not a number!", Fo...
sukeesh/Jarvis
jarviscli/plugins/hex.py
hex.py
py
503
python
en
code
2,765
github-code
36
15542188724
import unittest from unittest.mock import patch, mock_open, MagicMock from external_sort.file_merger import FileMerger class StubHandle: def __init__(self, data): self.data = data self.position = 0 def readline(self): if self.position >= len(self.data): return '' ...
xelibrion/sort-large-files
tests/test_file_merger.py
test_file_merger.py
py
1,715
python
en
code
0
github-code
36
28890243109
import torch import math from torch import nn from torch.nn import functional as F from data import utils as du from model import ipa_pytorch from model import frame_gemnet from openfold.np import residue_constants import functools as fn Tensor = torch.Tensor def get_index_embedding(indices, embed_size, max_len=2056...
blt2114/twisted_diffusion_sampler
protein_exp/model/reverse_se3_diffusion.py
reverse_se3_diffusion.py
py
10,866
python
en
code
11
github-code
36
40858069336
import matplotlib.pyplot as plt # 模拟导航路径数据 path = [(0, 0), (1, 1), (2, 3), (3, 4), (4, 2)] # 初始化绘图 fig, ax = plt.subplots() ax.set_xlim(-1, 5) ax.set_ylim(-1, 5) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_title('Navigation Path') # 绘制导航路径 x = [point[0] for point in path] y = [point[1] for point in path] ax.plot(x,...
haiboCode233/KivyPlusAR
testcode.py
testcode.py
py
897
python
zh
code
0
github-code
36
16927982669
def merge_sort(src): """ :type src: List(int) :rtype: None """ if src: return __helper(src, 0, len(src)) else: return None def __helper(src, lo, hi): if lo + 1 >= hi: return src[lo:hi] else: mid = (lo + hi) / 2 left = __helper(src, lo, mid) ...
YorkShen/CLRS
Python/sort/merge_sort.py
merge_sort.py
py
780
python
en
code
0
github-code
36
11263851417
import sqlite3 from flask import g from app.app import app from .model import Objective, User DATABASE = "data.db" def create_tables(): with app.app_context(): db = get_db() cursor = db.cursor() cursor.execute('''CREATE TABLE IF NOT EXISTS users ( us...
brunotsantos1997/robson-api
app/data/database.py
database.py
py
4,413
python
en
code
1
github-code
36
72244550505
import json # Load the mapping from inscriptions.json with open("inscriptions.json", "r") as json_file: data = json.load(json_file) # Create a mapping from "Goosinals #" to "id" mapping = {} for entry in data: number = int(entry["meta"]["name"].split("#")[1].strip()) mapping[number] = entry["id"] # Proce...
jokie88/goosinal_mosaic
map_goosinalnumber_to_hash.py
map_goosinalnumber_to_hash.py
py
617
python
en
code
1
github-code
36
74160148903
''' Pay attention to the situation when the characters are all 'S' or 'O', but in a wrong sequence just like the test example ''' import sys def marsExploration(s): # Complete this function num = 0 length = len(s) n = length // 3 start = 0 end = start + 3 for i in range(n): if end >...
CodingProgrammer/HackerRank_Python
Mars_Exploration.py
Mars_Exploration.py
py
667
python
en
code
0
github-code
36
40243581716
from django.conf import settings from django.db import models import logging import requests log = logging.getLogger('genoome.twentythree.models') class Token23(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, unique=True) access_token = models.TextField() refresh_token = models.TextField...
jiivan/genoomy
genoome/twentythree/models.py
models.py
py
4,655
python
en
code
0
github-code
36
11359117771
import sys sys.stdin = open('알파벳.txt') def dfs(x, y, cnt): global max_c if cnt > max_c: max_c = cnt check.append(data[x][y]) for k in range(4): nx = x + dx[k] ny = y + dy[k] if nx < 0 or nx >= R or ny < 0 or ny >= C: continue if data[nx][ny] in check: continue ...
Jade-KR/TIL
04_algo/study/Mine/알파벳.py
알파벳.py
py
690
python
en
code
0
github-code
36
40243457981
import torch.nn as nn import torch import torchvision import cv2 import time import numpy as np import os YOEO_CLASSES = ( "shark", "coral", "fish", "turtle", "manta ray", ) def preproc(img, input_size, swap=(2, 0, 1)): if len(img.shape) == 3: padded_img = np.ones((input_size[0], inpu...
teyang-lau/you-only-edit-once
src/utils/yolox_process.py
yolox_process.py
py
13,535
python
en
code
6
github-code
36
22204331425
from ..service.client_service import ClientService from flask_restx import Resource, Namespace, fields from flask import jsonify, request client_service = ClientService() api = Namespace('Cliente', 'Operações relacionadas aos clientes da loja') clients_fields = api.model('Cliente', { 'name': fields.String, '...
anaplb3/loja-api
app/main/controller/client_controller.py
client_controller.py
py
2,076
python
pt
code
0
github-code
36
43906527977
""" Process command line arguments and/or load configuration file mostly used by the test scripts """ import argparse import sys import os.path from typing import Union import yaml def do_args(): """ @brief { function_description } @return { description_of_the_return_value } """ # Parse ...
Aethylred/pyspectrumscale
pyspectrumscale/configuration/__init__.py
__init__.py
py
6,045
python
en
code
0
github-code
36
26089552298
import numpy as np import math import scipy.signal as juan import matplotlib.pyplot as plt plt.rcParams['font.sans-serif']=['KaiTi']#黑体:SimHei 宋体:SimSun 楷体KaiTi 微软雅黑体:Microsoft YaHei plt.rcParams['axes.unicode_minus'] = False#这两用于写汉字 n1 = np.arange(0,32,1) dom = [True if (i>=8 and i<=23) else False for i...
Mr-Da-Yang/Python_learning
2019vacational_project/matplotlib/xinhaojiance_02.py
xinhaojiance_02.py
py
1,391
python
en
code
0
github-code
36
73445915623
import IPython from IPython.utils.path import get_ipython_dir from IPython.html.utils import url_path_join as ujoin from IPython.html.base.handlers import IPythonHandler, json_errors from tornado import web import json # Handler for the /new page. Will render page using the # wizard.html page class New_PageHandler(IP...
Feldman-Michael/masterthesis
home/ipython/.local/share/jupyter/nbextensions/ma/server/services/ipy_html_distproject.py
ipy_html_distproject.py
py
996
python
en
code
1
github-code
36
14997087223
import typing from typing import Any, Callable, List, Tuple, Union import IPython.display as display import cv2 import numpy as np import os, sys from PIL import Image from .abc_interpreter import Interpreter from ..data_processor.readers import preprocess_image, read_image, restore_image, preprocess_inputs from ..da...
LoganCome/FedMedical
utils/InterpretDL/interpretdl/interpreter/score_cam.py
score_cam.py
py
7,112
python
en
code
44
github-code
36
32350610780
import sublime_plugin from ..package_creator import PackageCreator class CreatePackageCommand(sublime_plugin.WindowCommand, PackageCreator): """ Command to create a regular .sublime-package file """ def run(self): self.show_panel() def on_done(self, picked): """ Quick pa...
Iristyle/ChocolateyPackages
EthanBrown.SublimeText2.UtilPackages/tools/PackageCache/Package Control/package_control/commands/create_package_command.py
create_package_command.py
py
961
python
en
code
24
github-code
36
1000678117
__author__ = 'SOROOSH' import loadimpact import settings __all__ = ['ConfigurationGenerator', 'ConfigurationUploader'] class ConfigurationGenerator(object): def __init__(self, jmx_info): self.jmx_info = jmx_info def generate_configuration(self, scenario): domain = self.jmx_info.domain ...
s-soroosh/loadimpact-jmx-importer
jmx_importer/configuration.py
configuration.py
py
1,394
python
en
code
0
github-code
36
23109102237
import requests from datetime import datetime from bs4 import BeautifulSoup url = 'https://www.naver.com/' html = requests.get(url).text soup = BeautifulSoup(html, 'html.parser') #실시간 검색어 긁어온거 그대로 #한두개 코드 긁어서 전체적으로 긁어오려면 어떻게 써야할지 고민 # → li 태그 전체를 뽑아오게끔 손질해보자( li:nth-child(1) → li ) names = soup.select('#PM_ID_ct > d...
drhee0919/TIL
Chatbot/05_naver_rank.py
05_naver_rank.py
py
992
python
ko
code
0
github-code
36
29100418117
""" SORU 1: Bir a matrisinin tüm elemanları sıfır olan sütunlarının sayısını bulup bu bilgiyi geri döndüren Python fonksiyonunu yazınız. """ import numpy as np def sifiribul(matris): print(matris) yeni = np.transpose(matris) sutun=0 for i in yeni: say = 0 for a in i: ...
symydnnn/PythonExamples
23.12.2021/soru1.py
soru1.py
py
647
python
tr
code
0
github-code
36
993256569
import asyncio import serial_asyncio import threading from functools import partial class AsyncSerialConnection(object): def __init__(self, loop, device, port='/dev/ttyUSB0'): coro = serial_asyncio.create_serial_connection(loop, ZiGateProtocol, port, baudrate=115200) futur = asyncio.run_coroutine...
elric91/ZiGate
examples/async_serial.py
async_serial.py
py
1,929
python
en
code
18
github-code
36
9815950754
import discord import asyncio import time import sys import os import random import aiohttp useproxies = sys.argv[4] if useproxies == 'True': proxy_list = open("proxies.txt").read().splitlines() proxy = random.choice(proxy_list) con = aiohttp.ProxyConnector(proxy="http://"+proxy) client = ...
X-Nozi/NoziandNiggarr24Toolbox
spammer/cleanup.py
cleanup.py
py
1,446
python
en
code
0
github-code
36
75129886504
__all__ = ["Echo"] from textwrap import dedent from typing import Any, Dict from ..imagecrawler import BaseImageCrawler, Image, ImageCollection, ImageCrawlerConfig, ImageCrawlerInfo class Echo(BaseImageCrawler): def __init__(self, *, image_uri: str) -> None: super().__init__(image_uri=image_uri) @...
k4cg/nichtparasoup
python-package/src/nichtparasoup/imagecrawlers/echo.py
echo.py
py
1,743
python
en
code
40
github-code
36
1119124359
from typing import Iterable, Callable import SearchSpace from BenchmarkProblems.CombinatorialProblem import CombinatorialProblem from Version_E.Feature import Feature from Version_E.InterestingAlgorithms.Miner import FeatureSelector from Version_E.MeasurableCriterion.CriterionUtilities import Balance, Extreme, All fro...
Giancarlo-Catalano/Featurer
Version_E/Sampling/RegurgitationSampler.py
RegurgitationSampler.py
py
3,398
python
en
code
0
github-code
36
72225854504
#!/usr/bin/python3 """ Main 'BaseModel' class that defines all common attributes/methods for other classes """ import uuid import models from datetime import datetime class BaseModel: """ Base class constructor method """ def __init__(self, *args, **kwargs): """ Base class initializes the objects ""...
DevPacho/holbertonschool-AirBnB_clone
models/base_model.py
base_model.py
py
1,607
python
en
code
0
github-code
36
39910309614
#step1: import random suits =('Hearts', 'Diamonds', 'Spades', 'Clubs') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, ...
ngoNhi123t/python_udemy
project2_udemy.py
project2_udemy.py
py
7,514
python
en
code
0
github-code
36
35667300076
import tensorflow as tf from tensorflow import keras tf.compat.v1.enable_eager_execution() tf.executing_eagerly() class BaseModel(tf.keras.Model): ''' def __init__(self, n_features): super(BaseModel, self).__init__() self.inputs_layer = keras.layers.Input(shape=n_features) self.layer1 =...
takehigu26/adv_exp
my_adv_exp/models.py
models.py
py
2,946
python
en
code
0
github-code
36
3829740430
#! @PYSHEBANG@ # -*- coding: utf-8 -*- from __future__ import print_function, division import sys import os import getopt import time import socket try: import ntp.packet import ntp.util import ntp.agentx_packet ax = ntp.agentx_packet from ntp.agentx import PacketControl except ImportError as e: ...
ntpsec/ntpsec
ntpclients/ntpsnmpd.py
ntpsnmpd.py
py
47,973
python
en
code
225
github-code
36