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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
72404314984 | class Cart:
def __init__(self, x, y, dx, dy):
self.x = x
self.y = y
self.dx = dx
self.dy = dy
self.next = 'left'
def turn_left(self):
self.dx, self.dy = self.dy, -self.dx
def turn_right(self):
self.dx, self.dy = -self.dy, self.dx
def advance(sel... | jorendorff/advent-of-code | 2018/13/part1.py | part1.py | py | 2,031 | python | en | code | 3 | github-code | 36 |
73130978024 | from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include
from drf_spectacular.views import (
SpectacularAPIView,
SpectacularRedocView,
SpectacularSwaggerView,
)
from api.urls import urlpatterns as api_urls
# Common urls
# ===========================... | by-Exist/django-skeleton | backend/config/urls.py | urls.py | py | 1,252 | python | en | code | 0 | github-code | 36 |
6803651192 | import cx_Freeze
executables = [cx_Freeze.Executable("sk invader.py")]
cx_Freeze.setup(
name="Space Invader",
options={"build_exe": {"packages":["pygame"],
"include_files":["background.png","background2.jpg","fighter.png"]}},
executables = executables
) | subashal/SK-SPACE-INVADER | setup.py | setup.py | py | 298 | python | en | code | 0 | github-code | 36 |
36587398345 | # 인공지능 시계
import sys
input = sys.stdin.readline
a, b, c = map(int, input().split())
d = int(input())
h = (a + (b + (c+d)//60)//60)%24
m = (b + (c+d)//60)%60
s = (c+d)%60
print(h, m, s)
| meatsby/algorithm | boj/2530.py | 2530.py | py | 199 | python | en | code | 0 | github-code | 36 |
8088290282 | class Solution:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
arr.sort()
min_ = float('inf')
n = len(arr)
for i in range(1, n):
if arr[i] - arr[i - 1] < min_:
min_ = arr[i] - arr[i - 1]
result = []
for i in range(1, ... | alankrit03/LeetCode_Solutions | 1200. Minimum Absolute Difference.py | 1200. Minimum Absolute Difference.py | py | 442 | python | en | code | 1 | github-code | 36 |
4917659914 | from Player import *
from Chessgame import *
# from MorpionGame import is_game_over
import random
def is_game_over(board):
# bool_ = False
try:
win_conditions = ( (0, 1, 2),
(3, 4, 5),
(6, 7, 8),
(0, 3, 6),
... | ThomasAqtl/ProjetIA | IA.py | IA.py | py | 5,133 | python | en | code | 0 | github-code | 36 |
3289924772 | import sys
import pprint as _pprint_
from pyomo.core.kernel.numvalue import \
NumericValue
from pyomo.core.kernel.component_interface import \
(ICategorizedObject,
_ActiveComponentContainerMixin)
import six
def pprint(obj, indent=0, stream=sys.stdout):
"""pprint a kernel modeling object"""
# ugl... | igorsowa9/vpp | venv/lib/python3.6/site-packages/pyomo/core/kernel/util.py | util.py | py | 4,337 | python | en | code | 3 | github-code | 36 |
30758316388 | import pathlib
def create_directory(path: str) -> None:
directory = pathlib.Path(path)
if directory.exists():
raise FileExistsError(f"{path} is exist")
directory.mkdir()
def create_file(path: str, content: str = None) -> None:
file = pathlib.Path(path)
if file.exists():
raise Fi... | jonarsli/flask-restapi | flask_restapi/tool/core.py | core.py | py | 456 | python | en | code | 1 | github-code | 36 |
26921698345 | # -*- coding: utf-8 -*-
"""
This file contains any statistical calculation methods
@author: A00209408
"""
import math
# Calculation functions
def calculate_mean(data: []) -> float:
"""
Calculates the mean based on the input array
Parameters
----------
data : [] data values to perform mean... | sinderpl/PythonDataManipulation | calculationFunctions.py | calculationFunctions.py | py | 6,114 | python | en | code | 0 | github-code | 36 |
74137519144 | import math
estrName='Aleta 1'
nmbAleta=1
titSchedule=estrName.upper()
scale=1/25 # escala del dibujo
#Footing
wFoot=1.90 #ancho zapata
lWall=3.50 #longitud muro
thFoot=0.35 #espesor de la zapata
wToe=0 #ancho de la puntera
# Wall
wTop=0.25 #espesor del muro en coronación
hWallMax=2.6
hWallMin=1.26
slopeBack=0 #... | anaiortega/parametricDesign | examples/RCstruct_typology/three_sided_box_culvert_pilefound/data/data_wingwall1.py | data_wingwall1.py | py | 560 | python | es | code | 3 | github-code | 36 |
73118842984 | from datetime import datetime, timedelta
def work_day(start, end):
work = 0
curr_date = start
while curr_date <= end:
if curr_date.weekday() < 5:
work += 1
curr_date += timedelta(days=1)
return work
start_date, end_date = datetime(2023, 1, 1), datetime(2023, 12, 31)
print... | IlyaOrlov/PythonCourse2.0_September23 | Practice/achernov/module_10/task_2.py | task_2.py | py | 468 | python | en | code | 2 | github-code | 36 |
1264209352 | # This file is part of Camiba.
#
# Camiba is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Camiba is distributed in the hope that it... | SebastianSemper/camiba | camiba/algs/irls.py | irls.py | py | 2,026 | python | en | code | 11 | github-code | 36 |
17156637951 | import torch
from mapping.model_training.transformer_training_nsp import train_nsp
from mapping.model_training.training_data_utils import get_next_sentence_df
from mapping.mapping_models.data_fit_models.masking_lm.bert_masking_trained_mtl import BertMaskingTrainedMtlMapper
from utils.bert_utils import get_lm_embeddi... | Peter-Devine/Feedback-Mapping | mapping/mapping_models/data_fit_models/nsp_lm/bert_nsp_trained_mtl.py | bert_nsp_trained_mtl.py | py | 2,123 | python | en | code | 0 | github-code | 36 |
25918861038 | import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# Capacitor
capacitance = 3400 # [=] farads
esr = 0.00013 # [=] ohms
initial_voltage = 2.85 # [=] volts
# Railgun, projectile, leads, construction
w = 0.00635 * 2 # width of the rails [=] meters
h = 0.00635 * 2 # height of rail... | WhiteRabbit2006/Railgun | Calculator.py | Calculator.py | py | 5,512 | python | en | code | 0 | github-code | 36 |
31608719442 | import math
from functools import partial
from collections import defaultdict
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from . import torchvision_models
from .torchvision_models import load_pretrained, inflate_pretrained, modify_resnets
from network.non_loca... | Forrest0503/VAT-ABAW | network/resnet3D.py | resnet3D.py | py | 20,933 | python | en | code | 0 | github-code | 36 |
9996315350 | import re
from datetime import datetime
from async_lru import alru_cache
from discord import Permissions, Embed
from discord.utils import escape_markdown
import utils.discord
import utils.misc
import utils.tableBuilder
import wrappers.api.minecraft
import wrappers.api.wynncraft.v3.player
from handlers.commands import... | Freeder1k/NiaBot | handlers/commands/prefixed/playerCommand.py | playerCommand.py | py | 6,131 | python | en | code | 1 | github-code | 36 |
4871120057 | import urllib.request
from time import sleep
import json
from pprint import pprint
from bs4 import BeautifulSoup
from beautifulscraper import BeautifulScraper
scraper = BeautifulScraper()
years =[x for x in range(2009,2018)]
weeks = [x for x in range(1,18)]
stype = "REG"
gameids =[]
f = open("nfldata.json", "w")... | Jamada623/4883-SWTools-Joseph | Assignments/A03/scrape_game_ids_data_joseph.py | scrape_game_ids_data_joseph.py | py | 1,925 | python | en | code | 0 | github-code | 36 |
39453873198 | # -*- coding:utf-8 -*-
class Solution:
a = {}
def jumpFloorII(self, number):
if number ==0:
return 1
if number == 1 :
self.a[number] = 1
return 1
if number == 2 :
self.a[number] = 2
return 2
sum = 0
for i in range... | haodongxi/leetCode | jzoffer/9.py | 9.py | py | 629 | python | en | code | 0 | github-code | 36 |
74831337704 | from rushhour import *
import random
class MiniMaxSearch:
def __init__(self, rushHour, initial_state, search_depth):
self.rushhour = rushHour
self.state = initial_state
self.search_depth = search_depth
self.visited_states = 0
def minimax_1(self, current_depth, current_state):... | FinestStone/INF8215 | TP2/minimaxsearch.py | minimaxsearch.py | py | 10,810 | python | en | code | 0 | github-code | 36 |
41234096273 | from django.utils import timezone
import os
from rest_framework_simplejwt.tokens import RefreshToken
# url for user's image.
def upload_img_url(instance, filename):
date = timezone.now()
path = os.path.join("user-pic", instance.username, str(date.year), str(date.month), str(date.day), filename)
return path... | shaikhAhmed232/Socialogram-Backend | accounts/utils.py | utils.py | py | 682 | python | en | code | 0 | github-code | 36 |
21626078429 | import configparser
import os
# read the source under [browser] item
def get_browser(name):
global base_path, cf_path
base_path = os.path.dirname(os.getcwd())
cf_path = os.path.join(base_path, "config", "config.ini")
cf = configparser.ConfigParser()
cf.read(cf_path)
return cf.get('browser', na... | litongtongx/test | common/readconfig.py | readconfig.py | py | 435 | python | en | code | 0 | github-code | 36 |
31076470598 | # This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but ... | drewwalters96/subber | subber/reddit.py | reddit.py | py | 7,738 | python | en | code | 5 | github-code | 36 |
34543856455 | from pathlib import Path
from torch.utils.data import IterableDataset
class SceneDataset(IterableDataset):
"""
A dataset representing an infinite stream of noise images of specified dimensions.
"""
def __init__(self, path: Path):
"""
:param num_classes: Number of classes (labels)
... | manorzvi/VoteNet | data/dataset.py | dataset.py | py | 746 | python | en | code | 0 | github-code | 36 |
29721404683 | import random
guess = int(input("Guess a number b/w 1-100 :-"))
print(guess)
a = random.randint(1, 100)
# print(a)
if guess > a:
print(f"your guessed number is greater than random's number {a}")
elif guess < a:
print(f"your guessed number is less than random's number {a}")
else:
print("you guessed a correct... | mohitnamdev102/python | Python (Utsav Patel)/example/NumberGuessing.py | NumberGuessing.py | py | 331 | python | en | code | 0 | github-code | 36 |
9796518132 | import time
from urllib import quote, unquote
from webob import Request
from swift.common.utils import (get_logger, get_remote_client,
get_valid_utf8_str, TRUE_VALUES)
class InputProxy(object):
"""
File-like object that counts bytes read.
To be swapped in for wsgi.input f... | DmitryMezhensky/Hadoop-and-Swift-integration | swift/swift/common/middleware/proxy_logging.py | proxy_logging.py | py | 8,172 | python | en | code | 20 | github-code | 36 |
39060361009 | def read_multi_segment_file(msf_file):
from numpy import zeros
#First count the number of segments and the number of elements in each segment
Nsegments=0
Num_elements=[]
f=open(msf_file,'r')
first_line=True
while True:
line=f.readline()
if '>' in line:
i... | Ogweno/mylife | misc/read_an_msf_file.py | read_an_msf_file.py | py | 1,365 | python | en | code | 0 | github-code | 36 |
31287721678 | class Restaurant():
"""A Class For A Restaurant"""
def __init__(self,restaurant_name,cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def descibe_restaurant(self):
print(
"This is " + self.restaurant_name.title() +
... | BasselMalek/python-training-files | python_learning_projects/9_1_exercise.py | 9_1_exercise.py | py | 739 | python | en | code | 0 | github-code | 36 |
74784258662 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def ludwig_lang_plot(cation_data_fn, anion_data_fn, cations, anions):
cat_reader = pd.read_csv(cation_data_fn)
an_reader = pd.read_csv(anion_data_fn)
cat_data = []
for column in cat_reader:
cat_data.append(cat_reader[column].values)
samp_... | yashvardhan747/Statistical-and-Aqual-chemical-plots | AquaChemPlots/ludwig_lang_plot.py | ludwig_lang_plot.py | py | 1,452 | python | en | code | 0 | github-code | 36 |
26455397608 | #! /usr/bin/python3
# findspark import후 초기화
# 빨리 찾기위한 module 있으나 없으나 별 차이가 없다.
import findspark
findspark.init()
from pyspark.sql import SparkSession
#SparkSession 객체 생성 방법. (앱이름을 pyspark-hdfs1라는것으로 임의로 주고 .getOrCreate() 해준>
sparkSession = SparkSession.builder.appName("pyspark-hdfs2").getOrCreate()
# read.load()는 다양한 ... | jshooon/BigData_Hadoop | chap06/local_file_load2.py | local_file_load2.py | py | 812 | python | ko | code | 0 | github-code | 36 |
71352577065 | """
trainer of cycle architecture
works well on adt2gex, atac2gex, gex2atac subtasks
used the cycle consistancy loss the enhance the reconstruction effect
"""
import os
import logging
import numpy as np
import anndata as ad
from scipy.sparse import csc_matrix
from tensorboardX import SummaryWriter
import t... | itscassie/scJoint-neurips2021-modality-prediction | model/trainer/trainer_cycle.py | trainer_cycle.py | py | 13,131 | python | en | code | 0 | github-code | 36 |
18326177260 | from blackjack_simulator import BlackJack as Environment
from evaluate_policy import mc_first_visit, mc_every_visit, k_step_td
from control_policy import k_step_sarsa, q_learning, td_lambda
import sys
from tqdm.auto import tqdm
def eval_dealer_policy(eval_algo=0, num_expt=1, num_episodes=1000, k_step=1):
env = Env... | djin31/tabularRL | tabular_rl.py | tabular_rl.py | py | 2,069 | python | en | code | 0 | github-code | 36 |
7003120074 | from analysis import load_subset_data, define_meta_class, feature_choice
from analysis import keep_important_variables, create_pairs
from analysis import normalize_data, Bigger_Net, global_loop, save_error
from vizualisation import color_map
from torch.utils.data import dataset, DataLoader
import torch
import torch.nn... | pierrecavalier/graph_fink | main.py | main.py | py | 3,056 | python | en | code | 0 | github-code | 36 |
15870414551 | from typing import List, Union, Tuple
from functools import reduce
from rdkit import Chem
import torch
import torch.nn as nn
from .args import ModelArgs
from .features import BatchMolGraph, get_atom_fdim, get_bond_fdim, mol2graph
from .nn_utils import index_select_ND, get_activation_function
class MPNEncoder(nn.Mod... | gmum/graph-representations | graphrepr/chemprop/mpn.py | mpn.py | py | 8,069 | python | en | code | 18 | github-code | 36 |
36339474495 | import scipy.misc
import matplotlib.pyplot as plt
# This script demonstrates fancy indexing by setting values
# on the diagonals to 0.
# Load the ascent array
ascent = scipy.misc.ascent()
xmax = ascent.shape[0]
ymax = ascent.shape[1]
# Fancy indexing
# Set values on diagonal to 0
# x 0-xmax
# y 0-ymax
ascent[range(x... | denotepython/pythonbook | python数据分析/3358OS_Code/3358OS_02_Code/3358OS_02_Code/code2/fancy.py | fancy.py | py | 521 | python | en | code | 0 | github-code | 36 |
23519690319 | from sys import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import*
from socket import *
# 定位服务器
serverName='172.23.77.52'
serverPort=12000
# 定义聊天界面
class chat(QWidget):
number=''
def __init__(self,num):
self.number=num
super().__init__()
def start(self):
... | lblaoke/SimpleWechat | Client/GUI.py | GUI.py | py | 10,425 | python | en | code | 0 | github-code | 36 |
22562553412 | #!/usr/bin/python
filename='../data/data-1.txt'
#filename='../data/google-1.txt'
#filename='../data/reddit-1.txt'
with open(filename) as file:
rows = [line for line in file.read().strip().splitlines()]
lst=[]
count=0
maxcount=0
for i in (rows):
if i != '':
#print(count,i)
count += int(i)
elif i == '':
... | kalee/AoC2022 | day01.py | day01.py | py | 913 | python | en | code | 0 | github-code | 36 |
28891356701 | """Utilities for dealing with project configuration."""
import abc
import configparser
from typing import Iterable, Tuple, Type, TypeVar
from pytype.platform_utils import path_utils
import toml
_CONFIG_FILENAMES = ('pyproject.toml', 'setup.cfg')
_ConfigSectionT = TypeVar('_ConfigSectionT', bound='ConfigSection')
... | google/pytype | pytype/tools/config.py | config.py | py | 2,353 | python | en | code | 4,405 | github-code | 36 |
25423459811 | class Node:
def __init__(self,data):
self.data= data
self.left = None
self.right = None
def insert(self, x):
if x > self.data:
if self.right is None:
self.right = Node(x)
else:
self.right.insert(x)
... | arpitkansal/Span | max_element.py | max_element.py | py | 1,444 | python | en | code | 0 | github-code | 36 |
38033130776 | from typing import List, Optional
from pydantic import BaseModel
class Address(BaseModel):
city: str
country: str
class User(BaseModel):
name: str
address: Address
friends: Optional[List['User']] = None
class Config:
json_encoders = {
Address: lambda a: f'{a.city} ({a.c... | merlinepedra25/PYDANTIC | docs/examples/exporting_models_json_forward_ref.py | exporting_models_json_forward_ref.py | py | 816 | python | en | code | 1 | github-code | 36 |
73578540903 | # coding: utf-8
_all_ = [ ]
import os
from pathlib import Path
import sys
parent_dir = os.path.abspath(__file__ + 2 * '/..')
sys.path.insert(0, parent_dir)
from dash import Dash, dcc, html, Input, Output, State, ctx
from dash.exceptions import PreventUpdate
import argparse
import numpy as np
import pandas as pd
imp... | bfonta/bye_splits | bye_splits/plot/display_plotly/main.py | main.py | py | 4,073 | python | en | code | 2 | github-code | 36 |
36085301774 | import bs4
import requests
import pandas as pd
import re
import warnings
warnings.filterwarnings('ignore')
def get_page(url):
headers = {
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/106.0.0.0 Safari/537.36"}
... | MECAI2022/short_text_classification | webscraping.py | webscraping.py | py | 1,538 | python | en | code | 0 | github-code | 36 |
24018908747 | from cloudmesh.proceedings.api.proceedings import Proceedings
import os
import sys
from pprint import pprint
kind = 'paper1'
def read_file(filename):
with open(filename) as f:
s = f.read()
return (s)
print (read_file("title.tex"))
print ("""
\chapter{Preface}
\section{List of Papers}
\\begin{fo... | bigdata-i523/proceedings | paper2/review1.py | review1.py | py | 3,234 | python | en | code | 0 | github-code | 36 |
73334814183 | class Roman:
def romanToInt(self, s: str) -> int:
roman_to_integer = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
}
s = s.replace("IV", "IIII").replace("IX", "VIIII").replace("XL", "XXXX... | Adsol24/python | roman_numeral.py | roman_numeral.py | py | 671 | python | en | code | 0 | github-code | 36 |
1165217345 | import requests
import bs4
print('Loading page...')
url=f'https://www.myjobmag.co.ke/search/jobs?q=&field=Engineering+%2F+Technical'
def getJobtitle(soup):
title=soup.select('section h1')
return str(title[0].getText())
def getDescription(soup):
Description=soup.select('.job-details p')
... | petreleven/Webscraping-101 | webscraping101/jobmagRefactored.py | jobmagRefactored.py | py | 1,791 | python | en | code | 0 | github-code | 36 |
18832247030 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def find(self, root, current_max):
answer = 0
if root.val >= current_max:
current_max = ... | parkjuida/leetcode | python/count_good_nodes_in_binary_tree.py | count_good_nodes_in_binary_tree.py | py | 635 | python | en | code | 0 | github-code | 36 |
3677890020 | import os
DEFAULT_ENDPOINTS_PATH = "endpoints.yml"
DEFAULT_CREDENTIALS_PATH = "credentials.yml"
DEFAULT_CONFIG_PATH = "config.yml"
DEFAULT_DOMAIN_PATH = "domain.yml"
DEFAULT_ACTIONS_PATH = "actions"
DEFAULT_MODELS_PATH = "models"
DEFAULT_DATA_PATH = "data"
DEFAULT_RESULTS_PATH = "results"
DEFAULT_NLU_RESULTS_PATH = "n... | msamogh/rasa-frames | rasa/constants.py | constants.py | py | 1,536 | python | en | code | 4 | github-code | 36 |
32829514166 | # 문제 풀이 실패
# 모범 답안
from collections import deque
n, m = map(int, input().split())
graph = [list(map(int, input())) for _ in range(n)]
# 이동할 네 방향 정의
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
# BFS 구현
def bfs(x, y):
# queue 구현
queue = deque()
queue.append((x, y))
# queue가 빌 때까지 반복
while queue:
... | veluminous/CodingTest | [이것이 코딩테스트다] 실전 문제/[BFS] 미로 탈출.py | [BFS] 미로 탈출.py | py | 1,067 | python | ko | code | 0 | github-code | 36 |
74286557224 | # -*- coding: utf-8 -*-
from __future__ import division
def bateman_parent(lmbd, t, one=1, zero=0, exp=None):
""" Calculate daughter concentrations (number densities) from single parent
Assumes an initial parent concentraion of one (and zero for all daughters)
Parameters
----------
lmbd: array_... | bjodah/batemaneq | batemaneq/bateman.py | bateman.py | py | 2,482 | python | en | code | 4 | github-code | 36 |
30922847459 | from pylatex import Document, Section, Figure, SubFigure, Command, Subsection, Package, NoEscape
class PdfGenerator:
def __init__(self, directory, name):
geometry_options = {"right": "1cm", "left": "1cm", "top": "1cm", "bottom": "1cm"}
self.doc = Document("{}/{}-Report".format(directory, name), g... | bgreni/Set_Data_Report | PdfGenerator.py | PdfGenerator.py | py | 4,903 | python | en | code | 0 | github-code | 36 |
24713906 | from sys import stdin
input = stdin.readline
n = int(input())
dp = []
for i in range(n):
dp.append(list(map(int, input().split())))
for i in range(1, n):
for j in range(3):
dp[i][j] += min(dp[i-1][(j+1)%3], dp[i-1][(j+2)%3])
print(min(*dp[-1])) | kmgyu/baekJoonPractice | DynamicProgramming/DP1(practice)/RGB거리.py | RGB거리.py | py | 260 | python | en | code | 0 | github-code | 36 |
39541384276 | dictionaryExample={
"name":"aman",
"id": "12345",
"year" : "4yr"
}
#for x in dictionaryExample:
#print(x," : ",dictionaryExample.get(x))
#for x,y in dictionaryExample.items():
# print(x," : ",y)
del dictionaryExample["name"]
for x,y in dictionaryExample.items():
print(x," : ",y) | amanullha/Programming | PYTHON/dictionary.py | dictionary.py | py | 310 | python | en | code | 0 | github-code | 36 |
12536549602 | from datetime import datetime
from .models import Employee, Shift
import pulp
def save_shifts_to_database(prob, x, u, dienstplan, employee_id_to_idx):
num_hours_per_day = len(x)
num_days = len(x[0])
num_employees = len(x[0][0])
for h in range(num_hours_per_day):
for d in range(num_days):
... | reneHoellmueller/Algo_schedule | app/schedule/save_shifts_to_database.py | save_shifts_to_database.py | py | 1,300 | python | de | code | 0 | github-code | 36 |
18998758028 | # По данному целому неотрицательному n вычислите значение n!.
# N! = 1 * 2 * 3 * … * N (произведение всех чисел от 1 до N) 0! = 1
# Решить задачу используя цикл while
n = int(input('Введите число для вычисления факториала: '))
result = 1
number = n
if(n == 0):
result = 1
elif(n < 0):
print(f'{number} - отр... | kuha1088/GB_IntroPython_GU4025Sudakov | Seminars/Seminar2/Ex2-001/Ex2-001.py | Ex2-001.py | py | 722 | python | ru | code | 2 | github-code | 36 |
11166510919 | #! /usr/bin/env python
# prototype / test - for parsing commands from CLI
# basics: ArgumentParser
# https://docs.python.org/3/howto/argparse.html
#
# ArgumentParser - docs
# https://docs.python.org/3/library/argparse.html#type
# taking had written help like this and generating help using ArgumentParser (Python stdLi... | UnacceptableBehaviour/movie_picker | scripts/cli_parse.py | cli_parse.py | py | 7,173 | python | en | code | 0 | github-code | 36 |
32720426441 | # importing time and turtle module
import time
from turtle import Turtle,Screen
# defining screen properties
win=Screen()
win.title("Vande Matram")
win.bgcolor("black")
win.bgpic("flag1.gif")
# defining drawing pen properties
pen=Turtle()
pen.pensize(4)
pen.speed(1)
pen.up()
pen.goto(-150,200... | AmanPatel18/National-Flag | Flag.pyw | Flag.pyw | pyw | 1,868 | python | en | code | 0 | github-code | 36 |
36809853370 | # -*- coding:utf-8 -*-
import multiprocessing
import os
_debug = os.environ.get('DJANGO_SETTINGS_MODULE', 'karelapan.settings').endswith('dev')
bind = "unix:/tmp/gunicorn.sock"
#bind = "127.0.0.1:8000"
workers = multiprocessing.cpu_count() * 2 + 1
preload_app = True
daemon = not _debug
pidfile = os.path.normpath(os.p... | oca159/karelapan | gconfig.py | gconfig.py | py | 557 | python | en | code | 0 | github-code | 36 |
70190136745 | import re
from datetime import datetime
from bs4 import BeautifulSoup
from ..utils.http import wget
from ..utils.data import DataEngine
from dateutil import parser, tz
class Engine(object):
"""
Engine to process: https://www.letmeread.net
"""
__host__ = 'letmeread'
baseurl: str = "https://www.letm... | maborak/ebooks-dl | ebooksdl/engines/letmeread.py | letmeread.py | py | 6,996 | python | en | code | 2 | github-code | 36 |
16935982634 | from enum import unique
from flask import Flask, jsonify, request, render_template
from flask_sqlalchemy import SQLAlchemy
import json
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///students.sqlite"
db = SQLAlchemy(app)
class students(db.Model):
id = db.Column(db.Integer, unique=True, p... | Ernest0G/Grader | grader.py | grader.py | py | 3,221 | python | en | code | 0 | github-code | 36 |
35553846638 | from datetime import datetime
from turtle import position
from urllib.error import HTTPError
from td.client import TdAmeritradeClient
from td.rest.options_chain import OptionsChain
from Authenticator import TDAuthenticator
from time import sleep
class TDPosition():
def __init__(self, position_dict : dict):
... | gatordevin/TradingBot | v3/TD.py | TD.py | py | 19,700 | python | en | code | 1 | github-code | 36 |
3271562832 | import string
def criptografar(frase):
try:
for i in range(26):
if frase[i].upper() == ' ':
newfrase.append(' ')
else:
for j in range(26):
if frase[i].upper() == alfabeto[j]:
if j+3 > 25:
... | igorsromero/Projetos-Python | Cifra de César/criptografia.py | criptografia.py | py | 1,616 | python | pt | code | 4 | github-code | 36 |
7110168618 | from django.shortcuts import render, get_object_or_404
from django.views import generic
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post_save
from CodeConfab.models import Profile, Language,Post,FriendRequest,Poke, Prompt,Resources,Comment,Reply
... | Tekkieware/CodeConfab | CodeConfab/views.py | views.py | py | 10,814 | python | en | code | 0 | github-code | 36 |
29085566786 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import re
except_base_tag = ""
def process_line_exceptions(line):
global except_base_tag
if not " " in line or re.match(".*[а-яіїєґА-ЯІЇЄҐ] /.*", line):
return [line]
if re.match("^[^ ]+ [^ ]+ [^:]?[a-z].*$", line):
retur... | vlisivka/dict_uk | dict_uk/expand/tagged_wordlist.py | tagged_wordlist.py | py | 4,107 | python | en | code | null | github-code | 36 |
74248266663 | import argparse
import sys
import nested_diff
import nested_diff.cli
class App(nested_diff.cli.App):
"""Diff tool for nested data structures."""
supported_ofmts = ('auto', 'html', 'json', 'term', 'toml', 'text', 'yaml')
def diff(self, a, b):
"""
Return diff for passed objects.
... | grafviz/hatvp-json | modif_nested_diff/diff_tool.py | diff_tool.py | py | 4,955 | python | en | code | 0 | github-code | 36 |
3566593802 | import hits
import numpy as np
import pandas as pd
df_main = pd.read_csv("./data/HRDataset_v14.csv")
categorical = set(('Employee_Name','Position', 'State', 'Zip', 'DOB', 'Sex', 'MaritalDesc', 'CitizenDesc', 'HispanicLatino', 'RaceDesc', 'DateofHire', 'DateofTermination','TermReason' ,'EmploymentStatus', 'Department',... | NikhilPaleti/Privacy_Analysis | k_anonymity.py | k_anonymity.py | py | 2,303 | python | en | code | 0 | github-code | 36 |
42520787765 | from fastapi import FastAPI,Request
from fastapi import APIRouter
import aiomysql
from configuration.configuration import configuracion
from pydantic import BaseModel
from fastapi.param_functions import Body
from models.estudianteClass import estudianteClass
paralelo_router = APIRouter()
async def getConexion():
... | juanjoo0410/CS_Proyecto_API | controllers/paraleloController.py | paraleloController.py | py | 1,310 | python | en | code | 0 | github-code | 36 |
39562384945 | # Author: Zavier
import json
import random
import matplotlib.pyplot as plt
import numpy as np
import requests
import pandas as pd
import calendar
import datetime
from geopy.distance import geodesic
import geopy as gp
from app import *
from sklearn.linear_model import LinearRegression,Ridge,RidgeCV
from sklearn.prepr... | zavier250/ambulance_data_visualization | analysis.py | analysis.py | py | 12,820 | python | en | code | 0 | github-code | 36 |
32824298169 | speed = 3
game_state = "alive"
sythe = "standard scythe"
import pygame
import time
import sys
import random
money = 0
kills = 0
randX = random.randint(0,1626)
randY = random.randint(0,846)
pygame.init()
#This is where we set up the window that displays our game. The resolution is set here
screen = pygame.display.set_m... | GamesCreatorsClub/GCC-games-online | games/henrys-game/Main-platformer coppy.py | Main-platformer coppy.py | py | 11,324 | python | en | code | 0 | github-code | 36 |
18363762101 | from Bio import SeqIO, Entrez
from Bio.SeqFeature import FeatureLocation
import json, os, doctest
Entrez.email = "fayssal.el.ansari@gmail.com"
# TODO: faut modifier cette fonction pour accepter
# une seqRecord avec plusieurs sequences
def find_cds(seqRecord): #marche
'''Renvoie une liste des couples de positions ... | fayssalElAnsari/Bioinformatics-python-sequence-analyser | app/src/utilsTest.py | utilsTest.py | py | 6,111 | python | fr | code | 0 | github-code | 36 |
10955703754 | from datetime import datetime, timedelta
from itertools import islice, tee, izip
from django.conf import settings
from django.db import models
# output log if difference in traffic is less than than TRAFFIC_DELTA_MIN
TRAFFIC_DELTA_MIN = 1000.0
SLIDING_WINDOW_LEN = 4
LINK_ALIVE_INTERVAL = getattr(settings, 'GMAP_LINK_A... | shakirjames/ndnmap | gmap/models.py | models.py | py | 3,287 | python | en | code | 1 | github-code | 36 |
11828562957 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 21 10:41:14 2017
@author: Juan Antonio Barragán Noguera
@email: jabarragann@unal.edu.co
"""
import matplotlib.pyplot as plt
import numpy as np
FS=8000
TS=1/FS
f=1500
x=np.arange(0,200)
y=np.sin(2*np.pi*f*TS*x)
plt.stem(x,y)
| jabarragann/DiscretSignalsUnal | temp.py | temp.py | py | 283 | python | en | code | 0 | github-code | 36 |
33359438698 | import datetime
from typing import Optional
from zoneinfo import ZoneInfo
from fastapi import HTTPException
from passlib import pwd
from sqlalchemy import extract, or_, and_, func, Float, text, desc
from sqlalchemy.orm import aliased
import app.auth as auth
import app.models as models
import app.schemas as schemas
fr... | GabrielAndreata/gestione-backend | app/crud.py | crud.py | py | 37,649 | python | en | code | 1 | github-code | 36 |
24361808331 |
class Agent:
"""Class defining an agent defined by multiple attributes"""
def __init__(self, Agent_Breed, Policy_ID, Age, Social_Grade, Payment_at_Purchase, Attribute_Brand, Attribute_Price, Attribute_Promotions, Auto_Renew, Inertia_for_Switch):
"""Agent constructor"""
self.Agent_Breed = Agen... | adechamps/agent-test | agent.py | agent.py | py | 1,274 | python | en | code | 0 | github-code | 36 |
28304654413 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
import tasks.micro.nano as nano
from core.task import on_start, on_message
from tasks.competition.tests.helpers import task_messenger
from core.serializer ... | a0x8o/commai-env | src/tasks/micro/tests/test_nano.py | test_nano.py | py | 5,800 | python | en | code | 5 | github-code | 36 |
29412108576 | import mediapipe as mp
import json
mp_pose = mp.solutions.pose
def calculate_pose(image, pose):
results = pose.process(image)
if (results.pose_landmarks == None):
return {
"error": "NO LANDMARKS"
}
landmarks = results.pose_landmarks.landmark
landmarks_list = []
f... | flexinai/flexin-ipod-ad | calculate_pose.py | calculate_pose.py | py | 1,240 | python | en | code | 0 | github-code | 36 |
37005491530 | import pytest
import re
from itertools import chain
from pathlib import Path
from sphinx.application import Sphinx
from sphinx.util.docutils import docutils_namespace
from sphinx.testing.restructuredtext import parse as sphinx_parse
from .diffpdf import diff_pdf
from .pdf_linkchecker import check_pdf_links
from .uti... | Chris-Jr-Williams/rinohtype | tests_regression/helpers/regression.py | regression.py | py | 5,470 | python | en | code | null | github-code | 36 |
7438959251 | # -*- coding: utf-8 -*-
import random
#Libreria random
#librerias web scraping
from os import remove
import os, ssl
import urllib.request
from bs4 import BeautifulSoup
#librerias para descargar y guardar imagenes
#Para hacerlo sin certificaciones
import os, ssl
#Descargar imagen
import requests
#Mover ar... | eduardo-trejo-es/RecoleccionNotas_CronicaReg | old_App/Notas automatico a correo terminal final.py | Notas automatico a correo terminal final.py | py | 6,587 | python | es | code | 0 | github-code | 36 |
28431033139 | # -*- coding: utf-8 -*-
from __future__ import print_function
import time
import pygame
import OpenGL.GL as gl
import OpenGL.GLU as glu
import numpy as np
import itertools
import fractions
import copy
import numpy as np
#local imports
from common import COLORS, DEBUG, VSYNC_PATCH_HEIGHT_DEFAULT, VSYNC_PATCH_WIDTH_DE... | SridharLab/neurodot-present | neurodot_present/triple_checkerboard_flasher.py | triple_checkerboard_flasher.py | py | 8,015 | python | en | code | 0 | github-code | 36 |
3745949617 | # pylint: disable=C0413
# Standard Library
import logging
import os
import urllib
# Third Party
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# First Party
from resc_backend.db.model import Base
basedir = os.path.abspath(os.path.dirname(__file__))
logger = logging.getLogger(__name__)
... | abnamro/repository-scanner | components/resc-backend/src/resc_backend/db/connection.py | connection.py | py | 1,725 | python | en | code | 137 | github-code | 36 |
35863635019 | '''Write a Program to Calculate Permutation(nPr) for given values of n and r
The nPr (permutation) formula is:
p(n,r)= n!/(n-r)!'''
def n_fact(n):
i = 1
fact = 1
while i <= n:
fact *= i
i += 1
return fact
n = float(input("Enter the value for n: "))
r = float(input(... | codexmuneer/python-beginning-work | labtask8a.py | labtask8a.py | py | 476 | python | en | code | 0 | github-code | 36 |
1606737974 | from http.server import BaseHTTPRequestHandler
import json
import os
import shutil
import logging
import pytest
import requests
from pytest_httpserver import HTTPServer
from sunfish.lib.core import Core
from sunfish.lib.exceptions import *
from tests import test_utils, tests_template
class TestSunfishcoreLibrary():
... | OpenFabrics/sunfish_library_reference | tests/test_sunfishcore_library.py | test_sunfishcore_library.py | py | 4,902 | python | en | code | 0 | github-code | 36 |
24924782387 | import os
os.system('cls' if os.name == 'nt' else 'clear')
''' Density Normal Distribution '''
import numpy as np
mean = 4.5
sigma = 2
x = 1.2
p = np.exp(-np.square(x-mean)/ (2*sigma**2)) * (1/ np.sqrt(2*3.14*sigma**2))
print("\n--- Density : {} ---".format(p)) | fbenti/MachineLearning | 02450Toolbox_Python/Scripts/exam_script/normal_dist.py | normal_dist.py | py | 264 | python | en | code | 0 | github-code | 36 |
29752242940 | # Reading and writing compressed data files
# gzip compression
import gzip
# with gzip.open('somefile.gzip', 'rt') as f:
# text = f.read()
# print(text)
# bz2 compression
import bz2
# with bz2.open('somefile.bz2', 'rt') as f:
# text = f.read()
text = 'Some one not agreed.'
# write compresses data
with bz2... | pranavchandran/redtheme_v13b | c5_files_and_io/5_7_read_write_compressed_files.py | 5_7_read_write_compressed_files.py | py | 592 | python | en | code | 0 | github-code | 36 |
29788740858 | import time
import sys
import os
import socket
class BarcodeReader:
"""Class of the TCP connection"""
def __init__(self, ip="192.168.1.45", port=20002):
"""
Initialize client
Params:\n
- 'ip': ip of the connection
- 'port': port of the TCP connection
""... | humarobotics-france/doosan-examples | src/communication/barcode_reader/robot.py | robot.py | py | 2,404 | python | en | code | 0 | github-code | 36 |
14295656112 | import pinocchio as pin
import numpy as np
class NLinkCartpole(object):
def __init__(self, N, link_length, link_mass):
self.N = N
self.pin_model = pin.Model()
# Add the cart joint (prismatic joint along x axis)
jidx = 0
joint_model = pin.JointModelPrismaticUnaligned()
joint_model.axis[0] = 1
... | EpicDuckPotato/final_project_16715 | src/n_link_cartpole.py | n_link_cartpole.py | py | 2,776 | python | en | code | 2 | github-code | 36 |
29013033469 | from fastapi import WebSocket
from app.settings import SETTINGS
from app.websocket.exceptions import OnlineLimitException
from app.websocket.classes import OnlineUser
class OnlineUsersConnectionManager:
def __init__(self):
self.online_users: list[OnlineUser] = []
def add(self, online_user: OnlineUse... | mrdudov/tic-tac-toe | backend/app/websocket/connect_manager.py | connect_manager.py | py | 1,335 | python | en | code | 0 | github-code | 36 |
27515709525 | from discord import Embed
from discord.ext import commands
import discord
class ModerationCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(aliases=['удалить'])
@commands.has_role('Админ')
async def clear(self, ctx, amount: int = None):
await ctx.message.del... | RuCybernetic/CyberTyanBot | cogs/commands/moderation.py | moderation.py | py | 4,910 | python | ru | code | 1 | github-code | 36 |
15214495611 | import numpy as np
import random
path = 'datasets/nba/'
name = 'nba'
npy = '.npy'
data = np.load(path + name + npy, allow_pickle=True)
categories = np.load(path + name + "_categories" + npy, allow_pickle=True)
print(data)
print(categories)
num_of_sets = 100
num_of_vectors = 6
num_of_entries = 4
N = len(data)
result ... | kolejnyy/OxfordHack-2022 | matcher.py | matcher.py | py | 2,482 | python | en | code | 0 | github-code | 36 |
34400920616 | #!/usr/bin/python3
"""This module defines a class to manage file storage for airbnb clone"""
import json
class FileStorage:
"""Class manages storage of all instances for airbnb clone"""
__file_path = "file.json"
__objects = {}
def all(self):
"""Returns dictionary of all objects"""
ret... | Sami64/AirBnB_clone | models/engine/file_storage.py | file_storage.py | py | 1,685 | python | en | code | 0 | github-code | 36 |
31898090912 | from SPFEM_MFront import spfem_mfront
import numpy as np
import pygmsh
import os
mater = {
'rho':2000.,
'young':1.e6,
'poisson':.33,
'tau0':2.e4,
'taur':4.e3,
'b':5.
}
lx = 25.; ly=5.; mesh_size = .12
with pygmsh.geo.Geometry() as geom:
geom.add_polygon([[0.,0.],[lx,0.],[lx... | cenguo/SPFEM | retrogressive.py | retrogressive.py | py | 2,148 | python | en | code | 2 | github-code | 36 |
1224550679 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 18 23:04:53 2018
@author: Carla Pastor
Project: Heat Distribution.
"""
import numpy as np
import matplotlib.pyplot as lb
from matplotlib.colors import ListedColormap
if __name__ == "__main__":
inp=int(input("Enter the starting temperature: "))
... | carlaoutput/matplotlib | heatDistribution.py | heatDistribution.py | py | 2,384 | python | en | code | 0 | github-code | 36 |
34344785626 | import pika
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchange_declare(
exchange='publish',
exchange_type='fanout'
)
result = channel.queue_declare(
queue='',
exclusive=True
)
queue_name = result.method.queue
chann... | drupadh-eunimart/my_projects | RabbitMQ/PublishFanout/consumer.py | consumer.py | py | 628 | python | en | code | 0 | github-code | 36 |
20203939986 | import tkinter as tk
def on_button_click():
print(listbox.get(listbox.curselection()))
window = tk.Tk()
listbox = tk.Listbox(window)
listbox.insert(1, "Option 1")
listbox.insert(2, "Option 2")
listbox.insert(3, "Option 3")
listbox.pack()
button = tk.Button(window, text="Print selection", command=on_button_click)... | hw1186/IpPortScanner | TEST/Listbox.py | Listbox.py | py | 354 | python | en | code | 0 | github-code | 36 |
35290667799 | #!/usr/bin/env python
# coding: utf-8
# In[6]:
import math
import matplotlib
#define the function that need to find the root
def eval_func(z):
return pow(z,2)-4
#pick 2 initial points
x1=3
x2=5
tolerance=1.0e-10
for i in range(1000):
x3=x2-eval_func(x2)*(x2-x1)/(eval_func(x2)-eval_func(x1))
if eval... | linhphambuzz/NumericalMethod | Secant_method.py | Secant_method.py | py | 508 | python | en | code | 0 | github-code | 36 |
73574130983 | import torch
import torch.nn as nn
import torch.nn.functional as F
class discrete_policy_net(nn.Module):
def __init__(self, input_dim, output_dim, hidden_dim=128):
super(discrete_policy_net, self).__init__()
self.input_dim = input_dim
self.output_dim = output_dim
self.hid... | deligentfool/MAAC_pytorch | policy.py | policy.py | py | 1,529 | python | en | code | 0 | github-code | 36 |
36723052286 | from django.template import loader, RequestContext
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound, Http404
from django.conf import settings
from django.utils.safestring import mark_safe
from django.contrib.auth.views import redirect_to_login
from django import forms
from django.views.g... | stevecassidy/signbank-pages | pages/views.py | views.py | py | 4,101 | python | en | code | 0 | github-code | 36 |
1163783579 | # -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import csv
x = []
y = []
with open('input.csv','r',encoding = 'utf8') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
for row in plots:
x.append(row[0])
y.append(float(row[1]))
plt.plot(x,y, label='banana')
plt.xlabel('date')
plt.yl... | sytsao/TQC-web-data-capture-and-analysis-Python3 | TQC-web-crawler-and-analysis-Python3/第4章/綜合範例/GE4-1PYA401.py | GE4-1PYA401.py | py | 408 | python | en | code | 0 | github-code | 36 |
10035777489 | import numpy as np
from sklearn.model_selection import StratifiedKFold, GridSearchCV
from sklearn.metrics import roc_auc_score
from sklearn import preprocessing
def runTuneTest(learner, parameters, X, y):
"""
This method takes in a learning algorithm, the possible settings you would use for the algorithm and t... | ameetsoni/CompBioNSF-Module | soln/geneMLLib.py | geneMLLib.py | py | 3,118 | python | en | code | 1 | github-code | 36 |
42474907132 | manual_pancakebunny_pool = "0xEDfcB78e73f7bA6aD2D829bf5D462a0924da28eD"
cake_token = "0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82"
bsc_api_token = 'RU7Y28HFEAFBU7EB9ZV1QHMSMDUZSHNY1Q'
from brownie import *
def get_contract_by_address(address):
try:
print ('trying by accessing network')
contract = C... | gabrielfior/pools-apy-monitor | scripts/get_pancakebunny_manual.py | get_pancakebunny_manual.py | py | 1,738 | python | en | code | 0 | github-code | 36 |
36480992641 | from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QFileDialog, QGraphicsScene, QGraphicsView, QGraphicsPixmapItem, QDialog
from PyQt5.QtGui import QPixmap, QPainter, QColor, QImage
from gui import Ui_MainWindow
import sys
import math as m
import numpy as np
import matplo... | HamzaJamal782/MRI-Image-reconstruction- | test.secret.py | test.secret.py | py | 10,448 | python | en | code | 1 | github-code | 36 |
28260640471 | import pandas as pd
from matplotlib import pyplot as plt
pd.options.mode.chained_assignment = None
data = pd.read_csv("nieruchomosci2.csv", sep=';', decimal=',', header=None)
data = data.transpose()
rp = data[data[0] == "rynek pierwotny"]
rw = data[data[0] == "rynek wtórny"]
rp.loc[:, 3] = rp[3].str.replace(" ", "")
p... | sqrauwm/HOMEWORKS__PYTHON | SESJA_WIZUALIZACJA_DANYCH/WizualizacjaDanych_Zestawy-main/Zestaw_1/Z3/main.py | main.py | py | 330 | python | en | code | 0 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.