id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
11223726
import sys import logging from PyQt5.QtWidgets import ( QHBoxLayout, QGroupBox, QDesktopWidget, QMainWindow, QApplication, QMenu, QAction, QFileDialog, QSplitter, QActionGroup, QDialog, ) from PyQt5.QtCore import Qt from symupy.postprocess.visunet import logger from symupy...
StarcoderdataPython
255920
# Data taken from the MathML 2.0 reference data = ''' "(" form="prefix" fence="true" stretchy="true" lspace="0em" rspace="0em" ")" form="postfix" fence="true" stretchy="true" lspace="0em" rspace="0em" "[" form="prefix...
StarcoderdataPython
8180384
<reponame>tihbe/PCRITICAL<filename>modules/topologies.py from dataclasses import dataclass, asdict from typing import Union, Tuple import logging import numpy as np import networkx as nx from modules import reporter from scipy.spatial.distance import cdist from scipy.sparse import bsr_matrix, vstack from sklearn.metric...
StarcoderdataPython
398716
<reponame>COVID-Weather/regionmask import warnings import numpy as np import xarray as xr from .utils import _is_180, _wrapAngle, equally_spaced def _mask( self, lon_or_obj, lat=None, lon_name="lon", lat_name="lat", method=None, xarray=None, wrap_lon=None, ): """ create a gri...
StarcoderdataPython
225259
<gh_stars>0 import pickle import re import Levenshtein as lev import numpy as np import pandas as pd from sklearn import metrics from sklearn.metrics import accuracy_score from sklearn.naive_bayes import MultinomialNB class Models: def __init__(self, dataset, baseline1=False, baseline2=False): # Set the ...
StarcoderdataPython
9667943
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from...
StarcoderdataPython
5160403
<gh_stars>1-10 import pytest from boto3 import client from unittest.mock import patch from unittest.mock import MagicMock from botocore.exceptions import ClientError def create_mock_exc(message='', code=''): return ClientError({ 'Error': { 'Message': message, 'Code': code } ...
StarcoderdataPython
8137651
<gh_stars>10-100 from typing import (Callable, Tuple) from ground.base import (Location, Relation) from ground.hints import (Point, Segment) PointInCircleLocator = Callable[[Point, Point, Point, Point], Location] SegmentEndpoints = Tuple[Point, Po...
StarcoderdataPython
6430887
<gh_stars>0 from lingpy import * from sys import argv if 'all' in argv: fname='../output/A_Deepadung_' else: fname='../output/D_Deepadung_' alms = Alignments(fname+'partial.tsv', ref='cogids') alms.align() alms.output('tsv', filename=fname+'aligned', prettify=False)
StarcoderdataPython
3257026
<filename>tests/test_fda.py import numpy as np import unittest import finite_depth_analysis as fda c0 = 299792458 n0 = 1.5 c = c0/n0 def h_old(lambdas, lambda_prime, Z, r=-1, mode=1, k0=0): omega = 2*np.pi*c/lambdas omega_prime = 2*np.pi*c/lambda_prime if mode==2: if Z == 'inf' or Z == 'infini...
StarcoderdataPython
6410322
import os import toml def get_version() -> str: path = os.path.join(os.path.dirname(__file__), "..", "pyproject.toml") config = toml.load(path) version = config["tool"]["poetry"]["version"] return version if __name__ == "__main__": # pragma: no cover print(get_version())
StarcoderdataPython
11287406
#!/usr/bin/env python # coding=utf-8 """ Runs an execution node. """ import sys import ConfigParser from suricate.analytics import exec_node __author__ = 'tmetsch' config = ConfigParser.RawConfigParser() config.read('app.conf') # MongoDB connection mongo = config.get('mongo', 'uri') # Rabbit part broker = config...
StarcoderdataPython
1799319
'''Crie um programa que leia o ano de nascimento de sete pessoas. No final, mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores.''' from datetime import date maior = 0 menor = 0 for c in range(1, 8): nasc = int(input(f'qual o {c}° ano de nascimento? ')) idade = date.today().year - ...
StarcoderdataPython
6675742
<gh_stars>0 from geo.vector import Vector x = Vector([1,2,3]) print(x) print(x == Vector([1,2,3])) print(x == Vector([1,2,-3])) print(x + Vector([1,2,-3])) print(x - Vector([1,2,-3])) print(Vector([1,2,-3]) - x)
StarcoderdataPython
3303664
<reponame>juanrgon/advent-of-code<gh_stars>1-10 TEST = (("3,4,3,1,2", 5934),) TEST2 = (("3,4,3,1,2", 26984457539),) import sys from pathlib import Path from functools import cache import aoc @aoc.submit(part=1) @aoc.get_input @aoc.tests(TEST) @aoc.parse_text def part_1(raw: str, ints: list[int], strs: list[str]): ...
StarcoderdataPython
12833262
#!/usr/bin/env python import socket TCP_IP = '127.0.0.1' TCP_PORT = 7116 BUFFER_SIZE = 20 # Normally 1024, but we want fast response s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((TCP_IP, TCP_PORT)) s.listen(1) conn, addr = s.accept() print '...
StarcoderdataPython
4802173
<filename>classicML/api/plots/callbacks.py from classicML.api.plots import _plt as plt from classicML.api.plots.utils import _set_history_axis_and_background from classicML.api.plots.utils import _history_plot_config def plot_history(history): """可视化历史记录. Arguments: history: classicML.backend.callbac...
StarcoderdataPython
1712334
<filename>hotword.py import snowboydecoder import sys import signal import os.path class hotword: def __init__(self): self.interrupted = False self.model = ''.join([os.path.dirname(__file__), '/HARU.pmdl']) def signal_handler(self, signal, frame): self.interrupted = True def inter...
StarcoderdataPython
103658
<reponame>VU-IVM/Toponym-based-Algorithm-for-Grouped-Geoparsing-of-Social-media import pytz import datetime import operator def isoformat_2_date(datestr): return datetime.datetime.strptime(datestr, '%Y-%m-%dT%H:%M:%S') def daterange(start_date, end_date, timedelta, ranges=False, include_last=False, UTC=False): ...
StarcoderdataPython
9733865
<filename>venv/Lib/site-packages/pybrain/rl/explorers/__init__.py from discrete.__init__ import * from continuous.__init__ import *
StarcoderdataPython
3288584
from ._basic import FilterConstant from ._gbdt import GBDTFeatureSelector
StarcoderdataPython
330624
<filename>scrapy/tests/test_settings.py import unittest from scrapy.settings import Settings from scrapy.utils.test import get_crawler from scrapy.spider import BaseSpider class SettingsTest(unittest.TestCase): def test_get(self): settings = Settings({ 'TEST_ENABLED1': '1', 'TEST_...
StarcoderdataPython
5015976
import logging from ast import literal_eval from datetime import datetime from typing import Callable, Dict, Optional, Set, cast import asyncpg import discord from discord.ext.commands import Cog, CommandError, Context, command, guild_only from valuebot import RoleConfig, ValueBot from valuebot.utils import get_messa...
StarcoderdataPython
6615776
from ucsb.models import user, user_asset from rest_framework.response import Response from django.forms.models import model_to_dict from rest_framework.decorators import api_view from ucsb.repository.helpers import * from opt.optimization import * from opt.base_load import * from opt.utility.solar import * from opt.uti...
StarcoderdataPython
6418880
#!/usr/bin/env python3 """ Exercise 44: Cages Animals are now housed in cages. """ from animals import Parrot, Sheep, Snake, Wolf from cage import Cage if __name__ == '__main__': c = Cage() print(c) print() c2 = Cage() a_wolf = Wolf('grey') a_sheep = Sheep('black') a_snake = Sna...
StarcoderdataPython
8148991
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import djsonb.fields import uuid import django.contrib.gis.db.models.fields class Migration(migrations.Migration): dependencies = [ ('ashlar', '0005_auto_20150423_0148'), ] operations = [ ...
StarcoderdataPython
3263110
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from .greedy_alltoall import * from .gather_scatter_alltoall import * from .alltoall_subproblem import *
StarcoderdataPython
12824015
# -*- coding: utf-8 -*- from __future__ import division, absolute_import, print_function __copyright__ = "Copyright (C) 2009-15 <NAME>" __license__ = """ 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 S...
StarcoderdataPython
11238085
from datasets.basic_dataset_scaffold import BaseDataset import os, numpy as np, pandas as pd def Give(opt, datapath): data_info = np.array(pd.read_table(datapath+'/Eval/list_eval_partition.txt', header=1, delim_whitespace=True))[1:,:] train, query, gallery = data_info[data_info[:,2]=='train'][:,:2], data_in...
StarcoderdataPython
6554803
import os import pickle from slu import constants as const def save_label_encoder(model_dir, encoder): with open(os.path.join(model_dir, const.S_INTNET_LABEL_ENCODER), "wb") as handle: pickle.dump(encoder, handle) def read_label_encoder(model_dir): with open(os.path.join(model_dir, const.S_INTNET_L...
StarcoderdataPython
11203015
<reponame>trainorpj/probability # Copyright 2018 The TensorFlow Probability Authors. # # 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 # # Unl...
StarcoderdataPython
6618850
import logging from tqdm import tqdm import hail as hl from gnomad.resources.resource_utils import DataException from gnomad.utils.file_utils import parallel_file_exists from tgg.batch.batch_utils import ( check_storage_bucket_region, HG38_REF_PATHS, localize_file, init_arg_parser, init_job, ...
StarcoderdataPython
283663
import inspect from contextlib import ExitStack, contextmanager from typing import Iterator import numpy as np from gustavgrad.tensor import Tensor class Parameter(Tensor): " A Parameter is used to register a Tensor as part of a Module " def __init__(self, *shape: int) -> None: # TODO: Add possibil...
StarcoderdataPython
4868672
<gh_stars>0 import os import sys import numpy as np from seal import * PACKAGE_PARENT = '..' SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT))) from utils import seal_helper precision...
StarcoderdataPython
4838286
from __future__ import annotations import math import re from decimal import Decimal, ROUND_HALF_UP from dateutil.parser._parser import ParserError from typing import Dict, Hashable, Union import json import numpy import pandas from pandas import Series from .utils import to_utf8_bytes from .errors import InvalidReds...
StarcoderdataPython
5070954
<gh_stars>0 from django_filters import rest_framework as filters from rest_framework import viewsets from rest_framework.filters import SearchFilter, OrderingFilter from rest_framework.permissions import AllowAny from ..serializers.tipo_documento_serializer import TipoDocumentoSerializer from ...models import TipoDocu...
StarcoderdataPython
9606424
<reponame>kbj2060/pytrader import json def remove_dict_items(dictionary, key_list): list(map(dictionary.pop, key_list)) return dictionary def clean_duplicate_2d(arr2d): return list(set(map(tuple, arr2d))) def write_json(filename, dictionary): with open(filename, '+w', encoding='utf-8') as f: ...
StarcoderdataPython
6674306
<filename>ex079.py """Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma lista. o número já exista lá dentro, ele não será adicionado. No final, serão exibidos todos os valores únicos digitados, em ordem crescente.""" num = list() resp = 'S' while resp in "Ss": n = (int(i...
StarcoderdataPython
232611
""" Contains methods and classes pertaining to two dimensional bounds; specifically circles and squares. """ from abc import ABCMeta, abstractmethod import numpy as np class Bounds(metaclass=ABCMeta): """ Represents a two-dimensional bounding area that can be tested for intersections with a variety of g...
StarcoderdataPython
8142435
<reponame>ranjeethmahankali/galproject import pygalfunc as pgf import pygalview as pgv import os POINTS = [ (0, 0, 0), (1, 0, 0), (1, 1, 0), (-.3, 1, 0), (0, -1, 0), ] GLYPHDATA = ["/home/rnjth94/works/YouTube/GAL_BoundingCircle/receiverDishGlyph.png", "/home/rnjth94/works/YouTube/GAL...
StarcoderdataPython
3511436
<reponame>Jeff-Moorhead/flaskquotes import os import shutil from setuptools import setup, find_packages version = {} with open("README.md", "r") as fh: long_description = fh.read() with open("./flaskquotes/version.py", "r") as vh: exec(vh.read(), version) setup(name="flaskquotes", description="Get AF...
StarcoderdataPython
1910497
<filename>api/cloud_provider/migrations/0004_region_comment.py # Generated by Django 2.1.2 on 2019-07-30 03:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cloud_provider', '0003_auto_20190730_0239'), ] operations = [ migrations.AddF...
StarcoderdataPython
5085366
<gh_stars>10-100 def polynomial_decay(initial, final, max_decay_steps, power, current_step): """Decays hyperparameters polynomially. If power is set to 1.0, the decay behaves linearly. Arguments: initial {float} -- Initial hyperparameter such as the learning rate final {float} -- Final hyperpa...
StarcoderdataPython
3251788
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import logging import subprocess from Execution import ExecutionBase # Worker module i...
StarcoderdataPython
6555365
# seatable TEMPLATE_BASE_API_TOKEN = '' DTABLE_WEB_SERVICE_URL = '' EMAIL_TABLE_NAME = '' LINK_TABLE_NAME = '' LANG = '' # email EMAIL_SERVER = '' EMAIL_USER = '' EMAIL_PASSWORD = '' import os import sys if os.path.isfile(os.path.join(os.path.dirname(__file__), 'email_syncer_settings.py')): sys.path.insert(0, os...
StarcoderdataPython
3274113
import urllib2 from bs4 import BeautifulSoup import re adds = ['http://m.moneycontrol.com/sensex/bse/sensex-live'] for add in adds: page = urllib2.urlopen(add) soup = BeautifulSoup(page,'lxml') val_tag=str(soup.find("span", {"id":'ind_c_close'})) change_tag=str(soup.find("span", {"id":'ind_chg'})) re1='.*?' # Non...
StarcoderdataPython
347720
#!/user/bin/python3 # -*- coding: utf-8 -*- ''' 变量从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling Pickle的问题和所有其他编程语言特有的序列化问题一样,就是它只能用于Python, 并且可能不同版本的Python彼此都不兼容,因此,只能用Pickle保存那些不重要的数据, 不能成功地反序列化也没关系。 Python内置的json模块提供了非常完善的Python对象到JSON格式的转换 ''' import json import os import pickle d = {'name': 'Bob', ...
StarcoderdataPython
3477773
import xml.sax import copy from math import * from graphserver.vincenty import vincenty INFINITY = float('inf') def download_osm(left,bottom,right,top): """ Return a filehandle to the downloaded data.""" from urllib.request import urlopen fp = urlopen( "http://api.openstreetmap.org/api/0.5/map?bbox=%f,%f,...
StarcoderdataPython
8000911
import math from magicbot import tunable from components import swervedrive from .base_pid_controller import BasePIDComponent from . import field_centric, position_tracker class XPosController(BasePIDComponent): drive = swervedrive.SwerveDrive tracker = position_tracker.PositionTracker kP = tunable(0....
StarcoderdataPython
136626
<reponame>Kulbear/endless-2048<gh_stars>10-100 from .game import Game2048
StarcoderdataPython
171684
import torch import torch.nn as nn from .utils import _calc_padding, _unpack_from_convolution, _pack_for_convolution class GraphAndConv(nn.Module): def __init__(self, input_dim, output_dim, conv_kernel_size, intermediate_dim=None): super(GraphAndConv, self).__init__() if intermediate_dim is None: ...
StarcoderdataPython
12834935
<reponame>Anirban166/tstl import avl import random import sys import coverage import time import numpy start = time.time() branchesHit = set() maxval = int(sys.argv[1]) testlen = int(sys.argv[2]) numtests = int(sys.argv[3]) cov = coverage.coverage(branch=True, source=["avl.py"]) cov.start() for t in xrange(0,numt...
StarcoderdataPython
8165545
from typing import NoReturn from components.header import header from functions.square import squareAreaMenu from functions.triangle import triangleAreaMenu from functions.trapeze import trapezeAreaMenu from functions.diamond import diamondAreaMenu from functions.circle import circleAreaMenu def flatFiguresMenu() -...
StarcoderdataPython
306326
#!/usr/bin/env python # # Given a DNS name and type, return the records in the DNS answer # section only, excluding any RRSIG records. # import getdns, pprint, sys extensions = { "dnssec_return_status" : getdns.EXTENSION_TRUE } def get_rrtype(qtype): try: rrtype = eval("getdns.RRTYPE_%s" % qtype.upper())...
StarcoderdataPython
5124992
<gh_stars>1-10 n,m = map(int,input().split()) chess = [input() for _ in range(n)] min_n = 64 for i in range(n-7): for j in range(m-7): cnt1= cnt2= 0 st = chess[i][j] for k in range(i,i+8): for s in range(j,j+8): if k%2==s%2 and chess[k][s]!=st: cnt1+=1 elif k%2!=s%2 and chess[k][s]...
StarcoderdataPython
12866375
# !/usr/bin/env python # coding=utf8 import json import traceback from tornado.web import RequestHandler from pfrock.cli import logger from pfrock.core.constants import PFROCK_CONFIG_SERVER, PFROCK_CONFIG_ROUTER, PFROCK_CONFIG_PORT, ROUTER_METHOD, \ ROUTER_PATH, ROUTER_OPTIONS, ROUTER_HANDLER from pfrock.core.lib...
StarcoderdataPython
9621436
<filename>usermaker.py #!/usr/bin/env python3 import argparse, random, sys parser = argparse.ArgumentParser(epilog=""" This python script creates files that can be used to create and destroy a set of guest users. You need to supply a prefix for the filenames created, and a number of users to create. Use <output_pr...
StarcoderdataPython
260875
<reponame>AmreshTripathy/Python<gh_stars>1-10 t = ( 10, 11, 12, 34, 99, 4, 98) print (t[0]) t1 = (1, 1, 1, 2, 3, 4, 65, 65, 3, 2) #tuple with single element print (t1.count(1)) print (t1.index(65))
StarcoderdataPython
3236264
import numpy as np class ReplaceNulls(): def __init__(self): self.name = 'Replace Nulls' self.description = 'Replace NULL values in a raster with a user defined value.' def getParameterInfo(self): return [ { 'name': 'raster', 'dataType': 'r...
StarcoderdataPython
12829375
class _ANY(object): """ A helper object that compares equal to everything. Shamelessly stolen from Mock. """ def __eq__(self, other): return True def __ne__(self, other): return False def __repr__(self): return '<ANY>' ANY = _ANY() class CaseObject(object): ...
StarcoderdataPython
3355425
<filename>sift_pyx12/error_999.py ###################################################################### # Copyright # <NAME> <<EMAIL>> # All rights reserved. # # This software is licensed as described in the file LICENSE.txt, which # you should have received as part of this distribution. # #########################...
StarcoderdataPython
3496122
<gh_stars>0 # -*- coding: utf-8 -*- import toml import os, sys import re #################################################################################################### class to_namespace(object): def __init__(self, adict): self.__dict__.update(adict) def get(self, key): return self.__dict__.get(k...
StarcoderdataPython
9691069
<reponame>joshimbriani/Pyarks<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- def universalNameToID(name): if name == "IOA" or name == "Islands of Adventure": return 10000 elif name == "USF" or name == "Universal Studios Florida": return 10010 elif name == "USH" or name == "Univer...
StarcoderdataPython
12808631
<filename>keystoneclient/v3/role_assignments.py # 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 applica...
StarcoderdataPython
3260653
# ------------------------------------------------------------------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. # -------------------------------------------------------------------...
StarcoderdataPython
1727244
<gh_stars>0 from skype_log import Skypper my_log = Skypper() print(my_log.get_skype_path()) print(my_log.get_skype_user()) print(my_log.get_skype_database_path()) my_log2 = Skypper(skype_user="no_one") #print(my_log2.get_skype_user())
StarcoderdataPython
313685
<filename>plato/agent/component/dialogue_policy/deep_learning/reinforce_policy.py """ Copyright (c) 2019-2020 Uber Technologies, 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....
StarcoderdataPython
5173836
from recogn_img.model import PredResult from recogn_img.recogn import Recognizer from recogn_img.utils import read_classes from recogn_img.render import RecognRender
StarcoderdataPython
1674285
<filename>models/__init__.py from models.bilstm import BiLSTM from models.transformer import Transformer from models.transformer_bilstm import TransformerBiLSTM
StarcoderdataPython
8057320
import telebot from telebot import types import keyboard as kb TOKEN = '<KEY>' bot = telebot.TeleBot(TOKEN) PHOTOMENU = '<KEY>' PHOTOROLL = '<KEY>' PHOTOSUSI = '<KEY>' PHOTOSETS = '<KEY>' PHOTOPIZZA = '<KEY>' @bot.message_handler(commands=['start']) def startmenu(message): bot.send_...
StarcoderdataPython
12800114
<reponame>pawel-slowik/play-scraper import re import datetime from typing import Match def parse_balance(balance_str: str) -> float: match = re.search("^(?P<int>[0-9]+)(,(?P<fract>[0-9]{2})){0,1} z\u0142", balance_str) if not match: raise ValueError("invalid balance: %s" % balance_str) return pars...
StarcoderdataPython
10880
from .lexer import SolidityLexer, YulLexer __all__ = ['SolidityLexer', 'YulLexer']
StarcoderdataPython
4819705
from django.core.management.base import BaseCommand from main.models import Sample import csv class Command(BaseCommand): help = 'Check if an expedition sample code is listed in the database' def add_arguments(self, parser): parser.add_argument('input_filename', help="Filename containing the expeditio...
StarcoderdataPython
6653699
import csv import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt def is_number(c): try: int(c) return True except ValueError: return False def get_amount_chars_together(st): total = 0 previous_was_char = False for c in st: if not is_numbe...
StarcoderdataPython
3429110
# Lint as: python3 # Copyright 2019 DeepMind Technologies Limited. 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 # # ...
StarcoderdataPython
4822069
<reponame>boringhexi/gitarootools # -*- coding: utf-8 -*- # Copyright (c) 2019, 2020 boringhexi """subsong2common.py - common stuff used by the subsong2xxx scripts""" import argparse import os from gitarootools.audio.subsong import read_subsong, write_subsong from gitarootools.miscutils.cmdutils import ( argpars...
StarcoderdataPython
11281780
class Solution: def uniquePaths(self, m: int, n: int) -> int: return math.factorial(n+m-2)//(math.factorial(m-1)*math.factorial(n-1))
StarcoderdataPython
1990576
<filename>workers/mijialywsd02.py import logging import time from interruptingcow import timeout from mqtt import MqttMessage from workers.base import BaseWorker import logger REQUIREMENTS = ['bluepy', 'lywsd02'] monitoredAttrs = ["temperature", "humidity"] _LOGGER = logger.get(__name__) # Bluepy might need special...
StarcoderdataPython
11393559
import html, inspect, json, os, random, re, requests, time from flask import request from main import app from utils import * from variables import * @app.route("/join", methods=["POST"]) @msghook def on_join(): data = request.json if data["data"]["room_id"] != 106764: return "", 201 user = data[...
StarcoderdataPython
3396772
import pygame import time import os DISPLAY_WIDTH = 640 DISPLAY_HEIGHT = 640 BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) pygame.init() gameWindow = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT)) clock = pygame.time.Clock() pygame.display.set_caption("Tic Tac Toe") def game_intro(): in...
StarcoderdataPython
4992398
# ============LICENSE_START======================================================= # org.onap.dcae # ================================================================================ # Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. # ==================================================================...
StarcoderdataPython
4817108
<reponame>chessbr/rest-api-permission<filename>rest_jwt_permission/utils.py<gh_stars>10-100 # -*- coding: utf-8 -*- import inspect from django.utils.text import slugify def get_role_for(method, action=None): if action: return "{}:{}".format(action, method.lower()) return method.lower() def get_view...
StarcoderdataPython
9715977
import logging from unittest import TestCase import seq_dbutils from mock import patch, Mock logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') class ConnectionTestClass(TestCase): @patch('logging.info') @patch('sqlalchemy.create_engine') def test_create_sql_en...
StarcoderdataPython
4916740
import logging from monitors.safetystatemachine import SafetyStateMachine class Precedence(SafetyStateMachine): """ To describe relationships between a pair of events/states where the occurrence of the first is a necessary pre-condition for an occurrence of the second. We say that an occurrence of th...
StarcoderdataPython
5016332
""" Test for bootwrap/components/badge.py """ import pytest from bootwrap import Badge from .helper import HelperHTMLParser @pytest.mark.badge def test_badge(): badge = Badge('sometext').add_classes('someclass').as_primary() actual = HelperHTMLParser.parse(str(badge)) expected = HelperHTMLParser.parse(f...
StarcoderdataPython
11340252
<gh_stars>1-10 from django.conf.urls import include, url from django.conf.urls.static import static from django.views.generic.base import TemplateView from django.contrib import admin from django.conf import settings import os.path admin.autodiscover() urlpatterns = [ url(r'^django-admin/', include(admin.site.url...
StarcoderdataPython
5161489
<filename>heat/tests/functional/util.py # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # 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
9685231
<filename>models/ASIS/test.py import argparse import math import h5py import numpy as np import tensorflow as tf import socket from scipy import stats from IPython import embed import os import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) ROOT_DIR = os.path.dirname(os.path.dirname(BASE_DIR)) ...
StarcoderdataPython
3398328
# scope gl = 1 def f(x): global gl gl += 2 lo1 = 3 lo2 = 4 lo3 = 5 def f2(x, y): global gl nonlocal lo3 lo3 = 5 lo4 = gl + lo2 + lo3 return f2
StarcoderdataPython
3530260
<reponame>MrTanoshii/PyWeek-33-Metro<filename>src/save_data.py import json import src.const as C from src.tracker import Tracker from src.view.map import MapView class GameData: gold = None level_data = {} loadout = {} story = {} def __init__(self): pass # Load game data @clas...
StarcoderdataPython
11270241
<reponame>Anand1310/Benevolent-Bonobos from typing import Callable, List from blessed import Terminal class Render(object): """Render class to put things on the screen This class can be instantiated anywhere. Example: ``` from maze_gitb.core.render import Render render = Render(...
StarcoderdataPython
11294627
import sqlite3 as sql import queries as qrs import pandas as pd # assignment 1 def connect_db(db='../rpg_db.sqlite3'): return sql.connect(db) def exec(conn, query): curs = conn.cursor() curs.execute(query) res = curs.fetchall() return res # assignment 2 df = pd.DataFrame(pd.read_csv('../buddym...
StarcoderdataPython
13421
<filename>packages/utils/propagate_license.py #!/usr/bin/env python # Copyright 2014 Open Connectome Project (http://openconnecto.me) # # 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 # # ...
StarcoderdataPython
1711175
import os import numpy as np import pandas as pd import pickle import statsmodels.api as sm from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split import lightgbm as lgb from sklearn.linear_model import LogisticRegression, LinearRegression input_path = "/Users/christia...
StarcoderdataPython
3463843
from django.urls import path from todos.views import TodoListCreateAPIView, TodoDetailAPIView app_name = 'todos' urlpatterns = [ path('', TodoListCreateAPIView.as_view(), name="list"),#point the URL to the as_view() class method instead, # which provides a function-like entry to class-based views path('<i...
StarcoderdataPython
6553300
import argparse import platform import time import screen_brightness_control as SBC def get_monitors(args): filtered = SBC.filter_monitors(display=args.display, method=args.method) for monitor in filtered: yield SBC.Monitor(monitor) if __name__ == '__main__': parser = argparse.ArgumentParser(pro...
StarcoderdataPython
11326077
<filename>mpi_util.py #!/usr/bin/python import numpy as np import ctypes import os import sys from time import time, sleep, clock from functools import reduce, partial, update_wrapper #wraps from pyscf.lib.numpy_helper import ddot from multiprocessing import Pool # 1: map numpy dot, omp=cpu_per_task, 1 # 2: map pyscf...
StarcoderdataPython
1760611
from .models import Feedback class FeedbackDAO: def save_feedback(is_anonymous, user_id, title, content, feedbackid): new_feedback = Feedback(feedbackid=feedbackid, anonimity=is_anonymous, title=title, content=content, userid=user_id) new_feedback.save() def getFeedbacks(): feedbacks = Feedback.objec...
StarcoderdataPython
6410285
class SymbolTable(object): def __init__(self): self._symbols = {} def __str__(self): symtab_header = 'Tabela de Simbolos' lines = ['\n', symtab_header, '_' * len(symtab_header)] lines.extend( ('%7s: %r' % (key, value)) for key, value in self._symbols....
StarcoderdataPython
77983
<filename>seleniumbase/translate/japanese.py # Japanese Language Translations - Python 3 Only! from seleniumbase import BaseCase class セレンテストケース(BaseCase): # noqa def URLを開く(self, *args, **kwargs): # open(url) self.open(*args, **kwargs) def クリックして(self, *args, **kwargs): # click(sel...
StarcoderdataPython