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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
72964692179 | import json
class ConfigMaker:
def __init__(self):
print("Remote Control Solenoid Config Maker!\n")
def write_config(self,data_dict):
with open("config.json" , "w") as File:
data_to_write =json.dumps(data_dict)
File.write(data_to_write)
def create_config(self):
... | HOI-Devices/RemoteControlRelayController | config.py | config.py | py | 606 | python | en | code | 0 | github-code | 13 |
34927188785 | from ftplib import FTP
import ftplib
import os
"""
If the FTP server that you’re connecting to requires TLS security,
then you will want to import the FTP_TLS class instead of the FTP class.
The FTP_TLS class supports a keyfile and a certfile.
"""
# =================== CONNECTING TO FTP SERVERS ===================
... | joaofguerreiro/python3-course-advanced | 21_working_with_FTP/ftplib_sample.py | ftplib_sample.py | py | 3,748 | python | en | code | 2 | github-code | 13 |
12313206028 | #!/bin/python3
from typing import List
import array
def arrayManipulation(n: int, queries: List[List[int]]):
arr = array.array("i", [0] * (n + 1))
for a, b, k in queries:
arr[a - 1] += k
arr[b] -= k
maximum = 0
acc = 0
for v in arr:
acc += v
if acc > maximum:
... | uztbt/cp | HackerRank/ArrayManipulation/ArrayManipulation.py | ArrayManipulation.py | py | 457 | python | en | code | 0 | github-code | 13 |
72376556819 |
def hasDuplicates(array1, array2):
contains = {}
for item in array1:
contains[item] = True
for item in array2:
if item in contains:
return True
return False
print(hasDuplicates([1, 2, 3], [4, 5, 8]))
def hasDuplicates2(array1, array2):
# combined = array1 + array2
# filtered = set(combined)
# if... | Kra1ven/Algorithms-Structures-Dump | test.py | test.py | py | 14,607 | python | en | code | 0 | github-code | 13 |
7790960949 | import yfinance as yf
import pandas as pd
import numpy as np
import datetime as dt
import tensorflow as tf
from tensorflow.keras.models import load_model
import requests
def Zero_One_Scale(df):
df_scaled = (df - df.min()) / (df.max() - df.min())
return df_scaled
def One_One_Scale(df):
df_scaled = 2 * (df ... | tsugumi-sys/trading-bot | docker-yfinance-api/lstm.py | lstm.py | py | 6,260 | python | en | code | 0 | github-code | 13 |
12984632912 | import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
import csv
start = '2016-01-01'
end = '2019-01-01'
stocklist = []
with open('stock_Name.csv','r') as f:
reader = csv.reader(f)
for name in ... | TheGamlion/Stock_RNN | getData.py | getData.py | py | 784 | python | en | code | 0 | github-code | 13 |
3324350556 | import sys,getopt
sys.path.insert(0, "../")
from core.preprocessing.data_loader import load_dataset,DATASET
from core.preprocessing import DataUtil
from core.model.rule_models.invariant_model import InvariantRuleModel,PredicateMode
from sklearn.metrics import roc_auc_score
from core.preprocessing.signals import Contin... | NSIBF/InvariantRuleAD | experiments/main_ir.py | main_ir.py | py | 5,500 | python | en | code | 1 | github-code | 13 |
9063390233 | import sys
input = sys.stdin.readline
# n, m, k를 입력받음
n, m, k = map(int, input().split())
number = [0] * 1000001
s = [0] * 1000001
# n개의 숫자들을 입력받고, number[1] ~ number[i]까지의 합 s[i]를 계산
for i in range(1, n + 1):
number[i] = int(input())
s[i] = s[i - 1] + number[i]
# 변경된 사항을 담는 리스트, (x, y): x번째 숫자가 기존과 y만큼의 차이... | yudh1232/Baekjoon-Online-Judge-Algorithm | 2042 구간 합 구하기.py | 2042 구간 합 구하기.py | py | 1,301 | python | ko | code | 0 | github-code | 13 |
32212330390 | def solution(name):
after=[]
for i in name:
after.append(min(ord(i)-ord('A'),ord('Z')-ord(i)+1))
index=0
ans=0
while True:
ans+=after[index]
after[index]=0
if sum(after)==0:
break
left,right=1,1
while after[index-left]==0:
lef... | BlueScreenMaker/333_Algorithm | 백업/220604~230628/Programmers/조이스틱.py | 조이스틱.py | py | 557 | python | en | code | 0 | github-code | 13 |
71139731537 | """Added relationship
Revision ID: 10faf4b216d0
Revises: 85a6bc37561d
Create Date: 2020-12-16 13:15:41.124953
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '10faf4b216d0'
down_revision = '85a6bc37561d'
branch_labels =... | Ketsia-a/Charity-online | migrations/versions/10faf4b216d0_added_relationship.py | 10faf4b216d0_added_relationship.py | py | 2,598 | python | en | code | 0 | github-code | 13 |
40313023295 |
import cv2
import matplotlib.pyplot as plt
import numpy as np
import os
os.chdir(r'C:\Users\Goo\Desktop\Personal Learning\OpenCV_Tutorial')
from utils.mytool import stackImages,getContours
#%% 1 - Displaying image
img = cv2.imread('resources/lena.png')
cv2.imshow('output', img)
cv2.waitKey(0)
#%% 1 - ... | junseokkim93/OpenCV | OpenCV_Tutorial/OpenCV_Tutorial.py | OpenCV_Tutorial.py | py | 5,782 | python | en | code | 0 | github-code | 13 |
28341398977 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 3 18:18:18 2021
@author: blah
"""
# originalsTest
# we write out all of the originals
# assuming we are in a landscale A4 paper
# note you have to scale by .15 here
from pathlib import Path
import pickle
# font Proliferate script
from axidrawinternal import axi... | ottrp0p/axidraw-python | python/writeSVG.py | writeSVG.py | py | 5,014 | python | en | code | 0 | github-code | 13 |
3014572930 | from skbuild import setup
import os.path as osp
with open('VERSION', 'r') as f:
version = f.read().strip()
with open('README.md', 'r') as f:
long_description = f.read().strip()
setup( name='external_arrow',
version=version,
long_description=long_description,
long_description_content_type... | as6520/external_arrow | setup.py | setup.py | py | 2,050 | python | en | code | 1 | github-code | 13 |
29218142691 | import base64
import http.server
import json
import msgpack
import socketserver
import threading
"""
These mock severs are for the v2 indexer/algod path and response tests.
I was unable to get 'before_all' and 'after_all' working anywhere else besides
a file named 'environment.py in this directory. Otherwise all of t... | algorand/py-algorand-sdk | tests/environment.py | environment.py | py | 4,770 | python | en | code | 242 | github-code | 13 |
38631216651 | import time
import os
import drive_helpers
logfile = os.path.join(drive_helpers.get_unturned_path(), "Logs", "Client.log")
print(f"Extracting logs from: {logfile}")
# Keep track of the last line number that was read
last_line = 0
# if a log line has any of these strings in it, ignore it
IGNORE_SENTENCES = ["Look rota... | downj05/SuiteBanEv | log_reader.py | log_reader.py | py | 1,271 | python | en | code | 0 | github-code | 13 |
72206360019 | from nrclex import NRCLex
import pandas as pd
import matplotlib.pyplot as plt
def main():
sample_data = pd.read_csv('Tweets.csv')["text"]
bigString = ",".join(sample_data)
text_stuff = NRCLex(bigString)
results = text_stuff.raw_emotion_scores
labels = list(results.keys())
data = list... | Ifas87/nltkstuff | emotions.py | emotions.py | py | 523 | python | en | code | 0 | github-code | 13 |
40324017424 | import pygame, torch
import numpy as np
from alphagomoku.game import GomokuGame
from alphagomoku.players.basic_player import NaivePlayer
from alphagomoku.players.mcts_player import MCTS, NaiveMCTSPlayer, NaiveMCTS, get_valid_moves, Player
from alphagomoku.players.mcts_policy_player import PolicyMCTSPlayer, PolicyNet
#... | BangyaoZhao/gomoku | play_with_computer.py | play_with_computer.py | py | 2,775 | python | en | code | 0 | github-code | 13 |
16007361510 | import os
import numpy as np
import torch
import matplotlib.pyplot as plt
import nimblephysics as nimble
from solver.envs.rigidbody3d.r3d_grasp import GraspBox
from solver.envs.rigidbody3d.utils import arr_to_str
class TestSim(GraspBox):
def __init__(self, cfg=None):
super().__init__(cfg, A_ACT_MUL=1.)
... | haosulab/RPG | solver/envs/rigidbody3d/tests/test_sim_constants.py | test_sim_constants.py | py | 6,430 | python | en | code | 18 | github-code | 13 |
72926957778 | # pylint: disable=C0103, missing-docstring
def detailed_movies(db):
'''return the list of movies with their genres and director name'''
query= """
SELECT movies.title, movies.genres, directors.name
FROM movies
JOIN directors ON movies.director_id = directors.id
"""
db.execute(query)
results = db.fe... | arielimaa/data-sql-queries | queries.py | queries.py | py | 2,332 | python | en | code | 1 | github-code | 13 |
34911080964 | from list_items import MessageItem, ContactItem, FileTransferItem, InlineImageItem
from PySide import QtCore, QtGui
from tox import Tox
import os
from messages import *
from settings import *
from toxcore_enums_and_consts import *
from ctypes import *
from util import curr_time, log, Singleton, curr_directory, convert_... | SergeyDjam/toxygen | src/profile.py | profile.py | py | 49,373 | python | en | code | null | github-code | 13 |
21766353022 | class Integer:
import math
def __init__(self, value):
self.value = value
def roman_to_int(self, s):
rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
int_val = 0
for i in range(len(s)):
if i > 0 and rom_val[s[i]] > rom_val[s[i - 1]]:
... | DavidStoilkovski/python-oop | attributes-and-methods-python-oop/integer.py | integer.py | py | 1,288 | python | en | code | 0 | github-code | 13 |
21473492619 | counter_bake = int(input())
max_grade = 0
for i in range(0, counter_bake):
chef = input()
count_grade = 0
sum_grade = 0
is_stop = False
while not is_stop:
command = input()
if command == 'Stop':
is_stop = True
break
grade = int(command)
... | patsonev/Python_Basics_Exam_Preparation | easter_competition.py | easter_competition.py | py | 617 | python | en | code | 0 | github-code | 13 |
21886119984 | import random
n = int(input('Введите кол монеток '))
m = []
result = 0
for i in range(0,n):
random_num = round(random.randint(0,1))
m.append(random_num)
if random_num == 0 : result += 1
print (m)
print (result)
| KOMOKlazz/TEST | Homework/10.py | 10.py | py | 243 | python | en | code | 0 | github-code | 13 |
22862283323 | """
One useful package for web scraping in Python’s standard library is urllib, which contains tools for working with URLs.
The urllib.request module contains a function called urlopen() that can be used to open a URL within a program.
"""
import re
from urllib.request import urlopen
# Method 1 - Extract Text From HTM... | RuthraVed/web-scrapping-basics | scrapper_basic.py | scrapper_basic.py | py | 1,297 | python | en | code | 0 | github-code | 13 |
72723201299 | import sqlite3
import os
def departments():
db_name = './task_3/ledger.db'
database = sqlite3.connect(db_name)
cursor = database.cursor()
cursor.execute("SELECT * FROM departments")
temp = []
for b in cursor.fetchall():
temp.append(b)
return temp
def transactions():
db_name =... | KonstantinLjapin/samples_and_tests | tests/korus_consulting/task_3/data_base_function.py | data_base_function.py | py | 1,479 | python | en | code | 0 | github-code | 13 |
8298273626 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
"""
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing... | mniqxh/letcode | Linked List/lc19.py | lc19.py | py | 1,225 | python | en | code | 3 | github-code | 13 |
36582066112 | from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://web.whatsapp.com/')
a=1
while a!=0:
input('Scan QR code first and hit enter')
name = input('Enter the name of user or group : ')
msg = input('Enter your message : ')
count = int(input('Enter the count : '))
user = driver... | hastagAB/Awesome-Python-Scripts | send_whatsapp_message/whatsapp-message.py | whatsapp-message.py | py | 692 | python | en | code | 1,776 | github-code | 13 |
39240996616 | import os
from PySide6.QtWidgets import QDialog
from ide.logs import logger
try:
from data_ui.plugins import Ui_Dialog
except ImportError:
from ide.utils.ui_converter import ConvertationRecursive, ScriptOutput # pylint: disable=ungrouped-imports
ScriptOutput.logging_mode = True
ScriptOutput.print("... | n00-name/12345 | ide/frames/dialogs/plugins/dialog.py | dialog.py | py | 3,999 | python | en | code | 0 | github-code | 13 |
2193097850 | import random
import pygame
class Apple:
def __init__(self):
self.apple = pygame.Surface((10, 10))
self.x = 0
self.y = 0
self.position = self.x, self.y
def onGrid_Random_Spawn(self):
x = random.randint(0, 590) // 10 * 10
y = random.randint(0, 590) // 10 * 10
... | ThalesHenri/Snake_Game | apple.py | apple.py | py | 421 | python | en | code | 1 | github-code | 13 |
7100473025 | from django.shortcuts import get_object_or_404
from django.http import Http404
import django.template.context
from tagging.models import Tag, TaggedItem
from models import Post, Series, Category
def context_processor(target):
"""
Decorator that allows context processors with parameters to
be assigned (an... | davisd/django-blogyall | blog/context_processors.py | context_processors.py | py | 5,097 | python | en | code | 2 | github-code | 13 |
5131172344 | import math
def solution(fees, records) :
intime = {}
result = {}
for r in records :
time, num, inout = r.split()
if inout == "IN" :
intime[num] = convert(time)
if num not in result :
result[num] = 0
else :
result[num] += convert(... | jeongminllee/ProgrammersCodeTest | 프로그래머스/2/92341. 주차 요금 계산/주차 요금 계산.py | 주차 요금 계산.py | py | 774 | python | en | code | 0 | github-code | 13 |
14424006185 | from graph import Vertex, Edge, Graph
def dfs(g):
globals()['time'] = 0
for u in g.get_v():
u.color = "white"
u.parent = None
for u in g.get_v():
if u.color == "white":
dfs_visit(g, u)
def dfs_visit(g, u):
globals()['time'] += 1
u.d = time
u.color = "gray"
... | lancecopper/clrs | C22_C26/dfs.py | dfs.py | py | 843 | python | en | code | 1 | github-code | 13 |
74852841936 | import base64
import json
from django import template
from django.core.urlresolvers import reverse
from entity.models import KnowledgeServer
register = template.Library()
@register.simple_tag
def ks_info(ks, *args, **kwargs):
ret_html = "<p>" + ks.name
if hasattr(ks, "organization"):
ret_html += '<br>... | davidegalletti/koa-proof-of-concept | kag/ks/templatetags/custom_tags.py | custom_tags.py | py | 3,872 | python | en | code | 1 | github-code | 13 |
10488312724 | import datetime
import re
from discord.ext import commands
def get_datetime_obj(st: str) -> datetime.timedelta:
"""
Takes a string with #d#h#m#s and returns a time delta object of the string
"""
res = datetime.timedelta() # Initializes res
dig = re.split(r"\D+", st) # Splits on non digits
... | tfkdn/OnyxVot | Cogs/reminderRewrite/get_datetime_obj.py | get_datetime_obj.py | py | 1,440 | python | en | code | 0 | github-code | 13 |
38804541423 | #-----flightRadar24-----#
from selenium import webdriver
import json
from selenium.webdriver.common.keys import Keys
import time
lst = []
lst1 = []
lst2 = []
lst3 = []
#########---------------- Setting the path for chrome Driver---------------------------########
driver = webdriver.Chrome(executable_pat... | kushalbajje/FlightStatusTracking | flightRadar24/main.py | main.py | py | 1,992 | python | en | code | 0 | github-code | 13 |
4364576139 | from pypyodbc import Connection
from exceptions import CreateTeamExceptions
from model.Error import Error
from model.Player import Player
from model.Game import Game
from model.PlayerDB import PlayerDB
from model.Team import Team
from model.TeamList import TeamList
from model.TeamListDB import TeamListDB
from model.Tea... | m-ohit-s/ISC-SportsCarnival | ISC Sports Carnival/services/TeamService.py | TeamService.py | py | 7,029 | python | en | code | 0 | github-code | 13 |
7829759010 | import os
import sys
from celery import Celery
from cl.lib.celery_utils import throttle_task
# set the default Django settings module for the 'celery' program.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cl.settings")
app = Celery("cl")
# Bump the recursion limit to 10× normal to account for really big chains... | freelawproject/courtlistener | cl/celery_init.py | celery_init.py | py | 815 | python | en | code | 435 | github-code | 13 |
599254027 | #!/usr/bin/python
import psycopg2
from config import config
import datetime
conn = None
def connect():
""" Connect to the PostgreSQL database server """
params = config()
print('Connecting to the PostgreSQL database...')
global conn
conn = psycopg2.connect(**params)
def disconnect():
... | ting20000119/Most_frequent_words | r:Democrats_comments_counts/dbconnect.py | dbconnect.py | py | 703 | python | en | code | 0 | github-code | 13 |
6395555924 | import sqlite3
from utils import fmt
def create_connexion(db_file):
"""Crée une connexion a la base de données SQLite spécifiée par db_file
Args:
db_file (str): Chemin d'accès à la base de données
"""
try:
conn = sqlite3.connect(db_file)
# On active les foreign keys
c... | comejv/uni-projects | INF403/utils/db.py | db.py | py | 8,276 | python | fr | code | 2 | github-code | 13 |
22757225375 | from collections import namedtuple
Cell = namedtuple('Cell', ['key', 'x', 'y', 'type', 'is_empty', 'sortkey'])
def cells():
types = ['dim', 'flag', 'metric']
for i, row in enumerate(open('matrix.txt')):
dims, flags, metrics = sections = row.split()
j = 0
sortkey = '%s %s' % (flags, dim... | tuulos/sf-python-meetup-sep-2013 | data/utils.py | utils.py | py | 670 | python | en | code | 17 | github-code | 13 |
21571699333 | import math
import copy
eco = {10: 1.6, 20:0.8, 21:0.4}
comfort = {0:11.4, 10:2.4, 20:1.6, 21:0.8}
# max 8 hours of "off"
def recursive(temp, prices, curr_hour, curr_price, curr_comfort, curr_sol : list, best):
print(" "*curr_hour, curr_hour, curr_sol)
if curr_price > best[0]:
return (0, 0, curr_sol)... | luciusvinicius/personal-sauna | test_exhaustive_pruning.py | test_exhaustive_pruning.py | py | 2,642 | python | en | code | 0 | github-code | 13 |
19214732090 | # <table class="userInfo"><tbody><tr><td>ФИО:</td><td><strong>Азаров Дмитрий Викторович</strong></td></tr><tr><td>Пол:</td><td><strong>муж</strong></td></tr><tr><td>Дата рождения:</td><td><strong>03/05/1986</strong></td></tr><tr><td>Место рождения:</td><td><strong>с.Яр-Сале Ямальского р-на Тюменьской области</strong></... | azarovdimka/python | telebot/userinfo.py | userinfo.py | py | 2,282 | python | ru | code | 1 | github-code | 13 |
70166213459 | from framework.print.buffer import PrintBuffer
class ScanView(object):
"""
Encapsulates clang's 'scan-view' utility which displays 'scan-build'
results nicely in a broswer.
"""
def __init__(self, binary):
self.binary_path = binary['path']
self.binary_version = binary['version']
... | jarret/bitcoin_helpers | framework/clang/scan_view.py | scan_view.py | py | 590 | python | en | code | 0 | github-code | 13 |
3883157707 | import requests
param = {
"lat": -0.1,
"lon": 0.51,
"appid": "",
"exclude": "current,minutely,daily"
}
hours = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
response = requests.get(url="https://api.openweathermap.org/data/2.5/onecall", params=param)
response.raise_for_status()
data = (response.json())
... | Sidakveer/Intermediate_projects_2 | weather_tracking/main.py | main.py | py | 625 | python | en | code | 0 | github-code | 13 |
34278637751 | from datetime import date, datetime, timedelta
from decorators import catch_json_parse_errors
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.models import User as AuthUser
from django.contrib.auth.decor... | nrao/nell | scheduler/views.py | views.py | py | 36,425 | python | en | code | 0 | github-code | 13 |
74884806417 | import datetime
class Employee:
def __init__(self, name, title, start):
self.name = name
self.job_title = title
self.employment_start_date = start
class Company:
def __init__(self, name, address, industry):
self.business_name = name
self.address = address
self... | bparker12/python_class_practice | employees_departments.py | employees_departments.py | py | 1,401 | python | en | code | 0 | github-code | 13 |
38300884653 | from django.contrib import messages
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.db.models import Q
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.urls import reverse_lazy... | rebunitech/astu-store | astu_inventory/apps/core/views/borrow_request.py | borrow_request.py | py | 15,294 | python | en | code | 0 | github-code | 13 |
16132269163 | import boto3
def fetch_secret_from_aws(secret_name):
try:
session = boto3.session.Session()
client = session.client(service_name="secretsmanager", region_name="us-east-1")
get_secret_value_response = client.get_secret_value(SecretId=secret_name)
return get_secret_value_response["Se... | udhayprakash/PythonMaterial | python3/18_aws_cloud/a_AWS_Lambdas/e_boto3_usage/e_secretsmanager.py | e_secretsmanager.py | py | 750 | python | en | code | 7 | github-code | 13 |
26005042600 | import bgheatmaps as bgh
"""
This example shows how to use visualize a heatmap in 2D
"""
values = dict( # scalar values for each region
TH=1,
RSP=0.2,
AI=0.4,
SS=-3,
MO=2.6,
PVZ=-4,
LZ=-3,
VIS=2,
AUD=0.3,
RHP=-0.2,
STR=0.5,
CB=0.5,
FRP=-1.7,
HIP=3,
PA=-... | brainglobe/bg-heatmaps | examples/heatmap_2d.py | heatmap_2d.py | py | 608 | python | en | code | 20 | github-code | 13 |
22103762415 | # OSPF_Dijsktras: The program implement's an OSPF protocol using Dijkstra's algorithm to find the
# shortest path between vertices. It also calculates reachable vertices from any given vertex in the graph.
# Arguments: The program needs 1 argument, Name of the text file which has the initial condition of... | sumanttapas/Shortest-Paths-in-a-Network | OSPF_Dijkstras.py | OSPF_Dijkstras.py | py | 14,243 | python | en | code | 0 | github-code | 13 |
33763823049 | import pystan
import pickle
import argparse
import os
import pandas as pd
import numpy as np
import json
with open('SETTINGS.json', 'r') as f:
SETTINGS = json.load(f)
def create_stan_model():
'''
Compile model for stan
'''
model_code = '''
/*
pairwise logistic regression model of winning... | YouHoo0521/kaggle-madtown-machine-learning-madness-2019 | train.py | train.py | py | 5,746 | python | en | code | 4 | github-code | 13 |
34195737434 | import pygame
import math
from enum import Enum
from random import randint
from Sound import Sound, Sounds
from GameObject import GameObject
from DuckHuntSprites import DuckAnimationState
class Duck(GameObject):
#TODO: make it use sprites instead of image
def __init__(self, display, stoper, positionVector, s... | UcMarlo/DoocHunt | Duck.py | Duck.py | py | 7,126 | python | en | code | 2 | github-code | 13 |
73556714256 |
class Viajero_Frecuente:
__numviajero=0
__dni= " "
__nombre= " "
__apellido=" "
__millasacum=0
def __init__(self, num_viajero: int=0, DNI="", nombre="", apellido= "", millas_acum:int=0 ):
self.__numviajero= num_viajero
self.__dni= DNI
self.__nombre= nombre
... | Merypi/POO | Ejercicio 2/viajero.py | viajero.py | py | 1,364 | python | es | code | 0 | github-code | 13 |
73447779537 | from node.domain.config.models import TemplateKeyName
# Root templates - used by most of the read/write fields
sequence_root = TemplateKeyName('sequence_root')
shot_root = TemplateKeyName('shot_root')
step_root = TemplateKeyName('shot_task_root')
asset_root = TemplateKeyName('asset_root')
asset_step_root = TemplateKey... | Vincannes/vfxWrite | node/domain/config/fields.py | fields.py | py | 7,123 | python | en | code | 0 | github-code | 13 |
15186198662 | import torch
import torch.nn.functional as F
class FeatureMatchLoss(torch.nn.Module):
"""Feature matching loss module."""
def __init__(
self,
average_by_layers=True,
average_by_discriminators=True,
include_final_outputs=False,
):
"""Initialize FeatureMatchLoss modu... | kan-bayashi/ParallelWaveGAN | parallel_wavegan/losses/feat_match_loss.py | feat_match_loss.py | py | 1,597 | python | en | code | 1,427 | github-code | 13 |
2866587768 | from evoflow.engine import OP
from evoflow import backend as B
class Shuffle(OP):
O_AUTOGRAPH = True
O_XLA = True
def __init__(self, population_fraction, **kwargs):
"""Shuffle genes within the chromsome.
Args:
population_fraction (float): How many chromosomes
sho... | google-research/evoflow | evoflow/ops/shuffle.py | shuffle.py | py | 2,270 | python | en | code | 31 | github-code | 13 |
7600495606 | #!/usr/bin/env python3
import sys, getopt, fileinput
def main(argv):
help_string = 'USAGE: update_pip_version.py -v <versionstring>'
new_version = ''
try:
opts, args = getopt.getopt(argv, "hv:", ["version ="])
except:
print(help_string)
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print(help_str... | mhulden/pyfoma | .github/workflows/update_pip_version.py | update_pip_version.py | py | 779 | python | en | code | 25 | github-code | 13 |
36021849318 | from Zadanie import bubble_sort
import time
import random
def faster_bubble_sort(x):
for i in range(len(x)):
any_change = False
for j in range(0, len(x) - 1):
if x[j] > x[j + 1]:
any_change = True
temp_b = x[j]
x[j] = x[j ... | MatPatCarry/Algorithms_univerity_classes | WDA_List_2/Extended bubble sorts.py | Extended bubble sorts.py | py | 1,416 | python | en | code | 0 | github-code | 13 |
5014100850 | from django.contrib.auth.models import User
from django.http import HttpRequest, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from feedbacks.models import Feedback
# Create your views here.
@csrf_exempt
def post_detail(request: HttpRequest) -> HttpResponse:
if request.method == 'POST':
... | AbhiShake1/music-app-backend | feedbacks/views.py | views.py | py | 1,429 | python | en | code | 1 | github-code | 13 |
72097642577 | from pyradioconfig.parts.ocelot.calculators.calc_fec import CALC_FEC_Ocelot
class Calc_FEC_Sol(CALC_FEC_Ocelot):
def calc_postamble_regs(self, model):
demod_select = model.vars.demod_select.value
fcs_type_802154 = model.vars.fcs_type_802154.value
if demod_select == model.vars.demod_select... | jc-plhm/Z3GatewayHost_Sectronic | src/platform/radio/efr32_multiphy_configurator/pyradioconfig/parts/sol/calculators/calc_fec.py | calc_fec.py | py | 1,199 | python | en | code | 1 | github-code | 13 |
11080909152 | import time
def time_checker(func):
def wrapper(**kwargs):
t0 = time.time()
func(**kwargs)
t1 = time.time()
print("Time elapsed:", t1-t0, "seconds")
return wrapper
@time_checker
def useful_function(number):
# number = kwargs['number']
counter = 0
for i in range(n... | osakhsa/decorators | 2.py | 2.py | py | 534 | python | en | code | 0 | github-code | 13 |
22869018992 | import pytest
from aiogram import Bot
from tests.factories.chat import ChatFactory
from tests.mocked_bot import MockedBot
@pytest.fixture()
def bot():
bot = MockedBot()
token = Bot.set_current(bot)
yield bot
Bot.reset_current(token)
bot.me.invalidate(bot)
@pytest.fixture()
def private_chat():
... | Abdo-Asil/abogram | tests/conftest.py | conftest.py | py | 344 | python | en | code | 0 | github-code | 13 |
19776156418 | #! /c/Users/HP/AppData/Local/Programs/Python/Python310/python
import re
import sys
from pathlib import Path
filePath = sys.argv[1]
myDictionaryList = Path('./dictionary.txt').read_text().lower().split("\n")
def getInputWordList(filePath):
# Get one long string of all words in the file with all values lowercased... | VinceXIV/binary-search | grammar-checker.py | grammar-checker.py | py | 1,786 | python | en | code | 0 | github-code | 13 |
69976113298 | import numpy as np
import matplotlib.pylab as plt
import sklearn.datasets as skdata
import sklearn
numeros = skdata.load_digits()
target = numeros['target']
imagenes = numeros['images']
n_imagenes = len(target)
data = imagenes.reshape((n_imagenes, -1))
from sklearn.preprocessing import StandardScaler
from sklearn.mod... | CharlesCo12/CordobaCarlos_Ejercicio10 | predice_uno.py | predice_uno.py | py | 1,976 | python | en | code | 0 | github-code | 13 |
22912263328 | #Python libraries for math and graphics
import numpy as np
import matplotlib.pyplot as plt
import cvxpy as cp
import sys, os #for path to external scripts
script_dir = os.path.dirname(__file__)
lib_relative = '../../../CoordGeo'
fig_relative = '../figs/fig1.pdf'
sys.path.inser... | Muhammed-Hamdan/iith-fwc-2022-23 | optimization/advanced_assignment/codes/main.py | main.py | py | 3,361 | python | en | code | 3 | github-code | 13 |
5480576547 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import re
import sys
from sql_modules_utils import *
from typing import Union, List
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Stores documentation for CREATE {TABLE|V... | fred231084g/perfetto | tools/check_sql_modules.py | check_sql_modules.py | py | 14,349 | python | en | code | null | github-code | 13 |
1067889680 | from setuptools import setup, find_packages
import os
description = "CLI component for UCS"
author = "Intel Corporation"
license = "Apache"
etc = os.environ.get("DAIETC")
setup(name='ucs_cli',
version=os.environ.get("DAIVER"),
description=description,
author=author,
license=license,
pack... | unifiedcontrolsystem/dai-ds | cli/setup2.py | setup2.py | py | 834 | python | en | code | 5 | github-code | 13 |
36925807573 | #!/usr/bin/env python3
from asyncore import write
import subprocess
import re
import csv
def getPath():
return(subprocess.run(["pwd"], capture_output=True,
text=True).stdout.strip() + "/Desktop/week 6")
def get_user_statistics():
path = getPath()
user_dict = {}
with op... | imhariprakash/Courses | Google IT Automation with Python Professional Certificate/Using Python to Interact with the Operating System/week 6/ticky_check.py | ticky_check.py | py | 2,253 | python | en | code | 4 | github-code | 13 |
10669317546 | from backend.Utils import Utils
class User:
postgres = None
firebase_sdk = None
utils = Utils()
# Memorizza le sessioni attive
live_sessions = []
minutes_to_wait_before_generate_new_session = {
"walk": 6,
"bike": 5,
"car": 4
}
def __init__(self, postgres, fireb... | Krystian95/Context-Aware-Systems---Backend | backend/User.py | User.py | py | 13,620 | python | en | code | 0 | github-code | 13 |
43155016550 | import random
import string
import requests
import MySQLdb
import re
from cfg import *
from bs4 import BeautifulSoup
import urllib.parse
def python_web_crawler(url):
db = MySQLdb.connect(HOST, USERNAME, PASSWORD, DATABASE)
cursor = db.cursor() #made to execute sql commands
request = requests.get(url)
... | AYUSH-TRIPATHI786/Python-web-crawler | utils.py | utils.py | py | 3,275 | python | en | code | 0 | github-code | 13 |
32567690341 | import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
driver_service=Service(executable_path="C:\Python Notes\Python Selenium\drivers\chromedriver.exe")
driver=webdriver.Chrome(s... | jeevanxyz/TestDemo | Demo1/SelectDemo.py | SelectDemo.py | py | 897 | python | en | code | 0 | github-code | 13 |
16847332845 | import pandas as pd
import os
import numpy as np
from tqdm import tqdm
import pickle
import string
import spacy
from spacy.lang.en.stop_words import STOP_WORDS
nlp = spacy.load('en_core_web_sm')
import copy
ADJ_LIST = '../../data/adjacency_list.pickle'
W2I = '../../data/wordlist.pickle'
I2W = '../../data/index2word.pi... | shandilya1998/CS6251-project | source/dictionary_net/raw_data.py | raw_data.py | py | 5,561 | python | en | code | 0 | github-code | 13 |
35216272329 | import math
class Triangle():
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def area(self):
p=int((self.a+self.b+self.c))/2
print( math.sqrt(p*(p-self.a) * (p-self.b) * (p-self.c)))
trg1=Triangle(2, 3, 4)
trg1.area()
input()
| Egor2725/Lesson6 | 4.py | 4.py | py | 295 | python | en | code | 0 | github-code | 13 |
43101931902 | import os
import sys
import yaml
import json
from confluent_kafka import Producer, KafkaError
from pb.spug_kafka_format import Timestamp, Sample, Samples
get_forecast_config = os.environ.get('GET_FORECAST_CONFIG', '/apps/config/settings.yaml')
with open(get_forecast_config) as f:
settings = yaml.safe_load(f)
... | guo-tt/get-ai-dvc-deploy | src/utils/kafka_sink.py | kafka_sink.py | py | 1,346 | python | en | code | 0 | github-code | 13 |
35340690295 |
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchvision
from torchvision import *
from torch.utils.data import Dataset, DataLoader
import matplotlib.pyplot as plt
import numpy as np
import time
import copy
import os
def imshow(inp, title=None):
"""Im... | coolseraj/231_Tinder | ClassifierNetwork.py | ClassifierNetwork.py | py | 7,849 | python | en | code | 0 | github-code | 13 |
25923640423 | loc = open("ship-loc.txt", "w")
com = open("ship-com.txt", "w")
classes = ["corvette", "destroyer", "cruiser", "battleship", "titan", "colossus", "juggernaut", "science", "colonizer", "constructor", "transport", "military_station_small", "ion_cannon"]
prefixes = [["Lord", "Lady"],["Baron", "Baroness"],["Count", "Cou... | ThatLilSandi/mystical-name-lists | Mystical 1/Ship Names/shipnames-gen.py | shipnames-gen.py | py | 1,116 | python | en | code | 0 | github-code | 13 |
42628096665 | from pokedex import Pokedex
from database import Database
from helper.writeAJson import writeAJson
db = Database(database="pokedex", collection="pokemons")
db.resetDatabase()
Pokedex.acha_pokemon("Kakuna")
Pokedex.semMultipliers()
Pokedex.pokemon_com_2_fraquezas()
Pokedex.pokemon_fogo_ou_fraco_fogo()
... | coelhalice/Banco-de-Dados-II | relatorio_3_bd2/main.py | main.py | py | 353 | python | en | code | 0 | github-code | 13 |
43076524852 | import tensorflow as tf
from utils import conv2layer, pool2layer
from tensorflow.contrib.framework import arg_scope
from ops import *
from utils import *
import utils
from tensorflow.contrib.layers.python.layers import layers
########################################
############hyper parameters############
############... | Guo-Xiaoqing/SSL_WCE | nets/vgg.py | vgg.py | py | 5,414 | python | en | code | 14 | github-code | 13 |
19939681527 |
def as_str(i, positions, recipes):
text = "{:5d}: ".format(i)
for r in range(len(recipes)) :
if r == positions[0] :
t = "({}) ".format(recipes[r])
elif r == positions[1] :
t = "[{}] ".format(recipes[r])
else :
t = " {} ".format(recipes[r])
te... | pconley/advent2018 | p14b.py | p14b.py | py | 1,516 | python | en | code | 0 | github-code | 13 |
31390567671 | #!/bin/env python3
import random
import math
from dataclasses import dataclass
import sys
from matplotlib import pyplot as plt
def Roll():
res = 0
dice = random.randint(1,6)
res += dice
while(dice == 6):
dice = random.randint(1,6)
res += dice
return res;
class State:
Okay = 0... | Daar543/IF_Deadland_Simulace | IF_Deadland_Simulace/IF_Deadland_Simulace.py | IF_Deadland_Simulace.py | py | 8,400 | python | en | code | 0 | github-code | 13 |
11553523323 | #!usr/bin/env python
background_image_filename = 'sushiplate.jpg'
mouse_image_filename = 'fugu.png'
import pygame
#import pygame frame
from pygame.locals import *
#import some useful functions from pygame
from sys import exit
#borrow an exit function from sys frame
pygame.init()
#initial pygame, prepare for some hard... | ginlee/pygames | game1.py | game1.py | py | 967 | python | en | code | 0 | github-code | 13 |
37175493564 | import numpy as np
import kurucz_inten as ki
import scipy.constants as sc
import scipy.interpolate as si
"""
WINE: Waveband INtegrated Emission module
This set of routines calculate the integrated emission spectrum of
a signal over specified filter wavebands.
"""
def readfilter(filt):
"""
Load a filter ba... | exosports/BART | code/wine.py | wine.py | py | 5,665 | python | en | code | 31 | github-code | 13 |
19253736902 | # Вызывается tkinter и messagebox для дальнейшего использования
import tkinter as tk
from tkinter import messagebox
import area_data
root = tk.Tk()
min_game_area_size = 4
max_game_area_size = 10
game_area_size = 0
restart_button = None
game_area_data = []
buttons_list = []
# Функция для запуска игры с полем ввода ра... | Egor-123/Sapper | main.py | main.py | py | 3,637 | python | ru | code | 0 | github-code | 13 |
8441271144 | import board
from digitalio import DigitalInOut, Direction, Pull
from oled import oled_display, oled_text
import countio
import time
import pwmio
# Count rising edges only.
pin_counter = countio.Counter(board.GP21, edge=countio.Edge.RISE, pull=Pull.DOWN)
# pump_pwm = pwmio.PWMOut(board.GP14, frequency=30, duty_cycle=i... | greyliedtke/PyExplore | CircuitPython/OLD/Oil_flowrate/code.py | code.py | py | 674 | python | en | code | 0 | github-code | 13 |
70915540179 | import tensorflow as tf
from tensorflow import keras
class TensorRing_Based(keras.layers.Layer):
def __init__(self, units=1, activation=None, rank=10, local_dim=2,initializer=keras.initializers.glorot_normal(seed=None),regularizer=keras.regularizers.l2(0.0), **kwargs):
super().__init__(**kwargs)
... | KritonKonstantinidis/CPD_Supervised_Learning | Regression Tasks/TensorRing_Model.py | TensorRing_Model.py | py | 2,593 | python | en | code | 1 | github-code | 13 |
14316459980 | # -*- coding: utf8 -*-
bl_info = {
"name": "Import XYZ to Mesh",
"author": "europrimus@free.fr",
"version": (0, 6),
"blender": (2, 7, 0),
"location": "File > Import > Import XYZ to Mesh",
"description": "Import text point file to new Mesh object",
"warning": "",
"wiki_url": "",
"trac... | europrimus/Blender_Script | io_xyz2mesh.py | io_xyz2mesh.py | py | 10,450 | python | en | code | 0 | github-code | 13 |
43803196075 | """Module containing :class:`~song_match.song.songs.rain_rain_go_away.RainRainGoAway`."""
from typing import List
from cozmo.lights import Light
from song_match.cube.lights import BLUE_LIGHT
from song_match.cube.lights import CYAN_LIGHT
from song_match.cube.lights import PINK_LIGHT
from song_match.song import Song
f... | samuelschuler/CS4500 | cozmo-song-match-master/song_match/song/songs/rain_rain_go_away.py | rain_rain_go_away.py | py | 1,906 | python | en | code | 0 | github-code | 13 |
30310844710 | from xivo_bus.resources.common.event import TenantEvent, UserEvent
class _BaseUserEvent(TenantEvent):
def __init__(self, user_id, user_uuid, subscription_type, created_at, tenant_uuid):
content = {
'id': int(user_id),
'uuid': str(user_uuid),
'subscription_type': subscri... | wazo-platform/xivo-bus | xivo_bus/resources/user/event.py | event.py | py | 2,810 | python | en | code | 1 | github-code | 13 |
38916394313 | import matplotlib.pyplot as plt
import numpy as np
actual_steering = list()
computed_steering = list()
# get the standard deviation of the steering angle
std_steering = np.std(computed_steering)
# check whether the computed steering angle is within the threshold +/- 0.05
# and calculate the number of correct predictio... | DrakeAxelrod/Cyber-Physical-Systems-and-Systems-of-Systems | scripts/domagic.py | domagic.py | py | 876 | python | en | code | 24 | github-code | 13 |
73990908177 |
import re
import json
from decimal import *
from docpart import DocPart
from conditionparser import ConditionParser
class ProseMaker(object):
def __init__(self):
self._data = {}
self._json = ''
self._source = ''
## data property ------------------------------------------------
@... | DanielBaird/CliMAS-Next-Generation | climas-ng/climasng/parsing/prosemaker.py | prosemaker.py | py | 7,458 | python | en | code | 0 | github-code | 13 |
41906442102 | import os
import requests
from typing import Dict, List, Tuple
from pathlib import Path
from definitions import (TOKEN, HYPLAG_USER, HYPLAG_PASSWORD, HYPLAG_BACKEND_AUTH_TOKEN, HYPLAG_ID,
HYPLAG_BACKEND_POST_DOCUMENT, HYPLAG_BACKEND_GET_DOCUMENT, XML_FILES,
PDF_FILES)
f... | gipplab/chem_formula_extractor | src/hyplag_backend.py | hyplag_backend.py | py | 7,134 | python | en | code | 2 | github-code | 13 |
17046629754 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayTradePaygrowthPayabilityQueryModel(object):
def __init__(self):
self._biz_identity = None
self._open_id = None
self._real_pay_amount = None
self._request_fro... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/AlipayTradePaygrowthPayabilityQueryModel.py | AlipayTradePaygrowthPayabilityQueryModel.py | py | 2,978 | python | en | code | 241 | github-code | 13 |
31712665584 | class Solution:
def canConstruct(self, s, k):
if len(s) == k:
return True
count = {}
for char in s:
count[char] = count.get(char, 0) + 1
odd, even_sum = 0, 0
for key, value in count.items():
if value % 2 == 1:
odd = odd + ... | gsy/leetcode | dp/canConstruct.py | canConstruct.py | py | 535 | python | en | code | 1 | github-code | 13 |
74083524176 | from numpy import sqrt, pi, linspace
import matplotlib.pyplot as plt
from ODESolver import ODESolver, ForwardEuler, RungeKutta4
def f(u,t):
M = 1 # SolarMasses
G = 4*pi**2 # AU^3/(yr^2*SM)
x, y, vx, vy = u
dx = vx
dy = vy
radius = sqrt(x**2 + y**2)
dvx = -G*M*x/radius**2
dvy = -G*M*y/... | jgslunde/PythonPhysicsExercises | Python_solutions/ChapterE/orbits.py | orbits.py | py | 644 | python | en | code | 0 | github-code | 13 |
20976283975 | from torch.optim.lr_scheduler import _LRScheduler
class WarmupScheduler(_LRScheduler):
def __init__(self, optimizer, lr:float, num_warmup_iters:int, warmup_factor:float):
self.lr = lr
self.optimizer = optimizer
self.num_warmup_iters = num_warmup_iters
self.warmup_factor = warmup_fa... | universome/human-pose | src/optims/warmup_scheduler.py | warmup_scheduler.py | py | 958 | python | en | code | 3 | github-code | 13 |
38538088767 | import cgi
import urllib
import re
import uuid
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import mail
from google.appengine.ext.webapp import template
class Phone(db.Model):
number = db.S... | niryariv/rmmbr | main.py | main.py | py | 2,787 | python | en | code | 1 | github-code | 13 |
35216277709 |
class Square():
def __init__(self, s):
self.size = s
def change_size(self, n):
self.size += n
result = self.size**2
print(result)
square1 = Square(10)
square1.change_size(1)
input()
| Egor2725/Lesson6 | 6.py | 6.py | py | 242 | python | en | code | 0 | github-code | 13 |
10402122535 | # -*- coding: utf-8 -*-
"""Script destinado a obtener datos del equipo mediante el comando systeminfo,
solo valido en windows, y posterior alta del mismo utilizando la api de la
aplicacion de inventario"""
import platform as pf
import urllib3
import json
import os
URL_BASE = 'http://127.0.0.1:8080'
URL_LOC = '/api/l... | Wolksvidia/flask_inventory | get_machine_data.py | get_machine_data.py | py | 3,360 | python | es | code | 1 | github-code | 13 |
1553093051 | ####### Import Statements ############
import os
import sys
from PyInquirer import style_from_dict, prompt, Separator
from examples import custom_style_2
####### Global Variables ############
class DirectoryList:
"""
Class used to list the home folders and its child based on click.
"""
def __init__(self):
""" ... | sridharselvan/wordSearcher | base.py | base.py | py | 1,472 | python | en | code | 0 | github-code | 13 |
6369756051 | from flask import Flask
from flask_restful import Api, Resource, fields, marshal_with, marshal
import re
from flask import make_response, current_app
from flask_restful.utils import PY3
import json
app = Flask(__name__)
api = Api(app)
# 用来模拟要返回的数据对象的类
class User(object):
def __init__(self, user_id, name, age):
... | HZreal/flask-learn | 14_app_restful_response_marshal.py | 14_app_restful_response_marshal.py | py | 2,961 | python | en | code | 0 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.