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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
36810385194 | import argparse
import sys
import os
import TitaniaTest
def parse_args() -> argparse.Namespace:
# parse command line argument
parser = argparse.ArgumentParser(description="Titania Testing")
parser.add_argument('--output', type=str, default=".", help="\
Folderpath to store test results. \n \
... | i3drobotics/titania-testing | run.py | run.py | py | 7,169 | python | en | code | 0 | github-code | 1 |
2425239616 | # declare get employee id function that will return an emplyoee id
def getEmployeeId():
employeeIdCheck = False
while employeeIdCheck == False:
# prompt the user for their employee id
employeeId = input("Please enter a employee id: ")
# call employee id checker function
employee... | drewskerdu/it412_Jhartwick365 | Week1FunctionsAssignmentNew/Functions/my_functions.py | my_functions.py | py | 5,720 | python | en | code | 0 | github-code | 1 |
71933446754 | import tensorflow as tf
class GANModel(tf.keras.Model):
"""
This class builds the generator and discriminator models, and trains them.
"""
def __init__(self, height, width, nb_channels, noise_dim, **kwargs):
"""
Initialize the class.
Args:
- heigth (int): height of imag... | UluLord/Anime-Face-Generation-using-GAN-Model-Tensorflow- | models.py | models.py | py | 11,422 | python | en | code | 0 | github-code | 1 |
20643232235 | import sys
import os
import math
from random import randint
import networkx as nx
# import matplotlib.pyplot as plt
import random
from networkx.readwrite import json_graph
# 0 ≤ β ≤ 1 0\leq \beta \leq 1 and N ≫ K ≫ ln N ≫ 1 {\displaystyle N\gg K\gg \ln N\gg 1}
# num_nodes = 1024
# k = 50
# num_nodes = 512
# k = 28... | shishirrraic/LB-Spiral | network_generator.py | network_generator.py | py | 6,044 | python | en | code | 0 | github-code | 1 |
15297298404 | import logging
import psycopg2
from telegram import Update, ForceReply, ReplyKeyboardMarkup, KeyboardButton
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
# Инициализация логгера
logging.basicConfig(format='%... | Vadbond007/Bot | ChatBot_TheVaper.py | ChatBot_TheVaper.py | py | 18,477 | python | ru | code | 0 | github-code | 1 |
33931076345 | # 1001
print('Hello')
# 1002
print('Hello World')
# 1003
print('Hello')
print('World')
# 1004
print("'Hello'")
# 1005
print('"Hello World"')
# 1006
print('"!@#$%^&*()"')
# 1007
print('"C:\Download\hello.cpp"')
# 1008
import io, sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding... | progjs/coding_test | codeup100.py | codeup100.py | py | 9,731 | python | en | code | 0 | github-code | 1 |
30209391413 | import numpy as np
import torch
from botorch.acquisition.cost_aware import InverseCostWeightedUtility
from botorch.acquisition import PosteriorMean
from botorch.acquisition.knowledge_gradient import qMultiFidelityKnowledgeGradient
from botorch.acquisition.fixed_feature import FixedFeatureAcquisitionFunction
from botorc... | yiping514/LMGP | lmgp_pytorch/bayesian_optimizations/bo_steps.py | bo_steps.py | py | 6,790 | python | en | code | 0 | github-code | 1 |
27313697964 | import os
# from sys import argv
class Biils:
def __init__(self):
os.system('cls')
self.tot_elecbill = float (input ("How much is the total bill of Electricity? \n> "))
self.tot_gasbill = float (input("How much is the total bill of the gas? \n> "))
self.tot_tenants = int(input ("Ho... | Sandhy-W/Household-Budget | Holder_Bill.py | Holder_Bill.py | py | 3,280 | python | en | code | 0 | github-code | 1 |
18399366045 | friend_names=["santhosh","abhinay","ameer","nayeem","siraj","saleem","sadhik","shiva","gowtham","bhargav"]
for p in friend_names:
print("my friend name is",p)
family_names=["anwar","fathima","kalam","reshma","rowfa","areef","mobeen","mateen","amanu","ameen"]
for f in family_names:
print(f)
non_veg=[... | salam123o/assignment_6 | assign_6.py | assign_6.py | py | 926 | python | en | code | 0 | github-code | 1 |
74726793312 | from lib.cohort import Cohort
from lib.student import Student
class CohortRepository():
def __init__(self, connection):
self.connection = connection
def find_with_students(self, cohort_id):
rows = self.connection.execute(
"SELECT cohorts.id, cohorts.name, cohorts.start_date, stude... | TomMazzag/Makers-Learning | Week 5 - Databases/Find_with/lib/cohort_repository.py | cohort_repository.py | py | 826 | python | en | code | 0 | github-code | 1 |
37272849998 | import datetime
import time
import typing
import boto3
import pytest
DEFAULT_WAIT_UNTIL_TIMEOUT_SECONDS = 60*10
DEFAULT_WAIT_UNTIL_INTERVAL_SECONDS = 15
DEFAULT_WAIT_UNTIL_DELETED_TIMEOUT_SECONDS = 60*10
DEFAULT_WAIT_UNTIL_DELETED_INTERVAL_SECONDS = 15
ProxyMatchFunc = typing.NewType(
'ProxyMatchFunc',
typin... | aws-controllers-k8s/rds-controller | test/e2e/db_proxy.py | db_proxy.py | py | 3,439 | python | en | code | 58 | github-code | 1 |
17617829594 | import cv2
import numpy as np
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
from utils import detect_faces, predict_face, StatsStore, emotions, overlay_emoji
cap = cv2.VideoCapture(0)
stats = StatsStore({emot:0 for emot in emotions})
ret, frame = cap.read()
while (ret == True):
ret, frame = cap.read()
... | Core9nvidia/behavioural-assessment | code/emotion_detect.py | emotion_detect.py | py | 1,507 | python | en | code | 0 | github-code | 1 |
6862975559 | import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.optimizers import Adam
from losses import triple_loss, euclidean_dist
from generate_dataset import show_image
import numpy as np
import ra... | dwij2212/face-recognition | scripts/siamese_net.py | siamese_net.py | py | 3,920 | python | en | code | 0 | github-code | 1 |
41307500290 | '''
https://leetcode.com/problems/basic-calculator/description/
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
You may assume that the given expression is alwa... | huiwenhw/interview-prep | leetcode_Python/arr_Calculator.py | arr_Calculator.py | py | 2,121 | python | en | code | 22 | github-code | 1 |
32472440081 | # list_challenge.py
# Append size
def append_size(lst):
lst.append(len(lst))
return lst
print(append_size([23, 42, 108]))
# Append sum
def append_sum(lst):
x = 0
while(x < 3):
lst.append(lst[-1] + lst[-2])
x += 1
return lst
print(append_sum([1, 1, 2]))
# Larger list
def l... | jon-xo/python-practice | lesson-intro/lists/list_challenge.py | list_challenge.py | py | 2,397 | python | en | code | 0 | github-code | 1 |
33052490166 | """
PyCSP3 Model (see pycsp.org)
Data can come:
- either directly from a JSON file
- or from an intermediate parser
Examples:
python WarehouseLocation.py -data=Warehouse_example.json
python WarehouseLocation.py -data=Warehouse_example.txt -dataparser=Warehouse_Parser.py
python WarehouseLocation.py -data=Wareh... | csplib/csplib | Problems/prob034/models/WarehouseLocation.py | WarehouseLocation.py | py | 1,869 | python | en | code | 79 | github-code | 1 |
18273570891 | import torch.nn as nn
from torch.hub import load_state_dict_from_url
import torch
from model.utils import Normalize
from torch.nn.parameter import Parameter
from model.se_resnet import se_resnet_18
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152', 'resnext50_32x4d', ... | SJTUBME-QianLab/Dual-transformation | model/resnet.py | resnet.py | py | 20,984 | python | en | code | 6 | github-code | 1 |
73373964513 | from flask_shop.user import user_bp, user_api
from flask_shop import db, modles
from flask import request
import re
from flask_restful import Resource, reqparse
from flask_shop.utils.token import generate_token, verify_token, login_required
"""
get() 这是个比较特殊的方法。它用于根据主键来返回查询结果,因此它有个参数就是要查询的对象的主键。如果没有该主键的结果返回 None ,否则返回... | xixuan35/VueFlaskPrograms | Flask_Shop/flask_shop/user/views.py | views.py | py | 7,644 | python | en | code | 0 | github-code | 1 |
10995749085 | """
编写一个程序,找到两个单链表相交的起始节点。
如下面的两个链表:
a a1 -> a2
-> c1 -> c2 -> c3
b b1 -> b2 -> b3
在节点 c1 开始相交。
示例 1:
a 4 -> 1
-> 8 -> 4 -> 5
b 5 -> 0 -> 1
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值... | bendanwwww/myleetcode | code/lc160.py | lc160.py | py | 2,969 | python | zh | code | 1 | github-code | 1 |
10220625662 | from . import log
class MemLeak:
"""MemLeak is a caching and heuristic tool for exploiting memory leaks.
It can be used as a decorator, around functions of the form:
def some_leaker(addr):
...
return data_as_string_or_None
It will cache leaked memory (which requires either non-... | 17twenty/pwntools | pwnlib/memleak.py | memleak.py | py | 7,031 | python | en | code | null | github-code | 1 |
24645460146 | """
This module should contain your main project pipeline(s).
Whilst the pipeline may change during the analysis phases, any more stable pipeline should be implemented here so
that it can be reused and easily reproduced.
"""
# This must be set in the beggining because in model_util, we import it
logger_name = "FCRN-BI... | aleksei-mashlakov/fcrn-bidding | src/fcrn_bidding/train_models.py | train_models.py | py | 2,246 | python | en | code | 0 | github-code | 1 |
24523016647 | '''
Need to create 3 stacks using a single list
- Implment basic stack methods isEmpty and isFull, push, pop and peek
- length of each stack should be given.
- While using push, pop and peek methods, input will be given in terms of whihc stack to push to.
Approach:
Init
- Get the size of the single stack from user
- ... | abhi0203/DSAndAlgorithms | ThreeInOneStack.py | ThreeInOneStack.py | py | 2,942 | python | en | code | 0 | github-code | 1 |
29055986749 | from random import randint
from termcolor import cprint
class Сreation:
def __init__(self, name):
self.name = name
self.fullness = 10
self.house = None
class Man(Сreation):
def __init__(self, name):
super().__init__(name=name)
self.happiness = 10
def __str__... | Vladimir-82/code_wars_4 | people_and_cat_live.py | people_and_cat_live.py | py | 4,142 | python | en | code | 0 | github-code | 1 |
6550887142 | #!/usr/bin/env python2
import numpy as np
import cv2
import dlib
from imutils import face_utils
class FaceLandmarksFinder(object):
def __init__(self):
# Pre-trained model from dlib, will use this and
# then extract the landmarks we are interested in
p = "../shape_predictor_68_face_landmar... | Aboushady/Intelligent-Interactive-Systems---Computer-Vision | final/cv_group.py | cv_group.py | py | 3,825 | python | en | code | 2 | github-code | 1 |
16619218295 | """ logging things """
import logging
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s - %(levelname)s] - %(name)s - %(message)s",
datefmt="%d-%b-%y %H:%M:%S",
handlers=[
logging.StreamHandler()
]
)
def LOGGER(name: str) -> logging.Logger:
""" get a Logger object """
... | TelegramPlayGround/jw | jw.py | jw.py | py | 3,901 | python | en | code | 0 | github-code | 1 |
36368184243 | """Demonstration of read an energy config file saved by
https://github.com/xray-imaging/energy2bm in a dictionary
"""
import pickle
import json
import numpy as np
import yaml # pyyaml package name
import toml
def main():
full_file_name0 = 'energy2bm_18.conf'
full_file_name1 = 'energy2bm_20.conf'
inter... | decarlof/sandbox | json/energy_config_interpolate.py | energy_config_interpolate.py | py | 7,906 | python | en | code | 0 | github-code | 1 |
73498488672 | import torch
import time
from collections import OrderedDict
from torch import nn, optim
from torchvision import models
from utility_functions import process_image
def create_new_model(arch, hidden_units):
'''Function loads new pretrained CNN model (tourch.modules), freezes its parameters
and creates new cla... | alexlyss/udacity_rep | AIProgrammingWithPythonNanodegre/FinalProject/model_functions.py | model_functions.py | py | 5,191 | python | en | code | 0 | github-code | 1 |
30114197692 | import random
# Словарь с именами известных людей и датами их рождения
dict_people = {
'A_S_Pushkin': '06.06.1799',
'John_Lennon': '09.10.1940',
'M_Y_Lermontov': '15.10.1814',
'Albert_Einstein': '14.03.1879',
'Steve_Jobs': '24.02.1955',
'Bill_Gates': '28.10.1955',
'Yuri_Gagarin': '09.03.193... | cozmos001/console_file_manager | victorina.py | victorina.py | py | 3,344 | python | ru | code | 0 | github-code | 1 |
30705952137 | from __future__ import annotations
import numpy as np
from .utilities import vensim_name_to_identifier
from pysd.translators.structures.abstract_model import AbstractModel, AbstractSection
from pysd.translators.structures.abstract_expressions import IntegStructure, LookupsStructure, DataStructure
from pysd.translator... | Data4DM/stanify | stanify/builders/vensim_model.py | vensim_model.py | py | 10,792 | python | en | code | 2 | github-code | 1 |
24904622636 | import os
import sys
from sys import path
path.append('./modules')
path.append('./templates')
from flask import Flask, request, current_app
from flask.templating import render_template
import logging
import modules
from modules.process_text import ProcessText
from modules.anonymizeText import anonText
from flask_sqlalc... | jillbaggett81/GenderBiasDetector | app.py | app.py | py | 4,214 | python | en | code | 0 | github-code | 1 |
34139077905 | from model_encoders import *
def segmentation_model_fn(features, labels, mode, params):
print(2)
is_training = mode == tf.estimator.ModeKeys.TRAIN and not params['frozen']
init_model_path = params['init_model_path']
logger.info(f'!!! is_training: {is_training}')
if params['structure_mode'] == 'se... | Rayarrow/Semantic-Segmentation | model_estimators.py | model_estimators.py | py | 6,998 | python | en | code | 1 | github-code | 1 |
24797792076 | from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import csv, os
import pandas as pd
from datetime import datetime as dt
import re
from statistics import mean, median, variance, stdev
import matplotlib.animation as animation
import myErrors
from myUtils import CSVListIn
def ... | isseikz/BitTrader | visualizer.py | visualizer.py | py | 16,360 | python | en | code | 0 | github-code | 1 |
5037856383 | #Definido funções:
def leiaInt(msg):
ok = False
valor = 0
while True:
num = str(input(msg))
if num.isnumeric():
valor = int(num)
ok = True
else:
print('\n\033[1;31mVocê não digitou um número inteiro!\033[m\n')
if ok:
break
r... | anderportela/Learning--Python3--Curso_em_Video | Validando entradas de dados.py | Validando entradas de dados.py | py | 478 | python | pt | code | 0 | github-code | 1 |
42088014549 | #! /usr/bin/env python
import os
import sys
import argparse
import serial
import ctypes
import random
import multiprocessing
import rospy
import numpy as np
import time
import csv
from math import pi
from math import sin, cos
import datetime as dt
from kortex_driver.srv import *
from kortex_driver.msg import *
from se... | kracon7/drive_gen3 | scripts/autonomous_action_pub.py | autonomous_action_pub.py | py | 4,786 | python | en | code | 1 | github-code | 1 |
41977896798 | #!/usr/bin/python
"""This module provides the :class:`Card` object.
This module also has 3 constant attributes that help validate or string format
the :class:`Card` object: :attr:`POSSIBLE_SUIT`, :attr:`POSSIBLE_NUMBER`, and
:attr:`VALUE_TRANSLATION`
"""
#: an array with all the possible suit strings
POSSIBLE_SUIT = [... | suhasgaddam/blackjack-python | blackjack/card.py | card.py | py | 3,627 | python | en | code | 0 | github-code | 1 |
5916633737 | from dataclasses import dataclass
from typing import Dict, Any, List
import pytest
import typing
import pyfury
from pyfury import Fury, Language
def ser_de(fury, obj):
binary = fury.serialize(obj)
return fury.deserialize(binary)
@dataclass
class SimpleObject:
f1: Dict[pyfury.Int32Type, pyfury.Float64T... | alipay/fury | python/pyfury/tests/test_struct.py | test_struct.py | py | 2,479 | python | en | code | 2,061 | github-code | 1 |
10218524773 | #Import-Anweisungen
import snscrape.modules.twitter as twitterscraper
import pandas as pd
#Twitter-Account und Start-Datum für Scraping festlegen
twitter_account = 'HSGStGallen'
start_date = '2015-01-01'
#Leere Liste für die Tweets erstellen
tweets_list = []
#Loop durch die Tweets mit snscrape und zur erstellten Lis... | ThesisCoacher/Data2DollarFS23 | 04_Abgabe Bonuspunkte/SimonettaFrancesco.py | SimonettaFrancesco.py | py | 813 | python | de | code | 3 | github-code | 1 |
38062510333 | from datetime import date, datetime, timedelta
import copy
from django.shortcuts import redirect, render
from home.models import Product, Profile, Purchase, Tag, application_data, custom_user, user_preference
from home.models import custom_user
from django.apps import apps
from rest_framework.response import Response
i... | development0261/photo_studio | admin_site/views.py | views.py | py | 46,430 | python | en | code | 0 | github-code | 1 |
15697686246 | from django.urls import path
from . import views
urlpatterns = [
path('client/<str:pk>', views.client , name="client"),
path('about/', views.about),
path('', views.home , name="home"),
path('book/', views.boook , name="book"),
path('create', views.create , name="create"),
path('update/<str... | KHALIL2309/cabinet-medical-modification2 | cabinetMedical/urls.py | urls.py | py | 419 | python | en | code | 0 | github-code | 1 |
30743913243 | from time import time
import scipy.io as sio
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA as sklearnPCA
from sklearn.decomposition import SparsePCA
import sys,os
from pcp_outliers import pcp
iter =0
os.chdir('/home/niharika-shimona/Documents/Projects/Autism_Network/code/Datas... | Niharika-SD/Dimensionality-Reduction | Connections_PCA.py | Connections_PCA.py | py | 1,673 | python | en | code | 0 | github-code | 1 |
25067663712 | import pytest
import os
from pathlib import Path
import config
def test_output_dir_exists():
assert Path(config.OUTPUT_DIR).exists()
def test_output_dir_writable():
assert os.access(config.OUTPUT_DIR, os.W_OK)
def test_output_subdirectory():
"""check if all the sub-dirs exist, if not create them"""
... | regevti/Pogona_Pursuit | Arena/tests/test_output_dir.py | test_output_dir.py | py | 553 | python | en | code | 0 | github-code | 1 |
2534236 | import scrapy
from ..items import MlcrawlerItem
class MlSpider(scrapy.Spider):
name = 'ml'
start_urls = ['https://www.mercadolivre.com.br/ofertas?page=1']
def parse(self, response, **kwargs):
url = response.xpath('//a[contains(text(),"Alimentos e Bebidas")]/@href').get()
yield scrapy.Requ... | marciobrandstatterprof/ml-crawler | src/mlcrawler/spiders/ml.py | ml.py | py | 1,794 | python | en | code | 0 | github-code | 1 |
2566755036 | # Jan Faryad
# 23. 6. 2017
from math import fabs
import logging
class Conll_coref_adder_new():
def add_coreference( self, doc, id_vectors):
""" main method for adding detected coreference information """
self.list_of_coreferents = []
list_of_pronoun_coreferents = []
self.... | Jankus1994/Coreference | CoNLL/conll_coref_adder_new.py | conll_coref_adder_new.py | py | 6,958 | python | en | code | 0 | github-code | 1 |
72368558753 |
from general_tools import pload
data=pload('93J.p')
out_folder='template_data/sn1993J/'
phases=open(out_folder+'Spec.JD.phases','w')
phases.write('#\n#\n')
for fname in data.keys():
p=float(fname.split('_')[2])
specname=fname[:-13]
phases.write('%s\tfill\t%f\n' %(specname,p))
var=open(out_folder+fn... | kfinn6561/Light_Echoes | read_yuqian.py | read_yuqian.py | py | 553 | python | en | code | 0 | github-code | 1 |
39993672014 | import matplotlib.pyplot as plt
import numpy as np
angle = [-45, 0, 45]
forwards = [4.41, 0.6745, 3.99]
forwardserr = [0.284, 0.243, 0.264]
backwards = [-2.82, 0.00633, -3.387]
backwardserr = [0.294, 0.523, 0.429]
spinforwards = (forwards[0] - forwards[2])/2.0
spinbackwards = (backwards[0] - backwards[2])/2... | CBermingham/Photonic_Force | spinmomentum.py | spinmomentum.py | py | 2,130 | python | en | code | 0 | github-code | 1 |
30191290572 | def solve(root):
# CODE HERE
q = deque([None, root])
if not root or (not root.left and not root.right):
return 0
sum = 0
while q:
n = q.pop()
if n:
if n.left:
q.appendleft(n.left)
if n.right:
q.appendleft(n.right)
... | DevMatrix1/dsa-practice | Python/vedant_bhatnagar/DevsnestProblems_THA/Phase_2/Trees/sumofleftleaves.py | sumofleftleaves.py | py | 541 | python | it | code | 13 | github-code | 1 |
73577565155 | import requests
from bs4 import BeautifulSoup
import pandas as pd
url="https://www.ptt.cc/bbs/NBA/index.html"
#在headers中加入User-Agent參數模仿瀏覽器搜尋網站
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36'}
response = requests.get(url,headers... | HuangJoseph710/WebCrawler_practice | ptt_nba/ptt_nba_excel.py | ptt_nba_excel.py | py | 1,139 | python | en | code | 0 | github-code | 1 |
32484873171 | import sys
n = int(sys.stdin.readline().strip())
stats = []
team_s = []
team_l = []
combi = []
min_ = 1e9
for _ in range(n):
stats.append(list(map(int, sys.stdin.readline().strip().split())))
def org_team(x):
global min_, team_l, S_stat, L_stat
if len(team_s) == n//2:
S_stat = 0
L_stat ... | CrimsonTheLegoBuilder/MyBaekjoonSolve | Python_/bj14889_StartLink_my.py | bj14889_StartLink_my.py | py | 1,255 | python | en | code | 0 | github-code | 1 |
39999052014 | import modulefinder
import git
import yaml
import sys
import os
import fnmatch
import pprint
########################################################################
class Versions(object):
""""""
#----------------------------------------------------------------------
def __init__(self, scriptfname):
... | cbernet/heppy | heppy/utils/versions.py | versions.py | py | 1,986 | python | en | code | 9 | github-code | 1 |
26482348081 | # -*- coding: utf8 -*-
import telegram
import configparser
from handlers import Handlers
from loguru import logger
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
class ChrisBot:
def __init__(self, configfile):
self.__InitBot(configfile)
self.Addservices()
def __Init... | BourneXu/ChrisBot | ChrisBot.py | ChrisBot.py | py | 1,656 | python | en | code | 0 | github-code | 1 |
69860094434 | #!/usr/bin/python3
import json
import datetime
import uuid
from models import storage
class BaseModel:
def __init__(self, *args, **kwargs):
if kwargs:
for key, value in kwargs:
if key == "__class__":
continue
if key in ["created_at", "updated... | Tboy54321/trials | hbnb/models/base_model.py | base_model.py | py | 1,518 | python | en | code | 0 | github-code | 1 |
8097860585 | from irmagician import IrMagician
# irMagicianに接続 --- (*1)
mag = IrMagician("/dev/ttyACM0")
# キャプチャを実行 --- (*2)
while True:
print("> 赤外線リモコンのボタンを押してください")
print("...")
r = mag.ir_capture()
if r.find("Time Out") > 0 or r == "":
print("失敗(ToT)")
continue
print("ok")
break
mag.clo... | akiraseto/irremocon | ircapture.py | ircapture.py | py | 390 | python | ja | code | 0 | github-code | 1 |
71026939555 | import tkinter as tk # Importing the tkinter for the window
import random # Importing random to get random choice for the computer
import Game_class as gc # Importing the parent class to get necessary methods and constructor
# Rock-Paper-Scissors class
class rock_paper_scissors(gc.Game_Setup):
# Constructor of the... | TyronBech/Py_Games | RPS.py | RPS.py | py | 7,919 | python | en | code | 0 | github-code | 1 |
19574236996 | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import os
import sys
import scipy as sp
from scipy import stats
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp
plt.rcParams["figure.figsize"] = (14,8)
plt.rcParams['font.size'] = 14
purp = '#44015... | yazaazou/6950_project | weekly_temp_dist.py | weekly_temp_dist.py | py | 5,259 | python | en | code | 0 | github-code | 1 |
35876387514 | from django.db import models
from django.contrib.auth.models import User
from PIL import Image
from django.utils.translation import gettext_lazy as _
# Create your models here.
# I'm using "pillow" which is a library for working with images within python
# I can add other additional fields for info like bio and stuff... | PeterMarchev/MedHelp | users/models.py | models.py | py | 2,734 | python | en | code | 0 | github-code | 1 |
71109773794 | """
Functions to initialize the arkOS Kraken server.
arkOS Kraken
(c) 2016 CitizenWeb
Written by Jacob Cook
Licensed under GPLv3, see LICENSE.md
"""
import eventlet
import logging
import ssl
from logging.handlers import RotatingFileHandler
from kraken import auth, genesis
import arkos
from arkos import logger
from... | arkOScloud/kraken | kraken/application.py | application.py | py | 4,896 | python | en | code | 5 | github-code | 1 |
41245291352 | import math
from musicutils import normalize_pitch, CHROMATIC_NOTES_SHARP, CHROMATIC_NOTES_FLAT
class Temperament:
"""
In musical tuning, temperament is a tuning system that defines the
notes (semitones) in an octave. Most modern Western musical
instruments are tuned in the equal temperament system b... | walterbender/musicutils | temperament.py | temperament.py | py | 19,234 | python | en | code | 1 | github-code | 1 |
23724167253 | import boto3
from langchain.document_loaders import UnstructuredWordDocumentLoader
import logging
from botocore.exceptions import ClientError
import tempfile
from langchain.schema.document import Document
from typing import Tuple, List
def process_docx(s3_client: boto3.client, bucket_name: str, file_key: str) -> Tupl... | Giocrisrai/chatpdfgio | api/app/docx_processing.py | docx_processing.py | py | 1,977 | python | en | code | 0 | github-code | 1 |
71863134753 |
# build cov matrix
import numpy as np
import matplotlib.pylab as plt
data = np.loadtxt('3Ddata.txt')
x = data[:, 0:3]
# build graph
# distance matrix
def distance_matrix(data):
'''
tested
'''
distances = np.zeros([data.shape[0], data.shape[0]])
for (i, pointi) in enumerate(data):
for (j... | amanzotti/machine_learning | hw2/isomap.py | isomap.py | py | 3,499 | python | en | code | 0 | github-code | 1 |
25058272752 | import numpy as np
import nibabel as nib
import matplotlib.pyplot as plt
import scipy.io as scio
import os
import cv2
def temporal_pattern_fig_generation(temporal_path, save_fig_path):
basises = os.listdir(temporal_path)
for basis in basises:
sub_id = basis.split('_')[0]
part_id = basis.split(... | Shawey94/Gyral_Sulci_Project | Code/VisualizationInBroswer/temp_figs_generation.py | temp_figs_generation.py | py | 2,787 | python | en | code | 0 | github-code | 1 |
31386516576 | from lingpy import *
import networkx as nx
import igraph
from sys import argv
from lingpy.thirdparty import linkcomm
# preprocessing, load data, and modify the rimes
wl = Wordlist('O_shijing.tsv', col='shijing', row='stanza')
# define colors for vowels
colors = {
'ə' : ['black', 'red'],
'a' : ['white', 'green... | digling/shijing | C_refine_network.py | C_refine_network.py | py | 7,404 | python | en | code | 2 | github-code | 1 |
43299079454 | # --------------------------------------------------------------
# File: /my_server_app.py
# Project: Flask-Demo
# Author: Adrian Gould <Adrian.Gould@nmtafe.wa.edu.au>
# Created: 14/04/2021
# Purpose: ...
#
# Renamed app.py to my_server_app.py and removed client based
# code, except for some basic details
# --... | AdyGCode/Flask-Demo-2021S1 | my_server_app.py | my_server_app.py | py | 4,490 | python | en | code | 1 | github-code | 1 |
31635357894 | import math
from itertools import permutations
def check_prime(number: int) -> bool:
if number == 2:
return True
if number == 1 or number % 2 == 0:
return False
for i in range(3, math.floor(math.sqrt(number))+1, 2):
if number % i == 0:
return False
return True
per... | bentondavidl/ProjectEuler | Python/(41)Pandigital prime.py | (41)Pandigital prime.py | py | 564 | python | en | code | 0 | github-code | 1 |
38258568212 | import xml.etree.ElementTree
import sys
import collections
import os
import fnmatch
import pickle
# adapting http://stackoverflow.com/questions/1912434/how-do-i-parse-xml-in-python (ElementTree)
# Constants
kWindowSize = 4
def main():
'''
Invocation: python process_xml.py <dirname>
'''
#if True: retu... | tosmith97/cs224n | process_xml.py | process_xml.py | py | 4,871 | python | en | code | 0 | github-code | 1 |
40282545729 | import os
import spacy
from spacy import displacy
from typing import Optional, Union, List, Dict
class EntityRecognizer:
"""
A class that performs entity recognition using a specified model.
Args:
model_path (Union[str, os.PathLike]): The path to the entity recognition model.
doc (Optional... | yukunzGIT/ubc_cymax_nlp_product_knowledge_graph | src/entity_recognizer/entity_recognizer.py | entity_recognizer.py | py | 2,925 | python | en | code | 0 | github-code | 1 |
73373973793 | """empty message
Revision ID: c6b96b2c1007
Revises: 3c62dfd278cf
Create Date: 2023-05-16 16:27:57.244815
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c6b96b2c1007'
down_revision = '3c62dfd278cf'
branch_labels = None
depends_on = None
def upgrade():
# ... | xixuan35/VueFlaskPrograms | Flask_Shop/migrations/versions/c6b96b2c1007_.py | c6b96b2c1007_.py | py | 1,020 | python | en | code | 0 | github-code | 1 |
702464164 | from utomarket.skip_util import *
from utomarket.util import *
from selenium.webdriver.common.keys import Keys
from .personal_center_util import select_mode
def ad_detail_o(browser, name): # 进入广告详情
ad_div = browser.find_element_by_xpath("//a[contains(text(),'%s')]/../../.." % name)
click_btn = ad_div.find_e... | guzhijun369/test3 | utomarket/transaction.py | transaction.py | py | 6,502 | python | en | code | 0 | github-code | 1 |
7383920959 | """ """
import numpy as np
import cv2
from time import time
def timeit(func):
def call(*args, **kwargs):
t0 = time()
ret = func(*args, **kwargs)
t1 = time()
print(t1 - t0)
return ret
return call
class Filter:
def __init__(self, size):
pass
class Image:
... | mghmgh1281375/POCS | Resize/Image.py | Image.py | py | 2,463 | python | en | code | 4 | github-code | 1 |
21334497683 | import unittest
from HTMLTestRunner.runner import HTMLTestRunner
from sauce_demo_test import SauceDemoTestCase
from selenium_site_test import SeleniumEasyTest
# Test Suit Class
class TestingClass(unittest.TestCase):
# Test Suit for all the other tests
def test_suit(self):
my_test_suit = unittest.Tes... | nqryn/ITS-TA20 | lazarica_petrut/lazarica_petrut_proiect_final.py | lazarica_petrut_proiect_final.py | py | 805 | python | en | code | 0 | github-code | 1 |
18929231493 | import torch
import torch.nn as nn
from torch.autograd import Variable
import torchvision
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import numpy as np
import matplotlib.pyplot as plt
# Linear Regression:
# Hyper Params:
inputSize = 1
outputSize = 1
numEpochs = ... | RonTeichner/deepLearningCourse | LinearRegression.py | LinearRegression.py | py | 3,189 | python | en | code | 0 | github-code | 1 |
18291787743 | import pygsheets
import pandas as pd
import tkinter as tk
from tkinter import filedialog
import re
import datetime
from time import time
from DV360_checkedlatecampaign import update_main
today = datetime.datetime.now()
postdate = (str(today.year) + str(today.month).zfill(2))
gc = pygsheets.authorize(service_file=r'C:... | pandemonium0225/PyCharm_Office | DV360_Tracker_Info.py | DV360_Tracker_Info.py | py | 11,713 | python | en | code | 0 | github-code | 1 |
72840976035 | import polars as pl
# Візуалізувати дані
import matplotlib.pyplot as plt
import numpy as np
import mplcyberpunk
plt.style.use("cyberpunk")
"""
Завдання 3 із завантаження даних
Завантажте дані по вказаному посиланню, відкрийте як csv файл, в параметрах функції
вкажіть що немає заголовка в першому рядку... | VAlduinV/KPI_tasks | HW_1/py_files/third.py | third.py | py | 1,615 | python | uk | code | 0 | github-code | 1 |
32062231307 | from django.shortcuts import render, redirect
from django.db.models import Q
from .forms import ClientForm, ImmobileForm, RegisterLocationForm
from .models import Immobile, ImmobileImage
# Create your views here.
def list_location(request):
immobiles = Immobile.objects.filter(is_locate=False)
context = {'imm... | djangomy/immobile | myapp/views.py | views.py | py | 3,059 | python | en | code | 5 | github-code | 1 |
31663756224 | # author: sunshine
# datetime:2022/3/17 下午5:36
# -*- coding: UTF-8 -*-
import re
import sys
import datetime
import subprocess
from Crypto.Cipher import AES
from binascii import a2b_hex
from binascii import b2a_hex
class LicenseEncode:
def __init__(self, mac, license_path, expired_date=None):
self.mac = ma... | fushengwuyu/encrypt_license | app/license_utils.py | license_utils.py | py | 3,832 | python | en | code | 2 | github-code | 1 |
410370430 | from __future__ import absolute_import
import datetime
from datetime import date
from tests import util
import time
import transitfeed
class ServicePeriodValidationTestCase(util.ValidationTestCase):
def runTest(self):
# success case
period = transitfeed.ServicePeriod()
repr(period) # shouldn't crash
... | google/transitfeed | tests/transitfeed/testserviceperiod.py | testserviceperiod.py | py | 20,858 | python | en | code | 670 | github-code | 1 |
12994031629 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import tensorflow as tf
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
import pdb
from glimpse import GlimpseNet, EmissionNet, ContextNet
from utils impor... | AthiraJacob/Deep-RAM | dram.py | dram.py | py | 9,330 | python | en | code | 0 | github-code | 1 |
27780604033 | #推导式
p = [x for x in range(10)]
print(p)
cells = [(row,col) for row in range(1,10) for col in range(1,10)]
for cell in cells:
print(cell)
#字典推导式
my_text = "I love you,i love sxt,i love gaoqi"
char_count = {c:my_text.count(c) for c in my_text}
print(char_count)
#集合推导式
#迭代器推导式
ant = (x for x in range(1,20))
print... | Chuyongwei/Python-study | 小魏的永恒花园/推导式.py | 推导式.py | py | 370 | python | en | code | 0 | github-code | 1 |
36525627257 | from django.contrib.auth.mixins import UserPassesTestMixin
import xlsxwriter
from django.http import HttpResponse
from openpyxl import load_workbook
from .models import Student, MyUser, UsersData
from .forms import UploadExcelFileForm
import datetime
def read_excel_with_students(request_file):
'''Function to read... | vb1152/school2 | school/utils.py | utils.py | py | 9,081 | python | en | code | 0 | github-code | 1 |
3203854814 | from PyQt5.Qt import (QThread)
from PyQt5.QtCore import QTimer,QEventLoop,pyqtSignal
from PyQt5.QtWidgets import QApplication
from ulitities.base_functions import echoRuntime
from predict import predict
from main_gui import mywindow,Signal
import logging,time
class main_thread(QThread):
main_signal = pyqtSignal()
... | scrssys/SCRS_RS_AI | main_thread.py | main_thread.py | py | 2,433 | python | en | code | 1 | github-code | 1 |
17697300434 | #Global variables
game_still_going = True
current_player = "X"
winner = None
print("Tic Tac Toe")
#Board
board = ["-","-","-",
"-","-","-",
"-","-","-"]
def print_board():
print(board[0] + "|" + board[1] + "|" +board[2])
print(board[3] + "|" + board[4] + "|" +board[5])
print(board[6]... | ShreyasLokhande/Python-Tic-Tac-Toe | tic_tac_toe.py | tic_tac_toe.py | py | 3,826 | python | en | code | 0 | github-code | 1 |
19786642186 | #coding:utf-8
import re
from statistics import stdev
class McbReader:
def __init__(self, path):
self.path = path
def sentence(self):
'''
形態素解析ではなく、1文ごとに区切られたテキストが必要な時
'''
f = open(self.path, 'r', encoding="utf-8")
text = f.read()
f.close()
text... | YoshikiImatake/nlp-tools | McbReader.py | McbReader.py | py | 2,527 | python | ja | code | 0 | github-code | 1 |
7469433464 | #Python Tutorial for Beginners 7: Loops and Iterations - For/While Loops
# nums = [1, 2, 3, 4, 5]
# for num in nums:
# if num == 3:
# print('Found!')
# break #se por continue ele põe found no 3 e continua listando
# print(num)
# for num in nums:
# for letter in 'abc':
# print(num,... | lucasgoncalvess/SEII-LucasGoncalveseSilva | Semana 2/prog07.py | prog07.py | py | 526 | python | en | code | 0 | github-code | 1 |
72377919714 | import time
import requests
def get_num():
req = requests.get("https://desafios.cysource.com.br/PYTHON/stage1.php")
for line in req.text.split("<h3"):
if 'class="text-center">' in line:
cont = line.split("h3")[0].split("<")[0].split(">")[1]
try:
return eval(cont... | lvluanvinicius/ITSafe-Python-Scripts | Flask/Ex03/desafios/stage1.py | stage1.py | py | 898 | python | en | code | 0 | github-code | 1 |
37798513559 | import pytest
import meshio
from . import helpers
h5py = pytest.importorskip("h5py")
@pytest.mark.parametrize(
"mesh",
[
helpers.empty_mesh,
helpers.line_mesh,
helpers.tri_mesh,
helpers.tri_mesh_2d,
helpers.tet_mesh,
],
)
def test_io(mesh, tmp_path):
helpers.... | nschloe/meshio | tests/test_moab.py | test_moab.py | py | 563 | python | en | code | 1,691 | github-code | 1 |
69883606114 | """ from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.decorators import action
# Create your views here.
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.http import JsonResponse
from ... | Dhanush3213/Construction-cost-prediction-using-ml | server/APIProject/Prediction/views.py | views.py | py | 11,761 | python | en | code | 3 | github-code | 1 |
29452718616 | #
from timeit import default_timer
from scipy.spatial import distance_matrix as calc_distance_matrix
from verypy.classic_heuristics.parallel_savings import parallel_savings_init, clarke_wright_savings_function
from verypy.classic_heuristics.gaskell_savings import gaskell_lambda_savings_function, gaskell_pi_savings_func... | jokofa/NRR | baselines/savings.py | savings.py | py | 1,426 | python | en | code | 2 | github-code | 1 |
24295676759 | n = int(input())
count = 1
stack = []
result = []
for i in range(1, n+1):
data = int(input())
while count <= data: #입력받은 데이터에 도달할 때까지 삽입
stack.append(count)
count +=1
result.append('+')
if stack[-1] == data:
stack.pop()
result.append('-')
else:
print('No... | HyunSung-Na/TIL-algorism | 알고리즘/exam3.py | exam3.py | py | 398 | python | en | code | 0 | github-code | 1 |
5310380367 |
def helper(arr,n):
sum1=[]
d=[]
arr.sort()
def all_sub_sum(ind,d,sum1):
sum1.append(d[:])
for i in range(ind, n):
if i != ind and arr[i] == arr[i - 1]:
continue
d.append(arr[i])
all_sub_sum(i+1,d,sum1)
d.pop()
all_su... | Sourolio10/Leetcode-Practice | Recursion/Subsequences-Backtracking/subset_sum2.py | subset_sum2.py | py | 508 | python | en | code | 0 | github-code | 1 |
27744834926 | from typing import cast
import pytest
from gmpy2 import mpz
from pvss.asn1 import PreGroupValue
from pvss.zq import ZqGroup
def test_init() -> None:
with pytest.raises(ValueError, match="q is negative"):
ZqGroup(mpz(-13))
with pytest.raises(ValueError, match="q not prime"):
ZqGroup(mpz(12))... | joernheissler/pvss | tests/test_zq.py | test_zq.py | py | 1,976 | python | en | code | 6 | github-code | 1 |
8876634332 | """
FILE: reg_test.py
LAST MODIFIED: 17-04-2017
DESCRIPTION:
Radial Basis Function non-rigid registration of point clouds
===============================================================================
This file is part of GIAS2. (https://bitbucket.org/jangle/gias2)
This Source Code Form is subject to the terms of t... | musculoskeletal/gias2 | dev/rbfreg/reg_test.py | reg_test.py | py | 11,191 | python | en | code | 0 | github-code | 1 |
30491405724 | import numpy as np
from metadrive.examples.ppo_expert.numpy_expert import ckpt_path
from policydissect.metadrive.metadrive_env import MetaDriveEnv
from policydissect.utils.policy import ppo_inference_tf
# neuron at layer 0, index 123 is for lateral control
# neuron at layer 0, index 249 is for speed control
PPO_EXPER... | metadriverse/policydissect | play/play_metadrive.py | play_metadrive.py | py | 1,486 | python | en | code | 38 | github-code | 1 |
6335152002 | #!/usr/bin/env python
import arrow
from entry_db import EntryDB
from journal_entry import JournalEntry
import urwid
from edit import EditDisplay
from horizontal_menu import horizontal_menu,HorizontalMenu,SubMenu,Choice,EditMenu
from io import StringIO
editor_palette = [
('body','black','light cyan'),
('foot','... | MaxPrehoda/Jourminal | journal_app.py | journal_app.py | py | 4,728 | python | en | code | 4 | github-code | 1 |
41618660742 | from flask import Flask, render_template, request
import requests
import json
app = Flask(__name__)
@app.route('/')
def main_page():
return render_template('index.html')
@app.route('/search')
def search():
keyword = request.args.get('keyword')
payload = {'query':{'match_phrase':{'text':keyword}}}
r = reque... | qychen/TwittMap | main.py | main.py | py | 917 | python | en | code | 0 | github-code | 1 |
10991585048 | """aqmsProjectFile URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Cla... | subha9999/Air-Quality-Monitoring-System | aqmsproject/urls.py | urls.py | py | 1,262 | python | en | code | 0 | github-code | 1 |
71786252515 | def printHand(value):
hands = {1: 'Rock', 2: 'Paper', 3: 'Scissors'}
return hands.get(value)
def evaluate(userInput, computerInput):
if userInput == computerInput:
return "It is a draw"
elif userInput == 1 and computerInput == 2:
return "You lose"
elif userInput == 2 and computerIn... | AnmolBaldawa/Python-Practice | Rock Paper Scissors/Utils.py | Utils.py | py | 465 | python | en | code | 0 | github-code | 1 |
22495404935 | import requests
import json
def get_temperature_forecast(forecast_days, latitude, longitude):
api_url = f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&hourly=temperature_2m,precipitation_probability&forecast_days={forecast_days}"
# Send the API request
response = reques... | SarvagyaVaish/AI-Climate-Hackathon | backend/weather.py | weather.py | py | 2,645 | python | en | code | 1 | github-code | 1 |
32907596006 | # -*- coding: utf-8 -*-
from sora.iobuffer import IOBuffer
from sora.parser import Uncomplete
class DataHandler(object):
""" parser data and pass to callback """
def __init__(self, parser, callback):
self.parser = parser
self.callback = callback
self.buffer = None
def __call__(self... | mayflaver/sora | sora/datahandler.py | datahandler.py | py | 671 | python | en | code | 18 | github-code | 1 |
38662641179 | age = 20 # integer
price = 19.95 # float
first_name = "Sebastian" # string
is_online = False # bool
print(age)
# name = input("What is your name?: ")
# print(f"Hello {name}.")
# birth_year = input("Enter your birth year: ")
# age = 2020 - int(birth_year)
# print(f"Your age is: {age}")
course = "Python for Begin... | sheucke/PythonBeginner | app.py | app.py | py | 656 | python | en | code | 0 | github-code | 1 |
30328706454 | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
mat = [[0]*len(matrix[0]) for _ in range(len(matrix))]
dirs = [(-1,0),(1,0),(0,-1),(0,1)]
for i in range(len(mat)):
for j in range(len(mat[0])):
for di in dirs:
x ... | simratsingh14/algorithmns | 329-longest-increasing-path-in-a-matrix/329-longest-increasing-path-in-a-matrix.py | 329-longest-increasing-path-in-a-matrix.py | py | 1,184 | python | en | code | 0 | github-code | 1 |
72957137315 | __author__ = 'Williamchuang'
import turtle
t = turtle.Turtle()
wn = turtle.Screen()
wn.setworldcoordinates(-300, -300, 300, 300)
t.color("blue")
t.turtlesize(2)
t.shape("turtle")
f = open("record.txt", "r")
for aline in f:
items = aline.split()
if items[0] == "UP":
t.up()
else:
if items[0]... | athertoncapital/Python_Programming | lab7/replay_turtle.py | replay_turtle.py | py | 477 | python | en | code | 0 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.