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
553689261
class Solution(object): def isPalindrome(self, s): """ Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man,...
ljia2/leetcode.py
solutions/two.pointers/125.Valid.Palindrome.py
125.Valid.Palindrome.py
py
963
python
en
code
0
github-code
50
30180483161
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 19 18:14:00 2016 @author: Tavo """ '''This script will take a polygon shapefile and project it to UTM 23S using ogr/gdal by tawonque 19/12/2016''' #%% Import modules import os import sys from osgeo import ogr from osgeo import osr #%% If necess...
tawonque/Neuralimage
shapergis/Neuralimage_project_shp.py
Neuralimage_project_shp.py
py
5,117
python
en
code
0
github-code
50
101198986
import cv2 import numpy as np def calibrate(image, post_it_size_m=0.076) -> float: # 1. take the green only, # 2. blur and mask, # 3. count those pixels... total_i, total_j, _ = image.shape def percent_of_idx(idx, percent): return slice(int(idx * percent), -int(idx * percent)) reduce...
RAYemelyanova/lunchbox
src/lunchbox/analysis/calibrate.py
calibrate.py
py
876
python
en
code
0
github-code
50
25195111578
from flask import Flask, render_template from flask import Flask, request, jsonify, Response import json import mysql.connector from flask_cors import CORS, cross_origin app = Flask(__name__) @app.route('/') def hello_world(): return render_template('index.html') @app.route("/") def hello(): return "Flask in...
Pimpwhippa/recommender
flask/app_hello_world.py
app_hello_world.py
py
1,153
python
en
code
0
github-code
50
20194624735
import boto3 import uuid class TokenRepository: def __init__(self, tokenTable): self.table = boto3.resource('dynamodb').Table(tokenTable) def getToken(self, keyId): try: response = self.table.get_item( Key={ 'keyid': keyId ...
bryantrobbins/baseball
shared/btr3baseball/TokenRepository.py
TokenRepository.py
py
519
python
en
code
22
github-code
50
16878201823
import logging import vk_api from django.conf import settings from herald_bot.handlers.core.trigger import BaseTrigger from herald_bot.handlers.core.trigger import BaseTrigger from herald_bot.handlers.utils.helpers import make_keyboard_vk from herald_bot.models import User from vk_api.utils import get_random_id log...
mr8bit/herald
herald_bot/handlers/vk/trigger.py
trigger.py
py
2,530
python
en
code
1
github-code
50
42226074507
import numpy as np import sys import copy import random import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset from torch.utils.data import DataLoader import torch.optim as optim import numpy as np import math import pdb import pandas as pd from torch.nn.utils import cli...
Hunterryan725/AlphaZero-Connect-Four
connect4.py
connect4.py
py
5,767
python
en
code
0
github-code
50
17009498065
# -*- coding: utf-8 -*- import argparse from datetime import datetime, timedelta from dataclasses import asdict from typing import List import uuid import const from logging import Logger import logger from mq import MQ, MQMsgData import rapi def _send_msg(send_data: MQMsgData, queue_name: str, ...
pro-top-star/python-stock-out
app/stockout_rakuten_producer.py
stockout_rakuten_producer.py
py
3,588
python
en
code
2
github-code
50
42390489997
#!/usr/bin/env python3 import operator from functools import reduce # Width and height of the grid. Used in some calculations later. WIDTH = 100 HEIGHT = 100 # These are the coordinate transformations to use to check the state of the neighbours TESTS = [ (-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0)...
zandeez/adventofcode
2015/day18.py
day18.py
py
3,363
python
en
code
0
github-code
50
72053296156
""" * Write a python program that asks the user a minimum of 3 riddles. * You can look at riddles.com if you don't already know any riddles. * Collect the response of each riddle from the user and compare their answers to the correct answer. * Use a variable to keep track of the correctly answered riddles * Afte...
Maddox6647/level-0-module-1
_04_int/_1_riddler/riddler.py
riddler.py
py
1,744
python
en
code
0
github-code
50
3313890304
import struct import argparse from PIL import Image parser = argparse.ArgumentParser(description='Converts an image back to Quake conchars.') parser.add_argument('input_img', type=str, help='Input image.') parser.add_argument('output_chrs', type=str, help='Output conchars.') ...
Imakesoftware2/quake-conchar-tools
img_to_conchars.py
img_to_conchars.py
py
587
python
en
code
0
github-code
50
37990465074
#!/usr/bin/env python # -*- coding: iso-8859-15 -*- from pyramid.paster import get_appsettings from sqlalchemy import engine_from_config, create_engine from sqlalchemy.sql import text from sqlalchemy.ext.automap import automap_base from pyramid.view import view_config from pyramid.response import Response from pyramid....
foerstner-lab/CoxBase-Webapp
webapp/views/primer_query.py
primer_query.py
py
2,325
python
en
code
0
github-code
50
1180120399
# https://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds import time, traceback def every(delay, task, retry=False): next_time = time.time() + delay while True: time.sleep(max(0, next_time - time.time())) try: task() except Exception: ...
christofteuscher/TrailNapAlarm
src/_unused/every.py
every.py
py
1,133
python
en
code
3
github-code
50
29340460724
import random import sys import pygame from pygame.locals import * # globel variables FPS =30 SCREEN_WIDTH = 400 SCREEN_HEIGHT = 511 SCREEN = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT)) GROUNDY = SCREEN_HEIGHT*0.8 GAME_SPRITIES = {} GAME_SOUNDS = {} PLAYER = 'gallery/sprites/bird.png' BACKGROUN...
SaqibShoaib/Snake-Game
flappy_bird++.py
flappy_bird++.py
py
7,757
python
en
code
0
github-code
50
41432739744
# -*- coding: utf-8 -*- """ Created on Mon Jul 4 21:41:07 2022 @author: Zaha """ # -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import turtle import random class L_system: # Making lsystem class and defining some functions def __i...
zaha2020/Bio_Inspired_Computing
L-System_Grammer/Codes/L_SYSYEM.py
L_SYSYEM.py
py
7,049
python
en
code
1
github-code
50
24135211114
import pyb import machine import struct import utime # Import the necessary modules print(" Importing gateway/relay node function library...") import uac_network.main.gw_functions as gwf from sensor_payload.main.sensor_payload import SensorPayload from uac_modem.main.unm3driver import MessagePacket, Nm3 print(" Imp...
bensherlock/micropython-usmart-network
main/sensor_node.py
sensor_node.py
py
27,292
python
en
code
0
github-code
50
39675481106
import re def match_any_expression(value='', expressions=[]): """verifies if the input value matches any of the expressions using re Args: value (str, optional): [string to be tested against the expressions]. Defaults to ''. expressions (list, optional): [list of patte...
gelouko/useful-scripts
aws/find_and_tag/utils.py
utils.py
py
1,029
python
en
code
1
github-code
50
46770272718
def mergeOverlappingIntervals(intervals): retval=[] while intervals: range1 = intervals.pop(0) minval,maxval =range1 rangemodified=False merged_ranges=[] for idx in range(len(intervals)): range2=intervals[idx] if ( (range1[0]>=range2[0] and range1[0]<=range2[1]) or (range1[1]<=range2[0...
younelan/Code-Fun
algo/mergeIntervals.py
mergeIntervals.py
py
1,169
python
en
code
0
github-code
50
32186397331
import os import sys import arcpy import pandas as pd from arcgis.features import FeatureLayer, GeoAccessor from arcgis.gis import GIS from dotenv import load_dotenv arcpy.env.overwriteOutput = True def auto_download_data(data_url, outGDB, outname, from_date, to_date): """ Requires you to be logged into arcgis p...
WenkChr/NGD_AGOL_Download
automate_download.py
automate_download.py
py
19,015
python
en
code
1
github-code
50
759183855
import streamlit as st import pandas as pd import datetime as dt import altair as alt import requests import folium import plotly.graph_objects as go from folium.plugins import MousePosition from st_aggrid import ( AgGrid, ColumnsAutoSizeMode, GridOptionsBuilder, GridUpdateMode, JsCode, ) def load...
gorkemuna1/Latest-Earthquakes
utility.py
utility.py
py
13,643
python
en
code
2
github-code
50
36540049389
import pyaudio import wave import pygame import threading import time # Base 'Sound' class that all inherit from class Sound: def __init__(self): self.path = None self.volume = 1 def set_volume(self, val): self.volume = val def play(self): pass # For sound effects, only supports WAV. Use this when you do...
wg4568/PyStellarEngine
stellar/sound.py
sound.py
py
1,455
python
en
code
2
github-code
50
28201165059
# Create your views here. from django.http import * from django.contrib.auth import logout from django.shortcuts import render_to_response, get_object_or_404 from django.core.paginator import Paginator from skatemaps.maps.models import * def index(request): return render_to_response('index.html', {'spots': spots, 'us...
jsantos/SkateMaps
maps/views.py
views.py
py
1,182
python
en
code
3
github-code
50
71189193436
""" Bot file that controls that mail bot """ from automation import Automation import pandas as pd from datetime import datetime, timedelta from utils import filehandler as fh from utils import regextools as rt class MailBot(Automation): def __init__(self): super(MailBot, self).__init__() self.or...
djwatson-coder/automation_programs
mailbot/bot.py
bot.py
py
4,394
python
en
code
0
github-code
50
39273560017
class Solution: def countSubstrings(self, s: str) -> int: if len(s) == 1: return 1 result = 0 size = len(s) for i in range(size): for left, right in (i, i), (i, i + 1): while left > -1 and right < size and s[left] == s[right]: ...
Tammon23/LeetCodePractice
Medium/PalindromicSubstrings/PalindromicSubstrings.py
PalindromicSubstrings.py
py
421
python
en
code
0
github-code
50
28640447322
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Author: Linjian Zhang Email: linjian93@foxmail.com Create Time: 2018-01-14 14:31:15 Program: Description: """ import math import torch import warnings from torch.nn import Module, Parameter import torch.nn.functional as F from torch.autograd import Variable def clip...
linjianz/pytorch-deepvo
rnn/modules.py
modules.py
py
14,203
python
en
code
102
github-code
50
7816156641
import pandas as pd url_1='https://fbref.com/en/matches/109ad6ba/Argentina-Saudi-Arabia-November-22-2022-World-Cup#shots_all' urls=[url_1] def cambio_min(match): suma=[] for x in match.Minute: min=x.split('+') i = 2 if i == len(min): nuevo_min=int(min[0])+int(min[1]) ...
toledojm/wc2022_stats
data.py
data.py
py
878
python
en
code
0
github-code
50
5631903542
import os import json from collections import defaultdict import numpy as np import cv2 import masking class COCODoomDataset: BACKGROUND_CLASS = 0 def __init__(self, data, image_root, version="standard", batch_size=16, ig...
csxeba/COCODoomSeg
data.py
data.py
py
3,801
python
en
code
0
github-code
50
5990359491
import os import sys import cv2 import numpy as np import tensorflow as tf from lib.utils.timer import Timer from lib.fast_rcnn.config import cfg from lib.fast_rcnn.test import test_ctpn from lib.networks.factory import get_network from lib.text_connector.detectors import TextDetector from lib.text_connector.text_conn...
EssayKillerBrain/WriteGPT
RecognizaitonNetwork/ctpn/text_detect.py
text_detect.py
py
3,485
python
en
code
5,257
github-code
50
18490923987
import torch import cv2 from einops import rearrange import numpy as np import json from PIL import Image from torchvision.models import EfficientNet_V2_M_Weights from core.settings import model_config def load_pretrained(model: object, pretrained: str, device: str): checkpoints = torch.load(pretrained, map_loca...
saeed5959/object-detection-transformer
object_detection/utils.py
utils.py
py
6,259
python
en
code
6
github-code
50
42684283653
import psycopg2 import os from politico.config import APP_CONFIG from flask import current_app class DB: """Database initialization class""" def tables(self): users = """ create table if not exists users ( id serial primary key not null, firstname varchar(...
erycoking/Politico_API
politico/api/v2/db/__init__.py
__init__.py
py
11,512
python
en
code
1
github-code
50
10230090124
# !/usr/bin/python # -*- coding: utf-8 -*- from . import news from .. import db from flask import jsonify __author__ = 'AidChow' @news.route('/list/<page>', methods=['GET']) def news_list(page): page = int(page) if page == 0: page = 1 with db.connect().cursor() as cur: sql = 'SELECT * fr...
pengyuanqiuqiu/MinDa_news
app/news/view.py
view.py
py
1,378
python
en
code
0
github-code
50
45998640719
from settings import * class Shield(pygame.sprite.Sprite): def __init__(self, x, y, p): pygame.sprite.Sprite.__init__(self) if p == 1: self.image = pygame.image.load(os.path.join(img_folder, 'shield1.png')).convert() self.image.set_colorkey((0,0,0)) elif p == 2: self.image = pygame.image.load(...
ew073168/Star-Wars-PvP
Star Wars PvP/shield.py
shield.py
py
574
python
en
code
0
github-code
50
24510732417
import numpy as np from common.sparsenetworkmodel import EdgeWeightedQBAF import common.helper as helper import copy import time class PSO: """ This class represents the PSO algorithm with its parameters and functions Some of the attributes: experiment_id: identifier for the experiment vel...
bazomd/sparse-mlp-structure-learning
python/common/particle_swarm_optim_algorithm.py
particle_swarm_optim_algorithm.py
py
17,114
python
en
code
0
github-code
50
6959991626
import numpy as np import cv2 import msvcrt import math from math import pi, sin, cos from matplotlib import pyplot as plt #显示图像等用,若需要用几个演示函数则启用 from mpl_toolkits.mplot3d import Axes3D #同上 def rendering(dir): # z的尺度与x和y相同,大小等同于测试图像大小,位置与测试图像像素点一一对应 # imgs为渲染结果,大小等同于测试图像大小,位置与测试图像像素点一一对应 z = n...
MTCXin/Face-Image-Rendering-and-Reconstruction
rendering.py
rendering.py
py
21,607
python
en
code
0
github-code
50
11125464700
from horovod.ray import RayExecutor import horovod.torch as hvd import ray # Start the Ray cluster or attach to an existing Ray cluster ray.init(address='auto') num_workers = 4 # Start num_hosts * num_slots actors on the cluster settings = RayExecutor.create_settings(timeout_s=30) executor = RayExecutor(settings, nu...
chongxiaoc/ray-examples
horovod/ray_start.py
ray_start.py
py
859
python
en
code
0
github-code
50
39283561437
#!/usr/bin/python3 """ Wavefront obj model loading. Material properties set in mtl file. Uses the import pi3d method to load *everything* """ import demo import pi3d from math import sin, cos, radians # Setup display and initialise pi3d DISPLAY = pi3d.Display.create() # Fetch key presses inputs=pi3d.InputEvents() ...
PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition
Chapter07/3dModel.py
3dModel.py
py
1,767
python
en
code
26
github-code
50
5698550979
"""Loop through all "hadded" data files and save the total number of coincidences.""" import argparse from collections import defaultdict import itertools as it import json import multiprocessing import numpy as np import common import delayeds import adevent def one_file(run_key, data_file_path, energy_lookup, bin...
samkohn/dyb-event-selection
dyb_analysis/event_selection/compute_num_coincidences.py
compute_num_coincidences.py
py
7,131
python
en
code
0
github-code
50
1387659283
import sys import logging import numpy as np class Sent_embedding_model: ''' wrapper for sentence embedding models ''' def __init__(self, config) -> None: ''' choose embedding method, choose post processing method (gen sentence embedding first and then post-processing) ''' assert ...
BinWang28/EvalRank-Embedding-Evaluation
src/s_models.py
s_models.py
py
3,359
python
en
code
35
github-code
50
42269348578
import torch.nn as nn import os from os.path import join import json import copy import torch from PIL import Image from collections import Counter import torch.nn.functional as F import matplotlib.pyplot as plt from torch.utils.data import Dataset import time import torch.optim as optim from torchvision import transfo...
vbhavank/two-head-number-pytorch-classifier
code.py
code.py
py
9,758
python
en
code
0
github-code
50
39908424305
#!/usr/bin/env python3 import sys if len(sys.argv) == 2: print("Opening: %s" % sys.argv[1]) f = open(sys.argv[1]) lines = f.readlines() gamma = epsilon = "" for i in range(len(lines[0])-1): print("i: %d" % i) b0 = b1 = 0 for l in lines: if l[i] == "0": ...
malfaxio/adventofcode
2021/03/sol03p1.py
sol03p1.py
py
728
python
en
code
0
github-code
50
28785556759
from Question_3_predict_9am import predict_temp_9am import csv cities = ['Sydney', 'Melbourne', 'Brisbane', 'Perth', 'Canberra', 'Adelaide'] data_9am = [] for city in cities: mae_ensemble, r2_ensemble, accuracy_ensemble = predict_temp_9am(city) data_9am.append([mae_ensemble, r2_ensemble, accuracy_ense...
JiatongGao/cse163-final-project
Question 3/Question 3 9am/Q3_run_9am.py
Q3_run_9am.py
py
581
python
en
code
0
github-code
50
26272620668
import os from typing import List, Dict from openai_api import OpenAIResponder from utils import format_message from chat_store import ChatStore api_key = os.getenv('OPENAI_API_KEY') class SafeguardAI: def __init__(self, api_key: str, model: str = 'gpt-3.5-turbo-0613', logger=None): self._api_key = api_ke...
kpister/prompt-linter
data/scraping/repos/mihaitruta~examine-ai-2/backend~safeguard.py
backend~safeguard.py
py
2,884
python
en
code
0
github-code
50
41802337679
####PARt1 r1 = range(0, 10) for range1 in r1: print(range1) print("") r2 = range(5, 30) for range2 in r2: print(range2) print("") r3 = range(10,20) for range3 in r3: print(range3) print("") ####Part2 #variables left_boarder = "[!" right_boarder = "!]" inner = "_" name = "Lizveth" length = range(0,11) for l...
code-in-the-schools/Loops-and-range_LizvethM
main.py
main.py
py
403
python
en
code
0
github-code
50
4897162439
import sys from typing import List from threading import Timer from grid import Grid from entity import MovableEntity, Entity, ScoutingEntity from consts.direction import MovementDirection from shape_sprite import ShapeSprite from ui import Menu, Button from consts.movement_type import MovementType from consts import C...
ryancollingwood/arcade-rabbit-herder
game.py
game.py
py
17,791
python
en
code
10
github-code
50
26992677057
from tkinter import * from tkinter import messagebox import pyspeedtest # pip install pyspeedtest def check(): speed = pyspeedtest.SpeedTest("www.wikipedia.com") v1 = (str(speed.download()) + " [Bytes per second]") messagebox.showinfo("Your download speed is : ", v1) root = Tk() #Basic background for t...
Mansish-101M99/Python-Projects
Internet speed checker/inspdchk1.py
inspdchk1.py
py
666
python
en
code
1
github-code
50
73348443036
""" Author : Setu Gupta Email : setu18190@iiitd.ac.in Date : 24th Aug 2020 This tool is used compare and plot accuracies of probability model and simple perceptrons. The tool can be used via the following command python3 path/to/this/file path/to/the/accuracy_report Note: accuracy_report is in DoS_noxim_router_meta_...
Setu-Gupta/noxim_NoC_DoS
bin/tools/plot_gen/accuracy_comparision_plot/bar_plot.py
bar_plot.py
py
2,715
python
en
code
0
github-code
50
71336543836
import typing as t import discord from discord.ext import commands import bot.extensions as ext from bot.clem_bot import ClemBot from bot.consts import Colors class InviteCog(commands.Cog): def __init__(self, bot: ClemBot) -> None: self.bot = bot @ext.command() @ext.long_help("My invite link so...
ClemBotProject/ClemBot
ClemBot.Bot/bot/cogs/bot_info_cog.py
bot_info_cog.py
py
2,379
python
en
code
79
github-code
50
37275885434
# LZW Encoder ''' The input data is encoded using the encoder.py file, the dictionary of size 256 is built and initialized, using the python dictionary data structure in the dictionary, key are characters and values are the ascii values the lzw compression algorithm is applied and we get the compressed data, the progra...
himanshikohli19/Design_and_Analysis_of_Algorithms_using_Python
LZWEncoding.py
LZWEncoding.py
py
1,901
python
en
code
0
github-code
50
28925000982
# monoalphabetic.py - implements a monoalphabetic (Caesar) cipher. from rotate import cipher_rotate # def rotate(char, rotation): # """ # Function to cipher individual characters of strings. Takes individual characters as input and returns shifted characters # """ # digit = ord(char) # cipherdigit...
Michael-Flood/ciphertool
monoalphabetic.py
monoalphabetic.py
py
1,644
python
en
code
0
github-code
50
70382429916
""" ========================================= Preparing Data for Analysis ========================================= Date: April 21, 2023 This script cleans the input data, removes outliers, explores and visualizes the cleaned data, shuffles the data, and outputs it as a .csv How to run: python3 preparing_data.py -...
odumosuo/insurance_prediction
preparing_data.py
preparing_data.py
py
7,748
python
en
code
0
github-code
50
16189072160
import pandas as pd import numpy as np import json from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler class DataModels: float_cols = ['PM25_A', 'PM25_B', 'Humedad_Relativa', 'Temperatura', 'Presion'] data_splitted = False def __init__(self, purple, aire...
gziz/air-pollution-models
src/data_models.py
data_models.py
py
2,520
python
en
code
0
github-code
50
2032923031
from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() import hello.views # Examples: # url(r'^$', 'gettingstarted.views.home', name='home'), # url(r'^blog/', include('blog.urls')), urlpatterns = [ url(r'^$', hello.views.index, name='index'), url(r'^popular', hello.v...
inaz2/osiete.herokuapp.com
gettingstarted/urls.py
urls.py
py
668
python
en
code
0
github-code
50
30919291696
from src.shelf import data_review as dl from src.shelf import dicts as alp import codecs import matplotlib.pyplot as plt data = dl.selected_reviews important = alp.words image_location = "images" def rating_dist(data): rating = [0, 0, 0, 0, 0] for element in data: star = int(element[1]) base...
rcmayhew/model
src/bag_of_words.py
bag_of_words.py
py
4,045
python
en
code
0
github-code
50
17290277462
handler = open("R&J_WORD_FREQS.txt", 'r') word_list = {} word_list['a'] = 0 def checkNotPresent(str1): if word_list==None: return True for a in word_list.keys(): if a==str1: return False return True mf_count = 0 for line in handler: data = line.strip().split(" ") for i ...
Echomo-Xinyu/H2_Computing
python/python_lesson/3_29/ws3/ws3_5.py
ws3_5.py
py
618
python
en
code
3
github-code
50
32076053454
import os import numpy as np from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img # 图片生成器ImageDataGenerator # 用以生成一个batch的图像数据,支持实时数据提升。训练时该函数会无限生成数据,直到达到规定的epoch次数为止 # 参数 # featurewise_center: boolean, 使输入数据集去中心化(均值为0) # samplewise_center: boolean, 使输入数据的每个样本均值为0 # feature_st...
esdream/smile
training/test_keras_aug.py
test_keras_aug.py
py
2,613
python
zh
code
0
github-code
50
71629052634
# PROYECTO """ JUEGO DE ADIVINA EL NUMERO. - PEDIR NOMBRE DE USUARIO - ELEGIR NUMERO AL AZAR ENTRE 1 Y 100 - DAR 8 INTENTOS AL JUGADOR PARA ENCONTRARLO - SI EL NUMERO QUE INGRESA EL USUARIO ES MENOR A 1 Y MAYOR A 100 INDICARLO - SI EL NUMERO ES MENOR AL ELEGIDO INDICARLO - SI ES MAYOR INDICARLO - SI A...
AdamNoir/MyLearning
Python/Python 16 Días/Día 4/Proyecto.py
Proyecto.py
py
1,703
python
es
code
0
github-code
50
17019972814
# -------------------------------------------------------------------------- # Loads and processes files from the site's 'includes' directory. # -------------------------------------------------------------------------- import os from . import loader from . import renderers from . import site # Dictionary of render...
GregHattJr/malt
malt/includes.py
includes.py
py
867
python
en
code
null
github-code
50
1067872119
# Python - 2020 Summer Course # Day 8 # Topic: More on SQL and Database (Loading a Database) # Instructor: Patrick Cunha Silva # Former Instructors: Ryden Buttler, Erin Rossiter # Michele Torres, David Carlson, and # Betul Demirkaya # This is an addition to the course made by Pat...
pcunhasilva/python_summer2020
Day8/Lecture/day08p2.py
day08p2.py
py
2,132
python
en
code
2
github-code
50
36487965490
def print_newspaper(lines, align, width): final_lines = [] stars = "*" * (width + 2) final_lines.append(stars) for i, line in enumerate(lines): curr_line = [] while line: if len(" ".join(curr_line + [line[0]])) <= width: curr_line.append(line.pop(0)) ...
emilycheera/coding-challenges
newspaper.py
newspaper.py
py
1,084
python
en
code
1
github-code
50
16103621701
import socket import threading import datetime import select class SockThread(threading.Thread): def __init__(self,socket,addr,cli_struct): super().__init__() self.socket = socket self.addr = addr self.cli_struct = cli_struct def disconnection_times(self): name = thread...
wd15102/select_server
select.py
select.py
py
3,526
python
en
code
0
github-code
50
25125623386
#!/usr/bin/env python3 import torch import cv2 from ai_old.util.etc import resize_imgs from ai_old.util.face import custom_align_face from ai_old.util.inverse import get_outer_quad DI_K_192 = 16 OUTER_BOUNDARY_DIV = 32 def get_di_k(imsize): return int(DI_K_192 * (imsize / 192)) def get_dilate_kernel(imsize): ...
calvinpelletier/ai_old
util/outer.py
outer.py
py
2,776
python
en
code
0
github-code
50
16705202463
'''le de um arquivo as cidades mais populosas e retorna a mais populosa''' cidade = '' populacao = 0 with open("arq.txt",'a+') as arquivo: arquivo.seek(0) lista = arquivo.read().split('\n') for c in lista: a = c.split('-').copy() if populacao < int(a[1].replace('.','')): popula...
LucasSalu/Curso_Python_Basico_Avan-ado
Arquivos_de_texto/exercicio_text10.py
exercicio_text10.py
py
515
python
pt
code
0
github-code
50
27769680948
from .veloxchemlib import Molecule from .veloxchemlib import MolecularBasis from .veloxchemlib import AtomBasis from .veloxchemlib import BasisFunction from .veloxchemlib import ChemicalElement from .veloxchemlib import bohr_in_angstroms from .veloxchemlib import assert_msg_critical from .veloxchemlib import to_angular...
manuel-br/input_handling
inputparser.py
inputparser.py
py
10,435
python
en
code
0
github-code
50
33884785238
# https://www.codewars.com/kata/5412509bd436bd33920011bc # Your task is to write a function maskify, which changes all but the last four characters into '#'. def maskify(word): if len(word) <= 4: return word elif word == None: return " " else: last_four = word[-4:] hash ...
modjeskaa/code-wars-solutions
Credit Card Mask.py
Credit Card Mask.py
py
379
python
en
code
0
github-code
50
22573980841
#!/usr/bin/env python import os from PIL import Image class ImageExtfindError(Exception): """ Class for reporting errors related to the problems with the image extension/format """ def __init__(self, value): self.value = value def __str__(self): return repr(self.value) def verify_image(...
ox-vgg/vgg_frontend
siteroot/controllers/utils/imchecktools.py
imchecktools.py
py
2,340
python
en
code
3
github-code
50
21671800647
import random i = 1 ite = 0 sample = 10000 for j in range(1, sample): i = 1 while (True): ite = ite + 1 rand = random.randint(0, 100) if i == rand: print(i) i = i + 1 if i == 101: break print(ite) print("avg = ", ite / sample)
Dmendoza3/Python-exercises
random/boogleCount100.py
boogleCount100.py
py
303
python
en
code
0
github-code
50
8652076835
import sys sys.stdin = open('input.txt') q = lambda : map(int, sys.stdin.readline().split()) N, M = q() # M : 필요한 메모리 = 베낭 용량 m = list(q()) # 메모리 = 무게 c = list(q()) # 활성화하는데 드는 비용 = 가치 dp = [[0 for _ in range(M+1)] for __ in range(N+1)] for i in range(1, N+1): memory, value = m[i-1], c[i-1] for j in rang...
TValgoStudy/algo_study
감자조/지수/배낭문제/7579_앱/s1.py
s1.py
py
467
python
ko
code
3
github-code
50
24360520210
import sys from itertools import chain def check(): cnt = 0 for i in range(5): # 가로 if sum(bingo[i * 5: (i + 1) * 5]) == -5: cnt += 1 # 세로 if sum(bingo[i::5]) == -5: cnt += 1 # 대각선 if sum(bingo[0::6]) == -5: cnt += 1 if sum(bingo[4:...
phoenix9373/Algorithm
2020/백준문제/IM대비/2578_빙고.py
2578_빙고.py
py
731
python
en
code
0
github-code
50
4134197620
import random import torch import torch.utils.data from PIL import Image from glob import glob import numpy as np import torchvision.transforms as transforms import os class DataProcess(torch.utils.data.Dataset): def __init__(self, img_root, input_mask_root, ref_root, train=True): super(DataProcess, self)....
Cameltr/TransRef
data/dataprocess.py
dataprocess.py
py
1,708
python
en
code
21
github-code
50
36879729097
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 2 03:23:55 2020 @author: mhasan13 """ import pickle as pkl import numpy as np import brian2 as br class NeuronMeshGrid: ''' Data on neuron phase plane ''' def __init__(self, pickle_path:str) -> None: with open(pickle_path,...
mhasan13-here/phase-plane-torch
initial/ObjectClass.py
ObjectClass.py
py
17,059
python
en
code
0
github-code
50
43594036384
import os import json import math import matplotlib.pyplot as plt from sklearn.cluster import DBSCAN import numpy current_directory = os.getcwd() data_folder_path = "data" folder_path = os.path.join(current_directory, data_folder_path) dicts = [] names = [] for file_name in os.listdir(folder_path): path = os.path...
ArcadeCookie/ReconocimientoDeMacroPatrones
DBS.py
DBS.py
py
2,567
python
en
code
0
github-code
50
27873466527
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = 'JQ' SITENAME = 'Japan Trip 2018' SITEURL = 'http://localhost:2018' STATIC_PATHS = ['images', 'pdfs'] PATH = 'content' TIMEZONE = 'America/Chicago' DEFAULT_LANG = 'en' DEFAULT_DATE_FORMAT = '%-m/%-d/%Y' DEFAULT_CATEGOR...
johnwquarles/japan-trip
pelicanconf.py
pelicanconf.py
py
1,318
python
en
code
0
github-code
50
43012985588
def equalize_voltage(signal, init_voltage = 0.1, target_voltage = 1, f = 10000): signal.set_voltage(init_voltage) signal.set_freq(f) signal.run() voltage_meas1 = signal.read_voltage(f, 4000, 1) #print(voltage_meas1) signal.stop() voltage_set1 = target_voltage*init_voltage/voltage_meas1 ...
fabianlickert/automated_acoustofluidics
drivers/equalize_voltage.py
equalize_voltage.py
py
821
python
en
code
0
github-code
50
27242163880
import pandas as pd import glob import os folderPath = "*.png" import os print(os.getcwd()) Images_path = "/Users/pavankumar/Documents/Robotics MSc/Dissertation/Data Pre-processing/Dissertation Datasets/mangoes/images" fruit = "mango" os.chdir( Images_path ) print(os.getcwd()) filesList = glob.glob(folderPath) p...
PavanproJack/Fruit-Detection-in-Orchards
Data Processing Scripts/sortImages.py
sortImages.py
py
610
python
en
code
12
github-code
50
71214457114
# coding:utf-8 from optparse import OptionParser import os import sys import itertools from common.glob import iglob def empty_dirs( root_dir ): for curr_dir, dirs, files in os.walk( root_dir ): if len( dirs ) == 0 and len( files ) == 0: yield curr_dir def main(): parser = OptionParser( version=...
ciel-yu/canal-aux
scripts/cleanempty.py
cleanempty.py
py
958
python
en
code
0
github-code
50
13180648906
''' In this challenge, you will be given 2 integers, n and m. There are n words, which might repeat, in word group A. There are m words belonging to word group B. For each m words, check whether the word has appeared in group A or not. Print the indices of each occurrence of m in group A. If it does not appear, prin...
RobertEne1989/python-hackerrank-submissions
defaultdict_tutorial_hackerrank.py
defaultdict_tutorial_hackerrank.py
py
1,398
python
en
code
0
github-code
50
35546153534
import json from os import path import datetime import sqlite3 import time import urllib.request ''' def connect(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("www.blahinc.com",80)) ''' #will need to be changed so we can connect to server def getUrlforBTC(time):#time should come in form yy...
CryptoUmnTheProject/Algorithmic-Trading
Algorithms/helper_functions/helper.py
helper.py
py
4,207
python
en
code
3
github-code
50
43108338058
#!/usr/bin/env python # coding: utf-8 # # THE SPARKS FOUNDATION # # ### TASK 1- PREDICTION USING SUPERVISED MACHINE LEARNING # # # ### DESCRIPTION - PREDICT THE PERCENTAGE OF A STUDENT BASED ON THE NUMBER OF STUDY HOURS # # ### NAME - SATYAM KUMAR # # In[18]: import pandas as pd import matplotlib.pyplot as ...
satyamiitbhu/The-Spark-Foundation
THE SPARK TASK 1.py
THE SPARK TASK 1.py
py
2,425
python
en
code
0
github-code
50
42883176870
from __future__ import absolute_import from abc import abstractmethod from six import string_types from sagemaker.local import file_input from sagemaker.session import s3_input class _Job(object): """Handle creating, starting and waiting for Amazon SageMaker jobs to finish. This class shouldn't be directly...
ggiallo28/aws-deepracer-local
source/sagemaker-python-sdk/src/sagemaker/job.py
job.py
py
8,097
python
en
code
2
github-code
50
70382594396
from click.testing import CliRunner from ocxtools.cli import cli from ocxtools import __version__ def test_cli_version(): runner = CliRunner() result = runner.invoke(cli,['version']) assert result.exit_code == 0 assert __version__ in result.output def test_cli_validate_info(): runner = CliRunner...
OCXStandard/ocxtools
tests/test_cli.py
test_cli.py
py
636
python
en
code
0
github-code
50
39676546346
from setuptools import setup, find_packages version = '0.3.dev0' setup(name='webtest-casperjs', version=version, description="Use casperjs with WebTest", long_description=open('README.rst').read(), classifiers=[ "Development Status :: 5 - Production/Stable", "Framework :: Paste...
gawel/webtest-casperjs
setup.py
setup.py
py
1,268
python
en
code
6
github-code
50
4757653620
""" A simple sample module with command authorization testing and some useful functions """ import sys import os import time #import yaml import json from sharedVars import authorizedPath def isAuth(username): with open(authorizedPath) as file: auths = json.load(file) if username not in auths: return False els...
fmorisan/amaurascripts
authorized.py
authorized.py
py
669
python
en
code
0
github-code
50
16191703063
import sys import pdb class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' BGBLUE = '\33[44m' def criarMatriz(nome): m=[] try: with open(nome,"r") as...
es0j/mdiff
mdiff.py
mdiff.py
py
3,073
python
pt
code
0
github-code
50
3155330834
# 두 개의 정수를 입력받아 작은 수부터 큰 수까지 모든 정수의 합을 구하여 출력하는 프로그램을 작성하시오. # f = open("io_441.txt", "r") # VS Code에서 열려있는 편집기 위치에 따라 상대경로가 결정된다 # a, b = map(int, f.readline().split()) a, b = map(int, input().split()) if(a > b): tmp = a a = b b = tmp sum = 0 for i in range(a, b+1): sum += i print(sum) # f.c...
refresh6724/APS
Jungol/Lv1_LCoder_Python/pyi0_파일입출력/Main_JO_441_파일입출력_자가진단1.py
Main_JO_441_파일입출력_자가진단1.py
py
458
python
ko
code
0
github-code
50
1683989676
import unittest import parl from parl.remote.monitor import ClusterMonitor import time import threading from parl.remote import exceptions from parl.utils.test_utils import XparlTestCase import os import signal @parl.remote_class class Actor(object): def __init__(self, arg1=None, arg2=None): self.arg1 = a...
PaddlePaddle/PARL
parl/remote/tests/cluster_monitor_3_test.py
cluster_monitor_3_test.py
py
2,074
python
en
code
3,097
github-code
50
32636496240
from django.conf.urls import url, include from .views.metadata import resource_metadata_json, geographic_feature_metadata_json, geographic_raster_metadata_json, \ time_series_metadata_json, file_set_metadata_json, multidimensional_metadata_json, \ referenced_time_series_metadata_json, single_file_metadata_json...
hydroshare/hydroshare
hs_rest_api2/urls.py
urls.py
py
3,060
python
en
code
171
github-code
50
36683165416
import logging from telegram import Update from telegram.error import BadRequest, TelegramError from telegram.ext import CallbackContext from bot.conversation import Status from bot.markups import InlineKeyboard, Keyboard from database.models import Channel from utilities import d logger = logging.getLogger('handler...
zeroone2numeral2/reddit-test
bot/plugins/channel_config/channel_configuration/export_invite_link.py
export_invite_link.py
py
3,325
python
en
code
2
github-code
50
36860839918
from dataclasses import dataclass from pathlib import Path import pytest from bluemira.base.constants import raw_uc from bluemira.base.error import ReactorConfigError from bluemira.base.logs import get_log_level, set_log_level from bluemira.base.parameter_frame import ( EmptyFrame, Parameter, ParameterFra...
Fusion-Power-Plant-Framework/bluemira
tests/base/reactor_config/test_reactor_config.py
test_reactor_config.py
py
8,715
python
en
code
31
github-code
50
24719142862
#-*-coding:utf-8 -*- #代码详解 #classify函数的参数: #inX:用于分类的输入向量 #dataSet:训练样本集合 #labels:标签向量 #k:K-近邻算法中的k #shape:是array的属性,描述一个多维数组的维度 #tile(inX, (dataSetSize,1)):把inX二维数组化,dataSetSize表示生成数组后的行数,1表示列的倍数。整个这一行代码表示前一个二维 # 数组矩阵的每一个元素减去后一个数组对应的元素值,这样就实现了矩阵之间的减法,简单方便得不让你佩服不行! #axis=1:参数等于1的时候,表示矩阵中行之间的数的求和,等于0的时候表示列之间数的求和。 #argso...
scales123/machine-learning
book/ch02/kNNpw.py
kNNpw.py
py
4,448
python
zh
code
1
github-code
50
16185666697
import os import boto3 import csv def get_boto3_client(): #region = self.region # Dummy Credentials return boto3.client("ec2", aws_access_key_id="Value", aws_secret_access_key="Value", region_name="Value")...
priya-sharmaa/Tasks
Python/get_faultysg.py
get_faultysg.py
py
4,401
python
en
code
0
github-code
50
23793199245
from collections import deque cases = int(input()) dx = [-2, -1, 1, 2, -2, -1, 1, 2] dy = [-1, -2, -2, -1, 1, 2, 2, 1] for i in range(cases): l = int(input()) a, b = map(int, input().split()) c, d = map(int, input().split()) q = deque() check = [[-1] * l for i in range(l)] def bfs(x, y): ...
innjuun/Algorithm
baekjoon/Graph/7562.py
7562.py
py
877
python
en
code
2
github-code
50
5651658902
from typing import List, Union import tensorflow as tf class FeatureSpec: def __init__(self, layer_name: str, working_stride: int = None, width: int = -1): self.layer_name = layer_name self.working_stride = working_stride self.width = width @classmethod def from_last_tensor(cls,...
csxeba/Verres
verres/architecture/backbone/base.py
base.py
py
2,020
python
en
code
0
github-code
50
36213413446
from art import logo from replit import clear def calc(first_num): operator = input("+\n-\n*\n/\nPick an operation: ").lower() second_num = float(input("What's the next number?: ")) if operator == '+': result = first_num + second_num elif operator == '-': result = first_num - second_nu...
jman3/100-days-of-python
day10/calculator.py
calculator.py
py
1,110
python
en
code
0
github-code
50
11264066828
from requests_html import HTMLSession session = HTMLSession(); r = session.get('https://www.boannews.com/media/s_list.asp?skind=5') f = open("security_world_title_content_data.txt", "w", encoding='UTF-8') print(r.html) #Get News Title & Content Summary for line in r.html.find('.news_list'): print(line.text) print(...
epicarts/team-crawlcrawl
etc/crawling_test/yeni/security_world_title_content.py
security_world_title_content.py
py
357
python
en
code
7
github-code
50
19975311840
import os import sys sys.path.append('./utils/midi') from utils.midi.midi_utils import midiread, midiwrite from matplotlib import pyplot as plt import torch import numpy as np class PianoGenerationDataset(torch.utils.data.Dataset): def __init__(self, midi_folder_path, longest_sequence_length=1491): ...
Khamies/Piano-VAE
dataset.py
dataset.py
py
2,937
python
en
code
7
github-code
50
23832075008
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor import matplotlib.patches as patches from torchvision import transforms from pycocotools.coco import COCO import matplotlib.pyplot as plt import matplotlib.image as im import torch.utils.data from PIL import Image import pandas as pd import numpy as...
Andrey-Nedov/Mask-RCNN-Traffic-Sign-Recognizer
Release/1_main_script/_main_script 2 (with net).py
_main_script 2 (with net).py
py
10,861
python
en
code
0
github-code
50
36840944715
import aiohttp import asyncio from aiohttp import web import requests routes = web.RouteTableDef() @routes.get("/parseActivities") async def save_fact(request): try: json_data = await request.json() #print(json_data) #print(json_data.get("type")) if json_data.get("type") == "charity" or json_data.get("type")...
b0rke-mborina/distsys-zadace
04-zadaci/zadatak1-part2.py
zadatak1-part2.py
py
814
python
en
code
0
github-code
50
18705959979
def heapsort(unsorted): n= len(unsorted) for i in range(n//2-1,-1,-1): #n//2-1이 의미하는 바는 힙의 자료구조에서 마지막으로 오는 원소의 부모 라인의 노드 index를 말합니다. heapify(unsorted, i, len(arr)) #이제 최대 힙을 구성하였고 아래에서 정렬이 시작됩니다. for i in range(n-1,0,-1): unsorted[0], unsorted[i]=unsorted[i], unsorted[0] #가장 최대인 unsorted[0]을 배열의...
doodung/Algorithm
정렬/힙정렬.py
힙정렬.py
py
1,659
python
ko
code
4
github-code
50
19628336810
import adventofcode import hashlib from collections import deque SIZE = 4 VAULT_X = 3 VAULT_Y = 3 DIRECTIONS = [0, 1, 2, 3] DIR_LETTERS = ['U', 'D', 'L', 'R'] DIR_VALUES = [(0, -1), (0, 1), (-1, 0), (1, 0)] class path: def __init__(self, key, path, x, y): self.key = key self.path = path s...
bvschaik/advent-of-code
2016/day17.py
day17.py
py
2,301
python
en
code
0
github-code
50
42734906839
from pyspark.sql import SparkSession import datetime import pandas as pd from pyspark.sql.types import * class CollectHiveData(): def __init__(self, days): self.spark = SparkSession.builder.config("spark.sql.warehouse.dir", "hdfs://ns1/user/hive/warehouse/").appName( "collectUidAndTUidData")....
yijianfenghou/PyRecommendationSystem
DSSM/AdDSSMNet_torch/DataSet/collectHiveData.py
collectHiveData.py
py
4,766
python
en
code
2
github-code
50