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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
18441378219 | import sys
input = sys.stdin.readline
INF = 10**11
A,B,Q = map(int,input().split())
s = [-INF] + [int(input()) for _ in range(A)] + [INF]
t = [-INF] + [int(input()) for _ in range(B)] + [INF]
def binary_search(lis,x):
ok = 0
ng = len(lis)-1
while ng-ok > 1:
mid = (ok+ng)//2
if lis[mid] < x:
... | Aasthaengg/IBMdataset | Python_codes/p03112/s286406550.py | s286406550.py | py | 884 | python | en | code | 0 | github-code | 90 |
30809083621 | import turtle
from random import randint
# Set the background color
screen = turtle.Screen()
screen.bgcolor('white') # black
# Create a turtle
t = turtle.Turtle()
t.width(2)
t.color('red')
t.speed(100)
# side_length = 1366 / 2 = 683
# side_length2 = 768 / 2 = 384
def draw_rectangle():
t.penup()
t.goto(-68... | RyanSun1112/Python | Turtles/Square.py | Square.py | py | 964 | python | en | code | 0 | github-code | 90 |
42369272385 | import pdb
import os
import copy
from collections import defaultdict
import requests
import torch
from torch import nn
from transformers import AutoModel, AutoTokenizer
import numpy as np
import torchvision
from . import constants
class MedCLIPTextModel(nn.Module):
def __init__(self,
bert_type=constants.... | RyanWangZf/MedCLIP | medclip/modeling_medclip.py | modeling_medclip.py | py | 18,131 | python | en | code | 270 | github-code | 90 |
14409565712 | import sys
import os
from functools import reduce
filePath = "{}/in1.txt".format(os.path.dirname(os.path.abspath(__file__)))
if sys.argv[-1] == "local":
sys.stdin = open(filePath, "rt")
cardList = [i for i in range(1, 21)]
for i in range(10):
parms = list(map(int, input().split()))
startPoint = parms[0]... | ehghksvjscl/python-algorithm | 파이썬 알고리즘 문제풀이(코딩테스트 대비)/섹션 3/3. 카드 역배치/AA.py | AA.py | py | 574 | python | en | code | 0 | github-code | 90 |
70588233258 | import REUParsing as rp
import REULeakage as rl
import numpy as np
import pickle
import conllu
import networkx as nx
from tqdm import tqdm
from matplotlib import pyplot as plt
from scipy.spatial import distance
import os
import sys
MIN_TREES = 1
# Creates sparse vectors for every treebank in the train and test sets
d... | miriamwanner/reu-nlp-project | Leakage and How to Measure it/Sub-Tree Based Leakage/ComputeLeakage.py | ComputeLeakage.py | py | 6,110 | python | en | code | 1 | github-code | 90 |
1215661857 | import tkinter as tk
import datetime
import time
x = datetime.datetime.now()
window = tk.Tk()
window.title("Digital Clock")
canvas = tk.Canvas(window, height=200, width=500)
canvas.pack()
frame = tk.Canvas(window, bg='#696969')
frame.place(relx=0, rely=0, relheight=1, relwidth=1)
def get_time():
hour_min = ti... | newtechnovice/digital-clock | Digital Clock.py | Digital Clock.py | py | 1,777 | python | en | code | 1 | github-code | 90 |
69881607976 |
import numpy as np
from imageio import imread
from keras.preprocessing.image import ImageDataGenerator
from dtoolai.utils import identifiers_where_overlay_is_true
def tile_generator(im, ts=256):
rows, cols = im.shape[0], im.shape[1]
nr = rows//ts
nc = cols//ts
for r in range(nr):
for c ... | jic-dtool/dtoolai | dtoolai/__init__.py | __init__.py | py | 3,142 | python | en | code | 0 | github-code | 90 |
16425701881 | from django import forms
from .models import Seller
from applications.product.models import Product
class FormCreateProduct(forms.ModelForm):
class Meta:
model = Product
fields = ('name_product', 'description_product', 'price_product', 'quantity_product', 'code_product', 'categories_product')
... | kristianrpo/PriceByte | applications/seller/forms.py | forms.py | py | 409 | python | en | code | 1 | github-code | 90 |
2207410980 | import csv, codecs
import random
file = "../exam/students.csv"
fp = codecs.open(file, "r", "utf-8")
reader = csv.reader(fp, delimiter=',', quotechar='"')
with codecs.open('./output.csv', 'w', 'utf-8') as ff:
writer = csv.writer(ff, delimiter=',', quotechar='"')
for cells in reader:
print(cells[0], ce... | pidokige02/Python_study | hello-master/mytests/cd1.py | cd1.py | py | 490 | python | en | code | 1 | github-code | 90 |
5496866726 | delta = 0.02
delta_alfa = 1
omega = 4000 / 60
DATA_FILE_NAME = 'new_M_kr.txt'
if __name__ == "__main__":
M_kr_arr = []
with open(DATA_FILE_NAME) as f:
for line in f:
M_kr_arr.append(float(line.rstrip().replace(',','.')))
M_sr = sum(M_kr_arr) / len(M_kr_arr)
F = 0
for M_kr in ... | rakhimgaliyev/course_project | dynamics/1/moment_mahovika.py | moment_mahovika.py | py | 693 | python | en | code | 0 | github-code | 90 |
40199663795 | # -*- coding: utf-8 -*-
import curses
import curses.ascii
import logging
from sys import version_info, platform, version
try:
from .cjkwrap import PY3, is_wide, cjklen
except:
from cjkwrap import PY3, is_wide, cjklen
import locale
locale.setlocale(locale.LC_ALL, '') # set your locale
logger = logging.getLog... | codedarkness/pyradio | config-files/master/pyradio/simple_curses_widgets.py | simple_curses_widgets.py | py | 102,269 | python | en | code | 0 | github-code | 90 |
14074547730 | import pandas as pd
from pathlib import Path
from .settings import Settings
"""
def test_same_df(df1, df2):
# A function that verifies whether two Pandas DataFrames are in fact the same.
# NOTE: This function is overridden below.
try:
for cols in [[x for x in df1.columns], [x for x in df2.columns]]... | kallewesterling/drag-data-1930s | dataset/cache.py | cache.py | py | 3,200 | python | en | code | 0 | github-code | 90 |
7307215359 | from typing import Text, List, Iterable, Callable
from collections import deque
def search_eval(evaluator: Callable[[Text], bool], alphabet: Iterable[Text]) -> List[Text]:
"""Search for all non overlapping combination of alphabet's symbols that are accepted by evaluator
Args:
evaluator Callable(word)... | pointtonull/algorithms | src/radix_search.py | radix_search.py | py | 1,450 | python | en | code | 0 | github-code | 90 |
40439254029 | #!/usr/local/bin/python
import os
import json
import sys
def main():
file_hall_mark_gene_set="/data/project/MSG/lib/hallmark_genes_msigdb.txt"
file_json = "/data/project/MSG/lib/hallmark_genes_msigdb.json"
hall_info={}
temp={}
with open(file_json, "w") as f_out:
with open(file_hall_mark_gene_set, "r") as f_hal... | biovlab/biovlab_mcpg_snp_express | bin/formatting_hallmark_data.py | formatting_hallmark_data.py | py | 644 | python | en | code | 0 | github-code | 90 |
11028811529 | # product database was taken from here
# https://www.ars.usda.gov/northeast-area/beltsville-md-bhnrc/beltsville-human-nutrition-research-center/methods-and-application-of-food-composition-laboratory/mafcl-site-pages/sr11-sr28/
# background img was taken from https://unsplash.com/photos/lcZ9NxhOSlo
import os
from cs5... | NataTimos/CS50-Final-Project-Nutritions | application.py | application.py | py | 17,495 | python | en | code | 2 | github-code | 90 |
72208057258 | """
一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。
示例 1:
输入:nums = [4,1,4,6]
输出:[1,6] 或 [6,1]
示例 2:
输入:nums = [1,2,10,4,1,4,3,3]
输出:[2,10] 或 [10,2]
限制:
2 <= nums <= 10000
"""
import functools
from typing import List
class Solution:
def singleNumbers(self, nums: List[int]) -> ... | Asunqingwen/LeetCode | 每日一题/数组中数字出现的次数.py | 数组中数字出现的次数.py | py | 915 | python | zh | code | 0 | github-code | 90 |
74069364138 | from pathlib import Path
import tempfile
from unittest import mock
from aetherscale.services import SystemdServiceManager
def test_systemd_creates_file(tmppath: Path):
systemd = SystemdServiceManager(tmppath)
with tempfile.NamedTemporaryFile('wt') as f:
f.write('[Unit]')
f.flush()
sy... | aufziehvogel/aetherscale | tests/test_services.py | test_services.py | py | 1,462 | python | en | code | 0 | github-code | 90 |
18487592263 | class Codec:
def encode(self, strs: list[str]) -> str:
"""Encodes a list of strings to a single string.
"""
List = []
for i in strs:
for j in i:
if j == ' ':
List.append('\t')
else:
List.append(j)
... | comeonboi/algorithm-practise | loong's code/leetcode/editor/cn/271.py | 271.py | py | 1,074 | python | en | code | 5 | github-code | 90 |
6553593026 | #global variables, we will access throughout the program
accountantSalaryVar = 100000
dataAnalystSalaryVar = 100000
contractorSalaryVar = 80000
employeeCap = 10
totalAllowedBudget = '$960,000'
actualBudget = '$1,500,000'
#more global variables, we will access throughout the program
listOfEmployees = ['Ronald', 'Bi... | natestrong/ucla-data-science | module 0/Python_3_game/python3Game.py | python3Game.py | py | 2,199 | python | en | code | 0 | github-code | 90 |
1281063905 | import logging.config
import os
from flask import Flask, Blueprint
from itsajungleoutthere import settings
from itsajungleoutthere.api.routes.image import ns as images_namespace
from itsajungleoutthere.api.routes.tag import ns as tags_namespace
#from itsajungleoutthere.api.routes.dataset import ns as datasets_namespace... | Policonickolu/itsajungleoutthere | itsajungleoutthere/app.py | app.py | py | 1,759 | python | en | code | 0 | github-code | 90 |
22728318084 | # coding=utf-8
"""
@Time : 2020/12/26 11:17
@Author : Haojun Gao (github.com/VincentGaoHJ)
@Email : vincentgaohj@gmail.com haojun.gao@u.nus.edu
@Sketch :
"""
import os
import shutil
from utils.config import EXPERIMENT_DIR
def init(data_dir):
"""
准备工作
:param data_dir: 要 Text Rank 的数据文件夹
:return:... | VincentGaoHJ/Automatic-Taxonomy-Generation-based-on-Nonnegative-Matrix-Factorization | src/graphviz/func.py | func.py | py | 1,770 | python | en | code | 1 | github-code | 90 |
5327582486 | from sklearn.neural_network import MLPRegressor
import numpy as np
import sklearn
import pickle
import random
import pdb
import pandas as pd
import math
import numpy as np
from sklearn.externals import joblib
import warnings
warnings.filterwarnings("ignore")
import pandas as pd
from sklearn.metrics import mean_square... | deepsahni11/CILreal | regressor_predictions.py | regressor_predictions.py | py | 5,324 | python | en | code | 0 | github-code | 90 |
18290751669 | n=int(input())
a=[]
for i in range(n):
st,IN=map(str,input().split())
a.append([st,IN])
a=a[::-1]
x=input()
ss=0
for y in a:
if y[0]==x:
break
ss+=int(y[1])
print(ss)
| Aasthaengg/IBMdataset | Python_codes/p02806/s670583345.py | s670583345.py | py | 191 | python | en | code | 0 | github-code | 90 |
18369845739 | N=int(input())
A=[int(input()) for i in range(N)]
import bisect
B=[]
C=A[::-1]
for i in C:
a=bisect.bisect_right(B,i)
if a==len(B):
B.append(i)
else:
B[a]=i
print(len(B)) | Aasthaengg/IBMdataset | Python_codes/p02973/s722107537.py | s722107537.py | py | 184 | python | en | code | 0 | github-code | 90 |
43580262040 | # Imports
from flask import Flask
from flask_restful import Api
from flask_cors import CORS
import os
from predictions.Predict import Predict
from scheduling.Schedule import Schedule
UPLOAD_FOLDER = 'uploads'
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
for filename in os.listdir(UPLOAD_FOLDER... | jesgararm/GestorQuirofanos | API/src/app.py | app.py | py | 775 | python | en | code | 0 | github-code | 90 |
33062563786 | # -*- coding: utf-8 -*-
"""
Read and parse MCNP file text.
"""
from attr import attrs, attrib
from itertools import repeat
from pathlib import Path
from typing import Iterable, Union, TextIO, Optional, Generator, Callable, List, Tuple, NewType, Any
from .mcnp_section_parser import (
parse_sections_text, distribut... | rorni/mckit | mckit/parser/mcnp_input_sly_parser.py | mcnp_input_sly_parser.py | py | 7,623 | python | en | code | 3 | github-code | 90 |
73888036138 | import os
import joblib
from ml.data.BaseDataset import BaseDataset
from ml.random_forest.RandomForestModel import RandomForestModel
class RandomForestModelFactory(object):
def __init__(self, name='random_forest', predict_day=3, chart_size=60, batch_size=1000, new_model=False, path=None):
"""
d... | huangyuan3h/StockData | ml/random_forest/RandomForestModelFactory.py | RandomForestModelFactory.py | py | 1,335 | python | en | code | 1 | github-code | 90 |
15597668926 |
from collections import OrderedDict
from Classes_and_Functions.Class_Neural_Network_Training_Valid import Neural_Network_Training_Valid
from Classes_and_Functions.Class_Architecture import Model_Architecture
from Classes_and_Functions.Class_Other_Parameters import Other_Parameters
from Classes_and_Functions.H... | Ranim-94/Stage_Cense_2020 | Code/Main_Training.py | Main_Training.py | py | 3,300 | python | en | code | 1 | github-code | 90 |
30636181100 | from enum import Enum
import tkinter as tk
from PIL import Image, ImageTk
from .node import create_node, Node
from . import network
class Mode(Enum):
NONE = 0
ADD_NODE = 1
ONE_WAY_LINK = 2
TWO_WAY_LINK = 3
DFS = 4
BFS = 5
DIJKSTRA = 6
class Menubar(tk.Menu):
def __init__(self, *args... | nurlybek-dev/visual-graph | src/app.py | app.py | py | 9,457 | python | en | code | 0 | github-code | 90 |
31879886384 | import uuid
import yaml
from .constants import CONFIG_TYPES, APPLIANCE_TYPES
class NetworkConfig:
def __init__(self, config_file):
self.config_file = config_file
self.config = {}
for config_type in CONFIG_TYPES:
self.config[config_type] = {}
def appliance_exists(self, name... | mineiwik/network-lab | network_gen/utils/network.py | network.py | py | 3,635 | python | en | code | 0 | github-code | 90 |
22367021569 | # from dataloaders.datasets import cityscapes, kd, coco, combine_dbs, pascal, sbd
from torch.utils.data import DataLoader
import torch.utils.data.distributed
from SimpleITK import *
import SimpleITK as sitk
from os.path import join
import numpy as np
import math
def make_data_loader(args,**kwargs):
data_dict={}
... | wei-ln/seg_medical_autodeeplab | dataloaders/__init__.py | __init__.py | py | 11,265 | python | en | code | 1 | github-code | 90 |
28940050098 | # -*- coding: utf-8 -*-
import cv2
import numpy as np
'''
소벨 필터는 커널의 중심에서 멀어질수록 엣지 방향성의 정확도가 떨어진다.
이를 개선한 필터가 샤르 필터이다.
'''
img = cv2.imread('../img/sudoku.jpg')
# 샤르 커널을 직접 생성해서 엣지 검출
gx_k = np.array([[-3, 0, 3], [-10, 0, 10], [-3, 0, 3]])
gy_k = np.array([[-3, -10, -3], [0, 0, 0], [3, 10, 3]])
edge_gx... | syjung0130/opencv_python_sample | ch6_filter/edge_sharpening/edge_scharr.py | edge_scharr.py | py | 840 | python | ko | code | 0 | github-code | 90 |
74736022 | size = int(input())
input_ = list(map(int, input().split(' ')))
compare = input_.copy()
input_.sort()
di = []
for i in range(size):
di.append([i,input_[i]])
result = []
for i in range(size):
for j in range(size):
if di[j][1] == compare[i]:
result.append(di[j][0])
di[j][1] = max... | YeongHyeon-Kim/BaekJoon_study | 0413/1015_수열정렬.py | 1015_수열정렬.py | py | 621 | python | ko | code | 1 | github-code | 90 |
4072678578 | from collections import defaultdict
from django.conf import settings
import os
BASE_PATH = settings.BASE_DIR
class MixinBase:
template_name = "demo.html"
demo_template = None
subtitle = None
def get_files(self):
files = defaultdict(list)
path_ = lambda x: open(os.path.join(BASE_PATH,... | zodman/django-sockpuppet-expo | core/views/mixins.py | mixins.py | py | 2,527 | python | en | code | 13 | github-code | 90 |
3482032514 | #Author: Akshay Prakash
from tkinter import *
from tkinter.filedialog import *
filename = None
def newFile():
global filename #Using the global varibale
filename = "Untitled" #Because whenever you create a new file it is untitled
text.delete(0.0, END)
def saveFile():
global filename
... | aprakash7/texteditor | TextEditor.py | TextEditor.py | py | 1,705 | python | en | code | 1 | github-code | 90 |
73523801896 | import os
from flask import Flask
from flask_cognito import CognitoAuth
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from dotenv import load_dotenv
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
basedir = os.getcwd()
load_dotenv()
ap... | kybrdbnd/flask-sample-app | employee_management/__init__.py | __init__.py | py | 1,612 | python | en | code | 0 | github-code | 90 |
33105539150 | with open('dataset_3363_2.txt') as arr_in:
s = arr_in.readline().strip()
s_list = []
num = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
]
for i in range(len(s)):
char = s[i]
if char in num and i != len(s)-1:
if s[i-1] in num:
continue
elif s[i+1] not in num:
... | Evgeniy1984No/Learning | Stepik.org_The first course/stepik.org_files.py | stepik.org_files.py | py | 680 | python | en | code | 0 | github-code | 90 |
15231680980 | import logging
import urllib.parse
import requests
from os import path
from typing import Any, Callable, List, Literal, Optional, IO
from e2b.constants import TIMEOUT, ENVD_PORT, FILE_ROUTE
from e2b.sandbox.code_snippet import CodeSnippetManager, OpenPort
from e2b.sandbox.env_vars import EnvVars
from e2b.sandbox.file... | e2b-dev/e2b | packages/python-sdk/e2b/sandbox/main.py | main.py | py | 7,323 | python | en | code | null | github-code | 90 |
7756953614 | import unittest
import os
from app.logic.battle_manager import BattleManager
from app.logic.config_manager import ConfigManager
class TestConfigManager(unittest.TestCase):
def setUp(self):
# Create a temporary test config directory and file
self.temp_config_dir = os.path.join(os.path.expanduser("~... | onecrazygenius/cursedmage | tests/unittest/app/logic/test_config_manager.py | test_config_manager.py | py | 3,162 | python | en | code | 3 | github-code | 90 |
33405837457 | import tkinter
from tkinter import *
from tkinter.messagebox import *
from tkinter.filedialog import *
import os
class Notepad:
def __init__(self, **kwargs):
self.root = Tk()
self.width = 400
self.height = 400
self.text = Text(self.root)
self.menubar = Menu(self.... | NimmagaddaHarshini/Notepad-Clone | notepad.py | notepad.py | py | 3,994 | python | en | code | 0 | github-code | 90 |
6438810571 | # 삽입 정렬
# 두 번째 데이터부터 적절한 위치를 찾아 그 위치에 삽입한다
# 시간복잡도 O(n^2)
# 삽입 정렬은 거의 정렬되어 있는 상태라면 매우 빠르게 동작한다
arr = [7,5,9,0,3,1,6,2,4,8]
for i in range(1,len(arr)):
for j in range(i,0,-1):
if arr[j] < arr[j-1]:
arr[j], arr[j-1] = arr[j-1], arr[j]
else:
break
print(arr)
| namoo1818/SSAFY_Algorithm_Study | 이민지/[4주차]정렬/6-3.py | 6-3.py | py | 436 | python | ko | code | 0 | github-code | 90 |
18587837959 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 15:39:14 2020
@author: liang
"""
N = int(input())
A = [int(x) for x in input().split()]
d = [0]*N
ans = 0
for a in A:
if a > N :
ans += 1
else:
d[a-1] += 1
for i in range(N):
if d[i] > 0:
if d[i] > i+1:
ans += d[i] - (i... | Aasthaengg/IBMdataset | Python_codes/p03487/s851485042.py | s851485042.py | py | 391 | python | en | code | 0 | github-code | 90 |
18379540499 | N, L = list(map(int, input().split()))
ans = 0
l = N + abs(L)
for i in range(N):
a = L + i
if abs(a) < abs(l):
l = a
ans += a
print(ans - l)
| Aasthaengg/IBMdataset | Python_codes/p02994/s716943343.py | s716943343.py | py | 147 | python | en | code | 0 | github-code | 90 |
32361522886 | """
2.3 Delete Middle Node
Implement an algorithm to delete a node in the middle (i.e any node
but the first and last node, not necessarily the exact middle)
of a single linked list, given only access to that node.
"""
class Node:
def __init__(self,data):
self.data = data
self.next = None
def del... | simranjmodi/cracking-the-coding-interview-in-python | chapter-02/exercise-2.3.py | exercise-2.3.py | py | 472 | python | en | code | 0 | github-code | 90 |
73759543336 | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn import svm
df_e = pd.read_csv('geglobo_user_tweets.csv')
df_e_2 = pd.read_csv('globoesporters_user_tweets.csv')
df_e_3 = pd.read_csv('UOLEsporte_user_tweets.csv')
d... | PatrickLopesF/esporte_ou_politica | project.py | project.py | py | 3,226 | python | en | code | 1 | github-code | 90 |
73340191975 | # -*- coding: utf-8 -*-
import socket
class Client:
"""
This is the chat client class
"""
def __init__(self, host, server_port):
"""
This method is run when creating a new Client object
"""
# Set up the socket connection to the server
self.connection = socket.s... | FuelFighter/FF_GUI | recieve_client.py | recieve_client.py | py | 1,167 | python | en | code | 0 | github-code | 90 |
34546004638 | """
Script for converting Budget pdfs
Usage:
converter.py --idir=<id> [--odir=<od>] [--fformat=<f>]
Options:
--idir=<id> Provide input directory that has all pdfs
--odir=<od> Provide output directory that should have the output files
--fformat=<f> Provide the output format, eg: txt, xml, htm... | CivicDataLab/LABS | converter.py | converter.py | py | 862 | python | en | code | 1 | github-code | 90 |
42552060577 | # elegir lo que quieras en la tienda
import libreria
def Elegir_Manzana():
a=libreria.pedir_listas("frutas.txt")
print(a[0])
def Elegir_Naranja():
b=libreria.pedir_listas("frutas.txt")
print(b[1])
def Elegir_Uva():
c=libreria.pedir_listas("frutas.txt")
print(c[2])
def Mostrar_Frutas():
... | jose-brenis-lanegra/T10_Brenis.Niquen | Submenu02.py | Submenu02.py | py | 2,988 | python | es | code | 0 | github-code | 90 |
32890511387 | import bpy
from .blmfuncs import ShowMessageBox
bpy.types.PoseBone.constraint_active_index = bpy.props.IntProperty()
readonly_attr = ['__doc__', '__module__', '__slots__', 'bl_rna', 'error_location',
'error_rotation', 'is_proxy_local', 'is_valid', 'rna_type', 'type']
class QC_OT_contraint_action(b... | Irmitya/bone_layer_manager | constraint_operators.py | constraint_operators.py | py | 8,506 | python | en | code | 10 | github-code | 90 |
38844584216 | # coding:utf-8
import json
import os
import random
import string
from datetime import datetime
import urllib.parse
from apis.base import Base
from common.tools import get_content_type
from common.tools import retry
from common.define_exception import DException as Exc
from requests_toolbelt import MultipartEncoder
c... | zj1995-09-09/supercare_api | apis/device_management/device_account/apis_device_account.py | apis_device_account.py | py | 21,929 | python | en | code | 0 | github-code | 90 |
35715700110 | import pandas as pd
from elasticsearch import Elasticsearch
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import norm # Mainly used for the z-statistics
import seaborn as sns; sns.set_theme() # For the heatmap
from gurobipy import Model, GRB
from matplotlib.patches import Rectangle
pd.... | lucaskrol990/Code-portfolio | Python/Warehouse-planning/main.py | main.py | py | 20,445 | python | en | code | 0 | github-code | 90 |
5908175869 | # Problem description:
# https://leetcode.com/problems/valid-parentheses/
def is_valid(s):
stack = []
close_to_open = {')': '(', ']': '[', '}': '{'}
for char in s:
if char in close_to_open:
if stack and stack[-1] == close_to_open[char]:
stack.pop()
... | keremidarski/python_playground | LeetCode/0020_Valid_Parentheses.py | 0020_Valid_Parentheses.py | py | 583 | python | en | code | 0 | github-code | 90 |
36590114041 | import numpy as np
from typing import Tuple
from typing import Optional
import gym
from gym import spaces
from gym.utils import seeding
import torch
from torch.distributions import Normal # , Uniform
# from distance.soft_dtw import SoftDTW
"""
这个文件致力于探索environment较大幅度的改进,包括重用等等
待测试稳定后,再转移到environments.py上
"""
gym.lo... | sheldonresearch/Microsoft-Scoring-System | Bank/gym_hybrid/environments_beta.py | environments_beta.py | py | 23,126 | python | en | code | 0 | github-code | 90 |
18526403739 | def main():
n = int(input())
C = [1, ]
c = 6
while c < 100000:
C.append(c)
c *= 6
c = 9
while c < 100000:
C.append(c)
c *= 9
INF = float('inf')
dp = [INF] * (n + 1)
dp[0] = 0
for i in range(1, n + 1):
C_filtered = [c for c in C if c <= i]
... | Aasthaengg/IBMdataset | Python_codes/p03329/s693576642.py | s693576642.py | py | 431 | python | en | code | 0 | github-code | 90 |
41726128509 | import os
from pyevtk.vtk import (VtkPUnstructuredGrid,
VtkParallelFile,
)
from pyevtk.hl import _addDataToParallelFile
__all__ = ('writeParallelVTKUnstructuredGrid',)
def writeParallelVTKUnstructuredGrid(
path, coordsdtype, sources, ghostlevel=0, cellData=None, poi... | pyccel/psydac | psydac/utilities/vtk.py | vtk.py | py | 1,994 | python | en | code | 40 | github-code | 90 |
36533341592 | import requests
import git
import argparse
import json
import os
import datetime
class Build:
def __init__(self, json_dict):
self._json_dict = json_dict
@property
def number(self) -> int:
return self._json_dict['number']
@property
def web_url(self) -> str:
return self._json_dict['web_url']
... | google/llvm-premerge-checks | scripts/metrics/buildkite_master_stats.py | buildkite_master_stats.py | py | 3,414 | python | en | code | 41 | github-code | 90 |
31428859534 | import base64
import os
import cv2
import numpy as np
import os
import pyzbar.pyzbar as pyzbar
import psycopg2
conn = psycopg2.connect(host = 'localhost', database = 'banco', user = 'postgres', password='12345678')
cur = conn.cursor()
path = "imagens/"
dirs = os.listdir(path)
arquivo = eval(open("imagens.txt","r").r... | millerraycell/ProjetoFinal_RedesII | codigos/servidor/translator.py | translator.py | py | 1,059 | python | en | code | 0 | github-code | 90 |
42607399251 | from setuptools import setup, find_packages
version = '0.2.5'
setup(
name='pyrcws',
version=version,
description="pyrcws",
long_description="",
classifiers=[
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
],
keywords='redec... | renatogp/pyrcws | setup.py | setup.py | py | 580 | python | en | code | 11 | github-code | 90 |
22468195087 | import os, socket
from pyftpdlib.authorizers import DummyAuthorizer, AuthenticationFailed
from pyftpdlib.servers import FTPServer
from pyftpdlib.handlers import FTPHandler
def main():
PATH = '.'
os.chdir(PATH)
ip = socket.gethostbyname(socket.gethostname())
addr = (ip, 21)
authorizer = DummyAu... | MrVren/ftp-server | whatFTP.py | whatFTP.py | py | 1,249 | python | en | code | 1 | github-code | 90 |
25872145297 | import os
import csv
datapath=os.path.join("..","PyPoll","election_data.csv")
with open(datapath, 'r', newline="") as datafile:
datareader= csv.reader(datafile,delimiter=',')
dataheader=next(datareader)
# print(datareader)
# print(dataheader)
#count total votes made in this data set
#create l... | AlexandraOricchio/Python-challenge | PyPoll/PyPoll_Main.py | PyPoll_Main.py | py | 2,315 | python | en | code | 0 | github-code | 90 |
18025703279 | from collections import Counter
N = int(input())
a = list(map(int, input().split()))
na = len(set(a))
cnt = Counter(a)
ls = cnt.most_common()
lst = [ 2 for i in ls if i[1]%2==0]
if len(lst)%2==1:
print(na - 1)
else:print(na)
| Aasthaengg/IBMdataset | Python_codes/p03816/s417561051.py | s417561051.py | py | 232 | python | en | code | 0 | github-code | 90 |
14343545121 | import time, re
from collections import defaultdict
startTime = time.time()
# Opens file and reads steps and its pre-requisites
file = open("2018/inputs/day7.txt")
lines = file.read().strip().split("\n")
file.close()
stepsRegex = re.compile(r"Step (.) must be finished before step (.) can begin.")
stepsReq... | conradojordan/advent-of-code | 2018/python/day7part1.py | day7part1.py | py | 1,348 | python | en | code | 0 | github-code | 90 |
4007989461 | lunches_per_week = int(input("How many times a week do you eat at the student cafeteria? "))
price_per_lunch = float(input("The price of a typical student lunch? "))
grocery_cost_per_week = float(input("How much money do you spend on groceries in a week? "))
weekly_food_cost = lunches_per_week * price_per_lunch + groc... | MitenPatel-hub/helsinki_intro_python_mooc_2023 | completed_exercises/part01-19_food_expenditure/src/food_expenditure.py | food_expenditure.py | py | 497 | python | en | code | 0 | github-code | 90 |
20803703862 | from django.urls import path
from website.views import *
urlpatterns = [
path('', index_view, name = 'index'),
path('about', about_view, name = 'about'),
path('education', education_view, name = 'education'),
path('skills', skills_view, name = 'skills'),
path('projects', projects_view, name = 'proj... | alirafiei75/FirstCV | website/urls.py | urls.py | py | 383 | python | en | code | 0 | github-code | 90 |
41121386918 | import tornado.web
from tornado import gen
import database as DB
from database import Event,Team, Members, Points, PointToTeam,User
class BaseHandler(tornado.web.RequestHandler):
def initialize(self):
self.session = DB.Session()
def on_finish(self):
self.session.commit()
self.... | Monk-Liu/Orienteering | manager/handlers.py | handlers.py | py | 11,026 | python | en | code | 0 | github-code | 90 |
4422655578 | # -*- coding: utf-8 -*-
import json
from constants import DEFAULT_COVERAGE, ESTADOS_BRASIL
class SpiderCoverageMixin(object):
default_coverage = DEFAULT_COVERAGE
@classmethod
def check_multiple_coverage(cls, coverage_fields):
inter = len(set(ESTADOS_BRASIL).intersection(set(coverage_fields)))
... | arthurmoreno/spider-coverage | spidercoverage/mixins.py | mixins.py | py | 2,545 | python | en | code | 0 | github-code | 90 |
10751152415 | import struct
from io import BytesIO
from .base import load
def is_bmp(img):
"""
Checks whether the image represents a bitmap.
https://en.wikipedia.org/wiki/BMP_file_format#File_structure
:param img: the absolute path to the BMP image or a bytes/BytesIO object
:type img: str or bytes or BytesIO... | waikato-datamining/python-image-complete | src/image_complete/bmp.py | bmp.py | py | 1,413 | python | en | code | 0 | github-code | 90 |
37777824520 | from django import forms
from django.utils.translation import ugettext_lazy as _
from astrobin.models import SolarSystem_Acquisition
class SolarSystem_AcquisitionForm(forms.ModelForm):
error_css_class = 'error'
date = forms.DateField(
required=False,
input_formats=['%Y-%m-%d'],
widge... | astrobin/astrobin | astrobin/forms/solar_system_acquisition_form.py | solar_system_acquisition_form.py | py | 1,567 | python | en | code | 100 | github-code | 90 |
31381806134 | import win32gui
import win32ui
import win32con
import win32api
def set_wallpaper_from_bmp(bmp_path):
# 打开指定注册表路径
reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)
# 最后的参数:2拉伸,0居中,6适应,10填充,0平铺
win32api.RegSetValueEx(reg_key, "WallpaperStyle... | xahiddin/MyPython | GaoJi/Shot.py | Shot.py | py | 1,529 | python | en | code | 0 | github-code | 90 |
44872379408 | import sys
def recur(pos):
if pos == n:
if sum(temp) not in ans:
ans.append(sum(temp))
return
for j in range(4):
if table[j] < max(temp):
continue
temp[pos] = table[j]
recur(pos + 1)
temp[pos] = 0
n = int(sys.stdin.readline())
check ... | Quinsie/BOJ | Python/BOJ_16922_로마 숫자 만들기.py | BOJ_16922_로마 숫자 만들기.py | py | 419 | python | en | code | 0 | github-code | 90 |
39061207220 | # coding=utf-8
from datetime import datetime
from django.utils.translation import pgettext, ugettext as _
__all__ = ("date",)
def get_now(time):
return datetime.now(time.tzinfo)
def date(time):
now = get_now(time)
if time > now:
past = False
diff = time - now
else:
past =... | chi1231/wenda_backend | utils/pretty.py | pretty.py | py | 2,194 | python | en | code | 0 | github-code | 90 |
18534175149 | arr = input().split()
arr = list(map(int,arr))
a = arr[0]
b = arr[1]
c = arr[2]
d = arr[3]
if (abs(b - a) <= d and abs(c - b) <= d) or abs(a-c) <= d:
print('Yes')
else:
print('No')
| Aasthaengg/IBMdataset | Python_codes/p03351/s324094114.py | s324094114.py | py | 191 | python | en | code | 0 | github-code | 90 |
11586935261 | import requests
import json
url = 'https://api.n-cov.info/case'
try:
data = requests.get(url=url).json()
data = data["data"]
data = json.dumps(
data,
indent=2,
ensure_ascii=False,
)
f = open('data/hong-kong-data/raw.json', 'w')
f.write(data)
f.close()
except:
... | stevenliuyi/covid19 | data/hong-kong-data/crawler.py | crawler.py | py | 358 | python | en | code | 322 | github-code | 90 |
23217395132 | '''
*Assignment 3 - Edge Detection*
Script for cropping the text in an image and higlighting letters' edge contours using blurring and canny edge detection.
creating visual environmet, executing code from the terminal.
'''
# We need to include the home directory in our path, so we can read in our own module.
impor... | JakubR12/cds-visual-portfolio | assignments/assignment-3/src/edge_detection.py | edge_detection.py | py | 2,448 | python | en | code | 1 | github-code | 90 |
18410365209 | N = int(input())
s = []
for _ in range(N):
s.append(input())
in_str = 0
BX = 0
XA = 0
BA = 0
for str in s:
in_str += str.count('AB')
if str[0] == 'B' and str[-1] != 'A':
BX += 1
elif str[0] != 'B' and str[-1] == 'A':
XA += 1
elif str[0] == 'B' and str[-1] == 'A':
BA += 1
an... | Aasthaengg/IBMdataset | Python_codes/p03049/s901115423.py | s901115423.py | py | 467 | python | en | code | 0 | github-code | 90 |
12692108317 | import os
from learning_fc.callbacks import ProxyBaseCallback
class PeriodicSavingCallback(ProxyBaseCallback):
"""
Saves model all `save_freq` timesteps starting from `step_offset`.
"""
def __init__(self, save_path: str, save_freq: int = 0, offset: int = 0, verbose=1):
super(PeriodicSavingCa... | llach/learning_fc | learning_fc/callbacks/periodic_model_saving.py | periodic_model_saving.py | py | 1,104 | python | en | code | 0 | github-code | 90 |
13445620358 | import numpy as np
from numpy import pi, exp, sqrt
import matplotlib.pylab as plt
import cv2
from scipy.signal import convolve2d
import os
def compute_LoG(image, LOG_type=1):
if LOG_type == 1:
#method 1
sigma = 0.5
size = 5
# # Smoothing the image using gaussian filter
... | AnwarAsif/ComputerVision | lab2_Gabor_Segmentation_Image_Enhancement/Image_enhancement/compute_LoG.py | compute_LoG.py | py | 3,885 | python | en | code | 0 | github-code | 90 |
34856172393 | #Python sorting string using order defined by another string
str = "eksge"
pat = "asbcklfdmegnot"
priority = list(pat)
dict = {}
for i in range(len(priority)):
dict[priority[i]] = i
#print(dict)
str = list(str)
str.sort(key = lambda ele: dict[ele])
str.reverse()
print(''.join(str))
| mukulverma2408/PracticeGeeksforGeeks | PythonPracticeQuestion/Lambda.py | Lambda.py | py | 288 | python | en | code | 0 | github-code | 90 |
26122974494 | """
NAME
DimensionPlots
DESCRIPTION
This script plots the variation of the fractal dimension on a network
when the nodes are removed. The node to be removed is chosen according to
its centrality measure (degree, betweennes, closeness) or randomly.
This script generates two files:
-... | hernandcb/complexNetworksMeasurements | modules/dimensionPlots.py | dimensionPlots.py | py | 5,135 | python | en | code | 14 | github-code | 90 |
70049294697 | import json
def main():
date = "20160803"
# date can be modified
openfilepath = 'data/ga_sessions_'+date+'.json'
filepath = 'out/test' + date + ".json"
i = 0
outdict = {}
with open(filepath, "w") as fout:
with open (openfilepath, 'r') as fin:
for line in fin:
... | Asiotus/ga-etl | tests/test_data_generate.py | test_data_generate.py | py | 530 | python | en | code | 0 | github-code | 90 |
14775747502 | #射影変換を行い選手の位置情報を取得する(動画上と実際のコート上の選手の位置は異なるため)
import torch
import cv2
import numpy as np
import queue
from collections import deque
import math
import os
sequence = 0
frame_num = 0
#here
file_num = 719
casted_num = str(file_num)
#データ取得ファイル
course = "pull"
hand = "forehand"
model = torch.hub.load('ultralytics/y... | unione4/Pose-estimation-on-tennis | fore_pull_pos.py | fore_pull_pos.py | py | 6,170 | python | en | code | 0 | github-code | 90 |
9133811356 | import hashlib
import os
import warnings
from dataclasses import dataclass, asdict, field
from pathlib import Path
import torch
import torchaudio
from fastai.core import ifnone
from fastai.data_block import get_files
from fastprogress.fastprogress import progress_bar
from torchaudio.transforms import Spectrogram, MelSc... | potipot/fastai_audio | fastai_audio/config.py | config.py | py | 10,326 | python | en | code | null | github-code | 90 |
38394848565 | from flask import request
from utils.uitils import *
from db.db_config import *
menu_schema = MenuSchema()
menus_schema = MenuSchema(many=True)
menuLista_schema = Menu_listaSchema()
menuListy_schema = Menu_listaSchema(many=True)
#Menu.
def menu_api(id=None):
if request.method == 'GET':
# Get all menus.
if... | inowakowski/gastrocrm-backend-inz | app/api/api_menu.py | api_menu.py | py | 6,535 | python | en | code | 0 | github-code | 90 |
31682265607 | '''
Comfirm Django init app before database alive
Django會自動找management的資料夾並執行commands??
django.core.management.base
'''
from psycopg2 import OperationalError as psycopg2Error
from django.db.utils import OperationalError
from django.core.management.base import BaseCommand
from time import sleep
class Command(BaseComma... | BioPyRope/receipe-app-api | app/core/management/commands/wait_for_db.py | wait_for_db.py | py | 869 | python | en | code | 0 | github-code | 90 |
15277494287 | """
"""
import pygame
from enum import Enum, auto
import room
from room import Gravity, LayoutParams, MeasureSpec, MeasureParams
class Orientation(Enum):
VERTICAL = auto()
HORIZONTAL = auto()
class LinearLayout(room.Room):
def __init__(self, **kwargs):
self.spacing = kwargs.get('spacing', 1... | Elinvention/ice-emblem | gui/container.py | container.py | py | 7,276 | python | en | code | 12 | github-code | 90 |
18404829189 | import math
n , k = map(int, input().split())
res = 0
pi = 1 / n
for i in range(1, n + 1):
i = k / i
i = math.log2(i)
if i <= 0:
index = 0
elif int(i) == i:
index = int(i)
else:
index = int(i) + 1
res += pi / (2 ** index)
print(res)
| Aasthaengg/IBMdataset | Python_codes/p03043/s060492955.py | s060492955.py | py | 283 | python | en | code | 0 | github-code | 90 |
13117521129 | """This file contains my solutions to Leetcode problem 322: Coin Change."""
# Top down solution with Recursion
# time complexity: O(n * m), where 'n' is the amount and 'm' is the length of coins
# space comexplity: O(n)
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
if not c... | EricMontague/Leetcode-Solutions | medium/problem_322_coin_change.py | problem_322_coin_change.py | py | 2,549 | python | en | code | 0 | github-code | 90 |
23426319288 | class solution:
def majority_element(self,nums):
from collections import Counter
counter=Counter(nums)
maxi=0
val=0
for key in counter.keys():
# print('keys :'+str(key))
if counter[key] > maxi:
maxi=counter[key]
val=key
... | Poobalan1210/TUF-solutions | Day 3/problem 15/majority_element(nby2).py | majority_element(nby2).py | py | 481 | python | en | code | 1 | github-code | 90 |
37931364184 | import hashlib
import math
def encrypt_text(p_text,n):
ans = ""
for i in range(len(p_text)):
ch = p_text[i]
if ch==" ":
ans+=" "
elif (ch.isupper()):
ans += chr((ord(ch) + n-65) % 26 + 65)
else:
ans += chr(... | SaubhagyaSingh/pyqt-encryption-decryption-tool-gui | pythonmini.py | pythonmini.py | py | 5,050 | python | en | code | 1 | github-code | 90 |
18290307819 | import sys
def solve():
input = sys.stdin.readline
N = int(input())
P = [input().strip("\n").split() for _ in range(N)]
X = input().strip("\n")
sec = 0
lastId = 0
for i in range(N):
if P[i][0] == X:
lastId = i
break
for i in range(lastId + 1, N):
... | Aasthaengg/IBMdataset | Python_codes/p02806/s120265472.py | s120265472.py | py | 413 | python | en | code | 0 | github-code | 90 |
38375789845 | from django.shortcuts import render
from django.views import View
from django.contrib import messages
from django.views.generic import DetailView
from django.http import HttpResponseRedirect
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth import authenticate, login
from django.db imp... | vseop/music_store_DJANGO | store/mainapp/views.py | views.py | py | 12,555 | python | en | code | 1 | github-code | 90 |
70161036458 | from NotebookAPIFunctions import *
from StorageAPIFunctions import *
url = "http://dvfuflaskmachine.westus2.cloudapp.azure.com/"
def NotebookAPI():
isAlive = True
isAuthenticated = False
curr_session = ""
while isAlive:
if not isAuthenticated:
print("1: создать пользователя;")
... | P0wderGang3r/NotebookAPIClient | main.py | main.py | py | 4,288 | python | ru | code | 0 | github-code | 90 |
18369872639 | from bisect import bisect_left, bisect_right
import sys
input = sys.stdin.readline
INF = float('inf')
N = int(input())
As = [-int(input()) for _ in range(N)]
def getLenLNDS(As):
dp = [-INF]
for A in As:
if dp[-1] <= A:
dp.append(A)
else:
i = bisect_right(dp, A)
... | Aasthaengg/IBMdataset | Python_codes/p02973/s745037819.py | s745037819.py | py | 390 | python | en | code | 0 | github-code | 90 |
42292031877 | # flake8: noqa: F821
def cartpole_analytical_derivatives(model, data, x, u=None):
if u is None:
u = model.unone
# Getting the state and control variables
y, th, ydot, thdot = x[0].item(), x[1].item(), x[2].item(), x[3].item()
f = u[0].item()
# Shortname for system parameters
m1, m2, l,... | loco-3d/crocoddyl | examples/notebooks/solutions/cartpole_analytical_derivatives.py | cartpole_analytical_derivatives.py | py | 1,924 | python | en | code | 584 | github-code | 90 |
18438023789 | def root(i):
if par[i] < 0:
return i
else:
return root(par[i])
def size(a):
return -par[root(a)]
def union(a,b):
a = root(a)
b = root(b)
if a == b:#親が等しい
return False
if size(a) < size(b):#サイズが大きい方に繋げる
a,b = b,a
par[a] += par[b]
par[b] = a
return... | Aasthaengg/IBMdataset | Python_codes/p03108/s199199497.py | s199199497.py | py | 730 | python | en | code | 0 | github-code | 90 |
9550981863 | # -*- coding: utf-8 -*-
"""
Module dgi_qt3ui.
Loads old Qt3 UI files and creates a Qt5 UI.
"""
from importlib import import_module
from PyQt5 import QtCore, QtGui, QtWidgets # type: ignore
from xml.etree import ElementTree as ET
from binascii import unhexlify
from pineboolib import logging
import zlib
from PyQt5.Qt... | deavid/pineboo | pineboolib/application/parsers/qt3uiparser/dgi_qt3ui.py | dgi_qt3ui.py | py | 41,652 | python | en | code | 4 | github-code | 90 |
73357597737 | from django import forms
#from django.forms import ModelForm, TextInput, EmailInput
from .models import Task, Profile, Team, Visit, Audit, User
from django.forms import DateField
"""class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = ['selected']
widgets = {
... | Phunbie/sun-project | activesite/activityapp/forms.py | forms.py | py | 2,003 | python | en | code | 0 | github-code | 90 |
18254759469 | s=input()
n=len(s)
if n%2==1:
print('No')
else:
fail=0
for i in range(n):
if (s[i]!='h' and i%2==0) or (s[i]!='i' and i%2==1):
fail=1
if fail==0:
print('Yes')
else:
print('No') | Aasthaengg/IBMdataset | Python_codes/p02747/s085678957.py | s085678957.py | py | 204 | python | en | code | 0 | github-code | 90 |
21958437471 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 31 12:12:22 2017
@author: tsalo
"""
import pandas as pd
import decode
df1 = pd.read_csv('clusters.csv')
df2 = pd.read_csv('terms.csv', index_col='id')
for c in sorted(df1['cluster'].unique()):
sel_ids = df1.loc[df1['cluster']==c]['id'].values
... | NBCLab/reward-processing-meta-analysis | corpus_spesific_manual_functional_decoding/2_batch_decode.py | 2_batch_decode.py | py | 424 | python | en | code | 1 | github-code | 90 |
18372016569 | L, R = map(int,input().split())
Dif = abs(L-R)+1
if Dif >= 2020:
Ans = 0
else:
Box = []
for i in range(L,R+1):
Box.append(i%2019)
Box.sort()
Ans = 2020*2020
for i in range(len(Box)-1):
B1 = Box[i]
for j in range(i+1,len(Box)):
B2 = Box[j]
Ans = min... | Aasthaengg/IBMdataset | Python_codes/p02983/s371151319.py | s371151319.py | py | 355 | python | en | code | 0 | github-code | 90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.