id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
6428142 | <reponame>wesferr/Zombicide
# Copyright (c) 2018 by <NAME>. All Rights Reserved.
from pygame import *
from pygame.locals import *
class spriteButton(sprite.Sprite):
def __init__(self, screen, link, (x,y), (wid, hei)):
sprite.Sprite.__init__(self)
self.imgButton = image.load(link).convert_alpha()
... | StarcoderdataPython |
3564386 | <gh_stars>0
import torch
import numpy as np
from utils.functions import evaluation
from utils.re_ranking import re_ranking, re_ranking_gpu
from model.lmbn_n_fused import LMBN_n_Fused
from dgnet.utils import get_all_data_loaders, prepare_sub_folder, write_loss, get_config, write_2images, Timer
from dgnet.trainer import ... | StarcoderdataPython |
12849305 | # Copyright 2018 luozhouyang
#
# 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 or agreed to in writing, ... | StarcoderdataPython |
4974485 | """
Created by Sayem on 18 April, 2021
All rights reserved. Copyright © 2020.
"""
from Crypto import Random
from Crypto.Cipher import AES
import base64
from hashlib import md5, sha256
__author__ = "Sayem"
class AESCipher(object):
def __init__(self, key):
self.bs = AES.block_size
self.key ... | StarcoderdataPython |
8172201 | <filename>dashboard/urls.py
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.notifications, name="dashboard"),
#path("class", views.classupdates, name="classupdates")
] | StarcoderdataPython |
4820588 | from fabric.api import env, task
from envassert import detect, package, port, process, service
from hot.utils.test import get_artifacts, http_check
@task
def check():
env.platform_family = detect.detect()
site = "http://localhost/"
string = "example.com"
apache_process = 'apache2'
php_package = '... | StarcoderdataPython |
3546231 | #/u/GoldenSights
import praw
import time
import traceback
import sqlite3
''' USER CONFIG '''
APP_ID = ""
APP_SECRET = ""
APP_URI = ""
APP_REFRESH = ""
# https://www.reddit.com/comments/3cm1p8/how_to_make_your_bot_use_oauth2/
USERAGENT = ""
# This is a short description of what the bot does.
# For example "/u/GoldenS... | StarcoderdataPython |
104765 | <reponame>kampelmuehler/synthesizing_human_like_sketches
import torchvision
import torch.nn as nn
import torch.nn.functional as F
from collections import namedtuple
class PSim_Alexnet(nn.Module):
def __init__(self, num_classes=125, train=True, with_classifier=False):
super(PSim_Alexnet, self).__init__()
... | StarcoderdataPython |
8035449 | <filename>serving/video/common/steps.py
import time
from itertools import cycle
import cv2
import numpy as np
from .meters import MovingAverageMeter
from .pipeline import PipelineStep, AsyncPipeline
from .queue import Signal
from .models import AsyncWrapper
def preprocess_frame(frame, input_height, input_width):
... | StarcoderdataPython |
6570323 | <reponame>Abraham-Xu/TF2
# Copyright 2019 Inspur Corporation. All Rights Reserved.
#
# 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... | StarcoderdataPython |
8064520 | <filename>blog/models.py<gh_stars>1-10
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import QuerySet
from auth.models import CustomUser
class Post(models.Model):
NORMAl = 'N'
HIDDEN = 'H'
DELETED = 'D'
PUBLIC = ... | StarcoderdataPython |
9753590 | <filename>Chapter13.whileandforLoops/continue.py
#!/usr/bin/env python3
#encoding=utf-8
#--------------------------------
# Usage: python3 continue.py
# Description: example for continue
#--------------------------------
x = 10
print('even result: ', end='')
while x:
x -= 1 # x = x - 1
if x % 2 != 0:
... | StarcoderdataPython |
11200861 | import hashlib
file = open("test.txt", "rb")
data = file.read()
data_2 = hashlib.md5(data).hexdigest()
print(data_2[1:33])
print(len(data_2))
| StarcoderdataPython |
9795197 | # Standard library imports
from scrapy import Spider
from scrapy.loader import ItemLoader
# Local application imports
from quotes.items import QuotesItem
quote_item = QuotesItem()
class QuotesSpider(Spider):
""" Web Scraping Spider for Goodreads website. """
# Class attributes
name = "quotes"
start... | StarcoderdataPython |
11206452 | <gh_stars>0
#!/usr/bin/python2.6
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import operator
import os
import sys
import time
import traceback
import geto... | StarcoderdataPython |
1650163 | <filename>tests/test_utils/test_helpers.py
import unittest
class TestHelpers(unittest.TestCase):
def test_slugify(self):
from plenario.utils.helpers import slugify
self.assertEqual(slugify("A-Awef-Basdf-123"), "a_awef_basdf_123")
| StarcoderdataPython |
3407387 | import torch
import numpy as np
# import matplotlib.pyplot as plt
import torch.nn as nn
import torch.nn.functional as functional
from torchvision import transforms, datasets
a = np.array([[0,1], [1,2]])
scalar1 = torch.tensor([1.])
print(scalar1)
scalar2 = torch.tensor([3.])
print(scalar2)
add_scalar = scalar1+sc... | StarcoderdataPython |
4857977 | <gh_stars>0
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from .. import settings
_base = declarative_base()
_engines = dict()
_sessions = dict()
def get_connection_string(engine, user, password, host, port, name, ... | StarcoderdataPython |
1911145 | #!/usr/bin/python3
# 第一个注释
print("hello,word") # 第二个注释
'''
多行注释
多行注释
'''
print('hello,python')
'''
多行语句
'''
sum = 1 + 2 \
+ 3
print(sum)
'''
数字(Number)类型
python中数字有四种类型:整数、布尔型、浮点数和复数。
int (整数), 如 1, 只有一种整数类型 int,表示为长整型,没有 python2 中的 Long。
bool (布尔), 如 True。
float (浮点数), 如 1.23、3E-2
complex (复数), 如 1 + 2j、 1.... | StarcoderdataPython |
8182524 | <filename>openkongqi/exceptions.py<gh_stars>0
# -*- coding: utf-8 -*-
class OpenKongqiError(Exception):
pass
class ConfigError(OpenKongqiError):
pass
class CacheError(OpenKongqiError):
pass
class SourceError(OpenKongqiError):
pass
class FeedError(OpenKongqiError):
pass
class UUIDNotFound... | StarcoderdataPython |
3401880 | <filename>SourceCode/Module5/global_variables1.py
"""
Demonstrates a global variable
"""
#Creates a global variable.
my_value = 10
#The showvalue function prints
#the value of the global variable.
def showvalue():
print(my_value)
# Call the showvalue function.
showvalue()
| StarcoderdataPython |
3226922 | from indra.tools import assemble_corpus as ac
filter_functions = {}
def register_filter(function):
"""
Decorator to register a function as a filter for tests.
A function should take an agent as an argument and return True if the agent
is allowed to be in a path and False otherwise.
"""
filt... | StarcoderdataPython |
3539936 | <reponame>shouvikch97/Hacktoberfest-2k20
import numpy as np
class Function:
def __init__(self, before=None):
self.before = before
if before is None:
self.before_forward = lambda x: x
self.before_diff = lambda _: 1
else:
self.before_forward = before.forward
self.before_diff = before.diff
def _forw... | StarcoderdataPython |
329415 | <gh_stars>1-10
import os
import datetime
import logging
import re
import requests
import json
from requests.auth import HTTPBasicAuth
from dateutil.parser import parse as parse_datetime
from typing import List
import azure.functions as func
from .sentinel_connector import AzureSentinelConnector
from .state_manager imp... | StarcoderdataPython |
6571926 | <filename>web/JPS_EMISSIONS/python/latest/post_process_ccs.py
# ### 1.5 function that post process the ccs results
import numpy as np
import pandas as pd
# define a function that could calculate the overall annual emission and lock emission
def bau_ccs_post (df):
coal_annual_existing_emission = df.loc[:,('c... | StarcoderdataPython |
6413873 | <reponame>adh/appshell
from appshell.skins import Skin
from appshell.assets import assets, appshell_components_css
from flask_assets import Bundle
from appshell import current_appshell
from subprocess import check_output
from markupsafe import Markup
adminlte_js = Bundle('appshell/adminlte/plugins/jquery.slimscroll.mi... | StarcoderdataPython |
324134 | <reponame>inovex/multi2convai<gh_stars>1-10
from abc import abstractmethod
from enum import Enum
from pathlib import Path
from multi2convai.data.label import Label
from multi2convai.pipelines.base import BasePipeline, BasePipelineConfig
from multi2convai.pipelines.multilingual_domain_mappings import Multi2ConvAIMappin... | StarcoderdataPython |
1679397 | <filename>src/clims/services/transition.py
from __future__ import absolute_import
from django.db import transaction
from clims.models.transition import Transition as TransitionModel
from clims.models.transition import TransitionType
from clims.services.container import IndexOutOfBounds, PlateIndex
class TransitionSe... | StarcoderdataPython |
6704399 | import pytest
import autofit as af
from autofit import graphical as g
@pytest.fixture(
name="prior"
)
def make_prior():
return af.GaussianPrior(100, 10)
@pytest.fixture(
name="hierarchical_factor"
)
def make_hierarchical_factor(prior):
factor = g.HierarchicalFactor(
af.GaussianPrior,
... | StarcoderdataPython |
3379243 | import os
import threading
import time
import yarntf
def cluster_spec_test():
"""Assumes ClusterSpecGeneratorServer is running"""
threads = []
os.environ['TENSORBOARD'] = 'true'
for i in range(0, 3):
os.environ['TB_DIR'] = 'tensorboard_' + str(i)
thread = threading.Thread(target=yarntf.createCluster... | StarcoderdataPython |
1905595 | from copy import copy
from math import pow
from decimal import Decimal
from dateutil.parser import parse
from vnpy.api.oanda.const import OandaOrderState, OandaOrderType, OandaOrderPositionFill
from vnpy.api.oanda.utils import str2num
from vnpy.trader.vtObject import VtOrderData, VtPositionData, VtAccountData, VtCont... | StarcoderdataPython |
3427914 | <reponame>zidarsk8/aoc2020
test_data = """
mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
mem[8] = 11
mem[7] = 101
mem[8] = 0
""".strip()
test_data2 = """
mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
mem[8] = 11
mem[7] = 101
mem[8] = 0
mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
mem[9] = 11
mem[10] = 102
mem[9] = 0
""".s... | StarcoderdataPython |
1932955 | import sys
import warnings
from dataclasses import dataclass, field
from difflib import SequenceMatcher
from typing import Dict, List, NamedTuple, Optional
import numpy as np
from .thermodynamic_restrictions import ComplexFormation, DuplicateError, ThermodynamicRestrictions
class UnregisteredRule(NamedTuple):
e... | StarcoderdataPython |
326590 | from utils.db import *
from infiniti.params import *
import os
from utils.helpers import *
class Address(object):
incoming_value = 0
outgoing_value = 0
utxo = []
stxo = []
pubkey = None
address = None
wallet = None
def __init__(self,address=None,public_key = None,wallet_name=None):
self.pubkey = public_key
... | StarcoderdataPython |
3226396 | from utlis.rank import setrank,isrank,remrank,remsudos,setsudo, GPranks
from utlis.send import Name,Glang
from utlis.tg import Bot
from config import *
from pyrogram import ReplyKeyboardMarkup, InlineKeyboardMarkup, InlineKeyboardButton
import threading, requests, time, random, re,json
import importlib
def d... | StarcoderdataPython |
11232422 | from os.path import join, abspath, dirname
from setuptools import setup, find_packages
_here = abspath(dirname(__file__))
with open(join(_here, "./README.md")) as f:
readme = f.read()
setup(
name="jac_format",
version="0.1.4",
description="JAC (JSON as CSV) Format Conversion",
long_description=r... | StarcoderdataPython |
11222485 | # Copyright © 2021 Splunk, Inc.
#
# 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 or agreed to in writing,... | StarcoderdataPython |
9668416 | <filename>src/commercetools/testing/predicates.py<gh_stars>0
import ast
import logging
import operator
import re
import typing
import marshmallow
logger = logging.getLogger(__name__)
token_pat = re.compile(
r"""
(
(?:\d+\.\d+) | # Floats
(?:\d+) | # Integers
"(?:\\.|[... | StarcoderdataPython |
394223 | <reponame>defnngj/movie-website
"""
author: bugmaster
data: 2021-09-25
function: 爬取 豆瓣 top250 电影信息
"""
import os
import sqlite3
from requests_html import HTMLSession
session = HTMLSession()
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMG_DIR = os.path.join(BASE_DIR, "static", "images")
def save_db(name, im... | StarcoderdataPython |
11359287 | <reponame>Guilherme-Lanna/Python
from datetime import date
print('Me de algumas informações para eu saber sobre seu alistamento militar!')
atual = date.today().year
ano = int(input('Qual o seu ano de nascimento? '))
idade = atual - ano
if idade < 18:
print('Você deve se alistar daqui {} anos'.format(18-idade))
elif... | StarcoderdataPython |
51848 | <filename>app/db/models.py
import datetime
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
db = SQLAlchemy()
class Users(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, unique... | StarcoderdataPython |
9610633 | #!d:/python27/python -u
"""
Qt-for-Python (PySide2) GUI drawing framework
"""
import sys
import math
from PySide2 import QtGui, QtCore, QtWidgets
__author__ = '<NAME>'
__copyright__ = '2018'
__credits__ = []
__license__ = "MIT"
__version__ = "0.3"
__email__ = '<EMAIL>'
__status__ = 'Prototype'
... | StarcoderdataPython |
247385 | # Copyright 2015-2021 <NAME>
#
# This file is part of phonemizer: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# Phonemizer is distributed in the ho... | StarcoderdataPython |
9614982 | """Information about Python operators"""
from typing_extensions import Final
# Map from binary operator id to related method name (in Python 3).
op_methods: Final = {
'+': '__add__',
'-': '__sub__',
'*': '__mul__',
'/': '__truediv__',
'%': '__mod__',
'divmod': '__divmod__',
'//': '__floor... | StarcoderdataPython |
3373663 | <reponame>mononobi/charma-server<filename>src/charma/scraper/services.py
# -*- coding: utf-8 -*-
"""
scraper services module.
"""
from pyrin.application.services import get_component
from charma.scraper import ScraperPackage
def get(url, **options):
"""
gets the result of given url and returns a `Response` ... | StarcoderdataPython |
4829973 | import alerts
def handler(event, context):
alert_type = event['currentIntent']['slots']['AlertLevel']
print(alert_type)
alert_response = {
"dialogAction": {
"type": "Close",
"fulfillmentState": "Fulfilled",
"message": {
"contentType": "PlainText... | StarcoderdataPython |
8046184 | from core.advbase import *
def module():
return Xander
class Xander(Adv):
conf = {}
conf['slots.a'] = ['The_Shining_Overlord', 'His_Clever_Brother']
conf['slots.d'] = 'Gaibhne_and_Creidhne'
conf['acl'] = """
if c_s(1, enhanced)
`s3
`s4
`s2
`s1
else
... | StarcoderdataPython |
6503129 | class Solution:
def binaryGap(self, N: int) -> int:
bin_str = str(bin(N))[2:]
output = list()
tmp_index = 0
for index in range(0, len(bin_str)):
if bin_str[index] == "1":
output.append(index - tmp_index)
tmp_index = index
return m... | StarcoderdataPython |
3398952 | <filename>ope-backend/src/core/use_cases/order_use_cases/create_order_use_case.py<gh_stars>1-10
from src.core.validations import create_order_validation as validate
from datetime import datetime
class CreateOrder:
def __init__(self, order_repository):
self.order_repository = order_repository
def crea... | StarcoderdataPython |
1875390 | # Copyright 2016 Google Inc. All Rights Reserved.
#
# 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 or ag... | StarcoderdataPython |
5089468 | #
# Licensed Materials - Property of IBM
#
# (c) Copyright IBM Corp. 2007-2008
#
import unittest, sys
import ifx_db
import config
from testfunctions import IfxDbTestFunctions
class IfxDbTestCase(unittest.TestCase):
def test_015_InsertDeleteRowCount_01(self):
obj = IfxDbTestFunctions()
obj.assert_expect(... | StarcoderdataPython |
5039658 | <gh_stars>0
#Faça um programa que leia nome e peso de várias pessoas, guardando tudo em uma lista. No final, mostre:
#A) Quantas pessoas foram cadastradas. B)Uma listagem com as pessoas mais pesadas.
#C) Uma listagem com as pessoas mais leves.
dados = list()
grupo = list()
pesada = list()
leve = list()
cont = maior = m... | StarcoderdataPython |
120636 | <reponame>TakoiHirokazu/kaggle_commonLit_readability_prize
# ========================================
# library
# ========================================
from scipy.optimize import minimize
import os
import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error
import logging
import sys
from co... | StarcoderdataPython |
1880226 | <reponame>cekicbaris/inm703
from model import *
# -------------------
# Extinction Design
# -------------------
# Define the model
exitinction = Model_Rescorla_Wagner(experiment_name="Extinction", lambda_US=1, beta_US=0.5)
# Define the predictors
A = Predictor(name='A', alpha = 0.2)
# Define the experiment groups
exi... | StarcoderdataPython |
5035874 | ############
# BitTorrent server launch
############
import logging,sys,pdb,time,traceback,os
from thread import get_ident
from operator import mod
#need this prior to BT imports
import gettext
gettext.install('bittorrent', 'locale')
from BitTorrent.launchmanycore import LaunchMany
from BitTorrent.defaultargs imp... | StarcoderdataPython |
1951587 | <reponame>Goodjooy/AzurLane-GirlFrontLine-PaintingRestore
class DefferError(BaseException):
def __init__(self, arg):
self.arg = arg
class AzurLaneWork(BaseException):
def __init__(self, arg):
self.arg = arg
class GirlFrontLaneWork(BaseException):
def __init__(self, arg):
... | StarcoderdataPython |
11253419 | <filename>zeograph/dmeasure.py
"""This module provides functions to calculate graph distances.
"""
__author__ = "<NAME>"
__version__ = "1.0"
__email__ = "dskoda [at] mit [dot] edu"
__date__ = "Oct 7, 2019"
import numpy as np
import networkx as nx
EPS = 1e-10
WEIGHTS_DEFAULT = [0.45, 0.45, 0.10]
def distance_distrib... | StarcoderdataPython |
3376683 | <filename>code/ARAX/test/test_ARAX_resultify.py
#!/usr/bin/env python3
# Usage: python3 ARAX_resultify_testcases.py
# python3 ARAX_resultify_testcases.py test_issue692
import os
import sys
import pytest
sys.path.append(os.path.dirname(os.path.abspath(__file__))+"/../ARAXQuery")
from response import Response
... | StarcoderdataPython |
1720622 | from functools import reduce
from pandas import DataFrame
from pm4py.objects.log.log import Trace, EventLog
from src.labeling.common import add_label_column
ATTRIBUTE_CLASSIFIER = None
PREFIX_ = 'prefix_'
def complex_features(log: EventLog, prefix_length, padding, labeling_type, feature_list: list = None) -> Data... | StarcoderdataPython |
284808 | <filename>imp/dice.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import string
import random
# Simple recursive descent parser for dice rolls, e.g. '3d6+1d8+4'.
#
# roll := die {('+' | '-') die} ('+' ... | StarcoderdataPython |
8170541 | # -*- coding: utf-8 -*-
import torch
from torch import nn
from support_DynamicNet import getActivationList, getPoolingList, convOutputShape
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
class DynamicCNN(nn.Module):
def __init__(self, parameters, print_var = False, tracking_inpu... | StarcoderdataPython |
5052610 | import lief
import sys
import os
import json
def main():
if (len(sys.argv) == 2):
file_name = sys.argv[1]
if os.path.isdir(file_name):
return
pe_binary = lief.parse(file_name)
pe_sections = pe_binary.sections
magic_string = ".appseclimits_"
for section i... | StarcoderdataPython |
5056769 | <reponame>jfaccioni/dynafit
"""test_plotter.py - unit tests for plotter.py."""
import unittest
from typing import Sequence
from unittest.mock import MagicMock, patch
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import PolyCollection
from src.plotter import Plotter
from src.utils imp... | StarcoderdataPython |
156858 | <reponame>Granjow/platformio-core<gh_stars>1-10
# Copyright (c) 2014-present PlatformIO <<EMAIL>>
#
# 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... | StarcoderdataPython |
8108892 | #!/usr/bin/python
'''TuneHub Lyrics Library.
Copyright (C) 2011-2012 <NAME>
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list... | StarcoderdataPython |
4916773 | <reponame>voidstrike/TDPNet
import argparse
import torch
import os
import time
import imageio
import numpy as np
import torchvision.transforms as tfs
import sklearn.cluster as cls
from model.TDPNet import TDPNet
from torch.utils.data import DataLoader
from torch.optim import Adam, lr_scheduler
from torch.autograd impo... | StarcoderdataPython |
1930395 | # Copyright (c) OpenMMLab. All rights reserved.
import importlib
import logging
import os
import tempfile
from functools import partial
import mmcv
import pytest
import torch.multiprocessing as mp
import mmdeploy.utils as util
from mmdeploy.utils import target_wrapper
from mmdeploy.utils.constants import Backend, Cod... | StarcoderdataPython |
5041970 | <filename>cyder/cydhcp/vlan/views.py
from django.shortcuts import get_object_or_404
from cyder.base.views import cy_detail
from cyder.cydhcp.vlan.models import Vlan
def vlan_detail(request, pk):
vlan = get_object_or_404(Vlan, pk=pk)
return cy_detail(request, Vlan, 'vlan/vlan_detail.html', {
'Network... | StarcoderdataPython |
4977707 | import math
import numpy as np
# Returns whether M is in diagonal shape or not
# input: matrix M
# output: boolean
def is_diagonal(M):
A = np.zeros(M.shape)
np.fill_diagonal(A, M.diagonal())
return np.all(A == M)
# Solves Ax = b if A is in diagonal shape
# input: matrix A, vector b
# ou... | StarcoderdataPython |
1698582 | import numpy as np
import scipy.linalg as spla
from embedding import convert_to_graph
def get_degree_matrix(A):
return np.diag(np.sum(A,axis=1),0)
def get_laplacian(A):
return get_degree_matrix(A) - A
def _spectral_clustering_by_connected_components(L):
n,_ = L.shape[0]
u,v = spla.eigh(L)
number_... | StarcoderdataPython |
3388016 | <reponame>Zhylkaaa/nboost<filename>nboost/plugins/qa/base.py<gh_stars>0
from typing import Tuple
import time
from nboost.plugins import Plugin
from nboost.delegates import ResponseDelegate
from nboost.database import DatabaseRow
from nboost import defaults
from nboost.logger import set_logger
class QAModelPlugin(Plug... | StarcoderdataPython |
3424119 | from selenium import webdriver
from time import sleep
from selenium.webdriver.chrome.options import Options
import csv
# Options
chrome_options = Options()
chrome_options.add_argument("--incognito")
chrome_options.add_argument("--headless")
import re
#text_after = re.sub(regex_search_term, regex_replacement, text_bef... | StarcoderdataPython |
1729099 | <filename>webapp/api.py
# Copyright (c) The Diem Core Contributors
# SPDX-License-Identifier: Apache-2.0
from http import HTTPStatus
from typing import Union, Tuple
from uuid import UUID
from flask import Blueprint, Response, jsonify, request, current_app
from liquidity import create_liquidity_provider
from liquidit... | StarcoderdataPython |
5075768 | from django import forms
from mighty.models import PaymentMethod
from mighty.applications.shop.forms.widgets import (
CBNumberInput, CBCVCInput, CBDateInput,
IbanInput, BicInput
)
class PaymentMethodForm(forms.ModelForm):
class Meta:
model = PaymentMethod
fields = ('owner', 'iban', 'bic', '... | StarcoderdataPython |
11231717 | <reponame>bcdarwin/pydpiper
#!/usr/bin/env python
import networkx as nx
import Queue
import cPickle as pickle
import os
import sys
import socket
import time
from datetime import datetime
from subprocess import call
from shlex import split
from multiprocessing import Process, Event
import file_handling as fh
import pip... | StarcoderdataPython |
3386179 | """
Custom HTTP responses in JSON and standardized exceptions.
"""
from settings import *
from django.shortcuts import render
from django.http import HttpResponse
import json
class JsonResponse(HttpResponse):
"""
A JSON response converts a dictionary @d into JavaScript
Object Notation (JSON) and uses the "applicat... | StarcoderdataPython |
1610981 | <filename>app/apps/reporting/migrations/0004_taskreport_gpu_cost.py
# Generated by Django 2.2.23 on 2021-09-20 14:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('reporting', '0003_taskreport_cpu_cost'),
]
operations = [
migrations.Ad... | StarcoderdataPython |
1727738 | # This file is used to initialize the Supervisors package, it can be left blank unless otherwise needed.
# The supervisors package should include pages that supervisors can access. | StarcoderdataPython |
70037 | from __future__ import absolute_import, division, print_function, unicode_literals
from collections import namedtuple
import torch
import torch.nn.functional as F
from tests import utils
class SimpleConvTranspose2dModule(torch.nn.Module):
def __init__(self, stride=1, padding=0, output_padding=0, dilation=1, gro... | StarcoderdataPython |
8012625 | from .. import bp_location
from flask import g
from flask_login import current_user, login_required
from ..forms.location import LocationForm
from database.models import Location, Alert, Access, Role_dict
from web_app.modules._base_views import BaseUserItems, BasePanel, BaseLister, BaseAdder, BaseDeleter, BaseEditer... | StarcoderdataPython |
229163 | <gh_stars>0
import time
import board
import adafruit_si7021
import sys
sensor = adafruit_si7021.SI7021(board.I2C())
print("\nTemperature: %0.1f C" % sensor.temperature)
print("Humidity: %0.1f %%" % sensor.relative_humidity)
sys.exit(0) | StarcoderdataPython |
4847937 | <filename>module2-sql-for-analysis/assignment/main.py
"""Script entry point."""
from titanic import init_script
if __name__ == "__main__":
init_script()
| StarcoderdataPython |
8091260 |
# _return_guides_in_regions.py
__module_name__ = "_return_guides_in_regions.py"
__author__ = ", ".join(["<NAME>"])
__email__ = ", ".join(["<EMAIL>",])
# package imports #
# --------------- #
import pandas as pd
import regex
import seq_toolkit
def _id_PAMs_in_sequence(sequence, PAM, motif_key="pam", verbose=True):... | StarcoderdataPython |
5179170 | """
MIT License
Copyright (c) 2021 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distri... | StarcoderdataPython |
355363 | # coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2015-2016 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to d... | StarcoderdataPython |
173176 | from torch import nn
import torch
from model.Swin import SwinTransformer3D
import copy
class swin_encoder(nn.Module):
def __init__(self , device , drop , checkpoint_encoder):
super().__init__()
checkpoint = checkpoint_encoder
self.device=device
self.label= 'demo/label_map_k400.txt'
... | StarcoderdataPython |
1900085 | <reponame>KuangChih/Design-for-IoT-Middleware<filename>Lab2/Lab2-2.py
void setup() {
pinMode(2, INPUT);
pinMode(13, OUTPUT); //pin 13 for the Led on board
}
void loop() {
int touchPadState = digitalRead(2);
if (touchPadState == HIGH) { //touched
digitalWrite(13, HIGH);
} else {
digit... | StarcoderdataPython |
236173 | <filename>Problem_100_199/euler_125.py<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Problem 125
The palindromic number 595 is interesting because it can be written as the sum of consecutive squares: 62 + 72 + 82 + 92 + 102 + 112 + 122.
There are exactly eleven palindromes below one-thousand that can b... | StarcoderdataPython |
36452 | import torch
from torch import nn
import torch.optim as optim
import torch.multiprocessing as mp
import numpy as np
import time
class MPManager(object):
def __init__(self, num_workers):
"""
manage a single-instruction-multiple-data (SIMD) scheme
:param int num_workers: The number of proces... | StarcoderdataPython |
12851714 | from collections import deque
from itertools import islice
from .base import RollingObject
class Apply(RollingObject):
"""
Iterator object that applies a function to
a rolling window over a Python iterable.
Parameters
----------
iterable : any iterable object
window_size : integer, the ... | StarcoderdataPython |
3545783 | #!/usr/bin/env python3
# Copyright © 2019-2020 Intel Corporation
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... | StarcoderdataPython |
11359010 | import unittest
import sys
# If PATH is properly configured by your IDE you don't
# need this weird fix to dynamically add solutions to PATH
sys.path.append("../solutions")
from proth_theorem import proth
# from solutions.proth_theorem import proth
class ProthTest(unittest.TestCase):
def test_3_proth_prime(self)... | StarcoderdataPython |
9611696 | <filename>grammartest.py
######importe######
import nltk
from nltk import word_tokenize
import nltk.corpus.reader.tagged as tagged
import nltk.tag.hmm as hmm
from grammardefs import *
corpus_tiger= nltk.corpus.ConllCorpusReader('.', 'tiger9', ['ignore', 'words', 'ignore', 'ignore', 'pos'],encoding='utf-8')
trainer = h... | StarcoderdataPython |
6689718 | from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
class UserCreateForm(UserCreationForm):
class Meta:
fields = ('first_name', 'last_name', 'username', 'email', '<PASSWORD>', '<PASSWORD>')
model = get_user_model()
def __init__(self, *args, **kwargs):
... | StarcoderdataPython |
210177 | <reponame>PeakerBee/aioms
import json
from kazoo.client import KazooClient
from discovery.instance import ServiceInstance
from discovery.service import ServiceProvider
class ZookeeperServiceRegistry(ServiceProvider):
def __init__(self, zookeeper: 'KazooClient', root_path: str):
self.zookeeper = zookeep... | StarcoderdataPython |
114882 | <filename>docs/pyplots/volumetrics.py
import matplotlib.pyplot as plt
import numpy as np
exp = 2.0
near = 1.0
far = 10000.0
volumeDepth = 128.0
def volumeZToDepth(z):
return np.power(z / volumeDepth, exp) * far + near
t1 = np.arange(0.0, volumeDepth, 1.0)
plt.plot(t1, volumeZToDepth(t1), 'bo', t1, volumeZToDept... | StarcoderdataPython |
11357836 | <reponame>RohanMiraje/DSAwithPython<filename>DSA/linked_list/single_linked_list/head_tail_linked_list.py
class Node:
def __init__(self, value):
self.data = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_at_beg(self... | StarcoderdataPython |
8142040 | from mp_api.routes.thermo.query_operators import IsStableQuery
from monty.tempfile import ScratchDir
from monty.serialization import loadfn, dumpfn
def test_is_stable_operator():
op = IsStableQuery()
assert op.query(is_stable=True) == {"criteria": {"is_stable": True}}
with ScratchDir("."):
dump... | StarcoderdataPython |
11348128 | <gh_stars>10-100
# Created by MechAviv
# Valentine Damage Skin | (2439897)
if sm.addDamageSkin(2439897):
sm.chat("'Valentine Damage Skin' Damage Skin has been added to your account's damage skin collection.")
sm.consumeItem() | StarcoderdataPython |
3389272 | import itertools
from spw_pkg_guard import spw_pkg_guard
from nMigen_test import mytest, runtests, helper, uut_iface
DEBUG = False
VERBOSE = DEBUG
addr_width = 8
cnt_width = 32
@mytest
class handshake_test(helper):
def get_test_processes(self):
self.ui = ui = uut_iface(spw_pkg_guard(), VERBOSE)
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.