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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
41242720350 | # -*- coding: utf-8 -*-
# @Author : lileilei
# @File : views.py
# @Time : 2017/12/7 12:19
from flask import Blueprint
from flask import redirect,request,render_template,url_for,flash,session,abort,jsonify,make_response
from flask.views import MethodView
from app import db
from app.models import *
from app.fo... | mingming2513953126/pythondemo | FXTest-master/app/task/views.py | views.py | py | 12,466 | python | en | code | 0 | github-code | 36 |
43251284165 | #GUI for setting of experimental parameters in DLS GUI
import sys
try:
from Tkinter import *
except ImportError:
from tkinter import *
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
def vp_start_gui():
'''Starting point when module is the main routin... | farrarmj/FalCorr | FCSoptionWindow.py | FCSoptionWindow.py | py | 10,763 | python | en | code | 1 | github-code | 36 |
6704842108 | import os, sys
import asyncio
import aiohttp # pip install aiohttp
import aiofiles # pip install aiofiles
def download_files_from_report(file_name):
if sys.version_info[0] == 3 and sys.version_info[1] >= 8 and sys.platform.startswith('win'):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopP... | NurlanTanatar/download_mangas | get_files.py | get_files.py | py | 1,228 | python | en | code | 0 | github-code | 36 |
28040851490 | # import dependencies
from os.path import join
import pandas as pd
# import functions
from eir_functions import scrape_all, to_binary, to_csv, binary_to_csvs, clean_metadata, clean_measurements, clean_csvs, to_individuals
# bring in config values
from sys import path
path.insert(0, "..")
from config import eir_raw_so... | seneubauer/qc-modernization | eir_conversion/extract_eir_info.py | extract_eir_info.py | py | 3,365 | python | en | code | 0 | github-code | 36 |
28064994078 | from math import prod
from torch import zeros
from torch.nn import Module, Sequential, Conv1d, ReLU, Linear
class SimpleFFDQN(Module):
def __init__(self, obs_len, n_actions):
super().__init__()
self.fc_val = Sequential(
Linear(obs_len, 512),
ReLU(),
Linear(512... | Daggerfall-is-the-best-TES-game/reinforcement-learning | Chapter10/lib/models.py | models.py | py | 1,624 | python | en | code | 1 | github-code | 36 |
940338792 | import json
input_path_labor = "/input/labor/input.json"
input_path_divorce = "/input/divorce/input.json"
input_path_loan = "/input/loan/input.json"
output_path_labor = "/output/labor/output.json"
output_path_divorce = "/output/divorce/output.json"
output_path_loan = "/output/loan/output.json"
def predict(input_path... | china-ai-law-challenge/CAIL2019 | 要素识别/python_sample/main.py | main.py | py | 999 | python | en | code | 331 | github-code | 36 |
70441936743 | # Summary:
# referred to leetcode discussion: OldCodingFarmer(https://leetcode.com/problems/add-two-numbers/discuss/1032/Python-concise-solution.)
import sys
input = sys.stdin.readline
from collections import deque
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
... | cjy13753/algo-solutions | leetcode/solution_2.py | solution_2.py | py | 932 | python | en | code | 0 | github-code | 36 |
36784973558 | from collections import defaultdict
from nltk import ngrams
import pickle
class SentsFromCorpus():
def __init__(self, path):
self.path = path
def __iter__(self):
with open(self.path) as f:
for ln in f:
if ln == '\n':
continue
... | adamlek/swedish-lexical-blends | ngrams.py | ngrams.py | py | 1,633 | python | en | code | 0 | github-code | 36 |
9390258252 | n1 = n2 = int(input('Digite um número para ver seu fatorial: '))
f = 1
quant = 0
while quant != n1:
quant += 1
f *= n2
print(f'\033[37m{n2}', end='')
print('*' if n2 > 1 else '= ', end='')
n2 -= 1
print(f'\033[m{f}')
n1 = int(input('Digite outro número para ver seu fatorial: '))
f = 1
for c in rang... | github-felipe/ExerciciosEmPython-cursoemvideo | PythonExercicios/ex060.py | ex060.py | py | 600 | python | pt | code | 0 | github-code | 36 |
14521290687 | #imports contab package
from crontab import CronTab
#creates the cron job of Detect-IP.py script to run every hour
cron = CronTab(user="root")
detectIPjob = cron.new(command="python3 Detect-IP.py")
detectIPjob.hour.every(1)
cron.write()
#creates the cron job of Backup.py to run every Friday
cron = CronTab(user="root")
... | Splixxy/Cron-Job | Main.py | Main.py | py | 403 | python | en | code | 0 | github-code | 36 |
70806889703 | import sys
sys.stdin = open('input.txt')
N = int(sys.stdin.readline())
cranes = sorted(list(map(int, sys.stdin.readline().split())))
M = int(sys.stdin.readline())
boxes = sorted(list(map(int, sys.stdin.readline().split())))
answer = -1
cnts = [0] * N
# 무게 제한이 작은 크레인부터 순회
# 각 크레인으로만 이동 가능한 박스 개수
c, b = 0, 0
while b <... | unho-lee/TIL | CodeTest/Python/BaekJoon/1092.py | 1092.py | py | 1,607 | python | ko | code | 0 | github-code | 36 |
2672903172 | from django.forms import ModelForm
from .models import Ticket, Comment
from django import forms
from datetime import date
from dateutil.relativedelta import relativedelta
from bootstrap_datepicker_plus import DatePickerInput
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_use... | d120/pyticket | ticket/forms.py | forms.py | py | 3,129 | python | en | code | 3 | github-code | 36 |
40574898325 | import pytest
from game.radio.tacan import (
OutOfTacanChannelsError,
TacanBand,
TacanChannel,
TacanRegistry,
TacanUsage,
)
ALL_VALID_X_TR = [1, *range(31, 46 + 1), *range(64, 126 + 1)]
ALL_VALID_X_A2A = [*range(37, 63 + 1), *range(100, 126 + 1)]
def test_allocate_first_few_channels() -> None:
... | dcs-liberation/dcs_liberation | tests/test_tacan.py | test_tacan.py | py | 3,689 | python | en | code | 647 | github-code | 36 |
3845969200 | # С5.6. Итоговое практическое задание
# Телеграм-бот: Конвертор валют
# Студент: Кулагин Станислав
# Поток: FWP_123
import requests
import json
from config import keys, HEADERS
class APIException(Exception):
pass
class CryptoConvertor:
@staticmethod
def get_price(quote: str, base: str, amount: str):
... | kulstas/Skillfactory | С5.6._Telegram-bot/extensions.py | extensions.py | py | 1,359 | python | ru | code | 0 | github-code | 36 |
5057340753 | #!/usr/bin/python3
import logging
import logging.handlers
import speedtest
import thingspeak
import traceback
import json
import os
rootLogger = logging.getLogger('')
rootLogger.setLevel(logging.INFO)
def joinPathToScriptDirectory(path):
return os.path.join(os.path.dirname(os.path.abspath(__file__)), path)
def ... | barakwei/speedtestReporter | speedtestReporter.py | speedtestReporter.py | py | 1,783 | python | en | code | 0 | github-code | 36 |
17094646997 | """ Cheddargetter models used in framework."""
from collections import namedtuple
from hashlib import md5
import requests
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
from . import six
from .settings import settings
from .client import Client
from .utils import nam... | pavlov99/mouse | mouse/models.py | models.py | py | 3,132 | python | en | code | 3 | github-code | 36 |
16155570690 | import requests
from lxml import etree as et
import multiprocessing
import google.cloud.bigquery as bq
import os
import traceback
def position(arg):
l = arg
if l == 0:
pos = 1
return (pos)
else:
return (l + 1)
def foc_cum_call(url):
try:
return_list... | siva60/DataStructures | cumulative.py | cumulative.py | py | 5,114 | python | en | code | 0 | github-code | 36 |
23012205675 | """
Este código implementa a parte Coletora de um programa de fila de mensagens que coleta,
classifica e distribui tweets de acordo com tópicos selecionados pelo cliente.
Autores:
- Caio Miglioli @caiomiglioli
- Ryan Lazaretti @ryanramos01
Data de Criação: 30 de Maio de 2023
Ultima alteração: 31 de Maio de 2023
"... | caiomiglioli/sistemas-distribuidos | mq/colector/colector.py | colector.py | py | 2,464 | python | pt | code | 0 | github-code | 36 |
9829642790 | from collections import deque
PAID_COMMAND = "Paid"
END_COMMAND = "End"
q = deque()
while True:
command = input()
if command == PAID_COMMAND:
while q:
print(q.popleft())
elif command == END_COMMAND:
print(f"{len(q)} people remaining.")
break
else:
q.append(... | skafev/Python_advanced | 01First_week/03Supermarket.py | 03Supermarket.py | py | 329 | python | en | code | 0 | github-code | 36 |
19862950052 | from cvxopt import matrix, solvers
import numpy as np
import cvxopt
'''
问题描述:
minimize xQx+px
subject Gx <= h
Ax = b
注:Q=[[2, .5], [.5, 1]],即xQx=2x1^2+x^2+x1*x2
'''
Q = 2*matrix(np.array([[2, .5], [.5, 1]])) # 一定要乘以2
p = matrix([1.0, 1.0])
G = matrix([[-1.0, 0.0], [0.0, -1.0]])
h = matrix([0.0, 0.0])
A = mat... | 08zhangyi/multi-factor-gm-wind-joinquant | 掘金多因子开发测试/算法编写模板/CVXOPT/cvx_opt示例.py | cvx_opt示例.py | py | 449 | python | en | code | 180 | github-code | 36 |
73485148903 | import os
import sys
sys.stdin = open(
os.path.join("/", *__file__.split("/")[:-1], "sample_input.txt"), "r"
)
# https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5PpLlKAQ4DFAUq
import heapq
DR = [-1, 0, 1, 0]
DC = [0, 1, 0, -1]
STRUCT = {
0: [],
1: [0, 1, 2, 3],
2: [0,... | lexiconium/algorithms | swea/1953/1953.py | 1953.py | py | 1,337 | python | en | code | 0 | github-code | 36 |
10770344019 | import subprocess
import logging
import cliff.command
import configparser
import workflowlister
import json
import os
import sys
class Generator(cliff.command.Command):
"This Generator will generate new job orders based on the contents of ~/ini-dir. Be aware that it will also rewrite your params.json file and your... | ICGC-TCGA-PanCancer/cli | scripts/commands/generator.py | generator.py | py | 12,326 | python | en | code | 8 | github-code | 36 |
34091632487 | """
Реализовать структуру «Рейтинг», представляющую собой не возрастающий набор натуральных чисел. У пользователя
необходимо запрашивать новый элемент рейтинга. Если в рейтинге существуют элементы с одинаковыми значениями,
то новый элемент с тем же значением должен разместиться после них. Подсказка. Например, набор нат... | Vladarbinyan/GeekPython | Lesson02/HomeWork2.5.py | HomeWork2.5.py | py | 1,607 | python | ru | code | 0 | github-code | 36 |
71153098663 | import random
from copy import deepcopy
import numpy as np
from Individual import Individual
class Population:
def __init__(self, pop_size, p_cross, p_mut,
genotype_size, decode_fun, fit_fun,
cross_fun, plot=False):
self.population = [Individual(genotype_size, decode_fun,... | GrzegorzR/genetic_board_cut | src/genetic/Population.py | Population.py | py | 2,332 | python | en | code | 0 | github-code | 36 |
72594874024 | from django.urls import path
from .views import *
app_name = 'usermanagement'
urlpatterns = [
path('', login, name='login'),
path('dashboard', dashboard, name='dashboard'),
path('validate', login_validate, name='login_validate'),
path('logout/', logout, name='logout'),
] | kazimdrafiq/appraisal | usermanagement/urls.py | urls.py | py | 289 | python | en | code | 0 | github-code | 36 |
31654904058 | """
https://wikidocs.net/17114
Q4 리스트 총합 구하기
"""
A = [20, 55, 67, 82, 45, 33, 90, 87, 100, 25]
"""
sum = 0
B = []
for a in A:
if a>= 50:
B.extend([a])
sum += a
print("B:", B)
print("Sum:", sum)
"""
result = 0
B = []
while A:
mark = A.pop()
if mark >= 50:
B.extend([mark])
... | digitaldna4/helloworld | wikidocs-net/Q04.py | Q04.py | py | 387 | python | ko | code | 0 | github-code | 36 |
15502274443 | dadosTemp = dict()
cadastros = list()
while True:
nome = input('Nome: ').strip().lower().capitalize()
sexo = input('Sexo[M/F]: ').strip()[0]
while sexo not in 'MF':
sexo = input('Erro: Digite somente M ou F. Sexo[M/F]: ').strip()[0]
idade = int(input('Idade: '))
dadosTemp['nome'] = nome
... | JoaoGabsSR/EstudosDePython | PythonExercicios/ex094.py | ex094.py | py | 1,158 | python | pt | code | 0 | github-code | 36 |
3471857383 | import datetime
def message(msg):
print("\n------------------- "+msg.title()+" -------------------\n")
def box_message(msg):
s = "-" * (len(msg)+6)
print(s + "\n| "+msg.title()+" |\n"+ s)
def transformDate(date):
try:
splitted = list(map(lambda item : int(item), date.split("-")))
... | trset/Auction-System | utils.py | utils.py | py | 621 | python | en | code | 0 | github-code | 36 |
24206326335 | import os
import sys
import socket
import hashlib
fp = sys.argv[1]
unix_sock_fp = sys.argv[2]
mtds = set()
f = open(fp)
lines = f.read().strip().splitlines()
for line in lines:
line = line.strip()
if line[0:2] != '0x':
continue
# 0x7fb8e7f840c0 com.facebook.FacebookRequestError$b <init> ()V... | TOLLER-Android/main | useful-scripts/parse-minitrace-and-report.py | parse-minitrace-and-report.py | py | 622 | python | en | code | 20 | github-code | 36 |
31761726646 | import sys
horizon_n, vertical_n = map(int, sys.stdin.readline().split())
cut_N = int(input())
horizon_cut = [0, vertical_n]
vertical_cut = [0, horizon_n]
for i in range(cut_N):
tmp = list(map(int, sys.stdin.readline().split()))
if tmp[0]:
vertical_cut.append(tmp[1])
else:
horizon_cut.app... | 4RG0S/2020-Spring-Jookgorithm | 김노은/[List] 2628.py | [List] 2628.py | py | 664 | python | en | code | 4 | github-code | 36 |
36278467986 | import numpy
import scipy.linalg
from utils import utils
def compute_Sw_Sb(D, L):
num_classes = L.max()+1
D_c = [D[:, L==i] for i in range(num_classes)]
n_c = [D_c[i].shape[1] for i in range(num_classes)]
mu = utils.vcol(D.mean(1))
mu_c = [utils.vcol(D_c[i].mean(1)) for i in range(len(D_c))]
S... | aldopietromatera/2023_biometric_identity_verification_ML | BIV/biv/dimred/LDA.py | LDA.py | py | 1,155 | python | en | code | 0 | github-code | 36 |
75169232102 | # -*- coding:utf-8 -*-
__author__ = 'Jackie'
# import os
# import math
# from socket import *
# import logging
# import datetime
# import pickle
# import threading
# import sys
# from utils import constant as CONS
import random
if __name__ == "__main__":
i = random.random()
print(random.randrange(1, 100))
... | cyylele/DistributedSystem | test.py | test.py | py | 334 | python | en | code | 0 | github-code | 36 |
29288381937 | from src.futureLoc import futureLoc
import pytest
from unittest.mock import Mock, patch
from datetime import datetime
import requests
infoMessage = "On the 25/10/2023 at MLA airport: \n"
coldMessage = "It will be cold so you should wear warm clothing.\n"
warmMessage = "It will be warm so you should wear light clothing... | benbezz02/SoftwareTestingAssignment1 | tests/futureLoc_test.py | futureLoc_test.py | py | 3,395 | python | en | code | 0 | github-code | 36 |
26377828934 | from django.urls import path
from .views import *
urlpatterns = [
path('', BaseView.as_view(), name='base'),
path('catalog/all', CatalogView.as_view(), name='catalog'),
path('catalog/<str:slug>/', CategoryDetailView.as_view(), name='category_detail'),
path('catalog/<str:ct_model>/<str:slug>/', Product... | IvanPogorenko/MoonPie | todo/mainapp/urls.py | urls.py | py | 1,207 | python | en | code | 0 | github-code | 36 |
6347989238 | # 주소록 프로그램
# 2023-02-06
# DongHyun
# 예외처리!!
# 파일이 없을 때 발생하는 예외 - 예외 발생은 디버깅으로
# 입력시 개수가 다를 때
# 메뉴번호 입력 시 숫자외의 문자는 예외발생
import os # 운영체제용 모듈
# 2번
class Contact:
# 생성자 - 이름, 전번, 이메일, 주소
def __init__(self, name, phone_num, email, address) -> None:
self.__name = name
self.__phone_num = phone... | d0ng999/basic-Python2023 | project/address_app.py | address_app.py | py | 5,665 | python | ko | code | 0 | github-code | 36 |
3449199506 | # -*- coding: utf-8 -*-
r"""
Módulo ``cpwc``
===============
O CPWC (*Coherent Plane Wave Compounding*) é um algoritmo utilizado para
reconstruir imagens quando o tipo de inspeção é por ondas planas (*plane
waves*). Nesse método, todos os elementos de um transdutor do tipo *array*
linear são disparados simultaneamente... | matheusfdario/role-finder | AUSPEX-smart_wedge/imaging/cpwc.py | cpwc.py | py | 19,398 | python | pt | code | 0 | github-code | 36 |
17883605005 | import sys
from typing import TYPE_CHECKING, Callable, Dict, List
from PySide2.QtWidgets import QApplication
from PySide2.QtCore import Signal, QLocale, QTranslator
from lib.extensions.extensionlib import BaseExtension, BaseInterface
if TYPE_CHECKING:
pass
from lib.extensions.extensionlib import extension_li... | pyminer/pyminer | pyminer/packages/applications_toolbar/main.py | main.py | py | 5,307 | python | en | code | 77 | github-code | 36 |
40838203596 | names = ['John', 'Ana', 'Frank']
math = [80, 75, 91]
eng = [83, 76, 89]
sci = [81, 78, 92]
t = 0
ave = []
for m, e, s in zip(math, eng, sci):
ave.append((m + e + s)/3)
def gradeList(n, m, e, s):
print(f"{n[t]}'s grade (Math = {m[t]}, English = {e[t]}, Science = {s[t]}) and the average is {round(a... | lifershe/pythonEXP | bais_reycarlo_day5_act1.py | bais_reycarlo_day5_act1.py | py | 412 | python | en | code | 0 | github-code | 36 |
216944000 | # compose_flask/app.py
from flask import Flask
from redis import Redis
app = Flask(__name__)
redis = Redis(host='redis-container', port=6379)
@app.route('/')
def hello():
redis.incr('hits')
return ' - - - great has viewed {} time(s) - - -'.format(redis.get('hits'))
if __name__ == "__main__":
app.run(deb... | BigNews3/Docker | jour 2 - docker-compose/app/app.py | app.py | py | 356 | python | en | code | 0 | github-code | 36 |
19465887219 | '''
URLError异常
'''
#!/usr/bin/env python
#coding:utf-8
import urllib.request as request
import urllib.parse as parse
req=request.Request("http://blog.csdn.net/acq")
try:
response=request.urlopen(req)
print(response.read().decode("utf-8"))
except request.HTTPError as e:
print(e.code)
except request.URL... | zhongyoub/pythonSpider | src/Spider/URLError.py | URLError.py | py | 412 | python | en | code | 0 | github-code | 36 |
8010116096 | #!/usr/bin/env python3
# coding:utf-8
import subprocess
import re
from .taskbase import TaskBase
class Nmap(TaskBase):
'''调用Nmap的扫描任务
通过nmap执行扫描任务,因此参数格式遵循nmap调用格式
参数:options
{
'target': [ip1,ip2,ip3...],ip列表(nmap格式)
'port': '1-65535'/'--top-ports 100... | CrackerCat/nemo | nemo/core/tasks/nmap.py | nmap.py | py | 4,555 | python | en | code | 1 | github-code | 36 |
6105238329 | import numpy as np
import cv2
cap = cv2.VideoCapture(1 + cv2.CAP_V4L)
cap.set(cv2.CAP_PROP_CONVERT_RGB, 0) # turn off RGB conversion
while(True):
# Capture frame-by-frame
_, frame = cap.read()
bf81 = np.array(frame // 16, dtype=np.uint8)
# Create the mask
#binary = cv2.imread('Masked_Image.png', ... | maykef/Fluorometer | opencv_contours.py | opencv_contours.py | py | 736 | python | en | code | 0 | github-code | 36 |
33540682823 | #!/usr/bin/env python3
import logging
from apache_beam.runners import DataflowRunner
from modules import combined_pipeline
def run(argv=None):
logging.getLogger().setLevel(logging.INFO)
p = combined_pipeline.create_pipeline()
pipeline_result = p.run(argv)
if not isinstance(p.runner, DataflowRunner)... | HTTPArchive/data-pipeline | run_combined.py | run_combined.py | py | 405 | python | en | code | 3 | github-code | 36 |
6642673356 | ##LC 1252. Cells with Odd Values in a Matrix
#Solution
class Solution(object):
def oddCells(self, n, m, indices):
"""
:type n: int
:type m: int
:type indices: List[List[int]]
:rtype: int
"""
row = [0]*n
col = [0]*m
for ind in indices:... | Caonisandaye/LeetCode | 1252.py | 1252.py | py | 638 | python | en | code | 1 | github-code | 36 |
18540102269 |
import random
import numpy as np
import cv2
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
import os
import random
import math
from datetime import datetime
from collections import Counter
import pandas as pd
import numpy as np
import cv2
from PIL import Image
from pathlib import Pa... | byrongt12/CNN_fruit_disease_detection | code/dataset.py | dataset.py | py | 6,842 | python | en | code | 0 | github-code | 36 |
8844303859 | channels = 1
sr = 22050
input_dim = 60
dtw_cost = 'cosine'
dtw_k = 1.05
patterns_rel_path = "patterns"
models_rel_path = "model"
preprocessed_rel_path = "preprocessed"
pattern_path_suffix = "_pattern"
recording_extension = ".raw"
recordings_glob = "*" + recording_extension
model_extension = ".npy"
models_glob = "*" + ... | d32f123/master-thesis | python/config.py | config.py | py | 363 | python | en | code | 0 | github-code | 36 |
14472017953 | import numpy as np
from missile import Missile
from target import Target, Target2D
from interpolation import Interp1d
from math import *
class MissileGym(object):
@classmethod
def make_simple_scenario(cls, missile_opts, target_pos, target_vel):
"""
Классовый метод создания простого сценария д... | kirtis26/missile_project | missile_gym.py | missile_gym.py | py | 12,612 | python | ru | code | 0 | github-code | 36 |
16929362639 | import os
from sys import stdout
def red():
RED = "\033[1;31m"
stdout.write(RED)
def green():
GREEN = "\033[0;32m"
stdout.write(GREEN)
def blue():
BLUE = "\033[1;34m"
stdout.write(BLUE)
def yellow():
YELLOW = "\033[1;33m"
stdout.write(YELLOW)
def purple():
PURPLE = "\033[1;35m"... | yorkox0/fastMeterpreter | fastMeterpreter.py | fastMeterpreter.py | py | 3,938 | python | en | code | 4 | github-code | 36 |
70437591145 | import os
"""
Goes through each folder and replaces the google code with my code
"""
thePath = []
def pushPath(path):
thePath.append(path)
def popPath():
thePath.pop()
def replaceAllHtml(root):
try:
os.chdir('./'+ root)
for file in os.listdir('./'):
if '.html' in file:
replaceTheCode(file)
else:
... | dgs3/DGSITE | public_html/cgi-bin/googleAnalysisParse.py | googleAnalysisParse.py | py | 736 | python | en | code | 1 | github-code | 36 |
32341359777 | '''
Created on Jul 19, 2011
@author: rtaylor
'''
from segment import Segment
from shell import Shell
from circle import Circle
from mymath import reflect,calcShellAngle
from math import tan,atan
from numpy.linalg import norm
class Module:
'''
A complete foxsi module. By default, it consists of seven nested sh... | humatic/foxsi-optics-sim | src/foxsisim/module.py | module.py | py | 8,412 | python | en | code | 0 | github-code | 36 |
16779725846 | #quicksort
from random import shuffle
import pygame, time
from math import ceil
from random import shuffle
import pygame, time
sizex = 1800
sizey = 1200
surface = pygame.display.set_mode((sizex,sizey))
colour = [255, 5, 5]
black = (0,0,0)
red = (255, 5, 5)
black = (0,0,0)
green = (0, 255, 5)
blue = (5, 5, 255)
n ... | FergusMunro/Sorting-Algoritms-in-Pygame | quicksort.py | quicksort.py | py | 2,098 | python | en | code | 0 | github-code | 36 |
74497600425 | #!/usr/bin/env python3
import asyncio
import atexit
import json
import socket
from collections import deque
from datetime import datetime
from logging import getLogger, INFO, StreamHandler, FileHandler
from time import sleep
from subprocess import run
from os import path
from simple_pid import PID
from tinkerforge.i... | BenVosper/heated | regulated.py | regulated.py | py | 17,089 | python | en | code | 0 | github-code | 36 |
3050143393 | from smort.src.translate.theory.available_theories import *
def get_sort_in_synonym(symbol: str, pars: list, synonyms: dict):
"""
convert symbol to "basic" sort synonym
par_list is replaced by pars
"""
if symbol in synonyms:
sort, par_list = synonyms[symbol]
par_dict = {}
f... | nn9y/smort | smort/src/translate/theory/signatures.py | signatures.py | py | 2,340 | python | en | code | 0 | github-code | 36 |
34684398194 | #!/Users/kalindbl/bin/virtualenv/biopython/bin/python
'''
Take an xml file of MDS-IES annotations and produce a new XML file with these added annotations:
- whether the MDS annotation is "valid," i.e. covers the MAC chromosome completely with only pointer overlap
- which MAC contigs come from multiple MIC loci
- wh... | kelind/scrambling-pfsa | annotate_xml_maps.py | annotate_xml_maps.py | py | 5,720 | python | en | code | 0 | github-code | 36 |
16193335597 | # funzione che, data una lista di numeri, fornisce in output un
# istogramma basato su questi numeri, usando asterischi per disegnarlo.
# Ad esempio, data la lista [3,7,9,5] deve produrre questo grafico:
# ***
# *******
# *********
# *****
def istogramma():
stampa=''
while 3>1:
num=int(input('Inserisc... | francescaser/pyAcademy | Esercizi base 22-02/FuncIstogramma.py | FuncIstogramma.py | py | 576 | python | it | code | 0 | github-code | 36 |
74789760744 | import unittest
from .pick_up import PickUp
from embasp.languages.pddl.pddl_mapper import PDDLMapper
class PDDLMapperTest(unittest.TestCase):
def test(self):
instance = PDDLMapper.get_instance()
try:
instance.register_class(PickUp)
obj = instance.get_object("(pick-up b... | DeMaCS-UNICAL/EmbASP-Python | test/language/pddl/pddl_mapper_test.py | pddl_mapper_test.py | py | 541 | python | en | code | 2 | github-code | 36 |
15985105295 | from inspect import signature
import torch
import torch.nn as nn
from mmcv.runner import force_fp32
from mmdet.core import images_to_levels, multi_apply, unmap, MaxIoUAssigner
from mmrotate.core import (build_assigner, obb2hbb, build_sampler,
rotated_anchor_inside_flags, )
from ..builder i... | zhangiguang/EOOD | mmrotate/models/dense_heads/rotated_eood_head.py | rotated_eood_head.py | py | 23,502 | python | en | code | 2 | github-code | 36 |
11188337575 | import subprocess
import shlex
import re
import os
import time
import platform
import json
import sys
import base64
import random
import datetime
import traceback
import robot_util
import _thread
import copy
import argparse
#import audio_util
import urllib.request
import rtc_signaling
from subprocess import Popen, PIP... | robotstreamer/robotstreamer_win_obs | send_video_obs_webrtc.py | send_video_obs_webrtc.py | py | 9,495 | python | en | code | 0 | github-code | 36 |
22729212301 | #!/usr/bin/python3
import argparse
import os
import re
parser = argparse.ArgumentParser(description='Creates a directory with rasdaman import-ready files structure by creating symlinks to the cubeR native file structure.')
parser.add_argument('--dataDir', default='/media/GFTP/landsupport/cubeR/tiles/', help='directo... | IVFL-BOKU/landsupport | python/rename2rasdaman.py | rename2rasdaman.py | py | 2,855 | python | en | code | 0 | github-code | 36 |
13990607578 | """
This is faster approach leveraging counting sort algorithm,
whose complexity is linear; O(n), where n = len(s)
It may not be evident that algorithm below is linear, given the
intrinsic nested loops (3 levels). But one way to look at that,
is that we are imposing a tree structure of 2 levels above the list.
On the ... | dariomx/topcoder-srm | leetcode/zero-pass/google/sort-characters-by-frequency/Solution1.py | Solution1.py | py | 1,767 | python | en | code | 0 | github-code | 36 |
43471654353 | from fastapi import APIRouter, Query, Depends, status
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
from pydantic.error_wrappers import ValidationError
from online_inference.model_load import get_model, make_prediction
from online_inference import schema_utils
from online_inf... | made-mlops-2022/mlops_LisinFedor | src/online_inference/testing_router.py | testing_router.py | py | 2,361 | python | en | code | 0 | github-code | 36 |
75260155305 | from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
from core.models import Tag, Recipe
from recipes.serializers import TagSerializer
TAG_URL = reverse("recipes:tag-list")
def sa... | trolliama/recipes-api | app/recipes/tests/test_tags_api.py | test_tags_api.py | py | 3,796 | python | en | code | 0 | github-code | 36 |
34796148959 | from sage.matrix.special import diagonal_matrix, identity_matrix
def signed_hermite_normal_form(A):
"""
Signed Hermite normal form of an integer matrix A, see [PP19, Section 6].
This is a normal form up to left-multiplication by invertible matrices and change of sign of the columns.
A matrix in signed... | giove91/arithmat | arithmat/shnf.py | shnf.py | py | 4,063 | python | en | code | 1 | github-code | 36 |
34450879227 | import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap
from matplotlib.lines import Line2D
import pandas as pd
#Max R during main sequence and max R in general
z = [0.001, 0.02]
Rgen = np.zeros([70,3])
Rms = np.zeros([70,3])
n = 0
for metal in z:
i... | kajasiek/Astrophysics5 | Task 2/task2-data.py | task2-data.py | py | 4,441 | python | en | code | 0 | github-code | 36 |
2659394054 | #!/usr/bin/env python3
list_headers = []
list_seq = []
seq = ''
with open ('Q5.fasta','r') as file:
for line in file:
line = line.rstrip()
if line.startswith('>'):
list_headers.append(line)
if seq:
list_seq.append(seq)
seq = ''
else:
seq += line
list_seq.append(seq)
print (list_heade... | fishenm1/PFB_problemsets | Python6/Q5.FASTAparser.py | Q5.FASTAparser.py | py | 427 | python | en | code | 0 | github-code | 36 |
8425228760 | import os
from cv2.cv2 import CascadeClassifier, imread
def detect_face(image_path):
# Get user supplied values
casc_path = os.path.join(os.path.dirname(__file__), "haarcascade_frontalface_default.xml")
# Create the haar cascade
face_cascade = CascadeClassifier(casc_path)
# Read the image as gr... | wobeng/zappa_resize_image_on_fly | detect_face.py | detect_face.py | py | 748 | python | en | code | 17 | github-code | 36 |
74339878182 | #!/usr/bin/env python3
from restsyscollector_ps_interface_class import RestSysCollectorPsInterface
from restsyscollector_ps_system_class import RestSysCollectorPsSystem
from restsyscollector_format_class import RestSysCollectorFormat
import sys
sys.path.append("../python")
sys.path.append("src/main/python")
class Res... | kvogelgesang/py-rest-sys-collect | src/main/python/restsyscollector/restsyscollector_ps_main_class.py | restsyscollector_ps_main_class.py | py | 2,941 | python | en | code | 0 | github-code | 36 |
11488764915 | from enum import Enum
from pathlib import Path
from typer import Option, Typer
from .upload import upload
class Track(str, Enum):
internal = "internal"
alpha = "alpha"
beta = "beta"
production = "production"
rollout = "rollout"
app = Typer()
@app.callback()
def callback():
"""
Androi... | leynier/androidpublisher | androidpublisher/main.py | main.py | py | 1,007 | python | en | code | 4 | github-code | 36 |
7055227899 | #from django.shortcuts import render
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponse
import redis
# Create your views here.
def home(request): # load page home
return render(request,'task/home.html')
#*************************************************************
def is_... | rasoolgh71/isredis | task/views.py | views.py | py | 947 | python | en | code | 0 | github-code | 36 |
29989847785 | # Import dependencies
import os
import csv
election_data = os.path.join("election_data.csv")
# Assign Variables
TotalVotes = 0
Candidates = {}
Candidate = ""
WinnerVotes = 0
WinnerName = ""
with open(election_data, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
csv_header = next(csvf... | jeffersoncovey/Week4Python | PyPoll/Main.py | Main.py | py | 2,216 | python | en | code | 0 | github-code | 36 |
30609717940 | # Python: v3.9.13, OS: Windows 11
import os
import sys
import json
import random
import geojson
import folium
import webbrowser
import pandas as pd
# GTFS folder location
input_folder = r'D:\dev\github\GTFS_Visualization\01_source\Open_Data_MMTS_Hyd'
# Output folder location to store geojson, html files
output_fold... | sahachandan/GTFS_Visualization | 02_script/visualize_routes_without_shapes_txt.py | visualize_routes_without_shapes_txt.py | py | 8,835 | python | en | code | 0 | github-code | 36 |
72745850025 | from django.http import HttpResponse
from django.shortcuts import render, redirect
from .models import Movies
from .form import MovieForm
# Create your views here.
def Home(request):
movies = Movies.objects.all()
context = {
'movie_list': movies
}
return render(request, "home.html", context)
... | neetutom/movieProject | movie_project/movieApp/views.py | views.py | py | 1,327 | python | en | code | 0 | github-code | 36 |
36954801239 | import wttest
# test_autoclose
class test_autoclose(wttest.WiredTigerTestCase):
"""
Check that when closed handles are used, there is a catchable
error thrown, and that when a handle is closed, any subordinate
handles are also closed.
"""
uri = 'table:test_autoclose'
def create_table(self)... | mongodb/mongo | src/third_party/wiredtiger/test/suite/test_autoclose.py | test_autoclose.py | py | 4,487 | python | en | code | 24,670 | github-code | 36 |
17752793066 | import socket
from jsonNetwork import Timeout, sendJSON, receiveJSON, NotAJSONObject, fetch
from threading import Thread, Timer
import importlib
import sys
from championship import Championship, addPlayer, getAllPlayers, getState, changePlayerStatus, updateState, hookRegister
from graphics import ui
def checkClient(ad... | jmimassi/IA-Abalone | server.py | server.py | py | 3,582 | python | en | code | 0 | github-code | 36 |
71686600425 | def summation(*a):
summ=0
b=[]
for i in a:
if i<0:
b.append(abs(i)*2)
else:
b.append(i)
mx=max(b)
summ=sum(b)/mx
return summ
print(summation(-10,2,3,15,-4))
| VadimS077/ITAM_python_cource_2022 | homeworks/chapter-2/1_C.py | 1_C.py | py | 237 | python | en | code | 0 | github-code | 36 |
36902270914 | from fenics import *
from mshr import *
import scipy.io
import numpy as np
data = scipy.io.loadmat('neuron_input_1.hdf5')
if MPI.rank(MPI.comm_world) == 0:
print(data.keys())
x = data['x']
y = data['y']
z = data['z']
xlen = x.max() - x.min()
ylen = y.max() - y.min()
zlen = z.max() - z.min()
if MPI.rank(MPI.com... | CINPLA/KNPsim | examples/hay_model/make_mesh.py | make_mesh.py | py | 1,247 | python | en | code | 3 | github-code | 36 |
25234742924 | import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPool2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import load_model
from tensorflow.keras.callbacks import EarlyStoppi... | Ashish2Parimi/Chrome-Bot | Network.py | Network.py | py | 2,533 | python | en | code | 0 | github-code | 36 |
59323449 | import f90nml
import sys
import os
import shutil
import numpy as np
import subprocess
import integral2d
import math
from scipy.special import *
cwd = os.getcwd()
args = sys.argv
root = args[1]
dest = args[2]
opt = args[3]
coef = float(dest)
fdtd_path = "/home/b/b36288/large0/drude/fdtd"
root... | takagi-junya/pyprogs | param.py | param.py | py | 4,849 | python | en | code | 0 | github-code | 36 |
8912694482 | from config.config_train import dataset_type
model_file = {
"noun" : { "pretrain" : "cnn_noun_pretrain.pt", "train" : "cnn_noun_train.pt" },
"pronoun" : { "pretrain" : "cnn_pronoun_pretrain.pt", "train" : "cnn_pronoun_train.pt" },
"verb" : { "pretrain" : "cnn_verb_pretrain.pt",... | philgookang/pcr | config/config_file.py | config_file.py | py | 2,527 | python | en | code | 3 | github-code | 36 |
38697493522 | # TODO: import 見直し
import numpy as np
from collections import deque
from tqdm import tqdm # progress bar
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import gym
from gym import spaces
from gym.spaces.box import Box
import cv2
cv2.ocl.setUseOpenCL(False)
from stabl... | retrobighead/space_invaders | lib/environments.py | environments.py | py | 11,257 | python | en | code | 0 | github-code | 36 |
22533622469 | import requests
from config import API_KEY
# from flask import jsonify
def get_data(query):
# query = "Bread"
print(query)
url = "https://api.nal.usda.gov/fdc/v1/foods/search?"
query_url = f"{url}api_key={API_KEY}&query={query}"
x = requests.get(query_url)
# x = requests.get('https://ap... | reginesgit/Nutritional-Analysis-of-USDA-Foods | get_foods.py | get_foods.py | py | 634 | python | en | code | 1 | github-code | 36 |
19699158710 | import json
MANDATORY_SETTINGS = ('FunctionName', 'Handler', 'Role', 'Runtime')
def load_settings(filepath):
with open(filepath, 'r') as f:
settings = json.loads(f.read())
for key in MANDATORY_SETTINGS:
try:
assert key in settings
except AssertionError:
raise K... | InfraPixels/powerlibs-aws-lambda-deployer | powerlibs/aws/λ/deployer/lambda_settings.py | lambda_settings.py | py | 398 | python | en | code | 0 | github-code | 36 |
35279762446 | # 출력층 설계하기
# 기계학습 문제는 분류와 회구로 나뉩는다 분류는 데이타가 어느 클래스 속 하느냐 문제
# 항등 함수와 소프트맥스 함수 구현하기
# 항등 함수는 입력을 대로 출력
# 입력과 출력이 항상 같다는 뜻
# 소프트맥스 함수
# 소프트맥스의 출력은 모든 입력 신호로부터 화살표를 받는다
# 출력층의 각 뉴런이 모든 입력 신호에서 영향을 받기 대문이다
import numpy as np
a = np.array([0.3, 2.9, 4.0])
def softmax(a):
exp_a = np.exp(a) # 지수 함수
sum_exp_... | juneglee/Deep_Learning | Deep-Learning/scratch/chapter02/ex07.py | ex07.py | py | 744 | python | ko | code | 0 | github-code | 36 |
21654121522 | from requests import request
from json import loads
emails = [
("hello.world", "failure"),
("hello.world@company.com", "success"),
("hello.world@", "failure"),
("hello.world@.com", "failure"),
("hello.world@company.gov.in", "success"),
("hello.world@company.edu", "success")
]
for email in ... | Amitroshan1/python | JSON/email_api.py | email_api.py | py | 770 | python | en | code | 0 | github-code | 36 |
23959473202 | import pymongo
from datetime import datetime, timedelta
from db import DBHandler
from tinkof import FetchPrices, quotation2float
import asyncio
import os
connString = os.getenv('MONGODB_CONNSTRING')
dbName = os.getenv('MONGODB_DATABASE')
client = pymongo.MongoClient(connString)
db2 = client[dbName]
def CalcProfit(b... | Ne0Ment/nomisma | updateprices.py | updateprices.py | py | 2,162 | python | en | code | 1 | github-code | 36 |
27659344765 | import random
import string
import input_processing as w
def gen_LD(word, dist):
word_l = list(word)
if dist > len(word):
new_word = ''
for _ in range(dist):
new_letter = random.choice(string.ascii_lowercase)
while new_letter in word_l:
new_letter = ran... | samu9/keras_edit_distance | gen_LD.py | gen_LD.py | py | 2,617 | python | en | code | 0 | github-code | 36 |
938929232 | import os
from subprocess import run
from chimera_app.config import BIN_PATH
POWER_TOOL_PATH = os.path.join(BIN_PATH, 'power-tool')
DEVICE_DB = {
# Aya Neo 2021
'AMD Ryzen 5 4500U with Radeon Graphics' : {
'min_tdp' : 5,
'max_tdp' : 28,
'max_boost' : 2,
},
# Aya Neo Air
... | ChimeraOS/chimera | chimera_app/power.py | power.py | py | 1,742 | python | en | code | 189 | github-code | 36 |
29290633558 | __author__ = "Hao Qin"
__email__ = "awww797877@gmail.com"
import numpy as np
from data import dummy
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
BATCH_SIZE = 32
def get_y(poses, index_pose1, index_pose2, num_batch_images, max_transform, max_rotation):
transform = np.square(
... | QinHarry/CNN_SLAM | temp.py | temp.py | py | 1,927 | python | en | code | 6 | github-code | 36 |
75075865384 | from __future__ import unicode_literals
import frappe
from frappe.utils.make_random import how_many, can_make
from frappe.desk import query_report
from frappe.utils import cstr
from erpnext_demo import settings
def run_manufacturing(current_date):
from erpnext.projects.doctype.time_log.time_log import NotSubmittedEr... | frappe/erpnext_demo | erpnext_demo/manufacturing.py | manufacturing.py | py | 2,743 | python | en | code | 2 | github-code | 36 |
8446087178 | import pickle
import unittest
from cupy.cuda import cutensor
@unittest.skipUnless(cutensor.available, 'cuTensor is unavailable')
class TestExceptionPicklable(unittest.TestCase):
def test(self):
e1 = cutensor.CuTensorError(1)
e2 = pickle.loads(pickle.dumps(e1))
assert e1.args == e2.args
... | cupy/cupy | tests/cupy_tests/cuda_tests/test_cutensor.py | test_cutensor.py | py | 353 | python | en | code | 7,341 | github-code | 36 |
38724560306 | # import the packages
from getAnimePics.items import GetanimepicsItem
import datetime
import scrapy
from scrapy.exceptions import CloseSpider
pageNumber = 0
class CoverSpider(scrapy.Spider):
name = "gelbooruSearch"
allowed_domains = ['gelbooru.com']
start_urls = ["https://gelbooru.com/index.php?page=post&... | kkc028/Animage-Scraper | getAnimePics/spiders/coverspider.py | coverspider.py | py | 2,990 | python | en | code | 0 | github-code | 36 |
36521165263 | import json
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, f1_score
def train_model(features, target, train_params):
mt = train_params.model_type
if train_params.model_type == 'RandomForestClas... | made-mlops-2022/made_obarskayats | ml_project/models/model_fit_predict.py | model_fit_predict.py | py | 1,782 | python | en | code | 0 | github-code | 36 |
7253701477 | from core.models import Habit, DailyRecord, User
from rest_framework import serializers
class DailyRecordSerializer(serializers.ModelSerializer):
class Meta:
model = DailyRecord
fields = ("date", "note",)
class HabitSerializer(serializers.ModelSerializer):
daily_records = DailyRecordSerializ... | Momentum-Team-9/django-habit-tracker-esparr | api/serializers.py | serializers.py | py | 875 | python | en | code | 0 | github-code | 36 |
6631832723 | import numpy as np
from tqdm import tqdm
import random
import matplotlib.pyplot as plt
from simplenn.layers import *
class Model:
def __init__(self, layers, verbose=False):
self.layers = layers
def set_verbosity(self, verbose):
for l in self.layers:
if hasattr(l, 'verbose'):
... | tlsdmstn56/simple-nn | example/train_linear_model.py | train_linear_model.py | py | 3,129 | python | en | code | 0 | github-code | 36 |
42456044912 | import time
import numpy as np
import scipy.io as sio
from datetime import datetime
import cPickle as pickle
import sys
# local modules
import wtahash as wh
import cluster
import utils
class Evaluation:
''' Class for evaluating the speed and storing the rankings of a dataset
using WTAHash.
'''
def... | pombredanne/wtahash | evaluation.py | evaluation.py | py | 13,985 | python | en | code | 0 | github-code | 36 |
37734863671 | from __future__ import print_function
import time
import numpy as np
import matplotlib.pyplot as plt
from stats232a.classifiers.fc_net import *
from stats232a.data_utils import *
from stats232a.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array
from stats232a.solver import Solver
from stats232... | riemanli/UCLA_STATS_232A_Statistical_Modeling_and_Learning_in_Vision_and_Cognition | project2/stats232a/test.py | test.py | py | 27,975 | python | en | code | 0 | github-code | 36 |
21144519916 | import json
import logging
import os
import pickle
import random
import multiprocessing
from copy import deepcopy
import torch
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm
from ipdb import set_trace
from transformers import AutoTokenizer, BertTokenizer
class MemExamples:
def __init__(se... | KeDaCoYa/MKG-GC | knowledge_embedding/src/utils/lpbert_dataset.py | lpbert_dataset.py | py | 17,076 | python | en | code | 0 | github-code | 36 |
40311915793 | import backtrader as bt
from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (15,8)
import csv
cerebro = bt.Cerebro(stdstats=False)
cerebro.addobserver(bt.observers.BuySell)
cerebro.addobserver(bt.observers.Broker)
data = bt.feeds.GenericCSVData(
datan... | webclinic017/volatility-strategy | backtest/DemoVolatility.py | DemoVolatility.py | py | 6,703 | python | en | code | 0 | github-code | 36 |
74126359465 | import numpy as np
import math
def calculate(list):
# check if all elements are numbers.
try:
numbers = [float(x) for x in list]
except:
raise ValueError("List must only contain numbers.")
# if less then 9 elements, raise exceptions.
flattened_data = np.array(numbers)
if len(flattened_data) ... | alexbaraona/statics_calculator | mean_var_std.py | mean_var_std.py | py | 1,362 | python | en | code | 0 | github-code | 36 |
260051339 | #!/usr/bin/env python
'''
Handy script to prepare the data for Tensorflow object detection API.
'''
import tensorflow as tf
import yaml
import os
import sys
from object_detection.utils import dataset_util
flags = tf.app.flags
flags.DEFINE_string('output_path', 'out.record', 'Path to output TFRecord')
flags.DEF... | iamfaisalkhan/CarND-Capstone | traffic_light_detection/prepare_tf_record.py | prepare_tf_record.py | py | 3,358 | python | en | code | 1 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.