content stringlengths 5 1.05M |
|---|
"""Unit test package for dpybrew."""
|
__author__ = 'mehdibenchoufi'
IMAGE_SIZE_x = 512
IMAGE_SIZE_z = 512
NUM_IMG_DATA = 128
NUM_SAMPLES = 1672
OPENCV_RELATIVE_ANGLE = 512
CENTER_POINT_x = 400
CENTER_POINT_z = 100
SCAN_CONVERTER_SCALE = 200
|
import time
import nltk
import numpy as np
import pandas as pd
from textblob.classifiers import DecisionTreeClassifier
from textblob.classifiers import NaiveBayesClassifier
nltk.download('stopwords')
from nltk.corpus import stopwords
stopset = set(stopwords.words('english'))
ignoreDT = True
def remove_prefix(theLi... |
from .wgan import WGAN |
# interpret.py
"""Parses tokenized statements into nodes"""
from syntax.tokenizer import tokenize
from syntax.token import TokenType
from syntax.node import Node
def parse(tokens: list) -> object:
"""
Reads tokens to create a simple abstract syntax tree
"""
nodes = []
if not tokens:
retu... |
from pymongo import MongoClient
import sys, argparse, random
from numpy import array
from sklearn import model_selection, neural_network, svm
from sklearn.preprocessing import StandardScaler
from progressbar import *
import logging, pickle
from statistics import mean
from sklearn.metrics import confusion_matrix
logging... |
#!/usr/bin/env python3
import configparser
import logging
import os
import shlex
import socket
import subprocess
import threading
from datetime import timedelta
from glob import glob
from sys import argv
from time import sleep
import psutil
print("pineapple.py v1 - the scff daemon")
fpid = os.fork()
if fpid != 0:
... |
# -*- coding=utf-8 -*-
#
# NER 数据集有两种存储格式
# 默认采用的标注标准为 BIOES
import json
from typing import Dict, Any, Tuple, Optional, List
from jionlp import logging
__all__ = ['entity2tag', 'tag2entity']
def entity2tag(token_list: List[str], entities: List[Dict[str, Any]],
formater='BIOES'):
''' 将实体 enti... |
#factorial.py
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
print(fact(4))
print(fact(10)) |
import sys
from setuptools import setup, find_packages
requires = [
"pyramid==1.10.8",
"SQLAlchemy==1.4.3",
"transaction",
"pyramid_mako",
"pyramid_tm",
"pyramid_debugtoolbar",
"zope.sqlalchemy",
"wtforms",
"wtdojo",
"nose",
"mako",
"python-dateutil",
]
if sys.version_... |
from aws_data_tools.client import APIClient # noqa: F401
class TestAPIClient:
"""Test the APIClient class"""
def test_api(self):
"""Test API calls with the client"""
assert "pass" == "pass"
def test_init_with_client(self):
"""Test initializing an APIClient with a custom botocore... |
import os
import sys
from fabric import task
from invoke import run as fab_local
import django
# ----------------------------------------------------
# Add this directory to the python system path
# ----------------------------------------------------
FAB_BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.... |
# -*- coding:utf-8 -*-
from __future__ import unicode_literals
import re
from django.core.cache import cache
from django.db import models
class ParameterManager(models.Manager):
def get_choices(self):
cache_key = 'metrics.parameters.{0}'.format(
self.model.__name__.lower())
... |
import cv2
import matplotlib.pyplot as plt
import cvlib as cv
from cvlib.object_detection import draw_bbox
import os
import tensorflow
from datetime import datetime
import time
os.environ["CUDA_VISIBLE_DEVICES"]="-1"
total = 0
print(" ")
print("Hold down Shift T to stop the video feed and process.")
print("There ar... |
import time
from utils import epoch_time_to_digital
DEFAULT_EXPIRY_S = 60 * 60 * 4
class WouldPlay:
def __init__(self, player, game, for_time=None, expires_at=None):
self.player = player
self.game = game
self.recorded_at = time.time()
self.for_time = for_time
if self.for_... |
from torch import nn
from torchvision.models import googlenet, vgg16 , vgg19, resnet152, resnet50
model_dict ={
'googlenet': googlenet,
'vgg16': vgg16 ,
'vgg19':vgg19,
'resnet152':resnet152, # TODO Generate Perturbations
'resnet50':resnet50 # TODO Generate Perturbations
}
# Fixed Archi... |
from django.conf.urls import re_path
from .views import FilterQueryView
from . import settings
urlpatterns = [
re_path(r'^(?P<app_label>\w+)/(?P<model>\w+)/{}$'.format(settings.URL_PATH), FilterQueryView.as_view()),
re_path(r'^(?P<app_label>\w+)/(?P<model>\w+)/{}(?P<pk>\d+)/$'.format(settings.URL_PATH), Filte... |
from azsc.handlers.az.Generic import *
from azsc.handlers.az.EventGrid import *
from azsc.handlers.az.EventHubs import *
from azsc.handlers.az.ResourceGroup import *
from azsc.handlers.az.Storage import *
from azsc.handlers.az.CosmosDB import *
from azsc.handlers.az.AppService import *
from azsc.handlers.az.FunctionApp... |
import logging
from injector import inject
import app_config
from microsoft_graph import MicrosoftGraph
class MicrosoftGraphImages:
@inject
def __init__(self, graph: MicrosoftGraph):
self.graph = graph
def query_images(self):
images = self.graph.query(app_config.MSG_ENDPOINT_IMAGES).j... |
#!/usr/bin/env python
from eth_tester.exceptions import TransactionFailed
from pytest import raises, mark
from utils import longTo32Bytes, longToHexString, fix, AssertLog, BuyWithCash, nullAddress
from constants import BID, ASK, YES, NO
def test_cancelBid(contractsFixture, cash, market, universe):
createOrder = c... |
"""The kwb component."""
|
"""Unit test for analysis.py module"""
import datetime
import numpy as np
from matplotlib.dates import date2num
from floodsystem.analysis import polyfit, forecast
def test_polyfit():
dates = [datetime.datetime(2016, 12, 30), datetime.datetime(2016, 12, 31), datetime.datetime(2017, 1, 1),
datetime.datetime(2... |
import collections
import logging
import os
import pprint
from .simple_pwatcher_bridge import (PypeTask, Dist)
from . import io
LOG = logging.getLogger(__name__)
def task_generic_bash_script(self):
"""Generic script task.
The script template should be in
self.bash_template
The template will be su... |
# copied from python-2.7.3's traceback.py
# CHANGES:
# - some_str is replaced, trying to create unicode strings
#
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import types
from six import text_type
def format_exc... |
import torch
import torch.nn as nn
from math import sqrt
from IPython import embed
import sys
sys.path.append('./')
from .recognizer.tps_spatial_transformer import TPSSpatialTransformer
from .recognizer.stn_head import STNHead
import torch.nn.functional as F
class Conv_ReLU_Block(nn.Module):
def __init__(self):
... |
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license... |
import argparse
import os
from guacamol.assess_distribution_learning import assess_distribution_learning
from guacamol.utils.helpers import setup_default_logger
from .generator import RandomSmilesSampler
if __name__ == "__main__":
setup_default_logger()
parser = argparse.ArgumentParser(
description=... |
# -*- coding: utf-8 -*-
"""The main h application."""
from __future__ import unicode_literals
from h._compat import urlparse
import logging
import transaction
from pyramid.settings import asbool
from pyramid.tweens import EXCVIEW
from h.config import configure
from h.views.client import DEFAULT_CLIENT_URL
log = l... |
#! /usr/bin/env python3
# Copyright 2020 Desh Raj
# Apache 2.0.
"""This script takes an RTTM file and removes same-speaker segments
which may be present at the same time across streams. This is meant
to be used as a post-processing step after performing clustering-based
diarization on top of separated streams of au... |
nome = str(input('Digite seu nome: ')).strip()
print(f'{nome} tem Silva em seu nome?', 'SILVA' in nome.upper())
|
# -*- coding: utf-8 -*-
"""
Created on Fri May 6 21:38:13 2022
@author: DanielT17
"""
# %% Imports
from math import ceil
# %% Functions
def Preprocessing(packets,crc_width):
'''
Description:
This function preprocess the data by spliting the packets list into packet
and cr... |
ies = []
ies.append({ "iei" : "", "value" : "Payload container type", "type" : "Payload container type", "reference" : "9.10.3.36", "presence" : "M", "format" : "V", "length" : "1/2"})
ies.append({ "iei" : "", "value" : "Payload container", "type" : "Payload container", "reference" : "9.10.3.35", "presence" : "M", "for... |
#!/usr/bin/env python3
import sys
import time
import numpy as np
import tensorflow as tf
import cv2
# from object_detector_detection_api import ObjectDetectorDetectionAPI, PATH_TO_LABELS, NUM_CLASSES
class FROZEN_GRAPH_INFERENCE:
def __init__(self, model_person):
"""Tensorflow detector
"""
... |
while True:
temp = []
try:
a, k = [int(x) for x in input().split()]
except EOFError:
break
for _ in range(a):
temp.append(input())
print(temp[-k])
|
from __future__ import print_function, division, absolute_import
import numpy as np
def spin(x, dancers):
"""
Remove x characters from the end of the string
and place them, order unchanged, on the front.
Parameters
----------
x : int
Number of characters to be moved from end of dance... |
# import gym
# import random
# from config import *
# from cartpole import *
# from NEAT import Node, Edge, innov_maker
# glb_innov = {}
# glb_node_index = {}
# def init_nodes(num_input,num_output):
# #Is_input_node, Index, value, children, edges, move
# input_nodes = [Node(True, i, None, None, None) for i in r... |
from data_miner import plot_tally
import pytest
d_country = ["Vietnam", "Singapore", "US", "Malaysia"]
d_date = "03-05-2020"
d_timespan = 40
d_scale = ["linear", "log", "log", "linear"]
d_plot_type = "cdra"
def test_A():
assert plot_tally(d_country, d_date, d_timespan, scale=d_scale, plot_type=d_plot_type) == 0
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
"""empty message
Revision ID: ad15ef3317a6
Revises:
Create Date: 2019-09-09 07:24:22.448481
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = 'ad15ef3317a6'
down_revision = None
branch_labels = None
depends_on = None
d... |
"""Classes to represent and query categorical systems."""
import datetime
import importlib
import importlib.resources
import pathlib
import pickle
import typing
import natsort
import networkx as nx
import pandas
import strictyaml as sy
from black import Mode, format_str
from ruamel.yaml import YAML
from . import dat... |
from typing import TYPE_CHECKING, Iterable, Optional
from ..discount import DiscountInfo
from ..plugins.manager import get_plugins_manager
if TYPE_CHECKING:
from prices import TaxedMoney
from .models import Checkout, CheckoutLine
def checkout_shipping_price(
*,
checkout: "Checkout",
lines: Itera... |
# @Author: Manuel Rodriguez <valle>
# @Date: 16-Aug-2017
# @Email: valle.mrv@gmail.com
# @Filename: controllers.py
# @Last modified by: valle
# @Last modified time: 06-Sep-2017
# @License: Apache license vesion 2.0
import os
from valleorm.models import *
class HelperBase(object):
def __init__(self, JSONQuer... |
#! /usr/bin/python
# -*-coding:utf-8-*-
import mmap
from ctypes import *
#本函数只使用了python提供的库mmap,不直接涉及python调用c的操作,但是mmap可能是调用c来实现的,所以需要包含ctypes库。
#本函数完成内存映射,并且提供内存读写接口。
class dev_mem:
DEVNAME = '/dev/mem'
def __init__(self,BASE,LEN):
self.len = LEN
self.base = BASE
self.fd =... |
# -*- coding: utf-8 -*-
"""
lantz.drivers.labjack._internal
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Python drivers provided by LabJack.
:copyright: 2015 by Lantz Authors, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
|
"""Logging module for sentinel"""
import logging
import sys
def set_logging(level=None):
"""Set a logger STDOUT"""
logger = logging.getLogger('STDOUT')
out_hdlr = logging.StreamHandler(sys.stdout)
out_hdlr.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
logger.addHandler(o... |
from manti_by.apps.core.services import (
convert_to_mp3_preview,
convert_to_ogg_preview,
convert_to_ogg_release,
)
from manti_by.apps.core.utils import get_rq_queue
queue = get_rq_queue()
def generate_preview_for_post(post):
if not post.release:
return
if not post.mp3_preview_ready:
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2017 Graham Pugh
# Copyright 2019 Matthew Warren / haircut
# Copyright 2020 Everette Allen
#
# Based on the 'Slacker' PostProcessor by Graham R Pugh
# https://grahamrpugh.com/2017/12/22/slack-for-autopkg-jssimporter.html
#
# Licensed under the Apache License, Ver... |
import matplotlib.pyplot as plt
from pyhdx.fileIO import csv_to_protein
from pyhdx.alignment import align_dataframes
from matplotlib.colors import to_hex
from functions.align import alignments
from functions.base import *
from functions.formatting import *
from functions.logging import write_log
from functions.plottin... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
# Register your models here.
from django.contrib import admin
from .models import Board
admin.site.register(Board)
|
import torch
from torch import Tensor
class BPMLLLoss(torch.nn.Module):
def __init__(self, bias=(1, 1)):
super(BPMLLLoss, self).__init__()
self.bias = bias
assert len(self.bias) == 2 and all(map(lambda x: isinstance(x, int) and x > 0, bias)), \
"bias must be positive integers"
... |
import json
import logging
import os
import pysftp
import pdb
import sys
import click
def get_login_details(login_file):
try:
login_details = json.load(login_file)
username = login_details["username"]
password = login_details["password"]
except Exception as e:
logging.error("F... |
"""
Copyright (c) 2016-2017 Dell Inc. or its subsidiaries. All Rights Reserved.
"""
import fit_path # NOQA: unused import
import fit_common
import flogging
from common import api_utils
from nosedep import depends
from config.api2_0_config import config
from obm_settings import obmSettings
from nose.plugins.attrib imp... |
#!/usr/bin/env python3
# Copyright (c) 2019 Arm Limited and Contributors. All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Entry point for save-api-key action."""
from mbl.cli.utils.store import Store
from mbl.cli.utils.cloudapi import valid_api_key
def execute(args):
"""Execute the save-api-ke... |
"""
Basic unit tests for the awbw module on select sample replays.
To run:
python -m unittest -v
"""
import unittest
from .game import DefaultDict
# pylint: disable=no-self-use
class TestDefaultDict(unittest.TestCase):
"""Tests for the DefaultDict class"""
class ColorDict(DefaultDict):
"""Example ... |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
from secretpy import Atbash
from secretpy import alphabets
import unittest
class TestAtbash(unittest.TestCase):
alphabet = (
alphabets.ENGLISH,
alphabets.RUSSIAN,
alphabets.GERMAN,
alphabets.SPANISH,
alphabets.JAPANESE_HIRAGANA
... |
from dataclasses import dataclass
from typing import Union
import math
import numpy as np
import statistics
@dataclass
class Stat:
mean: Union[np.ndarray, float]
std: Union[np.ndarray, float]
n: int
def __repr__(self) -> str:
return f"Stat(mean: {self.mean}, std: {self.std}, n: {self.n})"
c... |
import websocket
import threading
import traceback
from time import sleep
import json
import urllib
import math
import logging
from qbrobot.util.api_key import generate_nonce, generate_signature
from qbrobot.util import log
logger = logging.getLogger()
# Naive implementation of connecting to BitM... |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 2.0.10
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (3,0,0):
new_instancemethod = lambda func, inst, cls: _RWStl.S... |
import importlib
import re
from functools import lru_cache
from inspect import getsource
from pathlib import Path
from typing import Iterator, Optional, List
from pycaro.api.constants import BUILTIN_OBJECTS
from pycaro.api.files import find_project_root, get_path_from_root, get_absolute_path
from pycaro.api.logger imp... |
import sys
import pdb
import pickle
import argparse
sys.path.append("../src")
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument("estNumber", help="Estimation number", type=int)
args = parser.parse_args()
estNumber = args.estNumber
modelSaveFilename = "results/{:08d}_estimatedM... |
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.shortcuts import render, get_object_or_404, redirect
from garbageday.models import GarbageDay
from houses.models import House
@login_required(login_url="account_login")
def garbageday_manage(request, house):
housem... |
#coding:utf-8
from basic_config import *
PCAS_PATH = 'D:\\datasets\\APS\\PCAS.txt'
PCAS_CODES = []
def select_topic(topic_list):
reserved_pcases = []
for pcas in topic_list:
if len(pcas) != 2:
continue
if pcas[0] not in [
'0', '1', '2', '3', '4', '5', '6', '7',... |
from src.utils.dataset_loader import load_olid_data_taska
import torch
from transformers import Trainer, BertForSequenceClassification, TrainingArguments, BertTokenizer
[train, test, dev] = load_olid_data_taska()
model = BertForSequenceClassification.from_pretrained('olid_clean/checkpoint-2500')
tokenizer = BertToken... |
from sqlalchemy import Column, Integer, SmallInteger, String, Text, DateTime, Boolean
from sqlalchemy import TypeDecorator, ForeignKey, inspect
from proj.config import CONF
from proj.extensions import sql_db
class ModelMixin(object):
def save(self):
sql_db.session.add(self)
sql_db.session.commit(... |
'''
Given a binary tree where node values are digits from 1
to 9. A path in the binary tree is said to be
pseudo-palindromic if at least one permutation of the
node values in the path is a palindrome.
Return the number of pseudo-palindromic paths going from
the root node to leaf nodes.
... |
from conans import ConanFile, CMake, tools
class MichaQtUtilisLibConan(ConanFile):
name = "MichaQtUtilisLib"
version = "0.2"
license = "MIT - https://github.com/jackdaimond/MichaQtUtilisLib/blob/master/LICENSE"
author = "Michael Kloske"
url = "https://github.com/jackdaimond/MichaQtUtilisLib.git"
... |
from unittest import TestCase
import astropy.units as u
import numpy as np
from esbo_etc.classes.Config import Configuration
from esbo_etc.classes.target.FileTarget import FileTarget
from esbo_etc.classes.target.BlackBodyTarget import BlackBodyTarget
from esbo_etc.classes.optical_component.StrayLight import StrayLight
... |
#!/usr/bin/env python
import os
import pygame
from pygame.locals import *
#define some colors
#color R G B
white = (255, 255, 255)
red = (255, 0, 0)
green = ( 0, 255, 0)
blue = ( 0, 0, 255)
black = ( 0, 0, 0)
cyan = ( 0, 255, 255)
btnCycle_col = white
btnPrev_col = white
btnNext_col = wh... |
data = open('file.in','r').read().strip()
def reduce_data(text):
data_old = None
while data_old != text:
data_old = text
for i in range(26):
text = text.replace(chr(ord('a')+i)+chr(ord('A')+i),'')
text = text.replace(chr(ord('A')+i)+chr(ord('a')+i),'')
return(len(tex... |
from __future__ import annotations
import hashlib
import json
import logging
from typing import Optional
import secrets
import aiohttp
from aioredis import Redis
import discord
from itsdangerous import Signer, BadSignature
from sanic import Sanic, Blueprint, response, exceptions
from sanic.request import Request
from... |
import pytest
import mock
from plenum.common.constants import DOMAIN_LEDGER_ID
from plenum.common.exceptions import UnknownIdentifier, InvalidSignatureFormat, InsufficientCorrectSignatures, \
CouldNotAuthenticate
from plenum.server.client_authn import CoreAuthNr
from sovtoken.test.wallet import TokenWallet
from so... |
import urllib.request
import bs4
lienImage = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_month.atom"
page = urllib.request.urlopen(lienImage)
xml = bs4.BeautifulSoup(page,'lxml')
e = xml.find_all('title')
for eq in e:
print(eq) |
# O mesmo professor do desafio 019 quer sortear a ordem de apresentação de trabalhos dos alunos.
# Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada.
import random
a1 = str(input('Informe o nome do(a) primeiro(a) aluno(a): '))
a2 = str(input('Informe o nome do(a) segundo(a) aluno(a): '))
a3 ... |
import json
from galaxy_test.base.api_asserts import (
assert_has_keys,
assert_status_code_is,
)
from galaxy_test.base.populators import (
DatasetPopulator,
)
from ._framework import ApiTestCase
class RolesApiTestCase(ApiTestCase):
def setUp(self):
super().setUp()
self.dataset_popula... |
import logging
import pytest
from ECAgent.Core import *
# Unit testing for src framework
class TestEnvironment:
def test__init__(self):
model = Model()
assert len(model.environment.components) == 0
assert len(model.environment.agents) == 0
assert model.environment.model is model
... |
from dataclasses import dataclass
from typing import List, Optional
## Exceptions
@dataclass
class NameNotFound(Exception):
name: str
local: Optional[bool] = None
@dataclass
class NameNotAssigned(Exception):
name: str
@dataclass
class CannotRebindConstant(Exception):
name: str
## Classes
@dataclass
... |
import string
class Solution:
def isPalindrome(self, s: str) -> bool:
l = []
for char in s:
if char in string.ascii_letters or char in string.digits:
l.append(char.lower())
news = '_'.join(l)
return self.check(news)
def check(self, news):
# ne... |
from django.test import TestCase
from demo import models
class CategoryTests(TestCase):
def setUp(self):
for i in range(10):
category = models.Category()
category.title = 'cat{}'.format(i)
category.save()
def test_count(self):
count = models.Category.object... |
class dotRebarSplice_t(object):
# no doc
BarPositions = None
Clearance = None
LapLength = None
ModelObject = None
Offset = None
Reinforcement1 = None
Reinforcement2 = None
Type = None
|
# -*- coding: utf-8 -*-
from slackbot.bot import respond_to
import re
import json
@respond_to('hello', re.IGNORECASE)
def greet(message):
attachments = [
{
'fallback': 'Fallback text',
'author_name': 'Hello from Keptn',
'author_link': 'https://keptn.sh',
'text': 'An opinionate... |
from contractpy.main.contract_validator import ContractValidator
import pytest
from contractpy.main.types import Types
from contractpy.main.exceptions.invalid_format import InvalidFormat
from contractpy.main.exceptions.invalid_value import InvalidValue
def test_validate_contract_returns_none_for_valid_formats():
... |
from collections import namedtuple
from linkedlist import Node
NODEDATA = namedtuple("Node", ["left", "item"])
class SinglyLinkedTree:
def __init__(self, items=None):
"""
Initialize the binary search tree and insert the given items.
"""
self.root = None
self.size = 0
... |
from david.components.nlu.simple import SimpleNLU
|
from .context import tweet_sentiment
from sklearn.linear_model import SGDClassifier
def test_model_load():
model = tweet_sentiment.load()
pred = model.predict(['süper bir haber bu'])
assert pred[0] == 0
|
#!/usr/bin/env python
import argparse
from logging import StreamHandler, basicConfig, getLogger
import argcomplete
import pkg_resources
import atcoder_helper.command.gen
logger = getLogger(__name__)
logger.setLevel("DEBUG")
version = pkg_resources.get_distribution("atcoder-helper").version
def get_sub_commands()... |
from itertools import chain
import numpy as np
from circuit_recognizer.connect.line import DirectedLine, detect_intersection_rect
class TestLine:
def test_detect_intersection(self):
image = np.array(
[
[False, False, True, False, False, False, False],
[False, ... |
nr = int(input("Digite um nr para ver a sua tabuada: "))
star = '-'
print(f'{star*12:^15}\n {nr} x 1 = {nr*1}\n {nr} x 2 = {nr*2}\n {nr} x 3 = {nr*3}\n {nr} x 4 = {nr*4}\n {nr} x 5 = {nr*5}\n {nr} x 6 = {nr*6}\n {nr} x 7 = {nr*7}\n {nr} x 8 = {nr*8}\n {nr} x 9 = {nr*9}\n {nr} x 10 = {nr*10}\n{star*12:^15}') |
# Generated by Django 2.0.3 on 2018-05-19 11:02
from django.db import migrations, models
import django.db.models.deletion
import modelcluster.fields
class Migration(migrations.Migration):
dependencies = [
('tests', '0007_add_bandmember_favourite_restaurant'),
]
operations = [
migrations... |
# public interface
from Regex import Regex
def match(pattern, string):
"""Try to apply the pattern at the start of the string, returning true
or None if no match was found."""
return Regex(pattern).match(string)
def fullmatch(pattern, string):
"""Try to apply the pattern to all of the string, return... |
import datetime
import matplotlib.pyplot as plt
import pynmea2
import simple_geo
def parse_nmea_messages(path: str):
nmea_messages = []
gps = open(path, 'r')
lines = gps.readlines()
for line in lines:
try:
# remove first character as csv has extra comma
nmea_message ... |
import datetime
class Solution:
# @return a list of lists of length 3, [[val1,val2,val3]]
def threeSum(self, nums):
#starttime = datetime.datetime.now()
target = 0
nums.sort()
l = len(nums)
m = 0
r = {}
for x in range(l):
if nums[x] >0 and m... |
from __future__ import absolute_import
from . import plexapp
from . import util
class Captions(object):
def __init__(self):
self.deviceInfo = util.INTERFACE.getGlobal("deviceInfo")
self.textSize = util.AttributeDict({
'extrasmall': 15,
'small': 20,
'medium': 30... |
class A():
def method(self):
print(1)
class B(A):
def method(self):
print(2)
a = A()
a.meth<caret>od() |
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring
import uuid
from tests import utils
from tests.modules.annotations.resources import utils as annot_utils
from tests.modules.asset_groups.resources import utils as sub_utils
from tests.modules.encounters.resources import utils as enc_utils
import pytest
from ... |
import numpy as np
import os
from urllib.request import urlretrieve
from tensorflow import keras
MNIST_PATH = "./mnist.npz"
def load_mnist(path="./mnist.npz", norm=True):
if not os.path.isfile(path):
print("not mnist data is found, try downloading...")
urlretrieve("https://s3.amazonaws.com/img-da... |
import os
import re
class LanguageModelContent:
def __init__(self, words,count):
self.words = words
self.count = count
def __str__(self):
return self.words + '\t' +self.count
if __name__ == "__main__":
dir_list = sorted(os.listdir('/Users/geekye/Documents/Dataset/LM/UniBiG... |
from django.apps import AppConfig
class AnalysisAndTrainingConfig(AppConfig):
name = "analysis_and_training"
|
print("hello world")
#what's up
|
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
# Turn on and off a LED from your Adafruit IO Dashboard.
# adafruit_circuitpython_adafruitio with an esp32spi_socket
import time
import board
import busio
from digitalio import DigitalInOut, Direction, Pull
import adafruit_... |
from socket import *
serverName = 'localhost'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
sentence = input('Input lowercase sentence:')
clientSocket.send(sentence.encode('utf-8'))
modifiedSentence = clientSocket.recv(1024)
print (modifiedSentence)
clientS... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.