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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
19951561410 | counter = 0
response = input("Do you want to calculate tution owed Yes or No")
while response == "Yes":
counter = counter + 1
lastname = input("Enter lastname")
credits = input("Enter credits taken")
district = input("Enter district code I or O")
if district == "I":
tuition = 250.0
else:
tution = 5... | Dbalboaaaa/CIS-106-W65-Spring-2022 | PS6P5.py | PS6P5.py | py | 623 | python | en | code | 0 | github-code | 36 |
71685390185 | __author__ = 'apple'
from turtle import *
colors=["blue","orange"]
N=400
def posadzka(n):
k=400/n
set_starting_point(n)
for i in range(n):
for j in range(n):
color=colors[(i+j)%2]
shape(k,color)
fd(k)
bk(k*n)
rt(90)
fd(k)
lt(90)... | chinski99/minilogia | 2009/etap 2/posadzka.py | posadzka.py | py | 746 | python | en | code | 0 | github-code | 36 |
36493183781 | """archetypal StructureInformation."""
import collections
from validator_collection import validators
from archetypal.template.constructions.base_construction import ConstructionBase
from archetypal.template.materials.opaque_material import OpaqueMaterial
class MassRatio(object):
"""Handles the properties of t... | samuelduchesne/archetypal | archetypal/template/structure.py | structure.py | py | 8,696 | python | en | code | 11 | github-code | 36 |
2134410901 | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
# This file is only used if you use `make publish` or
# explicitly specify it as your config file.
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'http://egel.pl'
# Following items are often ... | egel/blog | publishconf.py | publishconf.py | py | 946 | python | en | code | 0 | github-code | 36 |
39754184637 | # coding: utf-8
from ..objecter_core._SmartTemplate import template
from ..objecter_core._Base import _Base
from ..objecter_core._Smart import Translater
from ..objecter_core._common_classes import _NumberInt
from .url import url, Urler, to_exps
class Common(Translater):
class NumberInt(_NumberInt):
TYP... | awini/coup | coup/common/all.py | all.py | py | 1,645 | python | en | code | 0 | github-code | 36 |
13413427634 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from matplotlib.lines import Line2D
import pandas as pd
##############################################################
# Change these lines to apply on your custom datasets
#########################################################... | MiriUll/multimodal_ABSA_Elbphilharmonie | pca_vis_img_features.py | pca_vis_img_features.py | py | 3,060 | python | en | code | 2 | github-code | 36 |
13030737473 | import sys
from PySide6.QtCore import Qt, QTimer, QSettings, QThread, QRegularExpression
from PySide6.QtGui import QIcon, QAction, QPixmap, QIntValidator, QRegularExpressionValidator
from PySide6.QtWidgets import QApplication, QSystemTrayIcon, QMenu, \
QLabel, QWidgetAction, QWidget, QHBoxLayout, QMessageBox, QForm... | gmc-norr/getmod | getmod.py | getmod.py | py | 13,431 | python | en | code | 0 | github-code | 36 |
19800687308 | import sys
N, K = [int(n) for n in sys.stdin.readline().split()]
W = [0]
V = [0]
for _ in range(N):
w, v = [int(n) for n in sys.stdin.readline().split()]
W.append(w)
V.append(v)
dp = [[0] * (N + 1) for _ in range(K+1)]
for i in range(1, K+1):
for j in range(1, N+1):
if i < W[j]:
... | chelsh/baekjoon | Solved/12865_bag.py | 12865_bag.py | py | 437 | python | en | code | 1 | github-code | 36 |
31025538209 | class Solution:
def maxMoves(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
@cache
def dp(i: int, j: int) -> int:
if i < 0 or i >= m or j < 0 or j >= n: return 0
res = 0
cur = grid[i][j]
for x, y in [(-1, 1), (0, 1), (1, 1... | meetsingh0202/Leetcode-Daily-Coding-Challenge | 2684-maximum-number-of-moves-in-a-grid/2684-maximum-number-of-moves-in-a-grid.py | 2684-maximum-number-of-moves-in-a-grid.py | py | 594 | python | en | code | 0 | github-code | 36 |
11361181001 | import sys
sys.stdin = open('글자수.txt')
T = int(input())
for tc in range(1, T+1):
str1 = input()
str2 = input()
final_cnt = 0
tmp = []
for j in range(len(str1)):
cnt = 0
for k in range(len(str2)):
if str1[j] == str2[k]:
cnt += 1
tmp.append(cnt)
... | Jade-KR/TIL | 04_algo/수업/글자수.py | 글자수.py | py | 435 | python | en | code | 0 | github-code | 36 |
16248087762 | from .base import Scoring
from math import pi
import torch
__all__ = ["ComplEx"]
class ComplEx(Scoring):
"""ComplEx scoring function.
Examples
--------
>>> from ckb import models
>>> from ckb import datasets
>>> from ckb import scoring
>>> import torch
>>> _ = torch.manual_seed(... | raphaelsty/ckb | ckb/scoring/complex.py | complex.py | py | 2,492 | python | en | code | 20 | github-code | 36 |
2037492885 | #!/usr/bin/env python3
import argparse
import datetime
import importlib
import re
import site
import traceback
from pathlib import Path
import yaml
SECRET_FILENAME = "secrets.yaml"
SECRET_REGEX = re.compile(r"!secret\s(\w+)")
def main():
parser = argparse.ArgumentParser(description="Test sources.")
parser.... | geNAZt/home-assistant | custom_components/waste_collection_schedule/waste_collection_schedule/test/test_sources.py | test_sources.py | py | 5,022 | python | en | code | 0 | github-code | 36 |
25577884705 | class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
version1 = version1.split('.')
version2 = version2.split('.')
# the level we are comparing versions
level = 0
while level < len(version1) and level < len(version2):
# comparing each l... | korynewton/code-challenges | leetcode/CompareVersionNumbers/solution.py | solution.py | py | 1,025 | python | en | code | 0 | github-code | 36 |
7683932011 | # ----------------------------------------------------------------------------------------
# prepare environment (boilerplate)
# import the required packages using their usual aliases
import dash
from dash import dcc, html, Input, Output, State
import dash_bootstrap_components as dbc
import plotly.graph_objects as go
... | khurchla/sustain-our-soil-for-our-food-prod | app.py | app.py | py | 29,394 | python | en | code | 1 | github-code | 36 |
23426656669 | listA = []
listB = []
for a in range(3,18,2):
listA.append(a)
for b in range(2,17,2):
listB.append(b)
for x in listA:
for y in listB:
print(x,y) | NaifAlqahtani/100_DaysOfCode | 100 days of python/Day32-33.py | Day32-33.py | py | 178 | python | en | code | 0 | github-code | 36 |
7003913528 | from tkinter import *
import tkinter.messagebox as msg
def order():
msg.showinfo("Order Received!", f"We have received your order for {var.get()}. Thanks for ordering")
top = Tk()
top.geometry('400x200')
top.title('Tkinter - Radio Button')
Label(top, text = "What would you like to have sir?",font="lucida 19 bol... | salmansaifi04/python | chapter18(tkinter)/17_radio_button.py | 17_radio_button.py | py | 837 | python | en | code | 0 | github-code | 36 |
21119755777 | from typing import Counter, List
class Solution:
def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:
map = Counter()
for a, b in items1:
map[a] += b
for a, b in items2:
map[a] += b
return sorted([a, b] for a, b i... | plattanus/leetcodeDAY | python/2363. 合并相似的物品.py | 2363. 合并相似的物品.py | py | 625 | python | en | code | 0 | github-code | 36 |
31598739479 |
# Uses the same dynamics as the 6Dof (just a reduced state) and different model to compute Force and Torque because there are only 3 blades
# Receive user input for the objective position and attitude (later on will be received from a subscriber to pose of aruco pkg)
# Computes the necessary rotations per second on ea... | Guilherme-Viegas/PositionAndAttitudeEstimation3DoF_Free_Flyer | controller.py | controller.py | py | 7,527 | python | en | code | 1 | github-code | 36 |
12780766468 | def is_divisible(n, d):
while n >= d:
n = n - d
return n == 0
def is_premier(n):
for d in range(2, n):
if is_divisible(n, d):
return False
return True
def affiche_nombres_premiers_jusqua(n):
for i in range(2, n+1):
if is_premier(i):
print(i)
print(i... | janoscoder/experiments | incubator/nombres_premiers.py | nombres_premiers.py | py | 474 | python | en | code | 0 | github-code | 36 |
412173435 | import nltk
def init_wfst(tokens, grammar):
"""Updates diagonal elements of chart
Arguments:
---------
tokens (list):
List of words in input sentence
grammar (list):
List of production rules in the grammar
"""
num_tokens = len(tokens)
wfst = [[None... | aashishyadavally/MS_AI_Coursework | CS6900/Assignment06/homework6_1.py | homework6_1.py | py | 2,755 | python | en | code | 0 | github-code | 36 |
4399694937 | #!/usr/bin/env python
# coding: utf-8
from codecs import open # to use a consistent encoding
from os import path
from subprocess import check_output
from setuptools import setup, find_packages
def get_version():
cmd = "git describe"
try:
result = check_output(
cmd.split(),
).dec... | openworkload/swm-python-client | setup.py | setup.py | py | 1,828 | python | en | code | 1 | github-code | 36 |
72905658983 | from .utils import *
@pytest.fixture
def client():
app.config.from_object(TestingConfig)
db.create_all()
yield app.test_client()
db.session.remove()
db.drop_all()
class TestMain:
def test_home_page_shows(self, client):
response = client.get('/')
assert response.status_code ==... | KiTroNik/HabitTracker | tests/test_main.py | test_main.py | py | 1,625 | python | en | code | 0 | github-code | 36 |
30382090301 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 7 13:32:28 2018
@author: jon
"""
#import sys
#from pyuvdata import UVData
from pynfft import NFFT
import numpy as np
import matplotlib.pyplot as plt
from scipy import constants
from mslib import MS_jon
def singleFrequency():
imsize = (256, 25... | lord-blueberry/p8-pipeline | sandbox/img_test/pynfft_test.py | pynfft_test.py | py | 2,295 | python | en | code | 0 | github-code | 36 |
8735286229 | import requests
def linkCheck(linksFound):
goodLinks = []
badLinks = []
for link in linksFound:
res = requests.get(link)
if res.status_code == 200:
print(link + " <<<<<<<<<< 200")
goodLinks.append(link)
else:
badLink = res.status_code... | zipinel/Selenium_and_BeautifulSoup | Base/linkChecker.py | linkChecker.py | py | 467 | python | en | code | 0 | github-code | 36 |
35753678574 | import xlsxwriter
workbook = xlsxwriter.Workbook("1.xlsx")
mySheet = workbook.add_worksheet()
mySheet.write("A1", "t_value")
mySheet.write("B1", "y1_value")
mySheet.write("C1", "y2_value")
t = 0
t1 = 0
y2 = 0
t1_value = []
y1_value = []
y2_value = []
while int(t) != 2:
t += 0.1
y1 = (5 * t) + ((2 * t) ** 2... | toni7891/magshimimHW_10grade | selfProjects/physics/phisycaProg1.py | phisycaProg1.py | py | 893 | python | en | code | 3 | github-code | 36 |
39498051069 | from __future__ import absolute_import
__author__ = "Angelo Ziletti"
__copyright__ = "Angelo Ziletti"
__maintainer__ = "Angelo Ziletti"
__email__ = "ziletti@fhi-berlin.mpg.de"
__date__ = "14/08/18"
import unittest
from ai4materials.models.clustering import design_matrix_to_clustering
import numpy as np
import sklearn... | angeloziletti/ai4materials | tests/test_clustering.py | test_clustering.py | py | 2,367 | python | en | code | 36 | github-code | 36 |
25050897663 | # coding: utf-8
from typing import Any, Dict, List, Optional, Tuple, Union
import matplotlib.pyplot as plt
from matplotlib.axes import Axes
from matplotlib.colors import Colormap
from matplotlib.figure import Figure as mplFigure
from plotly.graph_objects import Trace
from plotly.graph_objs import Figure as plotlyFigur... | iwasakishuto/TeiLab-BasicLaboratoryWork-in-LifeScienceExperiments | teilab/utils/plot_utils.py | plot_utils.py | py | 5,241 | python | en | code | 0 | github-code | 36 |
19027441425 | from django.db import models
class SocialNetwork(models.Model):
"""Social Network model definitions"""
DEFAULT_SOCIALNETWORKS = (
(0, 'FaceBook'),
(1, 'Instagram'),
(2, 'Linkedin'),
(3, 'Twitter'),
(4, 'YouTube'),
)
title = models.CharField(
verbose_na... | ag-castro/brazil-ongs-mapping | ressonantes/core/models/social_network.py | social_network.py | py | 762 | python | en | code | 1 | github-code | 36 |
7737385160 | # -*- coding=utf8
import web, random, string
from StringIO import StringIO
from PIL import Image, ImageDraw, ImageFont, ImageFilter
#生成验证码的位数
vcodeLength = 4
#生成验证码图片的尺寸
vcodeSize = (60, 25)
#背景颜色, 默认白色
vcodeBgcolor = (238, 238, 238)
#字体颜色, 蓝色
vcodeFontcolor = (0, 0, 255)
#干扰线, 红色
vcodeLinecolor = (255, 0, 0)
#是否要加干扰线... | kungfucode-rex/jlgjg-admin | server/web/controller/Index_C.py | Index_C.py | py | 2,315 | python | en | code | 0 | github-code | 36 |
20777673952 | from pandas import read_csv
X = read_csv('./datasets/wine.csv')
blockSize=2000
scanned=0
for i in range(blockSize,len(X.index),blockSize):
dfAux=X[i-blockSize:i]
dfAux.to_csv(index=False,path_or_buf='./datasets/wine'+str(i)+".csv")
scanned+=blockSize
dfAux=X[scanned:]
dfAux.to_csv(index=False,path_or_buf... | ggonzalere19/OptimizacionProyecto | splitter.py | splitter.py | py | 363 | python | en | code | 0 | github-code | 36 |
17225040 | from pwn import *
p = remote('chal.2020.sunshinectf.org', 30002)
#p = process('./chall_02')
e = ELF('./chall_02')
p.readline()
input('...')
p.send('a'*0x12)
print('[INFO] launch /bin/sh 0x%.8x' %(e.symbols['win']))
line = b'a'*0x3e
line += p64(e.symbols['win'])
line += b'\n'
p.send(line)
p.interactive()
'''
[+... | hjlbs/ctf | 2020/sunshine/speedrun/02-exp.py | 02-exp.py | py | 745 | python | en | code | 0 | github-code | 36 |
26745748297 | """
Workhorse file to perform analysis on data taken by Andor Cameras using CSPY
Author : Juan Bohorquez
Created on : 06/04/2021
Last Modified : 06/04/2021
"""
import h5py
import os
import numpy as np
import warnings
from typing import Tuple
from HamamatsuH5 import HMROI
def load_data(
results_file: h5py.Fi... | JuanBohorquez3/Hybrid_H5 | H5_python3/AndorH5.py | AndorH5.py | py | 2,231 | python | en | code | 0 | github-code | 36 |
71712982823 | import requests
from behave import *
from hamcrest import *
@when('Make a get request')
def make_get_request_to_api(context):
context.resp= requests.get("https://reqres.in/api/users?page=2")
assert_that(context.resp.status_code, equal_to(200))
@then('Check if users list is returned')
def check_user_list(cont... | HarshDevSingh/docker_python_bdd | features/steps/rest_api.py | rest_api.py | py | 631 | python | en | code | 0 | github-code | 36 |
70077277545 | from path import Path
import sys, os
def rec(fname):
os.system('alsamixer')
os.system('sox -t alsa default "{fname}"'.format_map(vars()))
print('playback command: ~$ aplay {fname}'.format_map(vars()))
def initialize():
path = os.path.join(os.getcwd(), 'wavs')
os.path.exists(path) or os.mkdir(path)... | chris-hamberg/system_utils | alsa_record.py | alsa_record.py | py | 1,013 | python | en | code | 0 | github-code | 36 |
29144047296 | #!/usr/bin/python3
import numpy as np
from scipy.io import loadmat
from func import displayData, nnCostFunction, sigmoidGradient, randInitializeWeights,\
checkNNGradients, fmin_nn, fmin_nn1, predict
import matplotlib.pyplot as plt
def main():
# Setup the parameters you will use for this exercise
input_... | rossihwang/Coursera_ML_homework_with_python | week5/ex4.py | ex4.py | py | 3,839 | python | en | code | 1 | github-code | 36 |
43111990750 | import aws_cdk as cdk
from constructs import Construct
from aws_cdk import (aws_apigateway as apigateway,
aws_lambda as lambda_,
aws_dynamodb)
class TasksService(Construct):
def __init__(self, scope: Construct, id: str):
super().__init__(scope, id)
task_ta... | basv98/api-dynamodb | tasks/tasks_service.py | tasks_service.py | py | 1,208 | python | en | code | 0 | github-code | 36 |
25607794751 | from math import gcd
n,r = map(int,input().split())
p=1
d=1
if n-r<r:
r=n-r
if r!=0:
while r:
p=p*n
d=d*r
gcdval=gcd(p,d)
p=p//gcdval
d=d//gcdval
print(p,d)
n-=1
r-=1
print(p/d)
| Nirmalkumarvs/programs | Math Algorithms/NCR.py | NCR.py | py | 277 | python | en | code | 0 | github-code | 36 |
2893340600 | import re
from RegExp import *
from Detector import *
class CLanguageCS:
# Comments
SINGLE_LINE_COMMENT_PREFIX = "//"
MULTI_LINE_COMMENT_PREFIX = "/*"
MULTI_LINE_COMMENT_SUFFIX = "*/"
# Block
BLOCK_PREFIX = "{"
BLOCK_SUFFIX ... | AvivYaniv/FireWall | hw5/proxy/DetectorCS.py | DetectorCS.py | py | 8,586 | python | en | code | 1 | github-code | 36 |
1942576401 | class Solution:
def twoOutOfThree(
self, nums1: List[int], nums2: List[int], nums3: List[int]
) -> List[int]:
s1 = set(nums1)
s2 = set(nums2)
s3 = set(nums3)
result = set()
for n in s1:
if n in s2 or n in s3:
result.add(n)
for n... | hellojukay/leetcode-cn | src/two-out-of-three.py | two-out-of-three.py | py | 507 | python | en | code | 3 | github-code | 36 |
37349410877 | """Test all electron density for right interpretation of coreholes"""
import pytest
from ase.build import molecule
from ase.units import Bohr
from gpaw import GPAW, PoissonSolver
from gpaw.mixer import Mixer
from gpaw.test import gen
@pytest.mark.later
def test_aed_with_corehole_li():
"""Compare number of electro... | f-fathurrahman/ffr-learns-gpaw | my_gpaw/test/corehole/test_li2.py | test_li2.py | py | 1,336 | python | en | code | 0 | github-code | 36 |
37486834753 | from collection import deque
def fill(point, canvas, color):
if x not in canvas:
return
elif y not in canvas[x]:
return
x, y = point
if canvas[y][x] == color:
return
canvas[y][x] = color
fill((x + 1, y), canvas, color)
fill((x - 1, y), canvas, color)
fill((x, y ... | tvl-fyi/depot | users/wpcarro/scratch/facebook/recursion-and-dynamic-programming/paint-fill.py | paint-fill.py | py | 918 | python | en | code | 0 | github-code | 36 |
29572532106 | """ Notes
-Need to have opencv built with gstreamer support
print(cv2.getBuildInformation())
-Set Xavier to max power:
(do do manually or providing sudo password as script arg -p PASSWORD)
sudo nvpmodel -m 0
sudo jetson_clocks
-JTOP - helpful activity monitor
sudo apt-get install python3-pip -y
sudo python3 -m pip i... | LiellPlane/DJI_UE4_poc | Source/lumotag/mobilenet_inference_tidied.py | mobilenet_inference_tidied.py | py | 10,889 | python | en | code | 0 | github-code | 36 |
6811791128 | #!/usr/bin/env python3
from random import random
from z3 import *
import numpy as np
import time
from math import *
from statistics import *
from random_lib import *
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
from collections import defaultdict
import heapq
import faulthandler
faul... | Luckykantnayak/uav-project-2 | lucky_smt_v5.py | lucky_smt_v5.py | py | 38,555 | python | en | code | 0 | github-code | 36 |
19192518817 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 21:51:03 2021
@author: jyotm
"""
import numpy as np
from math import sqrt
import math
import warnings
warnings.filterwarnings("ignore")
test = True
#this is a continuation of programming drill exercises and quantum simulator of 4.2.1
#we are going to implement the... | jeromepatel/Quantum-Computing-for-Computer-Scientists | Programming_drill_4_3_1.py | Programming_drill_4_3_1.py | py | 2,316 | python | en | code | 3 | github-code | 36 |
4593625107 | import cv2
import json
import numpy as np
import matplotlib.pyplot as plt
from itertools import count
def put_speed_on_video(mp4_path, pred_text_path, act_text_path):
pred_speed_list = np.around(np.loadtxt(pred_text_path), decimals=1)
act_speed_list = np.around(np.loadtxt(act_text_path), decimals=1)[1:]
vi... | antoninodimaggio/Voof | demo_utils.py | demo_utils.py | py | 2,797 | python | en | code | 65 | github-code | 36 |
74062226345 | import argparse
from fauxcaml import build
def create_parser():
ap = argparse.ArgumentParser(
prog="fauxcamlc",
description="Compiles an OCaml source file to an x86-64 executable.",
epilog="project homepage: https://github.com/eignnx/fauxcaml",
)
ap.add_argument(
"source_... | eignnx/fauxcaml | fauxcaml/__main__.py | __main__.py | py | 757 | python | en | code | 2 | github-code | 36 |
18252831721 | from typing import List
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
res = []
people.sort(key = lambda x : (-x[0], x[1]))
for a in people:
res.insert(a[1], a)
return res
solution = Solution()
people = [[7,0],[4,4],[7,1],[5,0],... | hujienan/Jet-Algorithm | leetcode/406. Queue Reconstruction by Height/index.py | index.py | py | 465 | python | en | code | 0 | github-code | 36 |
26635576564 | angka_angka = [2, 3, 5, 5, 4, 2, 6, 5, 7, 8, 3]
angka_unik = []
for angka in angka_angka:
if angka not in angka_unik:
angka_unik.append(angka)
print(angka_unik)
#unpacking
#list
koordinat = [1, 2, 3]
x, y, z = koordinat
print(z)
#tupple
koordinat = (4, 5, 6)
a, b, c = koordinat
print(a)
... | Noorwahid717/PythonOop | list.py | list.py | py | 689 | python | jv | code | 0 | github-code | 36 |
12573047520 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root... | AG-Systems/programming-problems | Leetcode/Invert-Binary-Tree.py | Invert-Binary-Tree.py | py | 1,657 | python | en | code | 10 | github-code | 36 |
14581993222 | # -*- coding: utf-8 -*-
# @Author : DevinYang(pistonyang@gmail.com)
import numpy as np
import random
from torchtoolbox.transform import *
from torchtoolbox.transform.functional import to_tensor
trans = Compose([
# CV2 transforms
Resize(500),
CenterCrop(300),
Pad(4),
RandomCrop(255, 255),
Rand... | PistonY/torch-toolbox | tests/test_transform.py | test_transform.py | py | 960 | python | en | code | 409 | github-code | 36 |
17559817941 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import turtle
def koch(size,n):
if n==0:
turtle.fd(size)
else:
for angle in [0,60,-120,60]:
turtle.left(angle)
koch(size/3,n-1)
def main():
turtle.setup(600,600)
turtle.penup()
turtle.goto(-200,100)
turtle.pend... | quanproject/python-engineer | 5.3 科赫雪花.py | 5.3 科赫雪花.py | py | 477 | python | en | code | 0 | github-code | 36 |
40962236742 | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
import json
from flask import Flask,request
from base.base import *
app = Flask(__name__)
@app.before_request
def before_request():
if request.method == 'POST' and request.form.get("name"):
name=request.form.get("name")
if existfile(name):
... | 1185714392/moviesearch | app.py | app.py | py | 1,710 | python | en | code | 3 | github-code | 36 |
21088767071 | from structures.list import List
__all__ = ['Queue']
class Queue:
def __init__(self):
self.max_size = 100
self._list = List()
def enqueue(self, value):
# add element to end of queue
self._list.append(value)
if len(self) > self.max_size:
raise Exception('... | AlekseySh/computer_science | structures/queue.py | queue.py | py | 861 | python | en | code | 0 | github-code | 36 |
12829538864 | import json
class Participant:
# custom classes must be converted to dictionary or list to be serializable
def __init__(
self,
points=0,
total_points=0,
problems_solved=0,
easy=0,
medium=0,
hard=0,
won=0,
first=0,
) -> None:
... | misslame/BroncoderBot | participant_data_handling/participant.py | participant.py | py | 3,927 | python | en | code | 9 | github-code | 36 |
30467610617 | import collections
class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
node_to_neighbor = {}
# build graph
for account in accounts:
name = account[0]
for i in range(1, len(account)):
cur_email = account[i]
... | dundunmao/LeetCode2019 | 721. Accounts Merge.py | 721. Accounts Merge.py | py | 2,068 | python | en | code | 0 | github-code | 36 |
43046784986 | from datetime import datetime
from discord.ext import commands
import discord
from discordbot.errors import ErrorMessage
class UserInfo(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.color = 0xffffff
@commands.command(
brief="Erhalte Benutzerinfos",
description="... | AlexeiSur/bot12345 | discordbot/botcmds/userinfo.py | userinfo.py | py | 2,397 | python | de | code | 0 | github-code | 36 |
33512505076 | # -*- coding: utf8 -*-
from collective.contact.core.behaviors import IRelatedOrganizations
from collective.contact.core.testing import INTEGRATION
from ecreall.helpers.testing.base import BaseTest
from z3c.relationfield.relation import RelationValue
from zope.component import getUtility
from zope.interface import also... | collective/collective.contact.core | src/collective/contact/core/tests/test_related.py | test_related.py | py | 1,764 | python | en | code | 6 | github-code | 36 |
5547127979 | """
Voting 12/04/2022.
1. Refund previous depositor' spending to finance multisig 0x48F300bD3C52c7dA6aAbDE4B683dEB27d38B9ABb
with 254.684812629886507249 stETH.
2. Fund depositor bot multisig 0x5181d5D56Af4f823b96FE05f062D7a09761a5a53 with 130 stETH.
Vote passed & executed on Apr-15-2022 05:34:30 PM +UTC, block #14... | lidofinance/scripts | archive/scripts/vote_2022_04_12.py | vote_2022_04_12.py | py | 2,423 | python | en | code | 14 | github-code | 36 |
31428823001 | # 2021.09.09
# 2309
# 일곱 난쟁이
ls = []
for _ in range(9):
ls.append(int(input()))
target = sum(ls) - 100
for i in range(9):
flag = False
for j in range(i + 1, 9):
if (ls[i] + ls[j]) == target:
ls.pop(i)
ls.pop(j-1) # 하나 삭제되기 때문에 하나 줄여줘야 함
flag = True
... | Minkeyyyy/OJ | BaekJoon/All/2309.py | 2309.py | py | 471 | python | ko | code | 0 | github-code | 36 |
23728224660 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from StyleFrame import StyleFrame, utils
# read excel file to usable numpy arrays
def load_multispectral_data(excel_file):
df = pd.read_excel(excel_file, 'Multispectral Image')
nir = df[0:20].iloc[:, 1:].to_numpy()
red = df[22:42].ilo... | maxvanschendel/Geomatics | GEO1001/assignment_5.py | assignment_5.py | py | 5,084 | python | en | code | 0 | github-code | 36 |
72506677225 | from BetterDirectGui.DirectGui import *
def test():
print("click")
def test_setup1():
b1 = DirectButton(text="button1", command=test) # , suppressMouse=0, frameTexture="models/maps/circle.png")
b1.setScale(0.2)
b1.setPos(-0.7, 0, 0)
# b1["scale"] = 0.2
# b1["pos"] = (-0.7, 0, 0)
# b1["h... | Augustifolia/BetterDirectGui | tests/nesting_test.py | nesting_test.py | py | 1,901 | python | en | code | 0 | github-code | 36 |
24851114046 | #!/usr/bin/env python
import numpy as np
import pandas as pd
import lightgbm
path_in = 'sample/'
path_out = 'sample/'
classes = 9
def make_features_weighted(data):
weights = np.arange(data.shape[1], dtype=float)
weights /= np.sum(weights)
counters = pd.concat(
[((data == j)*weights).sum(axis=1)... | eugenbobrov/pzad2017 | task1/simple_lgbm.py | simple_lgbm.py | py | 1,023 | python | en | code | 0 | github-code | 36 |
20115987747 |
print(type("334"))
print(type(44.22))
score = int(input("请输入你的分数:"))
# elif = else if
if 100 >= score >= 90:
print('A')
elif 90 > score >=60:
print('B')
elif 60 > score >=0:
print('C')
else:
print("输入错误!")
# 三元表达式
x,y=4,5
small = x if x < y else y
print(small)
# 断言(assert) 当条件成立后让程序自动崩溃,确保某个条件一定为真
fa... | Linka39/pythonStudy | branch.py | branch.py | py | 1,007 | python | en | code | 0 | github-code | 36 |
71160406824 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
import sys
def normal(x, mean, var):
if var == 0:
var = 0.2
return math.e**-((x - mean)**2 / (2.0 * var)) / (2.0 * math.pi * var)**0.5
class Naive():
def __init__(self, label_n, pixel_n, bin_n=32, option=0):
self.label_count = [0 f... | chhu0830/NCTU_106-2_machine-learning | lab2/classifier.py | classifier.py | py | 3,307 | python | en | code | 0 | github-code | 36 |
70003678825 | from discord.ext import commands
import logging, traceback, discord
from collections import Counter
import datetime
import asyncio, aioredis
import os, sys, time
import random
from multiprocessing import Queue
from queue import Empty as EmptyQueue
import json
import hashlib
import config
import rethinkdb as r
import ... | harumaki4649/nekobot | shardedBot.py | shardedBot.py | py | 12,244 | python | en | code | 0 | github-code | 36 |
13160204578 | #!/usr/bin/python
import main.database as maria
import csv
db = maria.MySQLDatabase()
def create_csv():
sql = "SELECT * FROM PROBES;"
db.mycursor.execute(sql)
output_description = tuple([field[0] for field in db.mycursor.description])
m_list = db.mycursor.fetchall()
with open('persons.csv', 'wb'... | pdeesawat4887/python-cgi-monitor | tuesday-service-server/create_csv.py | create_csv.py | py | 1,033 | python | en | code | 0 | github-code | 36 |
4108486387 | import sys
input = sys.stdin.readline
n, q = [int(x) for x in input().split()]
arr = [int(x) for x in input().split()]
maxL = [0] * (n + 2)
maxR = [0] * (n + 2)
freqL = [1] * (n + 2)
freqR = [1] * (n + 2)
for i in range(n):
maxL[i + 1] = max(arr[i], maxL[i])
freqL[i + 1] = freqL[i]
if arr[i] == maxL[i]:
... | AAZZAZRON/DMOJ-Solutions | gfssoc2j5.py | gfssoc2j5.py | py | 963 | python | en | code | 1 | github-code | 36 |
19565250442 | from django.db import models
from users.models import User
from .validators import validate_year
class Category(models.Model):
name = models.CharField(max_length=256)
slug = models.SlugField(max_length=50, unique=True)
def __str__(self):
return self.name
class Meta:
ordering = ('nam... | Daniil-lev/infra_sp2 | api_yamdb/reviews/models.py | models.py | py | 2,321 | python | en | code | 3 | github-code | 36 |
31609478117 | s = list(input())
num = 0
slist = []
for i in range(len(s)):
if 47 < ord(s[i]) < 58: # number
num += int(s[i])
elif 96 < ord(s[i]) < 123 or 64 < ord(s[i]) < 91:
slist.append(s[i])
slist.sort()
# for i in range(len(slist)):
# print(slist[i], end='')
print(''.join(slist), end='')
print(num)
... | dongho108/ThisIsCodingTestByPython | implement/replaceStr.py | replaceStr.py | py | 351 | python | en | code | 0 | github-code | 36 |
30321707707 | from unittest.mock import patch
import unittest
import os
import uuid
from datetime import datetime
import cmr.util.common as com
# ******************************************************************************
class TestSearch(unittest.TestCase):
"""Test suit for Search API"""
# **************************... | nasa/eo-metadata-tools | CMR/python/test/cmr/util/test_common.py | test_common.py | py | 6,735 | python | en | code | 25 | github-code | 36 |
11784656842 | from aiogram import Dispatcher
from aiogram.types import Message
from database.database import GAME_USERS
from lexicon.lexicon_ru import LEXICON_RU
async def send_reverse_answer(message: Message):
if message.from_user.id not in GAME_USERS:
await message.reply('\n'.join([message.text[::-1], LEXICON_RU['sm... | faralost/ichiraku-telegram-bot | handlers/other_handlers.py | other_handlers.py | py | 662 | python | en | code | 2 | github-code | 36 |
21477740913 | import sys
direction = [(-1, 0), (0, 1), (1, 0), (0, -1)] # 시계방향순
# 빙산을 탐색한 갯수를 찾는 함수
def check(r,c):
global cnt
cnt = 1
stack = [(r,c)]
visited = [[False] * m for i in range(n)]
visited[r][c] = True
while stack:
r, c = stack.pop()
for i in range(4):
nx = r + direc... | Minsoo-Shin/jungle | week03/2573_빙산 copy.py | 2573_빙산 copy.py | py | 1,877 | python | ko | code | 0 | github-code | 36 |
26804643066 | # -*- coding: utf-8 -*-
import pymysql
import itertools
if __name__ == "__main__":
pre_deal()
#search all of the entities from db and remove duplicated entries.
def pre_deal():
db = pymysql.connect("localhost", "root", "302485", "imdb", charset='utf8')
cursor = db.cursor()
search_sql = """sea... | LYunCoder/imdb_analysis | subgraph_wikidata/construct_relations.py | construct_relations.py | py | 2,079 | python | en | code | 0 | github-code | 36 |
26755881531 | import random
class MT19937:
W, N, M, R = 32, 624, 397, 31
A = 0x9908B0DF
U, D = 11, 0xFFFFFFFF
S, B = 7, 0x9D2C5680
T, C = 15, 0xEFC60000
L = 18
F = 1812433253
index = N + 1
lower_mask = (1 << R) - 1
upper_mask = (not lower_mask) & ((1 << W) - 1)
def __init__(self, seed):
... | dominicle8/cryptopals | 3_21.py | 3_21.py | py | 1,466 | python | en | code | 0 | github-code | 36 |
43041407676 | import sys
a = int(sys.argv[1])
b = int(sys.argv[2])
c = int(sys.argv[3])
def solve_equation(a, b, c):
d = b * b - 4 * a * c
if d > 0:
x1 = (-b + d ** 0.5) / 2 * a
x2 = (-b - d ** 0.5) / 2 * a
return ("{0}\n{1}".format(int(x1), int(x2)))
elif d == 0:
x1 = x2 = -b / 2 * a
return ("{0}\n... | AlexanderdeI/python_coursera | week_01/solution_03.py | solution_03.py | py | 463 | python | en | code | 0 | github-code | 36 |
26676026029 | a,b,c = (int(x) for x in input().split())
lis= [a,b,c]
sum = a+b+c
for i in range(len(lis)-1):
for j in range(i+1,len(lis)):
if lis[i] == lis[j]:
print(sum - (lis[i]*2))
exit()
print(0)
| MasaIshi2001/atcoder | ABC/ABC203_1.py | ABC203_1.py | py | 226 | python | en | code | 0 | github-code | 36 |
27281502055 | """project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | mikha1lov/headway | project/urls.py | urls.py | py | 1,515 | python | en | code | 0 | github-code | 36 |
8290193445 | from lxml import etree as ET
def parse_params_xmlfile(params_xml_file):
parameter = dict()
tree = ET.parse(params_xml_file)
root = tree.getroot()
global_parameter = root.find('global')
parameter['rpn_nms_thresh'] = float(global_parameter.find('rpn_nms_thresh').text)
parameter['rpn_f... | PauliKarl/shipdet | shipdet/datasets/parse.py | parse.py | py | 2,919 | python | en | code | 1 | github-code | 36 |
29976190660 | #!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as pl
from numba import autojit
import time
import sys
@autojit
def stochastic(t, eta, amplitude, frequency):
"""
Create time series of stochastic oscillations for a given damping rate
(eta), amplitude and frequency. From De Ridder et al. ... | jsk389/Stochastic-Simulations | Oscillations/oscillations.py | oscillations.py | py | 3,024 | python | en | code | 1 | github-code | 36 |
24835307446 | import aiologger
from aiologger.handlers.streams import AsyncStreamHandler
from aiologger.handlers.files import AsyncFileHandler
import logging
class MyFormatter(logging.Formatter):
def format(self, record):
return f"{record.created} - {record.name} - {record.levelname} - {record.msg}"
def setup_async_l... | bucin98/fast_api_coin_price | app/get_logger.py | get_logger.py | py | 830 | python | en | code | 0 | github-code | 36 |
15903331919 | """
CP1404/CP5632 Practical
A testing area for subject_reader.py
"""
FILENAME = "subject_data.txt"
def main():
data = get_data()
print(data)
def get_data():
"""Read data from file formatted like: subject,lecturer,number of students."""
things = []
input_file = open(FILENAME)
for line in inp... | azariahpundari1/cp1404practicals | prac_04/subject_reader_test.py | subject_reader_test.py | py | 517 | python | en | code | 0 | github-code | 36 |
21301309349 | from celery.decorators import task
from tracker import celery_app
from api.models import User, Tracker
from core_listing_scraper import get_current_listings, make_dict
from mailgun_email_api.mailgun_email_api import send_confirmation_message, send_email_for_new_or_updated_listings
@task(name='create_tracker')
def cre... | brianleungwh/tracker | api/tasks.py | tasks.py | py | 2,626 | python | en | code | 0 | github-code | 36 |
21420497711 | import torch
import torch.nn as nn
import torch.nn.functional as F
## Defining the network
Hidden_layer = 64
Conv_kernel = 3
Conv_kerenl_time = 3
Padd_space = 1
Padd_time = 1
drop_out_level = 0.15
Bias = True
class Net(nn.Module):
def __init__(self):
super(Net,self).__init__()
#down layer 1
... | HMS-CardiacMR/DRAPR | InLineIntegration/network_arch.py | network_arch.py | py | 6,361 | python | en | code | 15 | github-code | 36 |
8089030032 | class Solution:
def findWords(self, words: List[str]) -> List[str]:
cache1 = set('qwertyuiopQWERTYUIOP')
cache2 = set('asdfghjklASDFGHJKL')
cache3 = set('zxcvbnmZXCVBNM')
def func(cache, word):
for x in word:
if x not in cache:
return ... | alankrit03/LeetCode_Solutions | 500. Keyboard Row.py | 500. Keyboard Row.py | py | 688 | python | en | code | 1 | github-code | 36 |
23458756442 | import logging
import os.path
import schedule
import time
import threading
import requests
import ip_provider
SERVER_ADDRESS = "http://{}:8080".format(os.getenv("KIOSK_SERVER", "localhost"))
CONNECTOR_SERVICE_ADDRESS = "/kiosksConnector"
AUTHENTICATION_HEADER_KEY = "Authentication"
SERVICE_CALL_INTERVAL_IN_SECONDS =... | z13z/Kiosks | kiosk-worker/alive.py | alive.py | py | 1,645 | python | en | code | 0 | github-code | 36 |
42911015376 | #define variables
standardCookieBatch= 12.0
standardCupsOfSugar= .33
standardCupsOfButter= .50
standardCupsOfFlour= 1.00
standardCostofSugar=.10
standardCostofButter=.25
standardCostofFlour=.10
#prompt user for input
userNumberOfCookies=float(input("How many cookies do you want to make?: "))
#calculation va... | FPU-CIS03/CIS312-Project2 | Mini-Project_LukeGiffen_2.py | Mini-Project_LukeGiffen_2.py | py | 2,377 | python | en | code | 0 | github-code | 36 |
28779315671 | """
Game of Life
author: Manny egalli64@gmail.com
info: http://thisthread.blogspot.com/2017/01/codeeval-game-of-life.html
https://www.codeeval.com/open_challenges/161/
"""
import sys
STEPS = 10
ALIVE = '*'
DEAD = '.'
def local_population(matrix, i, j):
result = 0
for row in [i-1, i, i+1]:
for c... | egalli64/pythonesque | ce/c161.py | c161.py | py | 1,459 | python | en | code | 17 | github-code | 36 |
9044071393 | """Sensor platform for Ambrogio Robot."""
from __future__ import annotations
from homeassistant.core import HomeAssistant
from homeassistant.const import (
ATTR_LOCATION,
ATTR_LATITUDE,
ATTR_LONGITUDE,
)
from homeassistant.components.device_tracker import SOURCE_TYPE_GPS
from homeassistant.components.devic... | sHedC/homeassistant-ambrogio | custom_components/ambrogio_robot/device_tracker.py | device_tracker.py | py | 2,892 | python | en | code | 2 | github-code | 36 |
10762317060 | from action_msgs.msg import GoalStatus
import rclpy
from rclpy.action import ActionClient
from rclpy.node import Node
from handy_msgs.action import Nav
from nav_msgs.msg import Path
from geometry_msgs.msg import PoseStamped
class MinimalActionClient(Node):
def __init__(self):
super().__init__('nav_instr... | bresilla/webo | webots_ros2_pioneer3at/webots_ros2_pioneer3at/path_server/instruct.py | instruct.py | py | 3,278 | python | en | code | 0 | github-code | 36 |
21428748001 |
import util.utilcube as utilcube
import util.spicube as spicube
import numpy as np
import time
import itertools
class blocks:
def __init__(self):
self.ex = False
def exit(self):
self.ex = True
def full_color_change(self):
grad = utilcube.get_grad_array()
while True:
... | ThomasMoellerR/11_02_rpi_cube | animations/blocks.py | blocks.py | py | 550 | python | en | code | 0 | github-code | 36 |
35713960656 | from mercurial.i18n import _
from mercurial.node import nullid, short
from mercurial import commands, cmdutil, hg, util, url, error
from mercurial.lock import release
def fetch(ui, repo, source='default', **opts):
'''pull changes from a remote repository, merge new changes if needed.
This finds all changes fr... | helloandre/cr48 | bin/mercurial-1.7.5/hgext/fetch.py | fetch.py | py | 5,611 | python | en | code | 41 | github-code | 36 |
22524801892 | from .extentions import (
login_manager,
db,
moment,
bootstrap,
avatarTeam,
avatarUser,
coverPost,
imgTeam,
coverUser,
commonImage,
ckeditor,
nav,
mail
)
from flask_uploads import patch_request_class, configure_uploads
from .config import config
from ... | Honglin-Li/TravelPlatform | app/__init__.py | __init__.py | py | 6,069 | python | en | code | 0 | github-code | 36 |
38380439299 | import matplotlib.pyplot as plt
import numpy as np
import netCDF4
def plot( file,ofile=None):
nc = netCDF4.Dataset( file )
fn = file.rpartition("/")[-1]
label = fn.split("_")[0]
var = nc.variables[label]
long_name = var.long_name
units = var.units
if len(var.shape) > 2:
print ( var.dimensions )
v... | cp4cds/cmip6_range_check_old | scripts/plot2.py | plot2.py | py | 1,090 | python | en | code | 1 | github-code | 36 |
74572928422 | from flask import Flask,render_template
from os import path
from flask_misaka import markdown,Misaka
from LocalStorageBackend import folderlist
##### this is the Template jinja stuff for the webpage
app = Flask(__name__, template_folder="views")
### need this line for the Misaka markdown rendering
Misaka(app,fenced_co... | gabrielmccoll/Simple-Terraform-Registry | LocalStorageGUI.py | LocalStorageGUI.py | py | 2,087 | python | en | code | 4 | github-code | 36 |
24706362299 | import pygame
from Snake import Snake
from Segment import Segment
class Player(Snake):
def __init__(self,x,y,w,h,filePath, winDims):
super().__init__(x,y,w,h,filePath)
self.winDims = winDims
def update(self,orbs,snakes):
self.calculateDirection()
return super().updat... | MCK144/Slither.io | Player.py | Player.py | py | 777 | python | en | code | 0 | github-code | 36 |
9659112930 | #!/usr/bin/env python
# coding: utf-8
# @Author: lapis-hong
# @Date : 2018/5/3
"""Prob 21. Merge Two Sorted Lists
https://leetcode.com/problems/merge-two-sorted-lists/description/
Description:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes o... | Lapis-Hong/Leetcode | python/easy/21.Merge-Two-Sorted-Lists.py | 21.Merge-Two-Sorted-Lists.py | py | 1,862 | python | en | code | 8 | github-code | 36 |
5807342443 | import heapq
class puzzle:
def __init__(self):
self.moves = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def input(self, state):
for i in range(9):
state.append(int(input(f"Enter element in position {i + 1}: ")))
return state
def hamming_distance(self, current_state, goal_state)... | varad-kadam/8-Puzzle | 8_puzzle_A*_hamming.py | 8_puzzle_A*_hamming.py | py | 2,274 | python | en | code | 0 | github-code | 36 |
21489617325 | import os
import pickle
from autoencoder.models import Encoder, Classifier
PARAM_LIMIT = 5e6
SIZE_LIMIT_MB = 20
ACC_THRESHOLD = 0.5
def load_model(model_path):
model_dict = pickle.load(open(model_path, "rb"))["classifier_pt1"]
encoder = Encoder(
model_dict["encoder_hparam"],
model_dict["enc... | chloeskt/deep_learning_topics | autoencoder/autoencoder/utils.py | utils.py | py | 1,119 | python | en | code | 0 | github-code | 36 |
40186857847 | # import community
import numpy as np
import networkx as nx
import matplotlib as mpl
from matplotlib.pyplot import imshow
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
import pygraphviz
from networkx.drawing.nx_agraph import write_dot, graphviz_layout
import random
import pydoc
from ds import Mc... | afshinbigboy/itmt | src/test.py | test.py | py | 1,675 | python | en | code | 0 | github-code | 36 |
31422423491 | from __future__ import barry_as_FLUFL, print_function, division
__version__ = '0.1'
__author__ = 'Maryam Najafian'
"""
* Implementing Part of Speech (POS) tagging
* Using RNN in Tensorflow
structure: Embedding --> GRU --> Dense
* INPUTs are one hot encoded words and OUTPUTs are tags
* Measure F1-score and accur... | MaryamNajafian/Tea_Maryam_NLP | Code/pos_tf.py | pos_tf.py | py | 8,941 | 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.