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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
34266922439 | import grpc
import service_pb2
import service_pb2_grpc
def run():
channel = grpc.insecure_channel('localhost:50051') # Адрес сервера
stub = service_pb2_grpc.MyServiceStub(channel)
request = service_pb2.Request(id = 1, par_1 = 5, par_2 = 4)
response = stub.MyMethod(request)
print(response.result)... | noemabbbg/factorial | factorial/hz chto/client1.py | client1.py | py | 371 | python | en | code | 0 | github-code | 90 |
20044876461 | if __name__ == '__main__':
t = int(input())
for _ in range(t):
n = int(input())
p = set()
li = list(map(int, input().split()))
new_list = []
for i in li:
if i not in p:
p.add(i)
new_list.append(i)
print(' '.join([str(x) ... | dkarthicks27/ML_Database | codeforces/restore_permutation.py | restore_permutation.py | py | 341 | python | en | code | 0 | github-code | 90 |
18370714609 | from collections import Counter
N = int(input())
A = list(map(int,input().split()))
c = Counter(A)
t = 0
for a in A:
t ^= a
if c[0] == N:
print('Yes')
elif N % 3 == 0:
if c[0] == int(N//3) and len(c) == 2:
print('Yes')
elif len(c) == 3 and t == 0:
print('Yes')
else:
print... | Aasthaengg/IBMdataset | Python_codes/p02975/s781845991.py | s781845991.py | py | 348 | python | en | code | 0 | github-code | 90 |
27159902164 | data_a = [2,3,4,5,6]
data_b = [data_a, 3,5,6,8,9]
print(f'''
Data a = {data_a}
Data b = {data_b} <- Nested data a in list data b
''')
customer01 = ['John Wick', 35, "London"]
customer02 = ['Blondie', 32, 'Los Angeles']
customer03 = ['Tarantino', 38, 'Las Vegas']
customers = [customer01, customer02, customer03]
print(... | susilo-hidayat/Latihan | 28. NESTED_LIST.py | 28. NESTED_LIST.py | py | 590 | python | en | code | 0 | github-code | 90 |
35854918370 | from __future__ import annotations
import collections
import itertools
import json
import shutil
import os
from collections.abc import Callable, Iterable
from pathlib import Path as P
from typing import Optional
import click
import requests
import yaml
# pylint: disable=redefined-builtin
from requests.exceptions imp... | projectsyn/commodore | commodore/helpers.py | helpers.py | py | 7,958 | python | en | code | 43 | github-code | 90 |
33371789976 | from face import base
import argparse
import cv2
import numpy as np
model = None
def do_recognize(rimg):
img, bbox = model.get_input(rimg)
f1 = model.get_feature(img)
return f1
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='face model test')
# general
parser.add_ar... | Li-Fish/Web-FaceRecognize | trash/test.py | test.py | py | 3,328 | python | en | code | 2 | github-code | 90 |
32647413320 | #!/usr/bin/python3
#coding=utf-8
import re
import os
import bs4
import time
import json
import pytube
import requests
from pytube import exceptions
from urllib.parse import urlparse
from urllib.parse import unquote
ua = "Mozilla/5.0 (Linux; Android 6.0.1; SM-G532G) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.... | MR-X-junior/Download | main.py | main.py | py | 11,857 | python | en | code | 0 | github-code | 90 |
18382031439 | n,k=map(int,input().split())
if k>(n-2)*(n-1)//2:
print(-1)
exit()
elif k==(n-2)*(n-1)//2:
print(n-1)
for i in range(n-1):
print(1,i+2)
exit()
ans=[]
for i in range(n-1):
ans.append((1,i+2))
cnt=(n-2)*(n-1)//2
a=2
b=3
while cnt>k:
cnt-=1
ans.append((a,b))
b+=1
if b==n+1:
b=a+2
a+=1
print(len(ans))
for x... | Aasthaengg/IBMdataset | Python_codes/p02997/s778823267.py | s778823267.py | py | 339 | python | en | code | 0 | github-code | 90 |
18011930479 | MOD = 1
m = 100
COMB_table = [[0]*(m+1) for _ in range(m+1)]
fac = [0] * m
finv = [0] * m
inv = [0] * m
def COMBinitialize(m):
fac[0] = 1
finv[0] = 1
if m > 1:
fac[1] = 1
finv[1] = 1
inv[1] = 1
for i in range(2, m):
fac[i] = fac[i-1] * i % MOD
inv[i... | Aasthaengg/IBMdataset | Python_codes/p03776/s345334248.py | s345334248.py | py | 1,418 | python | en | code | 0 | github-code | 90 |
16508981663 | from collections import deque
import sys
n = int(sys.stdin.readline())
q = deque()
for i in range(n):
command = sys.stdin.readline().split()
if len(command) == 2:
q.append(int(command[1]))
else:
if command[0] == 'front':
if q:
print(q[0])
else:
... | somm12/Algorithm-Study | baekjoon/queue/10845.py | 10845.py | py | 1,047 | python | ko | code | 0 | github-code | 90 |
41332896240 | class employee:
company="APPLE"
def show(self):
print(f"the name of the employee is {self.name} and he is working in {self.company}")
@classmethod
def change_company(cls,newcomapny):
cls.company=newcomapny
e1=employee()
e1.name="raghu"
e1.show()
e2=employee()
e2.name="ramesh"
e2.show()... | rohit9098singh/python_programming | ch29_1_classmethod.py | ch29_1_classmethod.py | py | 389 | python | en | code | 0 | github-code | 90 |
20438393717 | import requests, os, sys, collections, time, urllib.parse
from datetime import datetime
token_path = os.path.expanduser("~/.youtrack-token")
if not os.path.exists(token_path):
print("Please follow the instructions at https://www.jetbrains.com/help/youtrack/devportal/authentication-with-permanent-token.html to obta... | yole/youtrack-vote-distribution | youtrack-vote-distribution.py | youtrack-vote-distribution.py | py | 4,985 | python | en | code | 0 | github-code | 90 |
42092030226 | import math
import pygame as pygame
from pygame.math import Vector2
from src.discrete_fourier_transform import discrete_fourier_transform
from src.settings import Settings
from src.signal_generator import SignalGenerator
class FourierSeries:
def __init__(self):
pygame.init()
pygame.event.set_al... | lukaszmichalskii/Fourier-Series | src/fourier_series.py | fourier_series.py | py | 4,134 | python | en | code | 0 | github-code | 90 |
12844545310 | """Add on delete cascade to selection options to allow for deletion of filter types
Revision ID: 9cec67ca7bb0
Revises: e04509401aff
Create Date: 2020-01-23 19:06:09.695080
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '9cec67ca7bb0'
down_revision = 'e04509401... | akash-cis/PROJECTS | socialai/WebApp-API-develop/migrations/versions/2020-01-23-19-06_9cec67ca7bb0_add_on_delete_cascade_to_selection_.py | 2020-01-23-19-06_9cec67ca7bb0_add_on_delete_cascade_to_selection_.py | py | 1,018 | python | en | code | 0 | github-code | 90 |
15230174426 | from django.shortcuts import render,redirect
from django.contrib.auth.models import User, auth
from .models import Bus,Reservation,Contact
# Create your views here.
def index(request):
return render(request,'index.html')
def register(request):
if request.method == "POST":
if User.objects.filter(username=... | abhisalunkhe/bus_reservation | bus/views.py | views.py | py | 4,268 | python | en | code | 0 | github-code | 90 |
42280134007 | from __future__ import print_function, absolute_import
import underworld.function as fn
from underworld.scaling import non_dimensionalise as nd
from underworld.scaling import units as u
class Density(object):
def __init__(self):
self.temperatureField = None
self.pressureField = None
self... | underworldcode/underworld2 | underworld/UWGeodynamics/_density.py | _density.py | py | 2,927 | python | en | code | 140 | github-code | 90 |
18515756719 | N = int(input())
arr = list(map(int, input().split()))
ans = 0
flg = False
for i in range(1,N):
if flg:
flg = False
continue
if arr[i] == arr[i-1]:
ans += 1
flg = True
else:
flg = False
print(ans) | Aasthaengg/IBMdataset | Python_codes/p03296/s523375783.py | s523375783.py | py | 248 | python | en | code | 0 | github-code | 90 |
8500375615 | import discord
from discord.ext import commands
class Utility_av(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def av(self, ctx, user : discord.Member=None):
'''avatar command'''
if user == None:
_embed = discor... | nikhilvayeda/bhendi-bot-3 | cogs/av.py | av.py | py | 970 | python | en | code | 8 | github-code | 90 |
18259620299 | from collections import defaultdict
N, P = map(int, input().split())
S = input().strip()[::-1]
if P in [2, 5]:
ans = 0
for r in range(N):
if int(S[r]) % P == 0:
ans += N - r
print(ans)
exit()
cum = [0] * (N + 1)
for i in range(N):
now = int(S[i]) * pow(10, i, P)
cum[i + 1]... | Aasthaengg/IBMdataset | Python_codes/p02757/s128153813.py | s128153813.py | py | 476 | python | en | code | 0 | github-code | 90 |
18582888359 | def main():
import sys
def input(): return sys.stdin.readline().rstrip()
max_n = 100005
is_prime = [True]*max_n
is_prime[0], is_prime[1] = False, False
i = 2
while i*i < max_n:
if is_prime[i]:
k = 2
while i*k < max_n:
is_prime[i*k] = False
... | Aasthaengg/IBMdataset | Python_codes/p03476/s703169154.py | s703169154.py | py | 778 | python | en | code | 0 | github-code | 90 |
72999725738 | import tkinter as tk
from tkinter import ttk
root = tk.Tk()
combo1 = ttk.Combobox(root, values=['Option 1', 'Option 2', 'Option 3'])
combo1.pack()
combo2 = ttk.Combobox(root, state='disabled')
combo2.pack()
def enable_combo2(event):
combo2['state'] = 'readonly'
combo2['values'] = ['Suboption 1', 'Suboption ... | piroboyd/Tkinter_project | pokmin comboboxy.py | pokmin comboboxy.py | py | 407 | python | en | code | 0 | github-code | 90 |
7976888172 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Offer17:
# 某个提交代码真滴 思路六批 贴一下 这递归的思路着实厉害
# def HasSubtree(self, pRoot1, pRoot2):
# # write code here
# if not pRoot1 or not pRoot2:
# return False
# return... | LordwithGlory/Daily_Python | offer17.py | offer17.py | py | 1,978 | python | en | code | 0 | github-code | 90 |
35525619176 | # https://www.hackerrank.com/challenges/re-group-groups/problem
"""
group()
A group() expression returns one or more subgroups of the match
groups()
A groups() expression returns a tuple containing all the subgroups of the match
groupdict()
A groupdict() expression returns a dictionary containing all the named subgro... | urianchang/Algorithms | HackerRank/Algorithms/Python/Regex_and_Parsing/group_groups_groupdict.py | group_groups_groupdict.py | py | 552 | python | en | code | 17 | github-code | 90 |
4949468020 | import functools
import math
from typing import Dict, List, Tuple
import torch
import torch.nn as nn
import util
from variable import LatentVariable
LABEL_REAL, LABEL_FAKE = 1, 0
class AdversarialLoss:
def __init__(self):
self.loss = nn.BCELoss(reduction="mean")
self.device = util.current_devic... | raahii/infogan-pytorch | src/loss.py | loss.py | py | 2,385 | python | en | code | 14 | github-code | 90 |
39311885789 | """
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[... | at3103/Leetcode | 103_Binary Tree Zigzag Level Order Traversal.py | 103_Binary Tree Zigzag Level Order Traversal.py | py | 1,349 | python | en | code | 0 | github-code | 90 |
456329564 | import cv2
import numpy as np
PATH = '/home/felipe/Imagens/ball.png'
frame = cv2.imread(PATH)
img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 260, param1=30, param2=65, minRadius=0, maxRadius=0)
if circles is not None:
for x, y, r in circles[0]:
cv2.... | null | Resgate/teste/balls_black.py | balls_black.py | py | 420 | python | en | code | null | code-starcoder2 | 51 |
517585627 | from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone
from .models import Genre, Item, Order
from django.db.models import Sum
import re
from django.db.models ... | null | Entrega/LTAW/PRACTICA4/shop/views.py | views.py | py | 4,093 | python | en | code | null | code-starcoder2 | 51 |
242828482 | # 문제 20 : 몫과 나머지
# 공백으로 구분하여 두 숫자가 주어진다.
# 첫 번째 숫자로 두 번째 숫자를 나누었을 때 그 몫과 나머지를 공백으로 구분하여 출력하시오.
data = list(map(int, input().split()))
result = data[0] // data[1]
left = data[0] % data[1]
print(result, left)
| null | code/20.py | 20.py | py | 330 | python | en | code | null | code-starcoder2 | 51 |
146379151 | #!/usr/bin/env python3
from pprint import pprint
a = 5
b = 2
max = a if (a > b) else b
print(max)
#dies ist eine effizientere methode als untereindander zu schreiben jedoch schlechter lesbar
| null | python-test7.py | python-test7.py | py | 196 | python | en | code | null | code-starcoder2 | 51 |
41247363 | import requests
from bs4 import BeautifulSoup
def aliexpress(product,budget):
pages=1
max_pages=2
url='http://www.aliexpress.com/wholesale?catId=0&initiative_id=SB_20170821004256&SearchText='+str(product)
while(pages<=max_pages):
print("Page no. = " +str(pages))
print("Page link... | null | aliexpress.py | aliexpress.py | py | 1,405 | python | en | code | null | code-starcoder2 | 51 |
373881030 | from .SVM import SVM
from .DecisionTree import DecisionTree
model_list = {
"SVM": SVM,
"DecisionTree": DecisionTree,
}
def get_model(model_name,conf):
if model_name in model_list.keys():
return model_list[model_name](conf)
else:
raise NotImplementedError
| null | model/__init__.py | __init__.py | py | 290 | python | en | code | null | code-starcoder2 | 51 |
327864145 | """empty message
Revision ID: f49f08e77ed5
Revises: f484298d9b7b
Create Date: 2019-03-26 22:27:17.726994
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f49f08e77ed5'
down_revision = 'f484298d9b7b'
branch_labels = None
depends_on = None
def upgrade():
# ... | null | migrations/versions/f49f08e77ed5_.py | f49f08e77ed5_.py | py | 652 | python | en | code | null | code-starcoder2 | 51 |
327716316 | import mock
import pytest
from squeaknode.config.config import SqueaknodeConfig
from squeaknode.core.lightning_address import LightningAddressHostPort
from squeaknode.core.squeak_controller import SqueakController
from squeaknode.core.squeak_core import SqueakCore
from squeaknode.core.squeak_peer import SqueakPeer
fro... | null | tests/core/test_squeak_controller.py | test_squeak_controller.py | py | 3,619 | python | en | code | null | code-starcoder2 | 51 |
139945641 | class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
cnt = 1
odd, even = ListNode(0), ListNode(0)
firsteven = even
cur = ListNode(0, head)
while cur.next:
cur = cur.next
if cnt%2:
odd.next = cur
odd = odd.n... | null | src/328-odd_even_linkedlist.py | 328-odd_even_linkedlist.py | py | 620 | python | en | code | null | code-starcoder2 | 51 |
283641680 | import math
def prime(value):
if value % 2 == 0 or value % 10 == 0 or value % 3 == 0:
return False
for i in range(3, math.ceil(math.sqrt(value)) - 1, 2):
if value % i == 0:
return False
return True
if prime(int(input())):
print("Число простое")
else:
print("Число сост... | null | the_simplest_prime_num.py | the_simplest_prime_num.py | py | 354 | python | en | code | null | code-starcoder2 | 51 |
259617514 | import sys
input = sys.stdin.readline
sensor = int(input())
base = int(input())
coord = list(map(int, input().split()))
coord.sort()
#기지국의 개수가 센서의 크기와 같거나 크면 -> 센서의 위치에 그냥 설치
if sensor <= base:
print(0)
sys.exit()
dist = []
#각 인접 센서 사이의 거리
for i in range(1, sensor):
dist.append(coord[i]-coord[i-1])
dist... | null | 정렬/2212_센서.py | 2212_센서.py | py | 547 | python | en | code | null | code-starcoder2 | 51 |
356051032 | import time
import traceback, sys
import random
from statistics import mean
from statistics import median
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
QApplication.setAttribute(Qt.AA_Use96Dpi) # This fixes the scaling issue in Windows
# Sets (0 = OR set, 1 = AND s... | null | Tsetlin_GUI.py | Tsetlin_GUI.py | py | 23,671 | python | en | code | null | code-starcoder2 | 51 |
639110471 | '''
fcn.py 的任务
1. 实现双线插值
2. 实现FCN本人
(人 •͈ᴗ•͈) ۶♡♡
'''
import numpy as np
import torch
from torch import nn
from torchvision import models
#双插
def Bilinear_interpolation (src, new_size):
'''
使用双线性插值方法放大图像
params:
src(np.ndarray):输入图片
new_size(tuple):目标尺寸
ret:
dst(np.ndarry):... | null | models/fcn.py | fcn.py | py | 4,413 | python | en | code | null | code-starcoder2 | 51 |
53594229 | import setuptools
from distutils.core import Extension
with open("README.md") as f:
long_description = f.read()
setuptools.setup(
name="codesnap",
version="0.0.4",
author="Tian Gao",
author_email="gaogaotiantian@hotmail.com",
description="A profiling tool that can visualize python code in flam... | null | setup.py | setup.py | py | 1,134 | python | en | code | null | code-starcoder2 | 51 |
628842232 | import os
import pickle
import numpy as np
from datetime import timedelta
import matplotlib.pyplot as plt
from statsmodels.tsa.arima_model import ARIMA
def forecast(ser, start_date, end_date):
""" Function that uses the ARIMA model to return the forecasted
price of a user's stay and a visualization of the pri... | null | forecast.py | forecast.py | py | 1,265 | python | en | code | null | code-starcoder2 | 51 |
180396234 | import base64
import os
import sublime
import queue
from threading import Thread
from .session import Session
from . import formatter
from .client import Client
from ..log import log
def done(response):
return response.get("status") == ["done"]
def b64encode_file(path):
with open(path, "rb") as file:
... | null | src/repl/__init__.py | __init__.py | py | 6,193 | python | en | code | null | code-starcoder2 | 51 |
249862627 | import json, socket
from modules import query, response, data_structures, cashing, tools
ADDRESS = ("127.0.0.1", 53)
CASH_FILE = "cash.json"
ROOT_SERVERS = (('199.9.14.201', 53),
('198.41.0.4', 53),
('199.7.91.13', 53))
Q_TYPES = [1, 2]
class DNSServer:
def __init__(se... | null | dns_server/dns_server.py | dns_server.py | py | 5,852 | python | en | code | null | code-starcoder2 | 51 |
540271277 | # 支払い金額を求める
# 価格
beer_v = 200
otumami_v = 100
yakitori_v = 100
# 個数
beer_c = 2
otumami_c = 1
yakitori_c = 2
# 割引率
yakitori_rate = 0.2
# 使用ポイント数
point = 150
# 計算
beer_sum = beer_v * beer_c
otumami_sum = otumami_v * otumami_c
yakitori_sum = yakitori_v * (1 - yakitori_rate) * yakitori_c
payment = beer_sum + otumami_su... | null | src/task20180705.py | task20180705.py | py | 452 | python | en | code | null | code-starcoder2 | 51 |
44372395 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import logging.handlers
import os
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import classification_report
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.models import Sequential... | null | model1.py | model1.py | py | 2,854 | python | en | code | null | code-starcoder2 | 51 |
130172641 | #coding:utf-8
#Author : Crgig Richards
#Created : 2016.9.6
#Description : display current directory and subdirectories size
import os
directory = '.' # Set the variable directory to be the current directory
dir_size = 0 # Init file size
fsizedicr = {"Bytes": 1,
'Kilobytes':float(1)/1024,'M... | null | display_file_size.py | display_file_size.py | py | 649 | python | en | code | null | code-starcoder2 | 51 |
557736386 | import time
import os
import threading
# total time is 60 * 2
total_time = 30
alarm_1 = 25
alarm_2 = 20
class Alarm(threading.Thread):
def __init__(self, hours, minutes):
super(Alarm, self).__init__()
self.hours = int(hours)
self.minutes = int(minutes)
self.keep_running = True
... | null | Python/basictimer.py | basictimer.py | py | 1,690 | python | en | code | null | code-starcoder2 | 51 |
610188336 | #!/usr/bin/env python
try:
import tkinter
from tkinter import ttk
from tkinter import *
except ImportError:
import Tkinter
from Tkinter import ttk
from Tkinter import *
import cv2
import PIL.Image, PIL.ImageTk
import numpy as np
from keras.models import model_from_json
from keras.preprocessing im... | null | VisualAI_EmotionDetection_Final_APP.py | VisualAI_EmotionDetection_Final_APP.py | py | 5,039 | python | en | code | null | code-starcoder2 | 51 |
1065438 | from turtle import Screen
from paddle import Paddle
screen = Screen()
screen.bgcolor("black")
screen.setup(height=600, width=800)
screen.title("Pong")
screen.tracer(0)
r_paddle = Paddle((350, 0))
l_paddle = Paddle((-350, 0))
screen.listen()
screen.onkey(r_paddle.go_up, "w")
screen.onkey(r_paddle.go_down, "s")
screen.... | null | main.py | main.py | py | 463 | python | en | code | null | code-starcoder2 | 51 |
415624995 | import scrapy
from scrapy_splash import SplashRequest
from bs4 import BeautifulSoup
# 爬取地址http://45.76.194.124/news/1.html#
class NewsSpider(scrapy.Spider):
name = "onetwo"
start_urls = [
"http://45.76.194.124/news/1.html#",
]
def start_requests(self):
for url in self.start_urls:
... | null | spiders/newsone.py | newsone.py | py | 1,759 | python | en | code | null | code-starcoder2 | 51 |
368504799 | def get_data_loader(data_dir, batch_size, num_workers):
normalize = transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
jitter_param = 0.4
lighting_param = 0.1
def batch_fn(batch, ctx):
data = gluon.utils.split_and_load(batch[0], ctx_list=ctx, batch_axis=0)
label = gluon.... | null | Data Set/bug-fixing-5/e915c0b4968a5879ffc40d7c58ec78cd178ae6bf-<get_data_loader>-fix.py | e915c0b4968a5879ffc40d7c58ec78cd178ae6bf-<get_data_loader>-fix.py | py | 1,289 | python | en | code | null | code-starcoder2 | 51 |
619354040 | import matplotlib.pyplot as plt
values = list(range(1, 1000))
squares = list(v**2 for v in range(1, 1000))
plt.scatter(values, squares, s=40, c=squares, cmap=plt.cm.Blues)
plt.title('Squares of Numbers', fontsize=24)
plt.xlabel('Numbers', fontsize=14)
plt.ylabel('Squares', fontsize=14)
plt.tick_params(axis='both', w... | null | code/squares.py | squares.py | py | 392 | python | en | code | null | code-starcoder2 | 51 |
339957247 | from MyUtil import MyUtil as MyUtil
from ElasticNodes import ElasticNodes
from MySingletons import MyDevice
import numpy as np
import torch
# class ReverseLayerFunction(torch.autograd.Function):
# @staticmethod
# def forward(self, x, alpha=1.0):
# self.alpha = alpha
#
# return x.view_as(x)
#
... | null | NeuralNetwork.py | NeuralNetwork.py | py | 24,881 | python | en | code | null | code-starcoder2 | 51 |
12236195 | from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
import datetime
from django.utils import timezone
# from django.utils.html import mark_safe
from .thumbs import ImageWithThumbsField
class Department(models.Mode... | null | exam_system/stud_app/models.py | models.py | py | 5,322 | python | en | code | null | code-starcoder2 | 51 |
509230436 |
from xai.brain.wordbase.nouns._mothball import _MOTHBALL
#calss header
class _MOTHBALLED(_MOTHBALL, ):
def __init__(self,):
_MOTHBALL.__init__(self)
self.name = "MOTHBALLED"
self.specie = 'nouns'
self.basic = "mothball"
self.jsondata = {}
| null | xai/brain/wordbase/nouns/_mothballed.py | _mothballed.py | py | 254 | python | en | code | null | code-starcoder2 | 51 |
369931592 | from __future__ import division
import sys
import argparse
wgsim_path = "wgsim"
bedtools_path = "bedtools"
samtools_path = "samtools"
def rounder(x,y):
return int(round(x / float(y))) * y
class SmartFormatter(argparse.HelpFormatter):
def _split_lines(self, text, width):
if text.startswith('R|'):
... | null | dudeML.py | dudeML.py | py | 57,536 | python | en | code | null | code-starcoder2 | 51 |
157601671 | import keras
import numpy as np
from PIL import Image
import os
import matplotlib.pyplot as plt
from keras.utils import plot_model
MODEL_PATH = 'LENET-5CNN.h5'
PIC_FOLDER = 'C:/Users/Hsinyao/Desktop//Keras/pic/'
def preprocess_image(IMG):
img = Image.open(IMG)
img = img.resize((28, 28), Image.ANTIALIAS)
i... | null | my_keras_app.py | my_keras_app.py | py | 1,164 | python | en | code | null | code-starcoder2 | 51 |
650013833 | #!/usr/bin/python3
# searches in a dir for a filename: recursive search
# os_walk searches in the whole dir, including subdirs, returning with a join the
# complete path/filename :)
import os
import sys
import subprocess
def find_files(filename, search_path):
result = []
# Walking top-down from the root : os... | null | python_practices/bash2python_scripting/find_file_after_walk_dir.py | find_file_after_walk_dir.py | py | 1,663 | python | en | code | null | code-starcoder2 | 51 |
248374868 | #!/usr/bin/python3
import json
import flask
import random
import os
import ankura
import time
import pickle
from tqdm import tqdm
import sys
import tempfile
import threading
app = flask.Flask(__name__, static_url_path='')
user_data = list()
dataset_name = sys.argv[1]
train_size = 10000
test_size = 500
number_of_t... | null | tbuie.py | tbuie.py | py | 4,660 | python | en | code | null | code-starcoder2 | 51 |
200021098 | import logging
from threading import Thread, Event
class Job(Thread):
def __init__(self, interval, run_on_start, execute, *args, **kwargs):
Thread.__init__(self)
self.stopped = Event()
self.interval = interval
self.run_on_start = run_on_start
self.execute = execute
... | null | timeloop/job.py | job.py | py | 865 | python | en | code | null | code-starcoder2 | 51 |
243731428 | def Vigener(openText, key, whatDo):
alpha = {0: 'abcdefghijklmnopqrstuvwxyz',
1: 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'}
openText = openText.lower()
if whatDo == "Шифруем":
DO = 1
else:
DO = -1
if ord(key[0]) <= 127:
alpha_i = 0
else:
alpha_i = 1
... | null | Vigenеre.py | Vigenеre.py | py | 1,320 | python | en | code | null | code-starcoder2 | 51 |
46971736 | from tfmodel.model import PFNet, Transformer, DummyNet
import tensorflow as tf
import tensorflow_probability
import tensorflow_addons as tfa
import pickle
import numpy as np
import os
from sklearn.model_selection import train_test_split
import sys
import glob
import io
import os
import yaml
import uuid
import matplotli... | null | mlpf/tfmodel/model_setup.py | model_setup.py | py | 27,341 | python | en | code | null | code-starcoder2 | 51 |
512743474 | # _*_ coding:utf-8 _*_
# redis未授权检测脚本 单线程版
# 使用环境;
# 1.Python 3.8.10
# 2.python安装redis和func_timeout
#
# windows环境:管理员身份
# pip3 install func_timeout
# pip3 install redis
# Linux环境: sudo easy_install redis
# sudo easy_install func... | null | redisOneThread.py | redisOneThread.py | py | 2,111 | python | en | code | null | code-starcoder2 | 51 |
300980711 | import base64
from datetime import timedelta
import logging
import time
import uuid
import warnings
import httpx
from ably.types.capability import Capability
from ably.types.tokendetails import TokenDetails
from ably.types.tokenrequest import TokenRequest
from ably.util.exceptions import AblyException, IncompatibleCli... | null | ably/rest/auth.py | auth.py | py | 13,689 | python | en | code | null | code-starcoder2 | 51 |
603279648 | import numpy as np
from numpy import linalg
def compute_stats(m, w):
"""
m: 1-D array
w: 2-D array
"""
s_i = m
A = -w
for i in range(w.shape[0]):
A[i][i] = 1 / (1 - m[i] * m[i])
A_inv = linalg.inv(A)
s_i_s_j = np.dot(m.reshape(len(m), 1), m.reshape(1, len(m))) + A_inv
... | null | boltzmann/linear_respone.py | linear_respone.py | py | 340 | python | en | code | null | code-starcoder2 | 51 |
452662021 | from pathlib import Path
import torch
from torch import nn
from torch.nn.modules import Module
from typing import TypeVar, Callable, Tuple, Optional, Any, Mapping
from model import EAST
Model = TypeVar("Model", bound=Module)
# @dataclass
# class LoadedModel(Generic[Model]):
# model: Model
# device: torch.de... | null | reusable.py | reusable.py | py | 6,499 | python | en | code | null | code-starcoder2 | 51 |
155289661 | import unittest
import solutions.maximum_width_of_binary_tree.index as main
from solutions._class.tree_node import TreeNode, createTreeNode
class Test(unittest.TestCase):
def test_widthOfBinaryTree(self):
test_patterns = [
([0, 0, 0, 0, None, None, 0, None, None, None, 0], 4),
([1,... | null | solutions/maximum_width_of_binary_tree/test.py | test.py | py | 687 | python | en | code | null | code-starcoder2 | 51 |
230847347 |
import os
from collections import Counter
from operator import itemgetter
from classification import getModel
from classification import getTrTWContext
DATA = os.environ['data']
def eval_instances():
instance_file = os.path.join(DATA, 'twitter/self_reveal/user_pool0.csv')
filtered_file = os.path.join(DATA... | null | bigdata/reclassification.py | reclassification.py | py | 836 | python | en | code | null | code-starcoder2 | 51 |
86864985 | class Decode:
def __init__(self, codedText : str = "", key : str = ""):
self.__codedText = codedText
self.__key = key
self.__decodedText = ""
def decode(self):
self.decodeXor()
self.decodeCesar()
return self.__decodedText
def decodeCesar(s... | null | Practica_4/decode.py | decode.py | py | 1,487 | python | en | code | null | code-starcoder2 | 51 |
169059872 | i = 0
n = ['white', 'white', 'black', 'white', 'black', 'white', 'white', 'white', 'black', 'black']
# n = ['white', 'white', 'black', 'white', 'black']
answers = []
success_min = len(n) - 1
def find_parity(known):
print("Нийт малгай: ", n)
print("Мэдэгдэж байгаа: " + str(known))
no_white = known.count('wh... | null | WhiteOrBlackHats.py | WhiteOrBlackHats.py | py | 3,970 | python | en | code | null | code-starcoder2 | 51 |
412799970 | import numpy as np
from statistics import mode
from sklearn.model_selection import KFold
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.neural_network import MLPClassifier
class Ensamble:
# Constructor para inicializar datos
def __init__(self):
... | null | Ensamble.py | Ensamble.py | py | 4,906 | python | en | code | null | code-starcoder2 | 51 |
440408189 | # =============================================================================
# Authors: PAR Government
# Organization: DARPA
#
# Copyright (c) 2016 PAR Government
# All rights reserved.
# ==============================================================================
from maskgen.tool_set import getMilliSecondsAndFr... | null | plugins/FlowDrivenVideoTimeWarp/__init__.py | __init__.py | py | 3,055 | python | en | code | null | code-starcoder2 | 51 |
170060026 | from cities_format import city_format
print("\n\tEnter 'q' at any time to quit.")
while True:
city = input("\nInsert city : ")
if city == 'q':
break
country = input("Insert country : ")
if country == 'q':
break
population = input("Insert population (Empty if not) : ")
if popula... | null | src/cities.py | cities.py | py | 469 | python | en | code | null | code-starcoder2 | 51 |
15963227 | import unittest
import zserio
from testutils import getZserioApi
class VariableArrayVarUIntTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.api = getZserioApi(__file__, "array_types.zs").variable_array_varuint
def testBitSizeOf(self):
numElements = 33
compoundArray =... | null | test/language/array_types/python/VariableArrayVarUInt.py | VariableArrayVarUInt.py | py | 3,442 | python | en | code | null | code-starcoder2 | 51 |
394048038 | #!/usr/bin/env python
import pandas as pd
import sys
import os
import argparse
import math
import os
import altair as alt
import pandas as pd
import numpy as np
import yaml
import glob
from yaml import Loader, Dumper
def generic_df_reader(args):
if "npz" == args.input.split(".")[-1]:
npz = np.load('result.npz')
d... | null | bin/interactive_heatmap.py | interactive_heatmap.py | py | 8,164 | python | en | code | null | code-starcoder2 | 51 |
497589186 | #
#-*- coding: utf-8 -*-
#
# -------------------------------------------------------------------------
#
# -------------------------------------------------------------------------
import math
import numpy as np
def solveForComponents(fc, pm, kphi, kvco, N, gamma, loop_type='passive2'):
"""
:Parameters:
... | null | pll_calcs.py | pll_calcs.py | py | 38,887 | python | en | code | null | code-starcoder2 | 51 |
97753791 | # -*- coding: utf-8 -*-
# Copyright (c) 2015-2016 MIT Probabilistic Computing Project
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unles... | null | src/knn/mvknn.py | mvknn.py | py | 16,692 | python | en | code | null | code-starcoder2 | 51 |
404992545 | import unittest
from common import logger,login_token,base
from data.readexcel import ExcelUtil
data = ExcelUtil("MembershipSubscription").dict_data()
class Detailsofpayment(unittest.TestCase):
def setUp(self):
self.log = logger.Log()
def test_details_of_payment(self):
'''获取会员出款详情'''
... | null | java_auto_project/case/FundManagement(资金管理)/MemberWithdrawals(会员提款)/test_details_of_payment.py | test_details_of_payment.py | py | 976 | python | en | code | null | code-starcoder2 | 51 |
224795286 | import math, random
def getFinalList(N, n, input_tuple, pc1, pc2, pc3):
i1, i2, i3 = input_tuple
f1 = []
f2 = []
f3 = []
pc1 = pc1 / (pc1+pc2+pc3)
pc2 = pc2 / (pc1+pc2+pc3)
pc3 = pc3 / (pc1+pc2+pc3)
ceil1 = math.ceil(N*pc1)
ceil2 = math.ceil(N*pc2)
ceil3 = N-ceil1-ceil... | null | app/flaskapp/recommend/final_freelancers/bucketing.py | bucketing.py | py | 4,668 | python | en | code | null | code-starcoder2 | 51 |
493716852 | #!/usr/bin/env python
from prettytable import PrettyTable
import subprocess
import json
def shell(cmd):
sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = sp.communicate()
return out, err
def get_nodes():
cmd = "openstack baremetal node list --long -f j... | null | ironic/ironic_list/ironic_node_port_list.py | ironic_node_port_list.py | py | 1,376 | python | en | code | null | code-starcoder2 | 51 |
429046196 | from django import forms
from .models import \
PartnerSet, \
TransactionSet, \
ProductSet, \
ProductItem
class NewClientForm(forms.ModelForm):
class Meta:
model = PartnerSet
fields = ('name', 'code')
class NewTransactionForm(forms.ModelForm):
class Meta:
model = Pr... | null | app/forms.py | forms.py | py | 1,004 | python | en | code | null | code-starcoder2 | 51 |
121065528 | '''
Diciamo che un dizionario d rappresenta un albero (e lo indichiamo come dizionario-albero)
se ciascuna chiave di d e' un identificativo di un nodo dell'albero e l'attributo della chiave e' la lista
(eventualmente vuota) degli identificativi dei figli del nodo. Gli identificativi dei nodi
all'interno delle liste... | null | students/1800408/homework04/program01.py | program01.py | py | 7,256 | python | en | code | null | code-starcoder2 | 51 |
216013651 | from address import Address
from customer import Customer
from transaction import Transaction
from utility import get_current_date, get_current_time, global_customer_map, global_transactions, global_branches, \
send_message
class Account(object):
"""
Maintains a structure for all accounts
:param str a... | null | account.py | account.py | py | 9,212 | python | en | code | null | code-starcoder2 | 51 |
69936569 | # -*- coding: utf-8 -*-
# Copyright 2018 Mobicage NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | null | src/solutions/common/bizz/news.py | news.py | py | 34,441 | python | en | code | null | code-starcoder2 | 51 |
64147603 | from flask import Flask
try:
from flask import Blueprint
except ImportError:
# Blueprints only available starting with 0.7,
# fall back to old Modules otherwise.
Blueprint = None
from flask import Module
from flaskext.assets import Environment, Bundle
class TestUrlAndDirectory(object):
"""... | null | tests/test_integration.py | test_integration.py | py | 4,296 | python | en | code | null | code-starcoder2 | 51 |
408478612 | from flask import Flask, redirect, render_template, request, url_for, send_from_directory
from datetime import datetime
from contact import Contact
from user import User
from database import database
import os
import logging
app = Flask(__name__)
logging.basicConfig(level=logging.DEBUG)
@app.route('/favicon.ico')
de... | null | app.py | app.py | py | 5,125 | python | en | code | null | code-starcoder2 | 51 |
225592973 | splash = '''
888 888 888 .d888 888888b. 888
888 o 888 888 d88P" 888 "88b 888
888 d8b 888 888 888 888 .88P ... | null | main.py | main.py | py | 22,318 | python | en | code | null | code-starcoder2 | 51 |
322285138 | import csv
import re
rf = open('story.csv', 'r')
wf1 = open('genre.csv', 'w')
wf2 = open('genre_of_story.csv', 'w')
def get_names(string):
filtered1 = re.sub(r'\([^)]*\)', '', string)
filtered2 = re.sub(r'\[[^)]*\]', '', filtered1)
filtered3 = re.sub(r'\{[^)]*\}', '', filtered2)
filtered4 = re.sub(r'... | null | create_genres.py | create_genres.py | py | 914 | python | en | code | null | code-starcoder2 | 51 |
406594349 | """
Unit tests for Sample class
"""
import unittest
import sys
import os
from pathlib import Path
import numpy as np
import pandas as pd
sys.path.append(os.path.abspath('../..'))
from flowkit import Sample, transforms
data1_fcs_path = 'examples/gate_ref/data1.fcs'
data1_sample = Sample(data1_fcs_path)
xform_logicle... | null | flowkit/tests/sample_tests.py | sample_tests.py | py | 16,804 | python | en | code | null | code-starcoder2 | 51 |
477814710 | import itertools
import numpy as np
from list_rotations import list_rotations
def get_combinations(coordinate_system, point_to_reference_corner_of_cube, cube_parts, shape, dimension):
combinations = [coordinate_system]
for cube_part in cube_parts:
combinations_new = []
for combination in combi... | null | combinations.py | combinations.py | py | 1,295 | python | en | code | null | code-starcoder2 | 51 |
404989492 | from commands import _embedMessage, _mongoFunctions
async def edit_due_date_message(client):
guild_list = _mongoFunctions.get_guilds_information()
for guild in guild_list:
global guild_id, channel_id
for key, value in guild.items():
if key == 'guild_id':
guild_id =... | null | commands/_dueDateMessage.py | _dueDateMessage.py | py | 2,471 | python | en | code | null | code-starcoder2 | 51 |
620982439 | # uncompyle6 version 3.7.4
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: build/bdist.macosx-10.7-x86_64/egg/airflow/contrib/sensors/pubsub_sensor.py
# Compiled at: 2019-09-11 03:47:34
# Size of source mod 2**32: 4319 bytes
from airflow... | null | pycfiles/apache_airflow_arup-1.10.5-py3.6/pubsub_sensor.cpython-36.py | pubsub_sensor.cpython-36.py | py | 3,632 | python | en | code | null | code-starcoder2 | 51 |
190613859 | import numpy as np
import torch
class PrototypicalBatchSampler(object):
def __init__(self, labels, class_idxs, num_way, num_support, num_query, num_episode):
super(PrototypicalBatchSampler, self).__init__()
self.class_idxs = class_idxs
self.num_way = num_way
self.num_sample = num_s... | null | fsssl3d/data/prototypical_batch_sampler.py | prototypical_batch_sampler.py | py | 1,455 | python | en | code | null | code-starcoder2 | 51 |
344261979 | from socket import *
s = socket()
s.connect(('127.0.0.1', 8000))
message = input('->')
while message != 'q':
s.send(message.encode())
data = s.recv(1024)
print("recieved from server: " + str(data.decode()))
message = input('->')
s.close()
| null | lesson Threads/hw3_client.py | hw3_client.py | py | 257 | python | en | code | null | code-starcoder2 | 51 |
616105448 | import pywt
import numpy as np
import tensorflow as tf
#from tensorflow.contrib import rnn
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
def entry():
X_fill = load_data("train_filled.csv")
X_wv = denoise(X_fill)
X_train, ... | null | src/app.py | app.py | py | 5,486 | python | en | code | null | code-starcoder2 | 51 |
310358936 | from pico2d import *
import game_framework
name = "game_function"
class EndMessage:
image = None
times_up = None
rabbit = None
box = None
draw_sign = False
def __init__(self):
self.font = load_font('resource/210하얀바람B.ttf')
self.timer = 0
self.bye_timer = 0
self.... | null | AkooFlower/game_function.py | game_function.py | py | 2,418 | python | en | code | null | code-starcoder2 | 51 |
180981316 | import markovify
import sys
def make_markov():
with open('tweet-corpus.txt','r') as f:
text = f.read()
model = markovify.NewlineText(text)
return model
def tweet(model, length=140, out=sys.stdout):
tweet = model.make_short_sentence(length) + '\n'
out.write(tweet)
def generate_tweets(model, length=140):
whi... | null | markov.py | markov.py | py | 458 | python | en | code | null | code-starcoder2 | 51 |
234500338 | from sklearn.datasets import make_circles
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
import numpy as np
from scipy.spatial.distance import pdist, squareform
from scipy import exp
from scipy.linalg import eigh
def rbf_kernel_pca(X, gamma, n_components):
# Calculate pairwise squared Euclidea... | null | chapter5/chapter5_ex5.py | chapter5_ex5.py | py | 3,047 | python | en | code | null | code-starcoder2 | 50 |
259492790 | from data_science_tools.aoi_selection_tool import AoiPipeline
from data_science_tools.aoi_selection_tool.sqlalchemy_wrappers import BaseWrapper
from data_science_tools.aoi_selection_tool.frontend_components import *
def main():
primary = Primary(
kind="attributes",
imagery_refresh="2018-02",
... | null | scratch_1.py | scratch_1.py | py | 2,873 | python | en | code | null | code-starcoder2 | 50 |
51382394 | import cv2
import torch
import numpy as np
import global_vars
import models
from filters import skinMask,greyMask
from models import load_model, predict_gesture
from utils import *
class recognizer:
def __init__(self):
# CNN
self.model = load_model()
if torch.cuda.is_available():
... | null | realtime_gesture_recog/recog.py | recog.py | py | 1,655 | python | en | code | null | code-starcoder2 | 50 |
45343168 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# !@Time : 2021/4/14 下午3:57
# !@Author : miracleyin @email: miracleyin@live.com
# !@File : inference.py
import json
import csv
from pathlib import Path
from tqdm.notebook import tqdm
import torch
from torch.utils.data import DataLoader
from datasets import Inferenc... | null | inference.py | inference.py | py | 1,948 | python | en | code | null | code-starcoder2 | 50 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.