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
37706480646
import logging import torch from torch.optim import SGD import configs.classification.gradient_alignment as reg_parser import environment.animal_learning as environments from experiment.experiment import experiment from utils import utils from torch import nn from model import lstm from copy import deepcopy gamma = ...
khurramjaved96/columnar_networks
NoisyPatterns.py
NoisyPatterns.py
py
3,764
python
en
code
0
github-code
13
70278950097
# Run this only once. import sqlite3 DATABASE_PATH = "processed_data.sqlite" def db_connection(path: str): connection = None try: connection = sqlite3.connect(path) except sqlite3.Error as e: print("Error:", e) return connection connection = db_connection(DATABASE_PATH) cur = connect...
LassiLuukkonen/3D-Globe-Vis
Data/create_database.py
create_database.py
py
633
python
en
code
0
github-code
13
13129376348
from django.shortcuts import render from django.http import HttpResponse from django.http import JsonResponse from .models import programa from .models import categoria from .models import atajo # lista inicial de programas o datos de un programa especifico def index(request): id = request.GET.get('id', 0) i...
cgalvist/LinuxTricks
back_end/linuxtricks/programas/views.py
views.py
py
1,317
python
es
code
0
github-code
13
25927064880
from pydbl.test.management import Manager import unittest import sqlite3 class TestListsMgmt(unittest.TestCase): def test_list_operations(self): manager = Manager(verbose=True) list_name = "test-list" list_url = "http://test.example.com/list" list_description = "description" status = manager.run([ "-A", ...
mcptr/dbl-service
test/test_cli/test_lists.py
test_lists.py
py
2,372
python
en
code
0
github-code
13
70492336978
#Getting cube of key values in a dictionary. def Dict(a,b): Dic=dict() for i in range (a,b+1): Dic[i]=i**3 print('The Dictionary with cube of keyvalues:',Dic) def main(): print('To get the cube of keys in dictionary.') a=1 b=int(input('Enter the Range till you want to pr...
karmveershubham/Python-Codes
Dictionary_cube.py
Dictionary_cube.py
py
399
python
en
code
1
github-code
13
42517228226
from datetime import date from rest_framework import serializers from reviews.models import Category, Comment, Genre, Review, Title, User class CustomSlugRelatedField(serializers.SlugRelatedField): def to_representation(self, obj): return {'name': obj.name, 'slug': obj.slug} class UserS...
ArtemKAF/api_yamdb
api_yamdb/api/serializers.py
serializers.py
py
2,776
python
en
code
1
github-code
13
38910371406
import inject import json import logging from typing import Optional logger = logging.getLogger(__name__) class StorageService: """ This class will be used for storing and retrieving data in/from redis storage. """ MAIN_PATH = 'STORAGE' def __init__( self, identity: str, ...
stefan2811/port-16
port_16/api/common/service/storage.py
storage.py
py
6,303
python
en
code
0
github-code
13
21708719778
import requests import os import json from flask import Flask from flask import request from flask import make_response app = Flask(__name__) @app.route('/webhook', methods=['POST']) def webhook(): req = request.get_json(silent=True, force=True) print(">>> Request:") print(json.dumps(req, indent=4)) action = re...
wizehack/beanbird
app.py
app.py
py
1,535
python
en
code
0
github-code
13
36245907482
from dataclasses import dataclass @dataclass class Point: x: int y: int def distance(self, other: "Point") -> int: return abs(self.x - other.x) + abs(self.y - other.y) def __hash__(self): return hash((self.x, self.y)) def __eq__(self, other): return self.x == other.x and...
arjandepooter/advent-of-code-2022
aoc_2022/day15/solution.py
solution.py
py
2,185
python
en
code
0
github-code
13
35209235373
#PRACTICA5 #Repite la Práctica 4 pero guardando los datos del usuario en una variable de tipo diccionario en lugar de en una lista. varNombre = input("Tu nombre: ") varNaci = int(input("Cuantos años tienes: ")) dicci = {"Edad" : varNaci , "Nombre" : varNombre} for elemento in dicci: print ("Elemento : " + str(dicci[el...
brago12/Practicas_Python
practica5.py
practica5.py
py
1,227
python
es
code
0
github-code
13
29048309458
import random as python_random import argparse import numpy as np import json from sklearn.metrics import classification_report, confusion_matrix, ConfusionMatrixDisplay, accuracy_score from sklearn.preprocessing import LabelBinarizer from tensorflow.keras.optimizers import SGD, Adam from tensorflow.keras.losses...
chadji15/LearningFromData_Assignment3
src/grid_search.py
grid_search.py
py
5,813
python
en
code
0
github-code
13
34991762130
from stateMachine.statesEnum import ENVIAR_MENSAJES, EXPLORAR from threading import Timer from utils import convertTupleToString from properties import POI_POSITIONS, POI_TIMERS class actualizarMapa(): def __init__(self, bebop, dataBuffer, previousState, poisVigilar, poiVigilarTimeout, poiVigilarTimeoutDict, pois...
gRondan/MultipleUAVExploration
stateMachine/states/actualizarMapa.py
actualizarMapa.py
py
2,125
python
en
code
1
github-code
13
70922155539
import random from django import forms from django.contrib.auth import get_user_model from django.forms import formset_factory from . import models # CHOICES is the tuple that defines what colors a user can pick for their # background color in the ProfileForm CHOICES = [ ('random', 'Random'), ('blue', 'Blue'...
Zachary-Jackson/Social-Team-Builder
team_builder/profiles/forms.py
forms.py
py
4,048
python
en
code
0
github-code
13
29008075130
from typing import List from models.metrics import MetricBase # from models.modeltrainer import ModelTrainerBase class CallbackBase(object): def __call__(self, *args, **kwargs): raise NotImplementedError def on_train_begin(self, *args, **kwargs): raise NotImplementedError def on_epoch...
antonioguj/bronchinet
src/models/callbacks.py
callbacks.py
py
3,569
python
en
code
42
github-code
13
15791373340
import subprocess import time import threading from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient as mqttClient import logging import os import signal import json _logger = logging.getLogger(__name__) def startStreaming(): bash_script = './startStreaming.sh' global trigger_flag # Start the bash script...
JuanNavarro-DD/iotLearning
RasPi/turnCameraOn.py
turnCameraOn.py
py
2,213
python
en
code
0
github-code
13
35196207620
# Refazendo o desafio de progressão aritmetica com while n = int(input('Digite um numero para obter sua PA: ')) r = int(input('Qual é a razão ? ')) count = 0 primeiro_termo = n while True: n = n + r count += 1 print(n) if count == 10: break
Kaykynog/exercicios_guanabara
exercicios/063.py
063.py
py
275
python
pt
code
1
github-code
13
17046788464
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayUserAgreementSignConfirmModel(object): def __init__(self): self._apply_token = None self._cert_no = None self._confirm_no = None @property def apply_token(s...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/AlipayUserAgreementSignConfirmModel.py
AlipayUserAgreementSignConfirmModel.py
py
1,895
python
en
code
241
github-code
13
9070650630
n = int(input()) dungchi = [] for i in range(n): x, y = map(int, input().split()) dungchi.append((x, y)) res = [1] * n for i in range(n): for j in range(n): if dungchi[i][0] < dungchi[j][0] and dungchi[i][1] < dungchi[j][1]: res[i] += 1 for i in res: print(i, end=' ')
mins1031/coding-test
baekjoon/DungChi_7568.py
DungChi_7568.py
py
308
python
en
code
0
github-code
13
4170213077
# -*- coding: utf-8 -*- # @Time : 2020-08-02 11:18 # @Author : zcw # @Site : # @File : InputNameForm.py from PyQt5.QtWidgets import QDialog from PyQt5.QtCore import pyqtSignal, Qt from .InputNameUI import Ui_InputName class InputNameForm(QDialog): input_name = '' # 构造器,完成UI初始化,摄像头设备初始化等。 def __init__(s...
wenwen1205/faceRecognition
capturefaces/InputNameForm.py
InputNameForm.py
py
778
python
en
code
1
github-code
13
16991882789
# Python program to demonstrate delete operation # in binary search tree # A Binary Tree Node class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # A utility function to do inorder traversal of BST def inorder(...
NuthanReddy/Nuthan
DataStructures/MyBinarySearchTree.py
MyBinarySearchTree.py
py
5,042
python
en
code
1
github-code
13
30199274460
import gym from tqdm import tqdm import numpy as np import random env = gym.make('CartPole-v0') max_episodes = 10000 decay = 0.999 epsilon = 1 q = np.zeros((49, 200, 41, 200, 2)) alpha = 0.1 gamma = 1 pbar = tqdm(range(max_episodes), ascii=" .oO0", bar_format="{l_bar}{bar}|{postfix}") def format(st): st[0] = ro...
iamPres/cart-pole-RL
main.py
main.py
py
1,559
python
en
code
0
github-code
13
41727877312
import pymysql import config def lambda_handler(event, context): # db setting try: conn = pymysql.connect( host=config.db_hostname, user=config.db_username, password=config.db_password, db=config.db_name ) except pymysql.MySQLError as e: ...
GDG-Summer-Hackathon-Group12/serverless-backend
get_cafe_image_list.py
get_cafe_image_list.py
py
1,047
python
en
code
4
github-code
13
1797509147
from pydantic import ValidationError from pytest import raises from pathfinder_network.datamodel.string import String def test_valid_string(): # Test valid strings s1 = String(__root__="Hello, World!") assert s1 == "Hello, World!" s2 = String(__root__="1234") assert s2 == "1234" s3 = String(_...
JohnVonNeumann/pathfinder_network
tests/datamodel/test_string.py
test_string.py
py
731
python
en
code
2
github-code
13
42515334359
from pwn import * from ctypes import * def main(): binary = context.binary = ELF("./chall_17") p = process("./chall_17") libc = cdll.LoadLibrary("libc.so.6") libc.srand(libc.time(None)) p.sendline(str(libc.rand())) print(p.recv()) main()
Joel9241/Joelf_CPEG476_Speedruns
chall17.py
chall17.py
py
245
python
en
code
0
github-code
13
29423029149
from datetime import datetime import hashlib import string from io import BytesIO from PIL import Image from werkzeug.datastructures import FileStorage from __main__ import db class StoredImage(db.Model): __tablename__ = 'stored_images' id = db.Column(db.Integer, primary_key=True) md5_hash = db.Column(db.String(...
javilm/msx-center
models/StoredImage.py
StoredImage.py
py
4,565
python
en
code
0
github-code
13
70099253458
# apriamo il file da esaminare. Con with evitiamo il close alla fine with open('C:\\Users\\u_ex210831.log', 'r') as reader: key = '114.119.147.205' # chiave da ricercare i = 0 # contatore per le corrispondenze # Legge e stampa l'intero file riga per riga for line in reader: if key in line:...
FabGianc/Script
ricerca_nel_file.py
ricerca_nel_file.py
py
507
python
it
code
0
github-code
13
26275357820
"""Database models.""" from dataclasses import dataclass from datetime import datetime from enum import Enum from uuid import uuid4 from flask_login import UserMixin from sqlalchemy.dialects.postgresql import UUID, JSONB from sqlalchemy.schema import PrimaryKeyConstraint from sync_calendars.extensions import db user...
smurfpandey/sync_calendars
sync_calendars/models.py
models.py
py
3,805
python
en
code
0
github-code
13
7328507106
from turtle import back import pandas as pd import numpy as np import os from sklearn.metrics import accuracy_score, mean_squared_error, r2_score from sklearn import linear_model class LR: def __init__(self,): self.cwd = os.path.dirname(os.getcwd()) #获取当前文件的绝对路径 self.file_dirname = os.path.dirna...
OpenXLab-Edu/OpenBaseLab-Edu
BaseML/LR.py
LR.py
py
1,380
python
en
code
5
github-code
13
10348295531
import tensorflow as tf class BaseLSTMClass: def __init__(self, units, num_layers, output_units=None, drop_prob=None): if drop_prob is None: self.drop_prob = tf.placeholder_with_default(1., shape=()) else: self.drop_prob = drop_prob ...
rohanmukh/nsg
program_helper/sequence/base_lstm_class.py
base_lstm_class.py
py
1,519
python
en
code
20
github-code
13
17333187194
"""Module for PublishDiagnostics Provider which handles publishing of diagnostics for AaC Language Server.""" import logging from pygls.lsp import Diagnostic, DiagnosticSeverity, PublishDiagnosticsParams from pygls.server import LanguageServer from pygls.uris import to_fs_path from typing import Optional from aac.io.p...
jondavid-black/AaC
python/src/aac/plugins/first_party/lsp_server/providers/publish_diagnostics_provider.py
publish_diagnostics_provider.py
py
3,712
python
en
code
14
github-code
13
6143682962
#-*- coding: utf-8 -*- from antlr4.error.ErrorListener import * class MiniJava_ErrorListener(ErrorListener): ''' An inherited listener class to listen to the syntax errors. The error triger is defined in the .g4 file. ''' def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e): ''' An over...
vahidmohsseni/bscCompilerFa
MiniJavaError_Presenter.py
MiniJavaError_Presenter.py
py
1,207
python
en
code
2
github-code
13
20919581466
import sys import math import aocd from icecream import ic fuel = lambda m: max(math.floor(m/3)-2,0) def main(): # Read the input data = aocd.get_data(year=2019, day=1) modules = [int(line) for line in data.splitlines()] # Fuel for just the modules load = sum(map(lambda m: fuel(m), modules)) ic('part a:', loa...
colematt/advent-code
2019/day1.py
day1.py
py
607
python
en
code
0
github-code
13
29861870369
import kivy kivy.require('2.1.0') from kivy.graphics import Color, Rectangle from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.scrollview import ScrollView from kivy.uix.button import Button from kivy.uix.image import Image from kivy.uix.popup import Popup fr...
Blaiteray/CCMS
UI/signup.py
signup.py
py
7,768
python
en
code
0
github-code
13
20660483166
from math import ceil principal = float(input("Enter the loan principal: ")) print(""" What do you want to calculate? Enter 'm' to know how many months it will take to pay off the loan. Enter 'p' to know how much you should pay per month. """) selection = input() if selection == "m": mthly_pay_amt = int(input("En...
marydCodes/jetbrains_loancalculator
dreamworld.py
dreamworld.py
py
1,062
python
en
code
0
github-code
13
73643684497
# Ejercicio 217: Alternar el segundo carácter entre dos palabras de tres letras. # Solución: # las los => los las def intercambiar_caracteres(palabra1, palabra2): if len(palabra1) == 3 and len(palabra2) == 3: nueva_palabra1 = palabra1[0] + palabra2[1] + palabra1[2] nueva_palabra2 = palabra2[0] + ...
Fhernd/PythonEjercicios
Parte001/ex217_alternar_caracteres.py
ex217_alternar_caracteres.py
py
539
python
es
code
126
github-code
13
28396242593
import random import numpy as np import matplotlib.pyplot as plt import time #import json #import numpy as np #import random from keras.models import Sequential from keras.layers.core import Dense from keras.optimizers import sgd #import matplotlib.pyplot as plt # import matplotlib.animation # import IPython.display ...
alpaco42/EconThesisSeminar
EconAgentModel_v3_SingleCountryDecisions.py
EconAgentModel_v3_SingleCountryDecisions.py
py
17,447
python
en
code
0
github-code
13
74880179538
import os import argparse def delete_simulation_output(): """ This function is called by a forward model in ERT, deleting unnecessary simulation output files. Returns: Nothing """ parser = argparse.ArgumentParser(prog="Delete simulation output.") parser.add_argument( "ec...
equinor/flownet
src/flownet/ert/forward_models/_delete_simulation_output.py
_delete_simulation_output.py
py
590
python
en
code
57
github-code
13
20022522863
import datetime import functools import gc import hashlib import sys import time import threading def blah(func): @functools.wraps(func) def inner(*args, **kwargs): print("work it") return func(*args, **kwargs) return inner import wsgo @wsgo.cron(-2, -1, -1, -1, -1) @blah def every_two_min...
jonny5532/wsgo
wsgi.py
wsgi.py
py
1,461
python
en
code
2
github-code
13
21880685991
""" pyt_binary_classification.py: binary classification of 2D data @author: Manish Bhobe My experiments with Python, Machine Learning & Deep Learning. This code is meant for education purposes only & is not intended for commercial/production use! Use at your own risk!! I am not responsible if your CPU or GPU gets frie...
mjbhobe/dl-pytorch
pyt_binary_classification.py
pyt_binary_classification.py
py
9,630
python
en
code
8
github-code
13
17078826364
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.JsonOpenApiVO import JsonOpenApiVO class AlipayBossFncGfcenterBanklogtransferCreateResponse(AlipayResponse): def __init__(self): super(AlipayBossFncGfcen...
alipay/alipay-sdk-python-all
alipay/aop/api/response/AlipayBossFncGfcenterBanklogtransferCreateResponse.py
AlipayBossFncGfcenterBanklogtransferCreateResponse.py
py
969
python
en
code
241
github-code
13
72773726099
import javascript.proxy from javascript import require import logging import bot_functions import config Vec3 = require('vec3') mcData = require('minecraft-data')(config.settings['minecraft_version']) logger = logging.getLogger('bot_tasks') logger.setLevel(logging.DEBUG) handler = logging.FileHandler(filename=config...
rkaganda/minecraft_explore_bot
bot_tasks.py
bot_tasks.py
py
3,345
python
en
code
0
github-code
13
20325435785
import json from ibmcloudant.cloudant_v1 import CloudantV1 # 1. Create a client with `CLOUDANT` default service name ============ client = CloudantV1.new_instance() # 2. Get server information =========================================== server_information = client.get_server_information( ).get_result() print(f'Serv...
trls888s/django-IBM-captson
cloudant_test.py
cloudant_test.py
py
1,004
python
en
code
0
github-code
13
35869353302
from PIL import Image, ImageEnhance from cloudio import ImageIO, BucketConfig import logging, traceback, sys import json img_io = ImageIO() enhancers = { 'sharpness': ImageEnhance.Sharpness, 'contrast': ImageEnhance.Contrast, 'brightness': ImageEnhance.Brightness, } def generate_preview_images(img, nam...
WayneGGG/ECE1779-A3
enhancer/enhancement.py
enhancement.py
py
2,193
python
en
code
0
github-code
13
71251535697
from typing import List from scripts.debugCommands.command import Command from scripts.debugCommands.utils import add_output_line_to_log from scripts.game_structure.game_essentials import game from scripts.cat.cats import Cat class addCatCommand(Command): name = "add" description = "Add a cat" aliases =...
Thlumyn/clangen
scripts/debugCommands/cat.py
cat.py
py
2,691
python
en
code
135
github-code
13
3746376478
#!/usr/bin/env python from __future__ import print_function from optparse import OptionParser import re LANGUAGES_HPP_TEMPLATE = """\ #pragma once #include <array> #include <string> // This file is autogenerated while exporting sounds.csv from the google table. // It contains the list of languages which can be used ...
organicmaps/organicmaps
tools/python/tts_languages.py
tts_languages.py
py
1,793
python
en
code
7,565
github-code
13
14570753668
""" Created on Fri Mar 7 18:42:21 2014 @author: fritz """ import numpy as np #import matplotlib.pyplot as plt from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * window = 0 width, height = 800, 600 def draw_stuff(): data = [ [0, 0], [90, 0], [0, 90], [100,...
fgroes/pyFirstPerson
main.py
main.py
py
1,198
python
en
code
0
github-code
13
26387294210
#!/usr/bin/env python # coding: utf-8 import time import os import copy import numpy as np import pandas as pd from PIL import Image, ImageChops #from tqdm import tqdm from matplotlib import pyplot as plt import torch import torch.nn as nn import torch.optim as optim import torchvision import torch.nn.functional as ...
nsalas24/isic-2019
confident_classifier/conf_classifier_training.py
conf_classifier_training.py
py
10,924
python
en
code
1
github-code
13
4787029983
import pygame class Box: def __init__(self, number, row, col, width, height): self.number = number self.row = row self.col = col self.width = width self.height = height self.isSelected = False def draw_boxes(self, window): spacing = self.width / 9 ...
Madhur215/Sudoku
Box.py
Box.py
py
1,363
python
en
code
1
github-code
13
42852894497
import math n = int(input().split()[0]) for i in range(0, n): line = input().split() r, h1, h2 = line r, h1, h2 = float(r), float(h1), float(h2) h1 = h1 / 1000 # m to km h2 = h2 / 1000 # m to km theta1 = math.acos(r / (r + h1)) theta2 = math.acos(r / (r + h2)) print(((theta1 + theta2) ...
sreedhara-aneesh/open-kattis-submissions
exoplanetlighthouse.py
exoplanetlighthouse.py
py
357
python
en
code
0
github-code
13
17089266254
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.PreRepayPlanTermVO import PreRepayPlanTermVO class AlipayPcreditLoanBudgetQueryResponse(AlipayResponse): def __init__(self): super(AlipayPcreditLoanBudge...
alipay/alipay-sdk-python-all
alipay/aop/api/response/AlipayPcreditLoanBudgetQueryResponse.py
AlipayPcreditLoanBudgetQueryResponse.py
py
2,303
python
en
code
241
github-code
13
73210239698
from xmlrpc.server import ( SimpleXMLRPCServer, list_public_methods ) from caninehotel_backend.utils import register_rpc_operations from caninehotel_backend.handler import RequestHandler from caninehotel_backend.config import ( HOST, PORT, ) from caninehotel_backend.database import connect_to_mongodb def main...
HeinerAlejandro/caninehotel
caninehotel_backend/main.py
main.py
py
800
python
en
code
0
github-code
13
35185555216
import boto3 import json import os # Iris flower categories. irisCategory = { 0: 'setosa', 1: 'versicolor', 2: 'virginica' } def handler(event, context): """ Lambda handler. Processes MongoDB Change Events, invokes SageMaker enpoint with input read from event and writes results back to event ...
mongodb/mongodbatlas-cloudformation-resources
examples/quickstart-mongodb-atlas-analytics-amazon-sagemaker-integration/sagemaker-example/lambda_functions/process_mdb_change_event/app.py
app.py
py
2,165
python
en
code
51
github-code
13
39476914995
userInp = input('Zadejte cele cislo na preklad :') #Tohle vezme input od uzivatele userInp = int(userInp) #Tohle prevede input od uzivatele na int aby to program mohl zpracovat class romanNum: #Vytvorime funcki ktera vezme userInp jako vstupni parametr def intToRom(self, userInp): #Nadefinujeme si cisla...
KordacVojtech/Zaverecny-projekt-VS
romNumVS.py
romNumVS.py
py
969
python
hr
code
0
github-code
13
33246511843
from __future__ import absolute_import from __future__ import print_function from __future__ import division import tensorflow as tf from models import losses from models import preprocessing from models import vgg from models import vgg_decoder slim = tf.contrib.slim network_map = { 'vgg_16': vgg.vgg_16, '...
LucasSheng/avatar-net
models/autoencoder.py
autoencoder.py
py
5,339
python
en
code
173
github-code
13
8004189178
#http://www.codeskulptor.org/#user40_Pr2t3Pg6M4Wkq7O.py """ Student template code for Project 3 Student will implement five functions: slow_closest_pair(cluster_list) fast_closest_pair(cluster_list) closest_pair_strip(cluster_list, horiz_center, half_width) hierarchical_clustering(cluster_list, num_clusters) kmeans_cl...
chickenoverrice/python_game
python_closestPair.py
python_closestPair.py
py
6,522
python
en
code
0
github-code
13
2295554766
from flask import Flask, render_template, request from flask_sqlalchemy import SQLAlchemy from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired app = Flask(__name__) ENV = 'prod' #ENV = 'dev' app.config['SECRET_KEY'] = "my super secret key" if ENV ==...
sjackson1837/lexusfeedback
app.py
app.py
py
5,044
python
en
code
0
github-code
13
26148505680
from decimal import Decimal from math import ceil, log def isqrt(n): res = 0 # smallest power of 4 >= the argument bit = 4**int(ceil(log(n, 4))) if n else 0 while bit: if n >= res + bit: n -= res + bit res = (res >> 1) + bit else: res >>= 1 b...
maartenterpstra/Euler
euler64.py
euler64.py
py
844
python
en
code
0
github-code
13
2328044396
# getverse.py # gets a verse from verses database # e.g., when user enters "John 3:16" it pulls up the verse and reference import sqlite3 def get_verse(book, chapter, verse): connection = sqlite3.connect('verses.db') cursor = connection.cursor() # Query the database for the specified verse cursor.exe...
jwelkener/InstaBible
getverse.py
getverse.py
py
1,094
python
en
code
0
github-code
13
36754387428
#!/usr/bin/env python3 import pandas as pd def average_temperature(): df = pd.read_csv("src/kumpula-weather-2017.csv") mask = df["m"]==7 df1 = df[mask] df2 = df1["Air temperature (degC)"] return df2.mean() def main(): print("Average temperature in July: "+str()) return if __name__ == "__m...
tugee/dap2020
part04-e10_average_temperature/src/average_temperature.py
average_temperature.py
py
339
python
en
code
0
github-code
13
73564103696
#One hot encoding import pandas as pd import numpy as np from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_absolute_error from sklearn.model_selection import train_test_split from sklearn.preprocessing import OneHotEncoder from sklearn.model_selection import cross_val_score def get_m...
jaimecuellar14/MachineLearning
onehotencoding.py
onehotencoding.py
py
2,799
python
en
code
0
github-code
13
773523086
import re p = re.compile(r'42') text1 = "23 street" text2 = "42 meaning of life" efr = p.findall(text1) trg = p.findall(text2) if '42' in efr: print('42 not in the text1') print('42 in the text2') elif '42' in trg: print('42 not in the text1') print('42 in the text2')
Babushka312/dream_team
chapter_1/test_3.py
test_3.py
py
285
python
en
code
0
github-code
13
41726570064
from pygame import image, transform from constants import ICON_SIZE class FileReadingException(Exception): def __init__(self): super().__init__('Something went wrong while reading your file') def music_icon(window, music): # window - pygame.dispaly if music is True: is_on = 'on' else...
Sebastian-Abramowski/Snake
other.py
other.py
py
1,319
python
en
code
0
github-code
13
42647147157
import argparse, pickle, json, time, sys, os import pandas as pd sys.path.insert(1, os.getcwd()+"/../") sys.path.insert(1, os.getcwd()+"/../compass") sys.path.insert(1, os.getcwd()+"/../gestalt") sys.path.insert(1, os.getcwd()+"/../utils") sys.path.insert(1, os.getcwd()+"/../experiments") sys.path.insert(1, os.getcwd(...
osullik/GESTALT
code/experimentVariablesGT.py
experimentVariablesGT.py
py
13,593
python
en
code
0
github-code
13
21679027552
import actions.util as util import util.logger as logger import discord_handler.player_singleton as player_singleton import discord_handler.embed as embed import discord.ext.commands as commands import yt_dlp import os import asyncio import traceback YTDL_FORMAT_OPTIONS = { 'format': 'bestaudio/best', 'outtmpl...
Guisilcol/milharaaska_bot
milharaaska_bot/actions/play_command.py
play_command.py
py
3,054
python
en
code
0
github-code
13
23321799799
import scrapy class FacebookSpider(scrapy.Spider): name = "facebook" start_urls = ["https://www.metacareers.com/jobs?page=1&results_per_page=100#search_result"] def parse(self, response): for job_opening in response.xpath('//a[@class="_8sef"]'): relative_link = job_opening.xpath('./...
SW386/job-scraper
careers/spiders/facebook.py
facebook.py
py
2,623
python
en
code
1
github-code
13
33080014104
from django.db import models from django.contrib.auth.models import User from cloudinary.models import CloudinaryField STATUS = ((0, "Draft"), (1, "Published")) SCORE_CHOICES = [ (0, '0.0 - Worst Game Ever'), (0.5, '0.5 - Horrible'), (1, '1.0 - Terrible'), (1.5, '1.5 - Rubbish'), (2, '2.0 - Bad'), ...
JordanCH05/VideoGameReviews
reviewsite/models.py
models.py
py
1,639
python
en
code
1
github-code
13
36979126253
from contextlib import closing from pathlib import Path import tempfile import unittest from shark_engine.support.compiler_dl import * from shark_engine.support.compiler_api import * class DlFlagsTest(unittest.TestCase): def testDefaultFlags(self): session = Session() flags = session.get_flags() ...
stellaraccident/shark-engine
tests/support/compiler_test.py
compiler_test.py
py
4,300
python
en
code
0
github-code
13
16276208377
from os import system def batch(scriptname,*args,**kwargs): ''' Run script as a slurm batch (i.e. queued) *args are the bind parameters for the script, and must all be strings. ''' outfile = kwargs.pop('outfile','~/slurm/out%j.txt') errfile = kwargs.pop('errfile','~/slurm/err%j.txt') ...
theunissenlab/tlab
src/slurm.py
slurm.py
py
962
python
en
code
0
github-code
13
2718522291
n, k = map(int, input().split()) cds = [] for i in range(1, n + 1): if n % i == 0: cds.append(i) if len(cds) < k: print(0) else: print(cds[k - 1])
jinlee9270/algo
백준/Bronze/2501. 약수 구하기/약수 구하기.py
약수 구하기.py
py
169
python
en
code
0
github-code
13
73936447059
from re import match def grade_average( first_subject: str, second_subject: str, third_subject: str, first: float, second: float, third: float ) -> dict: grade = dict() grade[first_subject] = first grade[second_subject] = second grade[third_subject] = third grade_quantity ...
Wellinton-A/test-stag
7-grade_average/grade_av.py
grade_av.py
py
2,638
python
en
code
0
github-code
13
17988511642
import requests from bs4 import BeautifulSoup from utils import write_data def get_data(url): html = requests.get(url).text soup = BeautifulSoup(html, 'html.parser') updated = soup.select('.timetable > .info > span')[0].text # 업데이트날짜 data = soup.select('.rpsa_detail > div > div') data.pop() ...
LiveCoronaDetector/livecod
data/crawlKoreaRegionalData.py
crawlKoreaRegionalData.py
py
2,264
python
en
code
67
github-code
13
39814483010
import warnings warnings.filterwarnings("once", category=DeprecationWarning) import logging logging.basicConfig(format='%(asctime)s: %(name)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.DEBUG) import unittest import copy import time import pandas as pd from numpy.testing import asser...
Chris35Wills/oggm
oggm/tests/test_models.py
test_models.py
py
73,389
python
en
code
null
github-code
13
7575309031
import argparse from visualize import VisualizationStats def main(args): v = VisualizationStats(args.view_diff) v.open() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Tegrastats Graph') parser.add_argument("--view_diff", action='store_true') args = parser.parse_args()...
hjhwang-qed/jetson-usage-graph
main.py
main.py
py
336
python
en
code
0
github-code
13
15816866665
"""Plot results""" import os.path import numpy as np import math from scipy.interpolate import griddata import matplotlib.pyplot as plt from matplotlib.colors import LogNorm from cmc_robot import ExperimentLogger from save_figures import save_figures from parse_args import save_plots import os def plot_positions(tim...
shonigmann/ComputationalMotorControl
Lab9/Webots/controllers/pythonController/plot_results.py
plot_results.py
py
22,784
python
en
code
0
github-code
13
42675687954
from minepy import MINE import matplotlib.pyplot as plt import numpy as np def mic(): lgb_test_A = np.loadtxt("../result/lgb_A.txt") lgb_test_A_no = np.loadtxt("../result/lgb_A_no_useful2.txt") xgb_test_A = np.loadtxt("../result/xgb_A.txt") lr_test_A = np.loadtxt("../result/lr_A.txt") rf_test_A ...
squirrelmaster/rong360-8
src/base/analyze.py
analyze.py
py
1,054
python
en
code
0
github-code
13
19335873553
import csv import numpy as np import os # ten files test_cloud_1.txt, test_cloud2.txt, ..., test_cloud10.txt file_names = ['./test_clouds/test_cloud0.txt', 'test_clouds/test_cloud1.txt', './test_clouds/test_cloud2.txt', './test_clouds/test_cloud3.txt', './test_clouds/test_cloud4.txt', './test_clouds/test_cloud5.txt', ...
johngunerli/test_cloud_points_plot
mp.py
mp.py
py
3,930
python
en
code
0
github-code
13
17049319754
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class BizFundSettleSummary(object): def __init__(self): self._charge = None @property def charge(self): return self._charge @charge.setter def charge(self, value): ...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/BizFundSettleSummary.py
BizFundSettleSummary.py
py
837
python
en
code
241
github-code
13
12392302796
N = int(input()) lst = [list(map(int,input().split())) for i in range(N)] for i in range(N-2): for j in range(i+1,N-1): for k in range(j+1,N): x0,y0 = lst[i] x1,y1 = lst[j] x2,y2 = lst[k] x0 -= x2 x1 -= x2 y0 -= y2 y1 -= y2...
06keito/study-atcoder
src/abc181_c.py
abc181_c.py
py
415
python
en
code
0
github-code
13
16177240390
#Escreva um programa que leia um número N inteiro qualquer e mostre na tela os N primeiros elementos de uma Sequência de Fibonacci. Exemplo: #0 – 1 – 1 – 2 – 3 – 5 – 8 print('-' * 30) total = int(input('Quanto termos você quer mostrar? ')) print('-' * 30) c = 0 p3 = p2 = p1 = 1 print('0 -> 1 -> ', end='') while c < (to...
acksonpires/Phyton-Course-
ex063.py
ex063.py
py
489
python
pt
code
0
github-code
13
20368914250
from lxml import etree from requests import get from json import loads from urllib import urlencode def dbpedia(query): # dbpedia autocompleter autocomplete_url = 'http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?' # noqa response = get(autocomplete_url + urlencode(dict(QuerySt...
opi/searx_ynh
sources/searx/autocomplete.py
autocomplete.py
py
1,363
python
en
code
1
github-code
13
24337611042
import json import datetime # Функция для чтения заметок из файла def read_notes(): try: with open("notes.json", "r") as file: notes = json.load(file) except FileNotFoundError: notes = [] return notes # Функция для сохранения заметок в файл def save_notes(notes): with open(...
SHarldaevVladimir/NotesPython
import json.py
import json.py
py
3,654
python
ru
code
0
github-code
13
6847978865
# TODO: This file should be deprecated, it's just for testing. # TODO: TEST!!! import sys import os sys.path.append('/home/ubuntu/openhgnn/') os.chdir('/home/ubuntu/openhgnn/') from openhgnn.models.MAGNN import MAGNN from openhgnn.sampler.MAGNN_sampler import MAGNN_sampler, collate_fn from openhgnn.sampler.test_config...
BUPT-GAMMA/OpenHGNN
openhgnn/sampler/test_MAGNN_sampler.py
test_MAGNN_sampler.py
py
9,360
python
en
code
710
github-code
13
11407940522
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging from config import user_configuration from logging.handlers import RotatingFileHandler FORMATTER = logging.Formatter( "%(asctime)s — %(name)s — " + "%(levelname)s — %(filename)s:%(lineno)d — " + "%(message)s" ) LOG_FILE = user_configuration()["e...
OWASP/Python-Honeypot
core/log.py
log.py
py
944
python
en
code
383
github-code
13
42168555802
"""Calculates how high the hailstone numbers get for a given seed. Usage: import height Usage: from height import measure Usage: from height import measures >>> measure(5) 16 >>> measure(7) 52 >>> measure(1) 1 >>> measures(6) [(1, 1), (2, 2), (3, 16), (4, 4), (5, 16), (6, 16)] >>> measures(5) """ from hailstones i...
lzhengem/python-projects
LAB04/hailstoneslab/height.py
height.py
py
1,036
python
en
code
0
github-code
13
27803476982
N = int(input()) data = map(int, input().split()) def binary_search(start, end): global result mid = (start + end) // 2 dist = 0 for d in data: dist += abs(d - mid) result = min(result, dist) result = 0 binary_search(0, 100_000)
tkdgns8234/DataStructure-Algorithm
training/이코테/24.py
24.py
py
263
python
en
code
0
github-code
13
5858736743
import os def create(file): open(file, 'w').close() def add_file_content(file_name, content): with open(file_name, 'a') as file: file.write(content) file.write('\n') def replace(file_name, old_str, new_str): with open(file_name, 'r+') as file: file_content = file.read() ...
Ilian-Kossev/File_handling-exercises
3_file_manipulator/manipulator.py
manipulator.py
py
1,400
python
en
code
0
github-code
13
73049234577
import os.path as osp from typing import List from pytorch_lightning import LightningDataModule from torch.utils.data import DataLoader from data.dataset import CMD3Dataset class CMD3DataModule(LightningDataModule): def __init__( self, root_dir: str, batch_size: int, num_worke...
hangyeol013/cmd3
cmd3_audio/data/datamodule.py
datamodule.py
py
1,970
python
en
code
0
github-code
13
7216228999
import numpy as np class MatchCalculation: @classmethod def calculation(self,text1: str,text2: str,num_100 = False,ratio_calc = True): s = text1.lower() t = text2.lower() # Initialize matrix of zeros rows = len(s) + 1 cols = len(t) + 1 distance = np.zeros((rows...
paulussimanjuntak/Automatch
restapi/services/libs/MatchCalculation.py
MatchCalculation.py
py
2,067
python
en
code
0
github-code
13
20007337817
from sys import argv import recurrent from json import JSONEncoder as encoder json = encoder().encode try: text_content = ' '.join(argv[1:]) parsed_result = recurrent.parse(text_content) or None friendly_result = recurrent.format(parsed_result) if parsed_result else None print( json({ "parameterised": str(p...
maxichrome/reminderer
nlp/process.py
process.py
py
525
python
en
code
1
github-code
13
4999720305
""" you can use and to combine of statements ands come before or's in order of operations in python and is considered multiplications addition equates to or o's equate to false amd 1's equate to true x > and + > or 0 > false 1 > true a and false == false a and true == a a or false == a a or True == true not not...
kateculpepper/220
notes/notes.3.16.py
notes.3.16.py
py
4,182
python
en
code
0
github-code
13
10659926755
from django.contrib import admin # Core from core.models import BusinessUnitLov # Welderlist from core.models import fNumberLov from core.models import ProcessLov from core.models import tQualLov from core.models import DiameterLov from core.models import PositionLov from core.models import CesscoWeldProcedureLov fro...
rsombach/btm419_demo
cessco/core/admin.py
admin.py
py
3,379
python
en
code
0
github-code
13
16179930395
import os import pickle import tempfile import mdtraj as md import numpy as np import pytest from mdtraj.testing import eq try: from openmm import app import openmm.unit as u HAVE_OPENMM = True except ImportError: HAVE_OPENMM = False needs_openmm = pytest.mark.skipif(not HAVE_OPENMM, reason='needs Op...
mdtraj/mdtraj
tests/test_topology.py
test_topology.py
py
10,270
python
en
code
505
github-code
13
14039943929
#!/usr/bin/env python from distutils.core import setup DISTUTILS_DEBUG = True setup(name='PySpectrograph', version='0.3', description='Spectrograph Modelling Software', author='Steve Crawford', author_email='crawfordsm@gmail.com', url='http://code.google.com/p/pyspectrograph/', pa...
cmccully/pyspectrograph
setup.py
setup.py
py
563
python
en
code
null
github-code
13
16013037410
from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * from numpy import arange from math import sin, cos, pi import sys def init(): glClearColor(1, 1, 1, 1) gluOrtho2D(-2, 2, -2, 2) def plot_func(): glClear(GL_COLOR_BUFFER_BIT) glColor3f(0, 0, 0) glPointSize(1) # glRotat...
sagar-spkt/Learning
Etch-a-sketch/ex7.py
ex7.py
py
1,140
python
en
code
0
github-code
13
41995510879
#!/usr/bin/env python import sys from prettytable import PrettyTable,HEADER,NONE,FRAME DELIMITER=';' disp = PrettyTable() #disp.border = False disp.hrules = HEADER disp.vrules = NONE input_tags = list() col_names = list() tag2name = dict() tag2name = { '1' : 'Account' , '6' : 'AvgPx', '31' : 'LastPx...
kyoxiao/toolbox
extf.py
extf.py
py
1,721
python
en
code
0
github-code
13
71165003539
#!/usr/bin/env python import numpy as np import math import cv2 #Enter PGM or PGMA you would like to compress #If you would like to skip using the program I have provided some examples of results #Higher numbers = higher variance accepted before an area is all changed to the same value data=cv2.imread('baboon.pgma',-...
elijahjackson42/Quad-Tree-PGM-Compression
main.py
main.py
py
3,194
python
en
code
1
github-code
13
23725124846
from converter.items import * from .base_classes import LomBase from .base_classes import JSONBase import json import logging import requests import html from converter.constants import * import scrapy # Spider to fetch RSS from planet schule class WirLernenOnlineSpider(scrapy.Spider, LomBase, JSONBase): name = "w...
openeduhub/oeh-search-etl
converter/spiders/wirlernenonline_spider.py
wirlernenonline_spider.py
py
7,791
python
en
code
7
github-code
13
24853300184
""" 'Calliope' A locally deployable Mistral7B based chatbot optimized to function as a conversation partner and idea generator. Adapted from the example provided at: https://github.com/holoviz-topics/panel-chat-examples/blob/main/docs/examples/mistral/mistral_with_memory.py To execute: $ panel serve Calliope.py --sh...
Marcus-Sarcina/exitbot
exitbot_2/Calliope.py
Calliope.py
py
3,145
python
en
code
0
github-code
13
2463789859
from math import prod from itertools import combinations def domain_name(url): s = url.split('://') if 'http' in s[0]: ans = s[1].split('.') else: ans = s[0].split('.') if ans[0] != 'www': return ans[0] else: return ans[1] def int32_to_ip(int32): ...
Zheka-m-p/Python-Ylab
HomeWork1/HomeWork1.py
HomeWork1.py
py
1,870
python
ru
code
0
github-code
13
35013153204
from rpgpy import utils from numpy.testing import assert_array_equal import pytest def test_rpg_seconds2date(): date = utils.rpg_seconds2date(0) date_only = utils.rpg_seconds2date(0, date_only=True) res = ['2001', '01', '01', '00', '00', '00'] assert_array_equal(date, res) assert_array_equal(date_...
KarlJohnsonnn/rpgpy
tests/unit/test_utils.py
test_utils.py
py
701
python
en
code
null
github-code
13