content stringlengths 5 1.05M |
|---|
"""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 ... |
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)... |
# 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... |
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... |
# 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... |
def create_user(base_cls):
class User_info(base_cls):
__tablename__ = 'user_info'
__table_args__ = {'autoload': True}
return User_info |
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... |
"""
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... |
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
|
# 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... |
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 ... |
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',
... |
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... |
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... |
# -*- 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... |
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_... |
""" 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... |
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
... |
from .startapp import StartApplication
|
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... |
# 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 ... |
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... |
"""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... |
from BorutaShap import BorutaShap
def test_class_constructs():
BorutaShap()
|
#! /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_... |
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... |
# 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... |
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']
# ... |
import random
import config
def shuffle_characters():
characters = list(config.BASE_STRING)
random.shuffle(characters)
rearranged_string = ''.join(characters)
return rearranged_string
|
from . import common, core3
|
#!/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 ... |
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... |
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... |
#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 ... |
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... |
"""
"""
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... |
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... |
# 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... |
# 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... |
"""
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... |
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)
|
"""
To be filled in with official datajoint information soon
"""
from .connection import conn, Connection |
"""
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... |
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 = []
... |
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... |
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... |
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"... |
import pyfiglet
ascii_banner = pyfiglet.figlet_format("G o d s - e y e")
print(ascii_banner)
|
# 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... |
'''
siehe Bilder in diesem Ordner
F: Forget Gate -> welche vorherigen Informationen werden verworfen
I: Input Gate -> welche neuen Informationen sind wichtig
O: Output Gate -> welche Informationen werden intern im Cell State gespeichert
C: Candidate State -> welche Informationen werden intern dem Cell State (c) hinzuge... |
# stdlib
import os
import zipfile
from typing import Type, Union
# 3rd party
import handy_archives
import pytest
import remotezip
from apeye import URL
from coincidence.params import param
from coincidence.regressions import AdvancedDataRegressionFixture, AdvancedFileRegressionFixture
from domdf_python_tools.paths imp... |
class Postprocessor:
pass
|
from .test_task import TestEnv
# Robot Import
from .agents.stretch import Stretch
from .agents.pr2 import PR2
# Human Import
from .agents.human import Human
from .agents import human
# Robot Configuration
robot_arm = 'left'
# Human Configuration
# human_controllable_joint_indices = human.right_arm_joints
class Tes... |
from typing_extensions import Protocol
class HasStr(Protocol):
def __str__(self) -> str:
... |
# This entry point is intended to be used to start the backend at a terminal for debugging purposes.
from backend import app
app.main() |
"""
ASDF tags for geometry related models.
"""
from asdf_astropy.converters.transform.core import TransformConverterBase
__all__ = ['DirectionCosinesConverter', 'SphericalCartesianConverter']
class DirectionCosinesConverter(TransformConverterBase):
tags = ["tag:stsci.edu:gwcs/direction_cosines-*"]
types = ... |
import asyncio
import base64
import json
import os
from dataclasses import dataclass
from datetime import datetime, timezone
from email.message import EmailMessage
from enum import Enum
from io import BytesIO
from typing import List, Optional
from uuid import uuid4
import pytest
from aiohttp import ClientSession, Clie... |
from .alias import *
from .bookmark import *
__all__ = [ 'ALIAS_KIND_FILE', 'ALIAS_KIND_FOLDER',
'ALIAS_HFS_VOLUME_SIGNATURE',
'ALIAS_FIXED_DISK', 'ALIAS_NETWORK_DISK', 'ALIAS_400KB_FLOPPY_DISK',
'ALIAS_800KB_FLOPPY_DISK', 'ALIAS_1_44MB_FLOPPY_DISK',
'ALIAS_EJECTABLE_DIS... |
from django.apps import apps
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand
from django.utils import translation
User = get_user_model()
user_deletion_config = apps.get_app_config('user_del... |
# -*- coding: utf-8 -*-
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class OnTaskConfig(AppConfig):
name = 'ontask'
verbose_name = _('OnTask')
def ready(self):
# Needed so that the signal registration is done
from ontask import signals # noqa... |
from app import db
class Entity(db.Model):
__tablename__ = 'entities'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), index=True)
description = db.Column(db.Text, index=True)
def __repr__(self):
return "<Entity '{}'>".format(self.name)
class WikipediaSuggest(d... |
from wx import wx
from wx.lib.pubsub import Publisher
import select
import socket
import sys
import Queue
import os
from thread import *
from collections import defaultdict
uploadInfos = defaultdict(dict) # For seeders
downloadInfos = defaultdict(dict) # For leechers
pieceRequestQueue = defaultdict(dict) # For lee... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2021 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Community access system field."""
from invenio_rdm_records.records.systemfields.access... |
from datetime import datetime
from typing import List
from fastapi import APIRouter
from utils.database import database
from .models import replies
from .schema import ReplyIn, Reply, LikeIn, Like
replies_router = APIRouter()
@replies_router.get("/list-for-post/{post_id}/", response_model=List[Reply])
async def li... |
# Generated by Django 3.0.6 on 2020-05-20 10:05
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("resources", "0003_auto_20200520_0825"),
]
operations = [
migrations.RemoveField(model_name="land", name="images",),
]
|
#
# This file is part of BridgeDB, a Tor bridge distribution system.
#
# :authors: Isis Lovecruft 0xA3ADB67A2CDB8B35 <isis@torproject.org>
# please also see AUTHORS file
# :copyright: (c) 2007-2013, The Tor Project, Inc.
# (c) 2007-2013, all entities within the AUTHORS file
# :license: 3-clause BS... |
#-*- coding: utf-8 -*-
'''
Copyright (c) 2016 NSR (National Security Research Institute)
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 t... |
# Copyright 2021 The TensorFlow Authors 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 ... |
import curve25519
import time
# from urandom import randint
d = b'\x70\x1f\xb4\x30\x86\x55\xb4\x76\xb6\x78\x9b\x73\x25\xf9\xea\x8c\xdd\xd1\x6a\x58\x53\x3f\xf6\xd9\xe6\x00\x09\x46\x4a\x5f\x9d\x54\x00\x00\x00\x00'
u = b'\x09' + bytes(31)
v = b'\xd9\xd3\xce~\xa2\xc5\xe9)\xb2a|m~M=\x92L\xd1Hw,\xdd\x1e\xe0\xb4\x86\xa0\xb8\... |
import torch
import pytest
def test_nll(device):
from speechbrain.nnet.losses import nll_loss
predictions = torch.zeros(4, 10, 8, device=device)
targets = torch.zeros(4, 10, device=device)
lengths = torch.ones(4, device=device)
out_cost = nll_loss(predictions, targets, lengths)
assert torch.a... |
amount = int(input("Inserire il reddito imponibile: "))
married = input("Sei coniugato? [y/N]: ") == "y"
if married:
if amount > 64000:
tax = 8800 + (amount - 64000) * .25
elif amount > 16000:
tax = 1600 + (amount - 16000) * .15
else:
tax = amount * .10
else:
if amount > 32000:
... |
# Source Generated with Decompyle++
# File: device_parameter_component.pyc (Python 2.5)
from __future__ import absolute_import
from ableton.v2.control_surface.control import ControlList
from pushbase.device_parameter_component import DeviceParameterComponentBase
from mapped_control import MappedControl
class DevicePa... |
import codecs
from luadata.serializer.unserialize import unserialize
def read(path, encoding="utf-8", multival=False):
"""Read luadata from file
Args:
path (str): file path
encoding (str, optional): file encoding. Defaults to "utf-8".
Returns:
tuple([*]): unserialized data from l... |
# This is to test the conditions in python
# Demo for if and elsif
number = int(input("Please enter a number to check\n"))
if number <100:
print("the number is less that 100")
elif number == 100:
print("the number is equal to 100")
else:
print("number is more than 100\n")
# this part
city = ['Tokyo', 'Ne... |
#!/usr/bin/env python
# Han Xiao <artex.xh@gmail.com> <https://hanxiao.github.io>
import multiprocessing
import os
import random
import sys
import threading
import time
from collections import defaultdict
from datetime import datetime
from itertools import chain
from multiprocessing import Process
from multiprocessing... |
#!/usr/bin/env python
"""Application controller for FastTree
designed for FastTree v1.1.0 . Also functions with v2.0.1, v2.1.0, and v2.1.3
though only with basic functionality"""
from cogent.app.parameters import ValuedParameter, FlagParameter, \
MixedParameter
from cogent.app.util import CommandLineApplicati... |
from service_runner.service_runner.answeb.ansible_api import AnsibleApi
from service_runner.service_runner.asset.models import Host
from django.conf import settings
DEFAULT_PLAYBOOKS_PATH = settings.BASE_DIR + '/service_runner/answeb/playbooks/'
def format_uptime_result(host, result):
callback = {
'messa... |
# Copyright 2017 Google 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,... |
import random
import sys
def main():
amount = 1000000
min = 0
max = sys.maxsize #To get some big integer
#Fixed Length from 2 to 6
for i in range(2,7):
result = 0
#Generate N amount of array with fixed length above
for a in range(amount):
array = ... |
# some changes
|
from scapy.all import *
interface = 'mon0'
ap_list = []
def info(fm):
if fm.haslayer(Dot11):
if ((fm.type == 0) & (fm.subtype==8)):
if fm.addr2 not in ap_list:
ap_list.append(fm.addr2)
print "SSID--> ",fm.info,"-- BSSID --> ",fm.addr2
sniff(iface=interface,prn=info)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/4/17 13:48
# @File : db.py
# @Role : ORM
from datetime import datetime
from sqlalchemy import Column, String, Integer, DateTime, UniqueConstraint, DECIMAL
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import class_mapp... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** 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, overload
from . import ... |
import os
import unittest
from django.test import TestCase
from utils import description_for_objective, ellipsis, objectives_for_course
valid_course = 'MG4'
valid_objective = 'MG4-FACTMULT'
class BasicTests(TestCase):
def test_ellipsis(self):
long_str = 'yadayadayada'
self.assertEquals(ellipsis... |
# (c) 2016 James Turner <turnerjsm@gmail.com>
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
lookup: aws_service_ip_ranges
author:
- Jam... |
from deque import Deque
def isPalindrome(string: str)->bool:
d = Deque()
for character in string:
d.addRear(character)
isPalindromeFlag: bool = True
while d.size() > 1 and isPalindromeFlag:
if d.removeFront() != d.removeRear():
isPalindromeFlag = False
return ... |
from django.contrib.auth import views as auth_views
from django.urls import path
from accounts import views
from accounts.views import (
dealerSignupView, adminSignupView,
customerSignupView)
app_name = "accounts"
urlpatterns = [
path('login/', auth_views.LoginView.as_view(
template_name="accounts... |
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from knox.auth import TokenAuthentication
class RootView(APIView):
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
def get(... |
import sys
from collections import deque
from gym_snake.envs import *
from gym_snake.base.pos import Pos
from gym_snake.base.direc import Direc
class _HamiltonTableCell:
def __init__(self):
self.idx = None
self.direc = Direc.NONE
self.reset()
def __str__(self):
return "{ idx... |
#==================================================================================
# PROGRAM: "boat_sat.py"
# LOCATION: beluga>examples>Mansell
# Author: Justin Mansell (2016)
#
# Description: simple path optimization for a boat with bounded control used
# to demonstrate graph search continuation. Uses sa... |
import namespace_override as override
def _(methods, address, class_name):
ret = []
post = []
if 'using.cs' in methods:
add_to = [ret]
for line in methods['using.cs']:
if '---;' not in line:
add_to[0] += [line]
else:
add_to = [post]
... |
from abc import abstractmethod
from typing import Union, Optional, Any, List, Coroutine
import inspect
from .typings import TProtocol
from .interact import InteractiveObject, IOManager
from .component import MetadataComponent
from .behavior import BaseBehavior
from .utilles import IOStatus
class MonoMetaComponent(Me... |
try:
from . import generic as g
except BaseException:
import generic as g
class SectionTest(g.unittest.TestCase):
def test_section(self):
mesh = g.get_mesh('featuretype.STL')
# this hits many edge cases
step = .125
z_levels = g.np.arange(start=mesh.bounds[0][2],
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-03-27 10:58
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('aggregator', '0039_merge_20190316_2108'),
]
operations = [
mi... |
from django.test import TestCase
from rodan.models.job import Job
# from model_mommy import mommy
from rodan.test.helpers import RodanTestTearDownMixin, RodanTestSetUpMixin
class JobTestCase(RodanTestTearDownMixin, TestCase, RodanTestSetUpMixin):
def setUp(self):
self.setUp_rodan()
def test_save(self... |
import sys
import base64
import logging
import marshal
import importlib.util
from os import sep as path_sep
from paker.exceptions import PakerImportError
# use _memimporter if is available
_MEMIMPORTER = False
try:
import _memimporter
_MEMIMPORTER = True
except ImportError:
from paker.importers import _te... |
from dataclasses import dataclass
from typing import Optional, List
@dataclass
class Attack:
name: str
cost: List[str]
convertedEnergyCost: int
damage: Optional[str]
text: Optional[str]
|
from django import template
from django.utils import timezone
from schedules.services import get_times_from_day
from schedules.models import TimeOfDay
register = template.Library()
@register.inclusion_tag('templatetags/calendar_month.html')
def calendar_month():
variable = None
print(">>>>>>")
return {'... |
from mock import patch
from nerve_tools.envoy import get_envoy_ingress_listeners
def test_get_envoy_ingress_listeners_success():
expected_envoy_listeners = {
('test_service.main', 1234): 54321,
}
mock_envoy_admin_listeners_return_value = {
'listener_statuses': [
{
... |
import datetime
def convert_timestamp(ts: str) -> str:
"""Helper function that converts timestamp to %m-%d-%Y format"""
datetime_obj = datetime.datetime.fromtimestamp(ts)
date = datetime.datetime.strftime(datetime_obj,"%m-%d-%Y")
return date
def extract_attributes_from_subreddit(subreddit) -> dict:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.