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
31313726066
import json import os from dataclasses import dataclass from typing import Any, List import fire import tinytuya ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SNAPSHOTFILE = '%s/setup/snapshot.json' % ROOT_DIR rainbow = { 'red': [255, 0, 0], 'orange': [255, 127, 0], 'yellow': [25...
paraizofelipe/py_iot
py_iot/local.py
local.py
py
2,821
python
en
code
0
github-code
36
43699042743
#!/usr/bin/env pybricks-micropython from pybricks.hubs import EV3Brick from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor, InfraredSensor, UltrasonicSensor, GyroSensor) from pybricks.parameters import Port, Stop, Direction, Button, Color from pybricks.tools import wait, St...
brendanvarmazis/Mechatronics-Project
main (1).py
main (1).py
py
5,593
python
en
code
0
github-code
36
36901670976
import pandas as pd class HistoricalData: def __init__(self, raw_data: pd.DataFrame, open_index: str = "Open", close_index: str = "Close") -> None: self._raw_data = raw_data self.open_index = open_index self.close_index = close_index self._return_mean: float = None self._r...
ethanlee928/pyfmc
pyfmc/common/historical_data.py
historical_data.py
py
995
python
en
code
1
github-code
36
71607807144
# USAGE # To read and write back out to video: # python people_counter.py --prototxt mobilenet_ssd/MobileNetSSD_deploy.prototxt \ # --model mobilenet_ssd/MobileNetSSD_deploy.caffemodel --input videos/example_01.mp4 \ # --output output/output_01.avi # # To read from webcam and write back out to disk: # python people_cou...
smriti283/Seating-preferences-of-Metrotech-visitors
Object Tracking Python Script/people_counter4.py
people_counter4.py
py
16,223
python
en
code
0
github-code
36
18036744087
class Solution: def addStrings(self, num1: str, num2: str) -> str: num1, num2 = list(num1), list(num2) carry, res = 0, [] while len(num2) > 0 or len(num1) > 0: n1 = n2 = 0 if num1: n1 = ord(num1.pop()) - ord('0') if num2: n2 = ord(num2.pop()) - or...
LittleCrazyDog/LeetCode
415-add-strings/415-add-strings.py
415-add-strings.py
py
511
python
en
code
2
github-code
36
27918407911
# Python 3.5.1 tested # # If downloaded set is out of date, ie. does not contain most recent comic # then the comics since most recently downloaded will be downloaded. # If however the most recent comic is present, the script will scan all # previous comics, ensuring ALL of them are present # # It is possible that scri...
MikeCroall/xkcd-crawler
xkcd_crawler.py
xkcd_crawler.py
py
2,877
python
en
code
0
github-code
36
31279498412
from minio import Minio import redis import time import json APP = "wc" minio_client = Minio("minio-service.yasb-mapreduce-db.svc.cluster.local:9000", access_key="admin123", secret_key="admin123", secure=False) redis_client = redis.Redis(host="redis.yasb-mapreduce-db.svc.cluster.local", port=6379) def handle(req): ...
tju-hwh/Yet-Another-Serverless-Benchmark
mapreduce/openfaas/wc/functions/wc-mapper/handler.py
handler.py
py
2,118
python
en
code
0
github-code
36
41332456125
# coding=utf-8 import xml.etree.ElementTree as ET import matplotlib.pyplot as plt import collections import pprint as pp from scipy.stats import gaussian_kde from numpy import arange def violin_plot(ax,data,pos, bp=False): ''' create violin plots on an axis ''' dist = max(pos)-min(pos) w = min(0.15*max(dist,1.0),...
mimi33/DiplomskiProjekt
testing/5.velPop/boxplot.py
boxplot.py
py
2,615
python
en
code
0
github-code
36
41892613658
from django.db.models.signals import pre_save class Profile(models.Model): to_receive_new_user = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) @receiver(pre_save, sender=User) def update_profile(sender, instance, **kwargs): instance.to_receive_new_user = ...
Horlawhumy-dev/earthly-django-signals-article
pre_save.py
pre_save.py
py
367
python
en
code
2
github-code
36
22439806116
import os import torch import torchvision.transforms as transforms import torchvision.datasets as datasets from .. import config as conf processed_data_dir = conf.processed_data_dir raw_data_dir = conf.raw_data_dir # Create the directories if they don't exist os.makedirs(raw_data_dir, exist_ok=True) os.makedirs...
ayush0O7/Handwritten-Digit-Recognition
Handwritten_digit_recognition/src/data/download_mnist.py
download_mnist.py
py
1,360
python
en
code
0
github-code
36
19830605646
#! /bin/python3 # -*- coding: utf-8 -*- import numpy as np from selfnet.train import Trainer from selfnet.net import Network from selfnet.layers import LinearLayer, ActivationLayerRelu # create training data def output_y(x): return x * 3.0 X = np.random.sample((100, 1)) y = output_y(X) # create network net...
bricksdont/selfnet
examples/scalar.py
scalar.py
py
545
python
en
code
1
github-code
36
73583264745
import phunspell import inspect import unittest class TestRO(unittest.TestCase): pspell = phunspell.Phunspell('ro_RO') def test_word_found(self): self.assertTrue(self.pspell.lookup("nesesizată")) def test_word_not_found(self): self.assertFalse(self.pspell.lookup("phunspell")) def te...
dvwright/phunspell
phunspell/tests/test__ro.py
test__ro.py
py
592
python
en
code
4
github-code
36
16636486035
from __future__ import absolute_import import itertools import math import warnings from typing import List, Iterable, Tuple, Optional import cv2 import numpy as np from .torch_utils import image_to_tensor __all__ = [ "plot_confusion_matrix", "render_figure_to_tensor", "hstack_autopad", "vstack_auto...
BloodAxe/pytorch-toolbelt
pytorch_toolbelt/utils/visualization.py
visualization.py
py
7,811
python
en
code
1,447
github-code
36
6482852553
#pip install opencv-python import cv2 webcam = cv2.VideoCapture(0) try: if webcam.isOpened(): validacao, frame = webcam.read() cv2.imwrite("testeWebcam.png", frame) webcam.release() cv2.destroyAllWindows() except: print("Não foi possível abrir a câmera.")
msullivancm/ProjetosComAte10LinhasDeCodigoPython
FotoSurpresa.py
FotoSurpresa.py
py
293
python
pt
code
0
github-code
36
43693778478
numbers = input().split(", ") numbers = list(map(lambda n: int(n), numbers)) boundary = 10 while len(numbers) > 0: group_list = [num for num in numbers if num <= boundary] for n in group_list: if n in numbers: numbers.remove(n) print(f"Group of {boundary}'s: {group_list}") bound...
AntoniyaV/SoftUni-Exercises
Fundamentals/05-Lists-Advanced/06-group-of-10s.py
06-group-of-10s.py
py
330
python
en
code
0
github-code
36
2251689523
import os import imageio import argparse import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from natsort import natsorted from PIL import Image, ImageDraw, ImageFont def plot_generated(generated_imgs, dim=(1, 10), figsize=(12, 2), save_name=None): plt.figure(figsize=figsiz...
thbeucher/ML_pytorch
apop/GAN/plotter.py
plotter.py
py
4,225
python
en
code
0
github-code
36
5571329753
import pandas as pd import jieba import warnings import re warnings.filterwarnings('ignore') import json # 第一大部分,查全率,查准率的计算 def judge(strs): strs = strs.split(",") l = [] for s in strs: s = s.replace('[',"").replace(']',"").replace("'","") l.append(int(s)) return l def tongji(l1,l2): ...
MJ-NCEPU/HauZhongBei
DataMining.py
DataMining.py
py
7,045
python
en
code
0
github-code
36
15615165732
from sys import argv, exit from collections import OrderedDict from functools import reduce import re import httplib2 # Google API from apiclient import discovery from apiclient.errors import HttpError from oauth2client import client, tools from oauth2client.file import Storage # Reddit API import praw import OAuth2U...
JohnnyDeuss/reddit-bots
PenpalsVerification/PenpalsVerification.py
PenpalsVerification.py
py
16,850
python
en
code
5
github-code
36
18372870438
# -*- coding: utf-8 -*- """ Created on Tue Aug 4 06:23:00 2020 @author: niili 2_7 обчучение перцептрона Реализуйте метод vectorized_forward_pass класса Perceptron. n — количество примеров, m — количество входов. Размерность входных данных input_matrix — (n, m), размерность вектора весов — (m, 1), смещение (bias) —...
anasdy/stepic_bionf_neural_network
2_7_perceptron.py
2_7_perceptron.py
py
7,258
python
ru
code
0
github-code
36
72234605223
""" CEM Agent class, which takes in a PolicyModel object [1] Learning Tetris with the Noisy Cross-Entropy Method (Szita, Lorincz 2006) pdf: http://nipg.inf.elte.hu/publications/szita06learning.pdf """ from yarlp.agent.base_agent import Agent from yarlp.model.model_factories import cem_model_factory from y...
btaba/yarlp
yarlp/agent/cem_agent.py
cem_agent.py
py
5,867
python
en
code
12
github-code
36
22149140762
""" Document Scanner Algo : Take input from webcom Preprocess Image and return as Threshold image Find the biggest contour Using corner points to get bird eye view """ import cv2 import numpy as np window_width = 600 window_height = 350 webcam = cv2.VideoCapture(0) # Selecting webcam webca...
codescoop/Computer-Vision
Document_Scanner/DocumentScanner.py
DocumentScanner.py
py
4,538
python
en
code
0
github-code
36
29420272726
# -*- coding: utf-8 -*- """ Created on Mon Mar 20 13:57:06 2017 """ cube = 27 epsilon = 0.01 guess = 0.0 increment = 0.001 numguess = 0 while abs(guess**3 - cube) >= epsilon and guess <= cube: guess += increment numguess += 1 print("num of guesses=", numguess) if abs(guess**3 - cube) >= epsilon: ...
flexing/flexing
MITx6.001x/WEEK2 - Simple Programs/Excercises/cube_approx.py
cube_approx.py
py
429
python
en
code
0
github-code
36
74749464104
# -*- coding: utf-8 -*- from django.http import JsonResponse from django.db.models import Count, F, Case, When, Value, IntegerField from what.models import Composer, Instrument from api.shared.tools import get_instrument_parent_category from Octoopus.shared.tools import load_config def search_composers(request): ...
MrFaBemol/octoopus-django
api/views.py
views.py
py
5,689
python
en
code
0
github-code
36
2706087078
import hashlib import itertools import json import os import time from typing import Any, Dict, List import googlemaps PLACE_TYPES = [ "Gym", "Park", "Café", "Supermarket", "Restaurant", "Vegetarian Restaurant", "Burger Restaurant", ] DISTRICT_NAMES = [ "Neuehrenfeld, Cologne, Germany"...
sbunzel/city-explorer
src/city_explorer/maps.py
maps.py
py
5,926
python
en
code
1
github-code
36
19750927755
# Implement a class for a stack that supports all the regular functions (push, pop) # and an additional function of max() which returns the maximum element in the stack # (return None if the stack is empty). Each method should run in constant time. class MaxStack: def __init__(self): self.stack = [] se...
johnjagu25/Python-Daily-coding-challenge
max_stack.py
max_stack.py
py
982
python
en
code
0
github-code
36
29713065782
# -*- coding: utf-8 -*- """ Created on Fri Apr 6 15:21:50 2018 @author: Marcus """ import os import fdmt_date as fda import fdmt_data as fdt def main(): main_path=fdt.main_path bin_path=main_path+"bin/" ################################################################################## #Bat 01 ...
mtoingkeery/TheProcess
src/TP990_Generate_Batch.py
TP990_Generate_Batch.py
py
1,469
python
en
code
0
github-code
36
27717890086
import argparse import json import os import pickle from pathlib import Path import sqlite3 from tqdm import tqdm import random from utils.linking_process import SpiderEncoderV2Preproc from utils.pretrained_embeddings import GloVe from utils.datasets.spider import load_tables # from dataset.process.preprocess_kaggle i...
BeachWang/DAIL-SQL
data_preprocess.py
data_preprocess.py
py
2,914
python
en
code
90
github-code
36
38752654666
IMG_SIZE = 256 BATCH_SIZE = 4 EPOCHS = 100 IMG_TRAIN_DIR = 'src/train/img/' LABLE_TRAIN_DIR = 'src/train/label/' IMG_TEST_DIR = 'src/test/img/' RESULT_DIR = 'src/test/results/' BACKGROUND = [255, 255, 255] CAR = [255, 0, 0] WHEEL = [0, 0, 0] LIGHTS = [255, 255, 0] WINDOW = [0, 0, 255] COLORS = [BACKGROUND, CAR, WHEEL...
AleksMa/CarsSegmentator
config.py
config.py
py
391
python
en
code
2
github-code
36
25606608526
# Exercício Python 068: Faça um programa que jogue par ou ímpar com o computador. O jogo só será interrompido quando o # jogador perder, mostrando o total de vitórias consecutivas que ele conquistou no final do jogo. from random import randint cont = 0 while True: bot = randint(0, 10) n = int(input('Insira um n...
MarcosSx/CursoGuanabara
Exercicios/mundo2/aula015_interrompendoRepeticoesWhile/ex068-JogoDoParOuImpar.py
ex068-JogoDoParOuImpar.py
py
1,317
python
pt
code
0
github-code
36
73974477225
import contextvars import csv import logging from os import PathLike from typing import Callable, Dict, Union, Optional import xmltodict as xmltodict from discord.ext.commands import Bot, Context logger = logging.getLogger("bot.localization") class LocalizationHandler(object): default_handler = None # type: Lo...
Blaumeise03/AccountingBot
accounting_bot/localization.py
localization.py
py
3,837
python
en
code
6
github-code
36
17978575525
# 导入操作系统库 import os # 更改工作目录 os.chdir(r"D:\softwares\applied statistics\pythoncodelearning\chap3\sourcecode") # 导入绘图库 import matplotlib.pyplot as plt # 导入支持向量机模型 from sklearn import svm # 导入决策边界可视化工具 from sklearn.inspection import DecisionBoundaryDisplay # 导入iris数据集 from sklearn.datasets import load_iris # 导入绘图库中的字体管理包...
AndyLiu-art/MLPythonCode
chap3/sourcecode/Python3.py
Python3.py
py
1,949
python
en
code
0
github-code
36
29378610006
from bs4 import BeautifulSoup import requests req_headers = {"Accept": "*/*", "Accept-Encoding": "gzip, deflate, br", "User-Agent": 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/71.0.3578.98 Safari/537.36 ', "Connection": "keep-alive"} DO...
JanMird/scrapping-telegram-bot
scrape.py
scrape.py
py
4,252
python
en
code
0
github-code
36
71551273063
from functions import Complexity import os, re, csv, pickle import seaborn as sns import matplotlib.pyplot as plt plt.style.use('ggplot') import pandas as pd from scipy import stats import json # Get the interactions # Get the BDM values for each protein in each pair # get correlation # plot for fun # get interactio...
alyssa-adams/bdm_proteins
lambda_ppi.py
lambda_ppi.py
py
8,354
python
en
code
1
github-code
36
20485480675
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.module_utils.basic import AnsibleModule from ansible_collections.zp4rker.basic.plugins.module_utils import calculator def run_module(): module_args = dict( x=dict(type='int', required=True), operation=dict(type=...
zp4rker/ansible-basic-collection
plugins/modules/calculate.py
calculate.py
py
1,339
python
en
code
0
github-code
36
9164147549
from flask import Flask, request, jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) # rate_card_data = pd.read_csv('sample--rates.csv', dtype={ # 'member_csv': 'string', # 'age_range': 'string', # 'tier': 'string', # '500000': 'int64', # '700000': 'int64', # '1000000': 'int64...
sheetalparsa/health-insurance-calculator
backend/app.py
app.py
py
3,054
python
en
code
0
github-code
36
18133828972
""" File: annoying_recursion.py Author: Xin Li Purpose: In this project i will write several recursive function. """ def annoying_factorial(n): if n == 0: return 1 if n == 1: return 1 if n == 2: return 2 if n == 3: return 6 if n == 4: return 4 * a...
xinli2/python-recursion-practice
annoying_recursion.py
annoying_recursion.py
py
2,520
python
en
code
15
github-code
36
38308527532
from pytablewriter import MarkdownTableWriter import json def main(): f = open("results/arxiv_papers_6_Aug_2021.json") data = json.load(f) value_matrix = [] for item in data: temp = data[item]["summary"].find value_matrix.append( [item, data[item]["title"], data[item]["su...
FlokiBB/DeFiPapers
src/convert_json_to_md.py
convert_json_to_md.py
py
718
python
en
code
57
github-code
36
10309522654
from random import randint from discord.ext import commands import discord from discord import Member from discord.ext.commands import has_permissions, MissingPermissions intents = discord.Intents.default() intents.members = True intents.messages = True #LIGNE MARCHE CHEZ MOI #intents.message_content = True LIGNE DANS...
GregoirePichard1/Discord-Bot
src/main.py
main.py
py
1,696
python
en
code
0
github-code
36
30330496099
# !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/3/26 4:00 下午 # @Author : wangHua # @File : ProductAddCrawler.py # @Software: PyCharm from app.crawlers.BaseAmazonCrawler import BaseAmazonCrawler from utils import Http from app.repositories import ProductItemRepository, ProductRepository, SiteRepository ...
whale-fall-wh/producer-consumer
app/crawlers/ProductAddCrawler.py
ProductAddCrawler.py
py
2,295
python
en
code
0
github-code
36
36189988596
#packages imported import csv import subprocess import re import sys #Function to format the urls in the proper cases #Queries, HTML Trans and direct format supported. def fformat(oringUrl, destinyUrl): #regex validations to make the script compatible with most formats of the origin URL #Evaluates if the url ...
sergioandresmeneses/convert-Nginx-Redirect-Rules
convertNginxRedirectRules.py
convertNginxRedirectRules.py
py
3,518
python
en
code
0
github-code
36
14049558832
from . import views from django.urls import path urlpatterns = [ path('admin_dashboard', views.admin_dashboard, name="admin_dashboard"), path('admin_packages', views.admin_packages, name="admin_packages"), path('update_package/<package_id>', views.update_package, name="update_package"), path('delete_pa...
aniatki/pro-dad
admin_dashboard/urls.py
urls.py
py
389
python
en
code
0
github-code
36
2671644316
import math import os import sys import numpy as np import torch from torch import nn from torch.nn import Conv2d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm from . import commons, modules from .commons import get_padding from .modules import (ConvNex...
w-okada/voice-changer
server/voice_changer/RVC/inferencer/voras_beta/models.py
models.py
py
7,992
python
en
code
12,673
github-code
36
25686410069
import csv import os from keras.models import load_model import numpy as np import scipy.io as sio model = load_model("models/trained_model_h5.h5") def load_data(record_path, start_t, end_t): data = sio.loadmat(record_path) signal = data['ECG']['data'][0][0] signal = signal[:, start_t:end_t] featur...
AlexPetukhov/nnsu
GOOD/6sec/apply_model_no_delin.py
apply_model_no_delin.py
py
3,501
python
en
code
0
github-code
36
18287973881
import numpy as np import matplotlib.pyplot as plt from components.tests import ( test_helium, test_helium_x, test_helium_xc, test_helium_xc_Vosko ) from components.misc import get_n ## Command line arguments arg_verbose = False arg_plot = False ## r = radius in spherical coordinates r_max = 15 r_step = 0.015 rr ...
jdbosser/DFT-Jupyter
Notebooks/heliumdft.py
heliumdft.py
py
2,534
python
en
code
0
github-code
36
16926338982
import dash from dash import dcc from dash import html import dash_daq as daq from dash.dependencies import Input, Output import pandas as pd import numpy as np import plotly.graph_objs as go import plotly.express as px import umap from umap import UMAP import dash_bootstrap_components as dbc # Launch the applic...
EbruAyyorgun/3Dexplore
leukemia_dash_final.py
leukemia_dash_final.py
py
17,987
python
en
code
0
github-code
36
36492860982
#!/usr/bin/env python3 from __future__ import absolute_import, division, print_function, unicode_literals from . import invoke_rpc_builtin, invoke_rpc_python_udf from . import ProcessGroupAgent from .internal_rpc_utils import serialize, PythonUDF import sys import torch from enum import Enum _agent = None def _r...
reynoldsm88/pytorch
torch/distributed/rpc.py
rpc.py
py
5,784
python
en
code
null
github-code
36
37752345818
import sys # Prevent spurious errors during `python setup.py test`, a la # http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html: try: import multiprocessing except ImportError: pass from setuptools import setup, find_packages extra_setup = {} if sys.version_info >= (3,): extra_setup['use_2to3'] ...
civiccc/verifier_date_utils
setup.py
setup.py
py
1,161
python
en
code
0
github-code
36
70874373865
from __future__ import annotations from contextlib import contextmanager from datetime import datetime from decimal import Decimal from typing import ContextManager, List, Text from uuid import UUID, uuid4 import sqlalchemy as sa import sqlalchemy_utils as sa_utils from injector import inject from sqlalchemy import f...
lzukowski/workflow
src/ordering/db/buy_order.py
buy_order.py
py
4,190
python
en
code
5
github-code
36
37428719988
from gl import * from pyglet import resource Mat4Floats = GLfloat*4 NOTEXTURES = False class MDLdict(object): """Materials display lists""" def __init__(self): self.mat_dls = {} self.mat_textures = {} self.mat_trans = {} def __del__(self): if glDeleteLists: for...
scavpy/Scav-Team-Pyweek-Aug-2010
gamelib/tdgl/material.py
material.py
py
2,940
python
en
code
3
github-code
36
42998098746
from __future__ import annotations from typing import TYPE_CHECKING, Any from ..network import ID_TOKEN_AUTHENTICATOR from .by_plugin import AuthByPlugin, AuthType from .webbrowser import AuthByWebBrowser if TYPE_CHECKING: from ..connection import SnowflakeConnection class AuthByIdToken(AuthByPlugin): """I...
snowflakedb/snowflake-connector-python
src/snowflake/connector/auth/idtoken.py
idtoken.py
py
2,028
python
en
code
511
github-code
36
41669892511
# -*- coding: utf-8 -*- import os import tensorflow as tf from keras.applications.vgg16 import VGG16 from keras.applications.resnet50 import ResNet50,preprocess_input,decode_predictions from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential,Model from keras.layers import Input,Act...
POD-azlamarhyu/Python_resnet_recognition
src/resnet2.py
resnet2.py
py
2,806
python
en
code
0
github-code
36
33627483742
from sklearn.model_selection import train_test_split import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import pickle import torch import torch.nn as nn import torch.optim as optim from train_lgbm import * import lightgbm as lgb from torch.utils.data import TensorDataset,D...
tianyao-aka/BotSpot
vectorized_botspot.py
vectorized_botspot.py
py
26,961
python
en
code
0
github-code
36
41493530569
# -*- coding: utf-8 -*- """ Created on Fri Jan 29 10:51:07 2021 @author: REMI DECOUTY, DAMIEN LU """ import pandas import glob, os import igraph as ig import math # récupération de la liste de tous les fichiers à étudier os.chdir("data") allCsvFiles = glob.glob("*") os.chdir("..") # coloration d'une arête, en fonc...
dlu02/projet-bioinfo
projet_multithread.py
projet_multithread.py
py
9,281
python
fr
code
0
github-code
36
4543795483
import logging import requests class Move(object): def __init__(self, url, full_obj=None): self.full_obj = full_obj or self.get_from_api(url) self._name = None self._power = 0 @property def name(self): if self.full_obj is None: self.full_obj = self.get_move_fro...
yehted/pokemon
src/pokemon/moves.py
moves.py
py
998
python
en
code
0
github-code
36
39309304527
#!/usr/bin/python3 # # MEG sensor space analysis for visual LTP (vertical & horizontal gratings) # # Authors: Paul Sowman, Judy Zhu ####################################################################################### import os import mne import meegkit # for TSPCA import glob import matplotlib.pyplot as plt import...
Macquarie-MEG-Research/MEG_analysis_mne
Vince_MEG_MD_VEP.py
Vince_MEG_MD_VEP.py
py
7,910
python
en
code
0
github-code
36
24968801455
from typing import List from collections import deque class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: nei = [[-1, 0], [1, 0], [0, -1], [0, 1]] dq, seen = deque(), set() dq.append(entrance) row, col = len(maze), len(maze[0]) steps ...
inverseTrig/leet_code
1926_nearest_exit_from_entrance_in_maze.py
1926_nearest_exit_from_entrance_in_maze.py
py
1,646
python
en
code
0
github-code
36
24722131243
#-*-coding:utf-8-*- """ This is base modoul bank """ import imp import json import urllib2 import urllib import os import time import sys from thePath import rootPath class BANK(object): """ Base class """ def __init__(self): self.useragent = ( "Mozilla/5.0 (Linux; Android 6.0;" ...
WYL-BruceLong/bank_spider
superBank.py
superBank.py
py
2,022
python
en
code
0
github-code
36
41042866801
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import matplotlib.patches as patches import itertools from PIL import Image from scipy.cluster.hierarchy import dendrogram from sklearn.datasets import load_iris import numpy as np from sklearn.cluster import AgglomerativeClustering from pandas.c...
pletnev-aleksandr/nsd_hackathon
libb.py
libb.py
py
6,556
python
en
code
0
github-code
36
7137523065
import mysql.connector as connector import datetime as date import logging class User : dates1 = date.datetime.now() name = "RKFINANCE" def __init__(self): self.con = connector.connect(host='localhost', user='root', ...
Kitturamkrishna/RKFINANCE
User.py
User.py
py
4,361
python
en
code
0
github-code
36
722631652
""" Реализовать два небольших скрипта: а) итератор, генерирующий целые числа, начиная с указанного, б) итератор, повторяющий элементы некоторого списка, определенного заранее. Подсказка: Использовать функцию count() и cycle() модуля itertools. Обратите внимание, что создаваемый цикл не должен быть бесконечным. Необходи...
Jaidergan/Lesson04
lesson04/example06.py
example06.py
py
2,775
python
ru
code
0
github-code
36
21625949314
#!/usr/bin/env python # -*- coding: utf-8 -*- import time import argparse import numpy as np import networkx as nx import subprocess import os from tulip import tlp import pandas as pd from evalne.utils import preprocess as pp def parse_args(): """ Parses Fruchterman-Reingold arguments.""" parser = argparse....
aida-ugent/graph-vis-eval
methods/fruchterman_reingold.py
fruchterman_reingold.py
py
7,489
python
en
code
0
github-code
36
70996234665
import json from datetime import datetime, timezone from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import AccessMixin from django.db.models import Count, Q, F from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts ...
fnabiyevuz/crm
board/views.py
views.py
py
32,513
python
en
code
0
github-code
36
19764052199
#Topicos-especiais3.py import math #Listas com valores nao numericos lista=[-10,None,math.nan,3.14,float('-inf'),2,float('inf')] print(lista) for x in lista: if x is not None and math.isfinite(x): print(x) else: print('não é numerico') #operador ternario for x in lista: ...
beloim/data_science
CURSO DATA SCIENCE JOAO VICTOR/Topicos-especiais3.py
Topicos-especiais3.py
py
687
python
pt
code
0
github-code
36
8783273204
class Solution: # @param A : head node of linked list # @return an integer def lPalin(self, A): if A.next==None: return 1 middle=self.findMiddle(A) self.reverse(A,middle) p=A q=middle.next while q!=None: if p.val!=q.val: ...
abhisoniks/interviewbit
LinkedList/palindromList.py
palindromList.py
py
968
python
en
code
0
github-code
36
10863291429
import pytest from cleverwrap import CleverWrap from cleverwrap.errors import UnknownAPIError def test_init(): cw = CleverWrap("API_KEY") assert cw.key == "API_KEY" def test_say(mock_requests): mock_requests.add( mock_requests.GET, 'https://www.cleverbot.com/getreply?input=Hello&key=AP...
TotallyNotRobots/cleverwrap.py
tests/test_cleverwrap.py
test_cleverwrap.py
py
959
python
en
code
0
github-code
36
21902537705
import subprocess import time from wifi import Cell import pathlib script_path = pathlib.Path(__file__).parent.resolve() import sys sys.path.append('../') from common import mesh_utils def scan_wifi(interface): ''' Scan wifi with the AuthAP pattern. If more than one, select the best quality one. If ...
tiiuae/mesh_com
modules/sc-mesh-secure-deployment/src/1_5/features/mutual/utils/wifi_ssrc.py
wifi_ssrc.py
py
2,045
python
en
code
12
github-code
36
15229035002
import sys sys.stdin = open("input.txt","rt") print() # 어떤 자연수 n,q 가 있고 p를 q로 나눌때 나머지가 0이면 q는 p의 약수 # 이 중, K가 주어질 때, q중 K번째로 작은 수? # 약수 없으면 -1 출력 n,k = map(int, input().split()) count = 0 for i in range(1,n+1): if n % i == 0: count += 1 if count == k: print(i) break else: print(-1...
ValseLee/py_algo
algo_basic/1.K번째약수.py
1.K번째약수.py
py
409
python
ko
code
0
github-code
36
19750919685
# A look-and-say sequence is defined as the integer sequence beginning with # a single digit in which the next term is obtained by describing the previous term. # An example is easier to understand: # Each consecutive value describes the prior value. def look_and_say(num_val): to_text = str(num_val) len_to_t...
johnjagu25/Python-Daily-coding-challenge
look_and_say.py
look_and_say.py
py
1,235
python
en
code
0
github-code
36
75113361384
import arcade import random SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 COLORS = [arcade.color.BLUE, arcade.color.FANDANGO_PINK,arcade.color.GOLDEN_POPPY, arcade.color.TURQUOISE_BLUE,arcade.color.SPRING_GREEN,arcade.color.RED,arcade.color.LAVENDER_INDIGO] class Cercle(): def __init__(self,rayon,x,y,color): se...
Mousavir/main.py
Exercies_arcade.py
Exercies_arcade.py
py
1,984
python
en
code
0
github-code
36
2538475868
import uuid from django.db import models from django.db.models.deletion import CASCADE, SET_NULL # Create your models here. """ Crear un nuevo proyecto Django, con una app llamada PRODUCTOS, que sirva para manejar un catálogo de productos representado por las siguientes entidades: Producto(nombre, descripcion, url_i...
EsperanzaMacarena/ejerciciosDjango
ejercicio1/ejercicio1/productos/models.py
models.py
py
1,429
python
es
code
0
github-code
36
38870912445
# 1. def route_info(route): if route.get('distance') and type(route['distance']) is int: return f"Distance to your destination is {route['distance']}" elif (route.get('speed') and route.get('time') and type(route['speed']) is int and (type(route['time']) is int or float)...
Ky34/python-education
28. if else/task.py
task.py
py
1,026
python
en
code
0
github-code
36
617619433
# monitor import subprocess import os import time import datetime import threading import shutil import argparse import Dashboard BROWSER_PATH = '' METHOD = None URL = "http://127.0.0.1:8080/flag?" MODE1 = "--incognito" # 시크릿 모드 MODE2 = "--no-sandbox" # 샌드박스 비활성화 TIMEOUT = 300 # 5min p = None RUN_FLAG = False de...
BOB-Jour/Glitch_Fuzzer
run_fuzz_windows10.py
run_fuzz_windows10.py
py
3,327
python
en
code
0
github-code
36
17581792452
from typing import Any, Dict, Tuple, Optional from urllib.parse import urlparse from starwhale.utils import config from starwhale.base.uri.exceptions import NoMatchException def _get_instances() -> Dict[str, Dict]: return config.load_swcli_config().get("instances", {}) # type: ignore[no-any-return] def _get_d...
star-whale/starwhale
client/starwhale/base/uri/instance.py
instance.py
py
3,238
python
en
code
171
github-code
36
5456383430
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # @name : PhoneInfoga - Phone numbers OSINT tool # @url : https://github.com/sundowndev # @author : Raphael Cerveaux (sundowndev) from bs4 import BeautifulSoup import hashlib import json from lib.output import * from lib.request import send ''' Scanning phone numbe...
wagdev1919/BulkPhonenumberVerifier
BulkPhoneNumberVerifier/scanners/numverify.py
numverify.py
py
2,294
python
en
code
2
github-code
36
2795908861
from flask import Flask, render_template, redirect from flask_pymongo import PyMongo from .settings import Config from .search import Searcher from .forms import SearchForm def create_app(): app = Flask(__name__) app.config.from_object(Config) mongo = PyMongo(app, connect = True) webIndex = mongo.cx.w...
Patrick-Bender/wholesearchcatalog.com
flaskapp-Backup/flaskapp/__init__.py
__init__.py
py
965
python
en
code
0
github-code
36
3206846810
""" Provides an intermediate datastructure close to the PDF, which is used to transform the lines in the pdf into TimeTable objects. """ from __future__ import annotations import logging from operator import attrgetter from pathlib import Path from typing import Callable, TypeAlias from pdf2gtfs.config import Config...
heijul/pdf2gtfs
src/pdf2gtfs/datastructures/pdftable/pdftable.py
pdftable.py
py
11,459
python
en
code
1
github-code
36
10763879949
import numpy as np from scipy.optimize import minimize import scipy.io def sigmoid(z): return 1.0/(1 + np.e**(-z)) def lrCostFunction(theta,X,y,reg_param): m = len(y) J =((np.sum(-y*np.log(sigmoid(np.dot(X,theta)))- (1-y)*(np.log(1-sigmoid(np.dot(X,theta))))))/m + (reg_param/m)*np.sum(th...
kumudlakara/MRM
multiclass_logistic_regression.py
multiclass_logistic_regression.py
py
2,225
python
en
code
0
github-code
36
3023969689
n = int(input()) # size of board k = int(input()) # number of apple board = [[0]*n for i in range(n)] turn = [] #snake turn info for q in range(k): place = list(map(int, input().split())) board[place[0]-1][place[1]-1] = 1 l = int(input()) for i in range(l): t = list(input().split()) t[0] = int(t[0...
minshyee/Algorithm
old/Implementation/clear_dummy.py
clear_dummy.py
py
978
python
en
code
0
github-code
36
37313604132
''' 1. take no of cats, dogs and legs. 2. count the total no of legs. 3. counted legs does not exceed the total leg 4. if total legs and counted legs match 5. counting is correct 6. check for the missing cats leg, dog can hold 2 cats max so 4*2 legs can be missing. 7. counting is correct. 8. wrong counting. ''' t=int(...
Aashutosh748/comprino_tests
6_cats_dogs.py
6_cats_dogs.py
py
998
python
en
code
0
github-code
36
71685662504
import rospy from std_msgs.msg import String import Tkinter as tk class controller: def __init(self): self.speedTab = [-50,-40,-30,-20,0,20,22,24,26] self.zeroIndex = 4 self.angleStep = 5 self.root = tk.Tk() self.frame = tk.Frame(self.root, wi...
PSCX15/keyboardCommander
scripts/keyboardCommander.py
keyboardCommander.py
py
1,411
python
en
code
0
github-code
36
463033195
from base64 import decodebytes import discord from discord import embeds from discord.ext import commands import random import datetime from requests.models import Response class Events(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_ready(self): ...
Oreofreakshake/fodifulhu-discord-bot
cogs/events.py
events.py
py
3,572
python
en
code
3
github-code
36
13100771621
from time import time import subprocess import os def lambda_handler(event, context): file_size = event['file_size'] byte_size = int(event['byte_size']) file_write_path = '/tmp/file' start = time() with open(file_write_path, 'wb', buffering=byte_size) as f: f.write(os.urandom(file_siz...
ddps-lab/serverless-faas-workbench
aws/disk/sequential_disk_io/lambda_function.py
lambda_function.py
py
1,150
python
en
code
96
github-code
36
14359245018
from classifiers.NCC import NCC from classifiers.NBC import NBC from classifiers.GNB import GNB from sklearn.naive_bayes import GaussianNB from sklearn import metrics from sklearn import datasets import MNIST import numpy as np def modify_data(data): modified = [] for d in data: tmp = [] fo...
niklashedstrom/EDAN95
lab5/main.py
main.py
py
3,091
python
en
code
0
github-code
36
4002922556
#! /usr/bin/env python3 import json import time import rclpy from rclpy.node import Node from rclpy.executors import MultiThreadedExecutor from robot_navigator import BasicNavigator, TaskResult from geometry_msgs.msg import PoseStamped from std_msgs.msg import Float64MultiArray, Int32, String, Bool, Int32MultiArray ...
maurocs/knitting-amr
Navigation routine/AA_DOCK.py
AA_DOCK.py
py
11,537
python
en
code
2
github-code
36
30019222748
from flask import Flask, render_template, redirect import pymongo from flask_pymongo import PyMongo import scrape_mars #Spin up the Flask App app = Flask(__name__, template_folder='templates') app.config["MONGO_URI"] = "mongodb://localhost:27017/mars_app" mongo = PyMongo(app) #Or set inline #mongo = PyMongo(app, ur...
fabzum/web-scraping-challenge
Missions_to_Mars/app.py
app.py
py
1,218
python
en
code
0
github-code
36
28896311683
#!/usr/bin/env python # coding: utf-8 import numpy as np import pandas as pd import pyarrow as pa import pyarrow.parquet as pq import os from os import path import re class WeatherMax(): ''' pass file directory path with forward slashes ''' def __init__(self,directorypath): self.directorypath ...
bigdubya/Data_Engineer_DLG
Main_folder/weathermax.py
weathermax.py
py
3,239
python
en
code
0
github-code
36
31564159525
#!/usr/bin/env python3 """ 1 Aug 2022 Taeho Choi created for longhorn API python client KUBECONFIG needs to be imported properly before running this script """ import time import longhorn import os import json #Warning msg to user print("#"*40) print("!! WARNING: This script can cause catastrophic conseque...
nogodan/longhorn_python_client
longhorn_client.py
longhorn_client.py
py
7,674
python
en
code
0
github-code
36
35290662419
#!/usr/bin/env python # coding: utf-8 #program to demonstrate polynomial interpolation import numpy as np import math #ask user for x x0= float(input("Enter xo: \t")) x1= float(input("Enter x1: \t")) x2= float(input("Enter x1: \t")) x3= float(input("Enter x2: \t")) #function to construct each row of the matrix ...
linhphambuzz/NumericalMethod
Polynomial_Interpolation.py
Polynomial_Interpolation.py
py
1,725
python
en
code
0
github-code
36
11367854731
import torch from torchvision import datasets, transforms # Define paths for the data data_dir = 'flowers' train_dir = data_dir + '/train' valid_dir = data_dir + '/valid' test_dir = data_dir + '/test' dirs = { 'train': train_dir, 'val': valid_dir, 'test': test_dir } # Define transforms for the training,...
codeballet/image-classifier-flowers
get_data.py
get_data.py
py
1,448
python
en
code
0
github-code
36
9144895281
""" (39) Combination Sum https://leetcode.com/problems/combination-sum/description/ Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number...
RobLaughlin/LeetcodeSolutions
(39) Combination Sum.py
(39) Combination Sum.py
py
2,000
python
en
code
0
github-code
36
28062640486
# -*- coding: utf-8 -*- from plone.app.contenttypes.testing import PLONE_APP_CONTENTTYPES_FIXTURE from plone.app.robotframework.testing import REMOTE_LIBRARY_BUNDLE_FIXTURE from plone.app.testing import applyProfile from plone.app.testing import FunctionalTesting from plone.app.testing import IntegrationTesting from pl...
UPCnet/gwopa.theme
src/gwopa/theme/testing.py
testing.py
py
1,381
python
en
code
0
github-code
36
75216111782
import time #import img2txt import os import json from PIL import Image def load_file(fpath): # fpath是具体的文件 ,作用:#str to list assert os.path.exists(fpath) # assert() raise-if-not with open(fpath, 'r') as fid: lines = fid.readlines() records = [json.loads(line.strip('\n')) for line in lines] # str...
JoeLiHai/Mask_Detection_and_Social_Distance
data_preprocess/odgt2txt.py
odgt2txt.py
py
3,721
python
en
code
1
github-code
36
17443182071
#!/usr/bin/env python """ A thermometer display stimulus. This module contains a class implementing a thermometer display stimulus. """ from __future__ import absolute_import, print_function, division from builtins import * __author__ = 'Florian Krause <florian@expyriment.org>' __version__ = '' __revision__ = '' _...
expyriment/expyriment-stash
extras/expyriment_stimuli_extras/thermometerdisplay/_thermometerdisplay.py
_thermometerdisplay.py
py
10,984
python
en
code
20
github-code
36
2216377889
import cv2 import numpy as np from PIL import Image def main(): capture = cv2.VideoCapture(0) while True: if cv2.waitKey(1) & 0xFF == ord('q'): break ret, frame = capture.read() cv2.imshow('Current', frame) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) imag...
jpbel65/Robot-D3-E9-H2019
scripts/QRTest.py
QRTest.py
py
680
python
en
code
0
github-code
36
24955171162
from fastapi import APIRouter from BusinessLayer.PersonaNatural import * from EntityLayer.PersonaNaturalEntity import * from fastapi.encoders import jsonable_encoder from Utilidades.Entidades.ResponseAPI import ResponseAPI, ResponseAPIError PersonaNaturalRouter = APIRouter() ApiName = "PersonaNatural" @PersonaNatura...
josedtl/AlmacenLogistico
Proyecto/server/routes/PersonaNaturalRoute.py
PersonaNaturalRoute.py
py
2,243
python
en
code
0
github-code
36
71038539943
import torch.nn as nn import torch.nn.functional as F from ...utils import CONFIG from ..encoders.resnet_enc import ResNet_D from ..ops import GuidedCxtAtten, SpectralNorm class ResGuidedCxtAtten(ResNet_D): def __init__(self, block, layers, norm_layer=None, late_downsample=False): super...
XiaohangZhan/deocclusion
demos/GCAMatting/networks/encoders/res_gca_enc.py
res_gca_enc.py
py
3,937
python
en
code
764
github-code
36
73712138024
import os import pandas as pd def tag_line_items(df, configs): """ Labels rows in the dataframe based on their association with anchor items. This function processes the input dataframe to identify line items based on the provided configurations. The function checks the presence of the minimum nu...
h2oai/docai-recipes
post_processor/misc/csv2table.py
csv2table.py
py
3,689
python
en
code
4
github-code
36
75190584744
import gtk import pango import cairo import gobject import os import math from appenv import env from prefs import prefs from valcabuary import valcabuary from prefixdb import prefixdb from corrector import corrector from tooltip import cls_tooltip from simpledb import simpledb from contentmgr import cls_contentmgr fro...
luohao-brian/PPDict
appmain.py
appmain.py
py
14,209
python
en
code
0
github-code
36
7570177447
from tkinter import Frame, DoubleVar from tkinter.ttk import Scale from typing import Dict, Tuple, List from ui.misc import NoneTypeCheck from ui.Components import Component class Range(Component): """ Tkinter range value """ def __init__(self, parent: Frame, style: Dict, geometry: Tuple[int] | List...
TwoSails/maze-generator
ui/Components/range.py
range.py
py
987
python
en
code
0
github-code
36
30145542369
""" 1957 - Converter para Hexadecimal Os dados armazenados no computador estão em binário. Uma forma econômica de ver estes números é usar a base 16 (hexadecimal). Sua tarefa consiste em escrever um programa que, dado um número natural na base 10, mostre sua representação em hexadecimal. Entrada A entrada é um...
renefreire/URI-Python
1957 - Converter para Hexadecimal.py
1957 - Converter para Hexadecimal.py
py
1,077
python
pt
code
0
github-code
36