content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from unittest import TestCase
from src.chunker import Chunker
class TestChunker(TestCase) :
def test_chunker_yields_list_with_buffered_size(self) :
chunks = Chunker(range(5), 3)
chunk = next(chunks)
self.assertEqual(len(chunk), 3)
self.assertListEqual(chunk, [0,1,2])
... | python |
#!/usr/bin/env python3
import os
import sys
from setuptools import setup, find_packages
VERSION = os.environ.get('GITHUB_REF', '0.0.4').replace('refs/tags/v', '')
is_wheel = 'bdist_wheel' in sys.argv
_license = ""
if os.path.exists('LICENSE'):
with open('LICENSE') as lf:
_license = lf.readline().rstrip(... | python |
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from torchvision import transforms
import numpy as np
import cv2
from models.single_track import SiamRPNPP as base_model
from dataset.util import generate_anchor
class SiamRPNPP(nn.Module):
def __init__(self, tra... | python |
import argparse
from utils import levenshtein
import pdb
import re
def clean(label):
alphabet = [a for a in '0123456789abcdefghijklmnopqrstuvwxyz* ']
label = label.replace('-', '*')
nlabel = ""
for each in label.lower():
if each in alphabet:
nlabel += each
return nlabel
parse... | python |
"""
Create a pedestal file from an event file using the target_calib Pedestal
class
"""
from targetpipe.io.camera import Config
Config('checs')
from matplotlib.ticker import MultipleLocator, FormatStrFormatter, \
FuncFormatter, AutoMinorLocator
from traitlets import Dict, List
from ctapipe.core import Tool, Compon... | python |
import django_filters
import htmlgenerator as hg
from django import forms
from django.utils.html import mark_safe
from django.utils.translation import gettext as _
from django_countries.widgets import LazySelect
from .button import Button
from .notification import InlineNotification
class Form(hg.FORM):
@staticm... | python |
import sys
import pytest
sys.path.append(".")
sys.path.append("..")
sys.path.append("../..")
from Hologram.Network import Network
class TestNetwork(object):
def test_create_network(self):
network = Network()
def test_get_invalid_connection_status(self):
network = Network()
with pytes... | python |
from django.urls import path
from rest_framework_simplejwt import views as jwt_views
from . import views
from rest_framework_simplejwt.views import TokenRefreshView, TokenObtainPairView
urlpatterns = [
path('login/', views.loginView.as_view(), name='obtain_token'),
path('nlogin/', views.adminTokenObtainPairVie... | python |
"""The managers for the models
"""
from django.contrib.auth.models import UserManager as BaseUserManager
class UserManager(BaseUserManager):
"""The user manager
"""
def create_user(self, username, email=None, password=None, **extra_fields):
"""Create a user.
:param username: The user nam... | python |
"""
Project: RadarBook
File: ecef_to_lla.py
Created by: Lee A. Harrison
On: 3/18/2018
Created with: PyCharm
Copyright (C) 2019 Artech House (artech@artechhouse.com)
This file is part of Introduction to Radar Using Python and MATLAB
and can not be copied and/or distributed without the express permission of Artech House... | python |
x,y=map(int,input().split())
z=0
for j in range(x,y):
z=j
a=0
for i in range(len(str(j))):
r=j%10
a=a+r**3
j=j//10
if a==z:
print(a,end=" ")
print()
| python |
import os
from .base import *
API_DB_URL = os.environ.get("API_DB_URL", "sqlite+aiosqlite:///db.sqlite")
| python |
# -*- coding: utf-8 -*-
from django.conf.urls import url, patterns
from django.contrib import admin
from .views import ChatRoomTokenView, ChatRoomView
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^room/(?P<token>\w{32})$', ChatRoomView.as_view(), name='chat-room'),
url(r'^new-room/$', ChatRoomT... | python |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 ... | python |
from panflute import run_filter, Header
def increase_header_level(elem, doc):
if type(elem)==Header:
if elem.level < 6:
elem.level += 1
else:
return []
def main(doc=None):
return run_filter(increase_header_level, doc=doc)
if __name__ == "__main__":
main() | python |
# -*- coding: utf-8 -*-
import time
import json
import requests
import logging
import pika
from config import PROXY
from twython import TwythonStreamer
class sampleStreamer(TwythonStreamer):
"""
Retrieve data from the Twitter Streaming API.
The streaming API requires
`OAuth 1.0 <http://en.wikipedia.... | python |
""" Package for cookie auth modules. """
__author__ = "William Tucker"
__date__ = "2020-02-14"
__copyright__ = "Copyright 2020 United Kingdom Research and Innovation"
__license__ = "BSD - see LICENSE file in top-level package directory"
| python |
"""
Tests scikit-learn's KNeighbours Classifier and Regressor converters.
"""
import unittest
from distutils.version import StrictVersion
import numpy
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsRegressor, KNeighborsClassifier
from sklearn.pi... | python |
7
8
9
10
| python |
import sys
# mode is one of 'left', 'right', 'center'
def horizontal_align_print(s, width, mode='left', offsetChar=' ', end='\n',
os=sys.stdout):
p = _print_to_file_func(os)
if mode[0] == 'l': # left
offset = width - len(s)
p(s, end='')
for _ in range(offs... | python |
from os.path import join, dirname
import datetime
# import pandas as pd
# from scipy.signal import savgol_filter
# from bokeh.io import curdoc
# from bokeh.layouts import row, column
# from bokeh.models import ColumnDataSource, DataRange1d, Select
# from bokeh.palettes import Blues4
# from bokeh.plotting import figur... | python |
#!/usr/bin/env python3
import requests
import os
import json
from requests.auth import HTTPBasicAuth
import requests_unixsocket
MFMODULE_RUNTIME_HOME = os.environ['MFMODULE_RUNTIME_HOME']
ADMIN_USERNAME = "admin"
ADMIN_PASSWORD = os.environ['MFADMIN_GRAFANA_ADMIN_PASSWORD']
GRAFANA_SOCKET = "%s/tmp/grafana.sock" % MF... | python |
import os
from dotenv import load_dotenv
load_dotenv()
AV_API_KEY = os.getenv("AV_API_KEY", "value does not exist")
AV_API_KEY_2 = os.getenv("AV_API_KEY_2", "value does not exist")
BINANCE_KEY = os.getenv("BINANCE_KEY", "Binance key not found")
BINANCE_SECRET = os.getenv("BINANCE_SECRET", "Binance secret not found") | python |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... | python |
# -*- coding: utf8 -*-
#
# 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... | python |
"""
Lab jack GUI
"""
import datetime
import lab_jack_lib as lj
import PySimpleGUI as sg
def logprint(message=''):
"""
printing ='on'
print and return None
"""
form = '[{}, {}]'.format(datetime.datetime.now(), message)
print(form)
def now_datetime(type=1):
"""
typ... | python |
print("Hello Open Source")
| python |
def extractLightNovelsWorld(item):
"""
Light Novels World
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
# This comes first, because it occationally includes non-numbered chapters.
if 'Tsuki ga Michibiku Isekai Douchuu (POV)' in item['tags']:
if not postfix and '-' in item['titl... | python |
from torchvision import datasets, transforms
from core.data.data_loaders.base import BaseDataLoader
class CIFAR100Loader(BaseDataLoader):
""" CIFAR100 data loading + transformations """
def __init__(self, data_dir, batch_size,
shuffle=True, validation_split=0.0,
training=Tru... | python |
from pint import UnitRegistry
ureg = UnitRegistry()
ureg.define('kn_cm2 = kilonewton / centimeter ** 2 = kn_cm2')
ureg.define('kNcm = kilonewton * centimeter = kncm')
ureg.define('kNm = kilonewton * meter = knm')
_Q = ureg.Quantity
e = 0.00001 | python |
'''
Created on Jan 23, 2018
@author: kyao
'''
import numpy as np
import typing
from d3m.metadata import hyperparams, params
from d3m import container
from d3m.exceptions import InvalidArgumentValueError
import d3m.metadata.base as mbase
from sklearn.random_projection import johnson_lindenstrauss_min_dim, GaussianRa... | python |
"""IPs domain API."""
from ..base import ApiDomainResource
class IPs(ApiDomainResource):
"""
IPs domain resource.
"""
api_endpoint = "ips"
DOMAIN_NAMESPACE = True
def list(self):
"""
List the existing IPs on the domain.
"""
return self.request("GET")
def ... | python |
"""
pcolor: for plotting pcolor using matplotlib
"""
import matplotlib.pyplot as plt
import numpy as np
import os
import time
def is_linux():
import platform
s = platform.system()
return {
'Linux': True,
'Darwin': False,
'Windows': False,
}[s]
def is_mac():
import platform... | python |
from empire.python.typings import *
from empire.enums.base_enum import BaseEnum
class TimeUnits(BaseEnum):
NANOS: Final[int] = 0
MICROS: Final[int] = 1
MILLIS: Final[int] = 2
SECONDS: Final[int] = 3
MINUTES: Final[int] = 4
HOURS: Final[int] = 5
DAYS: Final[int] = 6
class TimeUtil:
@s... | python |
from __future__ import division
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable
from numpy.random import rand
#import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import cPickle as pickle
import pylab as plb
import os, sys
def run():
'''
Read results of clash score servey... | python |
# 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, software
# distributed under the... | python |
from utils.data_reader import prepare_data_for_feature, generate_vocab, read_data
from utils.features import get_feature
from utils.utils import getMetrics
from utils import constant
from baseline.baseline_classifier import get_classifier
from baseline.baseline_features import get_features_for_prediction
import numpy a... | python |
"""Users models."""
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
"""Custom user.
This inherits all the fields from Django's basic user,
but also has an avatar.
"""
def __str__(self) -> str:
"""Represent the user by their full ... | python |
n1 = int(input('Digite o numero inicial: '))
razao = int(input('Digite sua razão: '))
contador = 10
while contador != 0:
n1 += razao
print(n1)
contador -= 1
termos = int(input('Se Você deseja adicionar mais termos, informe o numero, caso contrario, digite 0: '))
contador += termos
while termos > 0:
whil... | python |
import magicbot
import wpilib
import ctre
import wpilib.drive
from robotpy_ext.common_drivers import navx
class MyRobot(magicbot.MagicRobot):
def createObjects(self):
self.init_drive_train()
def init_drive_train(self):
fl, bl, fr, br = (30, 40, 50, 10) # practice bot
br, fr, bl, fl... | python |
from notipy_me import Notipy
from repairing_genomic_gaps import cae_200, build_synthetic_dataset_cae, train_model
if __name__ == "__main__":
with Notipy():
model = cae_200()
train, test = build_synthetic_dataset_cae(200)
model = train_model(model, train, test, path="single_gap")
| python |
"""Tornado handlers for security logging."""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from tornado import web
from . import csp_report_uri
from ...base.handlers import APIHandler
class CSPReportHandler(APIHandler):
"""Accepts a content security policy v... | python |
"""exercism bob module."""
def response(hey_bob):
"""
Model responses for input text.
:param hey_bob string - The input provided.
:return string - The respons.
"""
answer = 'Whatever.'
hey_bob = hey_bob.strip()
yelling = hey_bob.isupper()
asking_question = len(hey_bob) > 0 and he... | python |
import os
"""
Guild how to read your graph
Description:
I provided several methods to read graph-network data but not limit other formats, please implement your own format as your need
### Graph Kinds & Data Structure
UNDIRECTED-GRAPH <SYMMETRIC-MATRIX, UPPER-MATRIX>
DIRECTED-GRAPH ... | python |
## Fake Binary
## 8 kyu
## https://www.codewars.com/kata/57eae65a4321032ce000002d
def fake_bin(x):
num = ''
for char in x:
if int(char) < 5:
num += '0'
else:
num += '1'
return num | python |
#!/usr/bin/env python3
import datetime
import argparse
from pathlib import Path
import importlib
target = ''
technique_info = {
'blackbot_id': 'T1530',
'external_id': '',
'controller': 'lightsail_download_ssh_keys',
'services': ['Lightsail'],
'prerequisite_modules': [],
'arguments_to_autocomp... | python |
import abc
import argparse
import functools
import os
import pathlib
import shutil
import numpy as np
import pandas as pd
def parse_args():
parser = argparse.ArgumentParser(description="Client allocation")
parser.add_argument('-c', '--train-clients', default=100, type=int)
parser.add_argument('-t', '--test-cli... | python |
# coding=utf-8
import argparse
import os
import random
import numpy as np
import torch
from torch.utils.data import DataLoader
from torch import nn
import pandas as pd
from Source import utils
import time
import logging
logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
... | python |
"""
Module: mercadopago/__init__.py
"""
from .sdk import SDK
| python |
import cv2 as cv
from utilities import show_in_matplotlib
def get_channel(img, channel):
b = img[:, :, channel]
# g = img[:,:,1]
# r = img[:,:,2]
return b
def remove_channel(img, channel):
imgCopy = img.copy()
imgCopy[:, :, channel] = 0
return imgCopy
def remove_channel_v0(img, channe... | python |
map = [0 for i in range(8*2*4)]
while(True):
x = int(input("Please input the operation number:\n1:get\n2:free\n3:show\n0:quit\n"))
if (x==0):
break
if (x==1):
map_index = []
file_size = int(input("Please input the file size\n"))
for i in range(8*2*4):
if (map[i]... | python |
"""Unit tests for powercycle_sentinel.py."""
# pylint: disable=missing-docstring
import unittest
from datetime import datetime, timezone, timedelta
from unittest.mock import Mock
from evergreen import EvergreenApi, Task
from buildscripts.powercycle_sentinel import watch_tasks, POWERCYCLE_TASK_EXEC_TIMEOUT_SECS
def ... | python |
import functools
class Codec:
db = []
def encode(self, longUrl):
"""Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str
"""
length = len(self.db)
self.db.append(longUrl)
return self.conversionA(length)
def decode(self, shortUrl)... | python |
# https://deeplearningcourses.com/c/data-science-natural-language-processing-in-python
# https://www.udemy.com/data-science-natural-language-processing-in-python
# Author: http://lazyprogrammer.me
import numpy as np
import matplotlib.pyplot as plt
import string
import random
import re
import requests
import os
impor... | python |
from collections import defaultdict
"""
students = 10
leads = 9
clues = [[1, 2], [3, 4], [5, 2], [4, 6], [2, 6], [8, 7], [9, 7], [1, 6], [2, 4]]
"""
class Unionfind():
def __init__(self, students, leads, clues):
self.students = students
# Set up parent for each node.
self.parent = {item:item... | python |
# Set up configuration variables
__all__ = ['custom_viewer', 'qglue', 'test']
import os
import sys
from pkg_resources import get_distribution, DistributionNotFound
try:
__version__ = get_distribution('glue-core').version
except DistributionNotFound:
__version__ = 'undefined'
from ._mpl_backend import Matp... | python |
def create_user(base_cls):
class User_info(base_cls):
__tablename__ = 'user_info'
__table_args__ = {'autoload': True}
return User_info | python |
import os
from enum import Enum
from pathlib import Path
import pandas as pd
import matplotlib.pyplot as plt
class Verbosity(Enum):
error = 1
warning = 2
info = 3
debug = 4
BASE_FOLDER = "output/"
class Logger:
current_run = None
def __init__(self, verbosity=Verbosity.info, markdown=False... | python |
"""
Attributes are arbitrary data stored on objects. Attributes supports
both pure-string values and pickled arbitrary data.
Attributes are also used to implement Nicks. This module also contains
the Attribute- and NickHandlers as well as the `NAttributeHandler`,
which is a non-db version of Attributes.
"""
import r... | python |
import asyncio
import logging
from .util import testing_exception_handler
loop = asyncio.get_event_loop()
loop.set_exception_handler(testing_exception_handler)
logging.getLogger('asynqp').setLevel(100) # mute the logger
| python |
# Generated by Django 2.2.13 on 2020-09-04 06:26
import enumfields.fields
from django.db import migrations
import leasing.enums
class Migration(migrations.Migration):
dependencies = [
("leasing", "0014_add_lease_identifier_field"),
]
operations = [
migrations.AddField(
mode... | python |
import os
import time
import libtorrent as lt
from Downloader.Utils.tasks import shutdown
from Downloader.configuration import TORRENT_PATH
from Downloader.Utils.file_operations import create_folder
def download_magnetic_link(_link, _path=TORRENT_PATH):
ses = lt.session()
ses.listen_on(6881, 6891)
if not ... | python |
log_level = "INFO"
max_task_count = 1000
poll_db_interval = 100
config_max_downloading = 10000
mq_queue = "download_retrier_queue"
mq_routing_key = "download_retrier_routing_key"
mq_exchange = "download_retrier_exchange"
max_file_size = 52428800
config_domains = ['youku.com', 'ykimg.com', 'tudou.com',
... | python |
import oemof.solph as solph
from .component import Component
class Supply (Component):
""" Generic supply component
(usually for grid supplied electricity, heat etc.) is created through this
class """
def __init__(self, params):
# Call the init function of the mother class.
Component... | python |
from dicom_parser.utils.sequence_detector.sequences.mr.dwi.derived import \
DWI_DERIVED_RULES
from dicom_parser.utils.sequence_detector.sequences.mr.dwi.diffusion import \
DWI_RULES
from dicom_parser.utils.sequence_detector.sequences.mr.dwi.fieldmap import \
DWI_FIELDMAP
from dicom_parser.utils.sequence_det... | python |
# -*- coding: utf-8 -*-
from typing import Union
import urllib3
from indico.config import IndicoConfig
from indico.http.client import HTTPClient
from indico.client.request import HTTPRequest, RequestChain, PagedRequest
class IndicoClient:
"""
The Indico GraphQL Client.
IndicoClient is the primary way t... | python |
import os
#import requests
import sys, urllib2, urllib
comp_err_file = open("compile.e", 'r')
comp_err_str = comp_err_file.read()
comp_out_file = open("compile.o", 'r')
comp_out_str = comp_out_file.read()
fileName = str(sys.argv[1])
print 'something'
data = urllib.urlencode({'fileName':fileName,'compileO':comp_out_... | python |
""" Keras Retinanet from https://github.com/fizyr/keras-retinanet
Some slight refactoring are done to improve reusability of codebase
"""
import keras
from .. import initializers
from .. import layers
from .. import losses
from ._retinanet_config import make_config
from ._retinanet import (
default_classificatio... | python |
from wtforms import fields, validators as va, Form
from receipt_split.models import MAX_MESSAGE_LENGTH
from . import UserSummaryForm
class PaymentForm(Form):
message = fields.StringField("Message", [va.length(min=1,
max=MAX_MESSAGE_LENGTH
... | python |
from .startapp import StartApplication
| python |
import numpy as np
from seedbank._keys import make_key, make_seed
class SeedState:
"""
Manage a root seed and facilities to derive seeds.
"""
_seed: np.random.SeedSequence
def __init__(self, seed=None):
if seed is None:
seed = np.random.SeedSequence()
self._seed = se... | python |
# By Nick Cortale
# 2017-06-28
#
# Extends the functionality of faker to a more data scientist-esque approach.
# Implements some of the functions from numpy to create some fake data. This is
# also useful for creating data sets with a certain demensionality and integer
# fields.
import faker
import pandas as ... | python |
import numpy as np
import pandas as pd
#from stat_perform import *
from utilities import *
'''
This program will calculate the IoU per emage per class
Inputs:
- .tflite: a segmentation model
- .jpg: a picture from pascal
- pascal_segmented_classes_per_image.csv file
Output:
- CSV file contains iou_sc... | python |
"""Microsoft Teams destination."""
import logging
import pymsteams
def build_notification_text(text_parameters) -> str:
"""Create and format the contents of the notification."""
nr_changed = len(text_parameters["metrics"])
plural_s = "s" if nr_changed > 1 else ""
report_link = f'[{text_parameters["r... | python |
from BorutaShap import BorutaShap
def test_class_constructs():
BorutaShap()
| python |
#! /usr/bin/env python
import numpy as np
import math
import time
import rospy
import roslib
from geometry_msgs.msg import Twist
from std_msgs.msg import String, Float32, Int32, Bool, Int32MultiArray, Float32MultiArray
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
frame_w = rospy.get_... | python |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from builtins import str
from builtins import range
from collections import defaultdict
from itertools import chain
from lxml import etree
from lxml.html import fromstring
import numpy as np
from fonduer.models... | python |
# coding=utf-8
#
# pylint: disable = wildcard-import, unused-wildcard-import, unused-import
# pylint: disable = missing-docstring, invalid-name, wrong-import-order
# pylint: disable = no-member, attribute-defined-outside-init
"""
Copyright (c) 2019, Alexander Magola. All rights reserved.
license: BSD 3-Clause Licen... | python |
from Tkinter import *
root = Tk()
var = StringVar()
var.set("Site View")
names = ('C-cex','Bittrex')
def ffet(param):
var.set(param)
print(param)
# Appends names to names list and updates OptionMenu
#def createName(n):
# names.append(n)
# personName.delete(0, "end")
# menu = nameMenu['menu']
# ... | python |
import random
import config
def shuffle_characters():
characters = list(config.BASE_STRING)
random.shuffle(characters)
rearranged_string = ''.join(characters)
return rearranged_string
| python |
from . import common, core3
| python |
#!/usr/bin/env python
#
# euclid graphics maths module
#
# Copyright (c) 2006 Alex Holkner
# Alex.Holkner@mail.google.com
#
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version ... | python |
from django.conf.urls import (
include,
url,
)
from .views import (
calls,
notifications,
reviews,
submissions,
)
app_name = 'submitify'
notification_urls = [
url(r'^(?P<notification_id>\d+)/$', notifications.view_notification,
name='view_notification'),
url(r'^(?P<notificatio... | python |
from flask import Flask, request, jsonify
from service import Service
app = Flask(__name__, static_url_path='/static')
service = Service()
@app.route("/")
def hello():
return '', 200
@app.route("fullinsert")
def fullinsert():
service.init()
return '', 200
#To access parameters submitted in the URL (?ke... | python |
#Exercício Python 73: Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de Futebol, na ordem de colocação. Depois mostre:
# a) Os 5 primeiros times.
# b) Os últimos 4 colocados.
# c) Times em ordem alfabética.
# d) Em que posição está o time da Chapecoense.
tabela_brasileirao ... | python |
from argparse import ArgumentParser
import flom
from trainer import train
def make_parser():
parser = ArgumentParser(description='Train the motion to fit to effectors')
parser.add_argument('-i', '--input', type=str, help='Input motion file', required=True)
parser.add_argument('-r', '--robot', type=str, h... | python |
"""
"""
from django.core.urlresolvers import reverse
from django.test import TestCase
from wagtail.tests.utils import WagtailTestUtils
class BaseTestIndexView(TestCase, WagtailTestUtils):
"""
Base test case for CRUD index view.
"""
url_namespace = None
template_dir = None
def _create_s... | python |
from ect_def import add_dict
"""
Rules of Follow
1) if A is a nonterminal and start sign then FOLLOW(A) include $
2) if B -> aAb, b != epsilon then FOLLOW(A) include FIRST(b) without epsilon
3) if B -> aA or B -> aAb b=>epsilon then add FOLLOW(B) to FOLLOW(A)
"""
def getFollow(terminals:list, non_terminals:list, cfg... | python |
# Copyright 2018-2020 Jakub Kuczys (https://github.com/jack1142)
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | python |
# Exercícios sobre Listas, do curso Python Impressionador da Hashtag
## 1. Faturamento do Melhor e do Pior Mês do Ano
# Qual foi o valor de vendas do melhor mês do Ano?
# E valor do pior mês do ano?
meses = ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez']
vendas_1sem = [25000, 2900... | python |
"""
Module to look for, and parse, Function and settings.
"""
import os
import json
from . import logger
def is_function(folder: str) -> bool:
return os.path.isfile("{}/function.json".format(folder))
def get_functions(path: str) -> list:
functions = []
for file in os.listdir(path):
candidate = "{}/{}".format(p... | python |
from django.contrib import admin
from django.apps import apps
models = apps.get_models()
for model in models:
# admin.site.register(model)
admin.register(model)
| python |
"""
To be filled in with official datajoint information soon
"""
from .connection import conn, Connection | python |
"""
pipeline effects
"""
import sys
import abc
import enum
import logging
from itertools import zip_longest
from typing import Dict, Optional
from .actions import Action, SendOutputAction, CheckOutputAction
from .exceptions import CheckDelivery, Retry
from .utils import NamedSerializable, class_from_string
_regist... | python |
import numpy as np
from . import backends
from importlib import import_module
class Predictor():
def __init__(self, model, config={}, backend=backends.backend()):
self.model = model
self.config = config
self.backend = backend
assert(model)
self.postprocessors = []
... | python |
MAX_ARRAY_COUNT = MAX_ROWS = 9
MAX_ARRAY_SUM = 45
COMPLETE_ARRAY = [1, 2, 3, 4, 5, 6, 7, 8, 9]
SUBGRIDS_BY_ROWS = [
[0, 0, 0, 1, 1, 1, 2, 2, 2],
[0, 0, 0, 1, 1, 1, 2, 2, 2],
[0, 0, 0, 1, 1, 1, 2, 2, 2],
[3, 3, 3, 4, 4, 4, 5, 5, 5],
[3, 3, 3, 4, 4, 4, 5, 5, 5],
[3, 3, 3, 4, 4, 4, 5, 5, 5],
[6... | python |
import logging
from django import http
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.core.mail import EmailMultiAlternatives
from django.http import Http404, HttpResponse
from django.shortcuts import get_obj... | python |
from django.urls import path
from . import views
app_name = 'kandidaturen' # here for namespacing of urls.
urlpatterns = [
path("", views.main_screen, name="homepage"),
path("erstellen", views.kandidaturErstellenView, name="erstellenView"),
path("erstellen/speichern", views.erstellen, name="erstellen"... | python |
import pyfiglet
ascii_banner = pyfiglet.figlet_format("G o d s - e y e")
print(ascii_banner)
| python |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.