content
stringlengths
5
1.05M
#!/usr/bin/env python2.7 """ Check the .lib file for an SRAM """ import unittest from testutils import header,openram_test import sys,os,re sys.path.append(os.path.join(sys.path[0],"..")) import globals from globals import OPTS import debug class lib_test(openram_test): def runTest(self): globals.init_op...
import pytest # module-level parameterization pytestmark = pytest.mark.parametrize('x', [(1,), (1.0,), (1+0j,)]) def test_param_13(x): assert x == 1 class TestParamAll(object): def test_param_13(self, x): assert x == 1 def test_spam_13(self, x): assert x == 1
from itertools import count from math import sqrt def counting_rectangles(target): """ Returns the area of the rectangular grid with the nearest to target number of rectangles. """ mindiff = target bestarea = 0 def rectangles(n, m): return int((n**2 + n) * (m**2 + m) / 4) ...
from abc import ABC from requests.auth import AuthBase, HTTPBasicAuth, HTTPDigestAuth class RegistryAuthBase(AuthBase, ABC): """Base class that all RegistryAuth drives from""" class RegistryHTTPBasicAuth(RegistryAuthBase, HTTPBasicAuth): """Implements HTTP Basic Authentication""" class RegistryHTTPDigest...
import os import numpy as np import pytest from config.stage import ConfigStage from extract.stage import ExtractStage from preprocess.stage import PreprocessStage @pytest.mark.parametrize("action", ['train']) def test_extract_stage(action): path = os.path.abspath(os.path.join(__file__, "../../..", 'resources/co...
# Conway's game of life import random, time, copy WIDTH = 60 HEIGHT = 20 #Create a list of list for the cells. nextCells = [] for x in range(WIDTH): column = [] for y in range(HEIGHT): if random.randint(0,1) == 0: column.append('#') #creates a living cell else: column...
#!/usr/bin/python # smartpiano Python Client # Copyright (c) Jeremy Collette 2020. # This software is released under the MIT license. # See the 'LICENSE' file for more information. import sys from smartpianofactory import SmartPianoFactory if __name__ != "__main__": sys.exit(0) print("smartpiano Python Client v...
from flask import Blueprint, request, jsonify from flask_jwt_extended import jwt_required from marshmallow import Schema, validate, fields from jcapi.models import Contract from jcapi import db contract = Blueprint('contract', __name__) @jwt_required @contract.route('/', methods=['POST']) def create_contract(): ...
# Licensed under an MIT style license -- see LICENSE.md import numpy as np import warnings from scipy import stats from seaborn.distributions import ( _DistributionPlotter as SeabornDistributionPlotter, KDE as SeabornKDE, ) from seaborn.utils import _normalize_kwargs, _check_argument import pandas as pd __author...
from api.models import Category, Customer, Item, Restaurant from conftest import create_app, make_auth_header app = create_app() ### RESTAURANTS ### def test_pass_get_restaurants(client): response = client.get('/restaurants') assert response.status_code == 200 restaurants = response.get_json() asse...
from django.db.models.signals import pre_save from django.dispatch import receiver from .models import CustomUser @receiver(pre_save, sender=CustomUser) def auto_rename_user(sender, instance, **kwargs): user = instance """ Extract a name from the email in case user has no name Ex.xyz@gmail => name=xyz """ ...
#!/usr/bin/env python from setuptools import setup setup( setup_requires=[ 'pbr>=5.2', 'reno>=2.11', 'setuptools>=41.0', ], pbr=True, )
# Generated by Django 3.0.8 on 2020-08-23 11:02 from django.db import migrations def fill_foirequests_field(apps, schema_editor): InformationObject = apps.get_model('froide_campaign', 'InformationObject') for information_object in InformationObject.objects.all(): request = information_object.foireque...
# @copyright@ # Copyright (c) 2006 - 2019 Teradata # All rights reserved. Stacki(r) v5.x stacki.com # https://github.com/Teradata/stacki/blob/master/LICENSE.txt # @copyright@ # # @rocks@ # Copyright (c) 2000 - 2010 The Regents of the University of California # All rights reserved. Rocks(r) v5.4 www.rocksclusters.org # ...
import itertools class Suitor: def __init__(self, id, preference_list): """ A Suitor consists of an integer id (between 0 and the total number of Suitors), and a preference list implicitly defining a ranking of the set of Suiteds. E.g., Suitor(2, [5, 0, 3, 4, 1, 2]) says the third...
import yaml from dotmap import DotMap def get_config(path: str): with open(path) as f: cfg = yaml.safe_load(f) cfg = DotMap(cfg) return cfg
#!/bin/python3 import sys def solve(grades): # Complete this function for i in range(len(grades)): if grades[i] < 38: continue else: mod = grades[i] % 5 multi5 = int(((grades[i] - mod) / 5 + 1) * 5) if multi5 - grades[i] < 3: gra...
# File produced automatically by PNCodeGen.ipynb from scipy.integrate import solve_ivp import numpy as np from numpy import dot, cross, log, sqrt, pi from numpy import euler_gamma as EulerGamma from numba import jit, njit, float64, boolean from numba.experimental import jitclass from scipy.interpolate import Interpolat...
# -*- coding: utf-8 -*- from __future__ import unicode_literals # El code_menu debe ser único y se configurará como un permiso del sistema MENU_DEFAULT = [ {'code_menu': 'acceso_programaciones_didacticas', 'texto_menu': 'Programación General Anual', 'href': '', 'nivel': 1, 'tipo': 'Accesible', ...
#!/usr/bin/env python # coding: utf-8 import pickle from pathlib import Path import numpy as np import pandas as pd from gensim import models from gensim.models.doc2vec import Doc2Vec from gensim.models.word2vec import Word2Vec # --- load ground truth --- # loading gt EN from semsim.constants import DATA_DIR, TMP_...
"Re-saves all things which might produce GL transactions." import os, time from optparse import make_option import inspect import importlib from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.core.exceptions import ObjectDoesNotExist from django.db import tran...
#Read input file # parameters: # input file - .i input file def is_number(s): try: float(s) return True except ValueError: return False def read_input_file(input_file,number_of_inputs): inputs = {} with open(input_file) as f: for line in f: if '=' in l...
from rest_framework import serializers from leads.models import Lead from accounts.models import Tags, Account from common.serializer import ( UserSerializer, AttachmentsSerializer, LeadCommentSerializer, CompanySerializer ) from contacts.serializer import ContactSerializer from teams.serializer import ...
def _jupyter_server_extension_paths(): # Locally import to avoid install errors. from .notebookapp import NotebookApp return [ { 'module': 'nbclassic.notebookapp', 'app': NotebookApp, 'name': 'jupyter-nbclassic' } ]
# standard lib import sys import pdb # 3rd-party lib import numpy as np import torch import torch.distributed as dist import torch.nn.functional as F # mm lib import mmcv DISTANCES = ['mse','cosine','relation'] def multi_gpu_test_with_distance(model, meta, teacher_data_loader, student_data_loader, distance_metric, ...
""" ---> Wiggle Subsequence ---> Medium """ class Solution: def wiggleMaxLength(self, nums) -> int: n = len(nums) final_nums = [nums[0]] for i in range(1, n): if i == 1 or len(final_nums) == 1: if nums[i] > final_nums[0] or nums[i] < final_nums[0]: ...
class PalindromesCount: def count(self, A, B): def is_palindrome(s): return s == s[::-1] return sum(is_palindrome(A[:i] + B + A[i:]) for i in xrange(len(A) + 1))
import json import logging from .cutom_serializers import HassIoSerializers from homeassistant.components.http import HomeAssistantView import homeassistant.core as ha from homeassistant.helpers.service import async_get_all_descriptions from .const import ONBOARDING_DOMAIN ,ONBOARDING_STEP_USER ,ONBOARDING_STEP_CORE...
import sys sys.path = ["."] + sys.path from petlib.ec import EcGroup from petlib.bn import Bn from hashlib import sha256 import math ## ###################################################### ## An implementation of the ring signature scheme in ## ## Jens Groth and Markulf Kohlweiss. "One-out-of-Many Proofs: ## ...
from rest_framework import serializers from .models import CartoDBTable, GatewayType, Location, LocationRemapHistory class CartoDBTableSerializer(serializers.ModelSerializer): id = serializers.CharField(read_only=True) class Meta: model = CartoDBTable fields = ( 'id', ...
from __future__ import unicode_literals import threading import socket import os.path from .constants import * class RoonDiscovery(threading.Thread): """Class to discover Roon Servers connected in the network.""" _exit = threading.Event() _discovered_callback = None def __init__(self, callback): ...
'''see also: https://github.com/python/cpython/blob/master/Lib/test/crashers as well as https://wiki.python.org/moin/CrashingPython''' import sys from utils import print_file print('oh come on, you knew running this was a bad idea') print_file(__file__) def recurse(n=0): if n == 0: print("yup, that's 0 a...
from Bio.Align import MultipleSeqAlignment from Bio import AlignIO import u2py u2py.initContext( './' ) inputAlignments = [] inputFile = open( '../../data/samples/CLUSTALW/COI_copy1.sto', 'rU' ) inputAlignments.append( AlignIO.read( inputFile, 'stockholm' ) ) inputFile.close( ) inputFile = open( '../../data/samples/C...
import os from mlsploit_local import Job from data import ( build_image_dataset, get_or_create_dataset, process_image, recreate_image, ) from defenses import DEFENSE_MAP def main(): # Initialize the job, which will # load and verify all input parameters Job.initialize() defense_name...
from __future__ import print_function, division, absolute_import from llvm.core import Type, Constant import llvm.core as lc import llvm.ee as le from llvm import LLVMException from numba.config import PYVERSION import numba.ctypes_support as ctypes from numba import types, utils, cgutils, _helperlib, assume _PyNone ...
""" pyifc.compress._pack -------------------- Functions for packing .ifc files. """ import os import pathlib import tarfile from zipfile import ZipFile from pyifc._utils import timeit from pyifc.compress._compress import compress from pyifc.compress._validators import existence_validator, extension_validator def _c...
from pytest import raises from pydantic import BaseModel, ValidationError from pydantic_jsonapi import JsonApiResponse from tests.helpers import ItemModel class TestJsonApiResponse: def test_attributes_as_dict(self): MyResponse = JsonApiResponse('item', dict) obj_to_validate = { 'dat...
from django.conf.urls import include from django.conf.urls import url urlpatterns = [url(r"^api/morango/v1/", include("morango.api.urls"))]
import re import ast from setuptools import setup _version_re = re.compile(r'__version__\s+=\s+(.*)') with open('markpy/__init__.py', 'rb') as f: version = str(ast.literal_eval(_version_re.search( f.read().decode('utf-8')).group(1))) setup( name='markpy', version=version, url='https://github....
import pandas as pd import pickle # Deserialize your dictionary using the load function of pickle deserialized_dict = pickle.load( open("nested_population_dict.pkl", "rb") ) # Get the dataframe of data related to Sweden sweden_population_df = deserialized_dict['Sweden'] # Show the data print(sweden_population_df)
""" file : diffusion_models.py implemetation of 'steps' in file diffusion.py each function describe here takes a set of parameters and update some of it """ import numpy as np def infinite_surface(x, y, vx, vy, dt): ''' A bunch of paticles put in an infinite plane surface. modelled with euler-maruyana...
#!/usr/bin/python # -*- coding: utf-8 -*- doc+='''<!DOCTYPE html>\n<html>\n<head>\n ''' try: doc+=str(incluir(data,"head")) except Exception as e: doc+=str(e) doc+='''\n \n</head>\n<body>\n<link rel="stylesheet" type="text/css" href="''' try: doc+=str(config.base_url) except Exception as e: doc+=str(e) doc+='''Componen...
class Persona: def __init__(self,id,nombre,apellido,fechan,sexo,nombre_us,contraseña,especialidad,telefono,tipo): self.id = id self.nombre = nombre self.apellido = apellido self.fechan = fechan self.sexo = sexo self.nombre_us = nombre_us self.contraseña = con...
from carbonserver.api.infra.repositories.repository_projects import SqlAlchemyRepository from carbonserver.api.schemas import ProjectReport class ProjectSumsUsecase: def __init__(self, project_repository: SqlAlchemyRepository) -> None: self._project_repository = project_repository def compute_detaile...
""" This module contains multiple functions in order to run MSAF algorithms. """ import logging import os from os.path import basename, dirname, splitext, join import librosa import numpy as np from joblib import Parallel, delayed import msaf from msaf import jams2 from msaf import input_output as io from msaf impor...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR {{ info.version }} on {{ info.date }}. # {{ info.year }}, SMART Health IT. class FHIRElementFactory(object): """ Factory class to instantiate resources by resource name. """ @classmethod def instantiate(cls, resource_name, js...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2021 Edward Higgins <[email protected]> # # Distributed under terms of the MIT license. """ """ import os import base64 import json import dash_html_components as html import dash_core_components as dcc from dash.dependencies import ...
from labelbox.orm import query from labelbox.orm.db_object import DbObject, Updateable from labelbox.orm.model import Entity, Field, Relationship class Webhook(DbObject, Updateable): """ Represents a server-side rule for sending notifications to a web-server whenever one of several predefined actions happens ...
try: x = int(input("Please enter a number: ")) print("Number: {}".format(x)) except ValueError: print("Oops! That was no valid number. Try again...")
import numpy as np import random import matplotlib.pyplot as plt import torch import train_2D_rt_v2 as tr2 def plot_PMF(p_list,y_list,npdf,model,get_ypred_at_RT,kld=True): '''Plots predicted and true PMF for given parameter, ykerlist and ylist (one p, yker, y in each list)''' position = 0 ...
############################################################################## # # Copyright (c) 2002 Zope Foundation and Contributors. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS I...
import tornado.web import tornado.util from monstro.conf import settings from monstro.urls import urls application = tornado.web.Application( urls(settings.urls), cookie_secret=settings.secret_key, debug=settings.debug, **getattr(settings, 'tornado_application_settings', {}) )
# Copyright 2016-present CERN – European Organization for Nuclear Research # # 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...
import torch import numpy as np import torch.distributions as dists import torch.nn.functional as F from scipy.optimize import linear_sum_assignment def compute_accuracy(training_step_outputs, discrete_vae, mode="stochastic"): num_clusters = discrete_vae.latent_dim num_classes = training_step_outputs[-1]["y"]...
from gna.ui import basecmd import numpy as np import h5py from gna.pointtree import PointTree class cmd(basecmd): @classmethod def initparser(cls, parser, env): super(cmd, cls).initparser(parser, env) parser.add_argument('--fcscan', required=True) parser.add_argument('--output', type=s...
import pika import time import os from rabbit import connection, wait_for, SERVER ME = os.environ['HOSTNAME'] MODULO = int("0x{}".format(ME[0:3]), 16) % 2 print(" MODULO: {}".format(MODULO)) def callback(ch, method, properties, body): print("<= Receiver {}".format(body)) # time.sleep(int(body)) # print("...
from django.contrib import admin from . import models class AccountAdmin(admin.ModelAdmin): list_display = ('title', 'type', 'active') list_filter = ('type', 'active') search_fields = ('title',) class WithdrawalSlipAdmin(admin.ModelAdmin): list_display = ('title', 'type', 'account', 'amount', 'comp...
# coding: utf-8 from __future__ import unicode_literals import pytest @pytest.mark.parametrize("text", ["(under)"]) def test_da_tokenizer_splits_no_special(da_tokenizer, text): tokens = da_tokenizer(text) assert len(tokens) == 3 @pytest.mark.parametrize("text", ["ta'r", "Søren's", "Lars'"]) def test_da_tok...
from myapp.server import _run_server @app.task(bind=True) def run_task_redis(self): _run_server()
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # 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 ...
from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import from __future__ import division from random import shuffle from random import seed import matplotlib.pyplot as plt from sklearn.decomposition import PCA from sklearn.feature_extraction import DictVector...
from abc import ABC, abstractmethod class State(ABC): """ State object, which stores a solution via its decision variables. The objective value is evaluated via its ``objective()`` member, and should return a numeric type - e.g. an ``int``, ``float``, or comparable. The State class is abstract - ...
# Lint as: python3 # # Copyright 2020 The XLS 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 # # Unless required by applicable law...
import pysam import argparse import sys import logging import os from asyncore import read parser = argparse.ArgumentParser(description="Convert fai to bed", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-i', '--input', action='store', nargs='?', help='I...
import streamsx.hdfs as hdfs from streamsx.topology.topology import Topology import streamsx as streamsx from streamsx.topology.tester import Tester import streamsx.spl.toolkit as tk import streamsx.rest as sr import streamsx.spl.op as op from streamsx.topology.schema import StreamSchema import unittest import date...
from fibo import fib def test_fib(): assert fib(0) == 0 assert fib(1) == 1 assert fib(10) == 55
# Copyright 2021 Google LLC # # 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, ...
from django.db import models from django.shortcuts import reverse from django.utils.text import slugify class Discussion(models.Model): slug = models.SlugField(max_length=80, unique=True, blank=True) name = models.CharField(max_length=60, unique=True, blank=True) description = models.TextField(blank=True) ...
word_list = ["""a-cxl""", """a-delta""", """a-i""", """a1-""", """a1c""", """a2-marker""", """a20""", """aap""", """aapcc""", """aarhus""", """aarss""", """aavg""", """aavgs""", """ab-secreting""", """ab023""", """aba""", """abandoned""", """abbott""", """abc""", """abdomen""", """abdomenwere""", """abdominal""", """ab...
from django.db import models from kbspre.users import models as user_models # Create your models here. class TimeStampedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class Image(TimeStampedMo...
import logging import pickle import collections logging.basicConfig(format='%(asctime)s : %(levelname)s :: %(message)s', level=logging.DEBUG) logging.debug('started.') input_file = './most_common.pickle' with open(input_file, 'rb') as input_fp: data = pickle.load(input_fp) logging.debug('read preprocessed data f...
# With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], # write a program to make a list whose elements are intersection of the above given lists. list1=[1,3,6,78,35,55] list2=[12,24,35,24,88,120,155] set1=set(list1) set2=set(list2) print set1 & set2
import json import logging import os import boto3 from pyspark.sql import SparkSession boto3.setup_default_session(region_name=os.environ.get('REGION', 'us-east-1')) source_location_uri = os.path.join(os.environ['SILVER_LAKE_S3URI'], '') target_location_uri = os.path.join(os.environ['GOLD_LAKE_S3URI'], '') log_level ...
import torch import torch.nn as nn import torch.nn.functional as F class LuongAttention(nn.Module): def __init__(self, hidden_size_enc, hidden_size_dec, use_cuda=True, method='general'): super().__init__() self.hidden_size_enc = hidden_size_enc self.hidden_size_dec = hidden_size_d...
import functools import logging def logger(func): logging.basicConfig(filename=f"logger", level=logging.INFO) @functools.wraps(func) def aninhada(*args, **kwargs): logging.info(f"'{func.__name__}' executado com os argumentos: {args}") return func(*args, **kwargs) return aninhada de...
from save_the_giphies.runner import create_app from save_the_giphies.config import config from typing import TYPE_CHECKING if TYPE_CHECKING: from flask import Flask if __name__ == '__main__': """ Entry point """ app: "Flask" = create_app() app.run(debug=config.debug)
from django.contrib import admin from .models import (Domain,mcqQuestions,typeQuestions,Responses,User) from django.utils.html import format_html import csv from django.http import HttpResponse class ExportCsvMixin: def export_as_csv(self, request, queryset): meta = self.model._meta field_names = ...
r"""This module provides decoding functionality of struct +-------+--------+-------------------------------+---+---+---+---+---+---+---+---+ | Byte | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | +-------+--------+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ | bit | ...
from protocol_lib import IHashable def test_hashable() -> None: class Impl: def __hash__(self) -> int: return 42 impl: IHashable = Impl() assert hash(impl) == 42
import os import re from pathlib import Path from typing import List import testsuites from resultinterpretation import CSVFileExtractor from resultinterpretation.model import TestSuiteResult, TestStepResult class ResultInterpreter: def __init__(self, inputDir: Path): """ :param inputDir: The roo...
# Copyright 2013 OpenStack Foundation. # # 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 r...
img_norm_cfg = dict(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_pipeline = [ dict(type='LoadImageFromFile'), dict( type='ResizeOCR', height=32, min_width=128, max_width=128, keep_aspect_ratio=False, width_downsample_ratio=0.25), dict( ...
from __future__ import print_function # PY2 import sys import traceback import platform import ctypes.util from ctypes import (POINTER, CFUNCTYPE, CDLL, pythonapi, cast, addressof, c_int, c_char_p, c_void_p, c_size_t, py_object) WINDOWS = platform.system().lower() == "windows" def get_libc(): if WINDOWS: pat...
import requests import json from globalVar import log class SendMessage(object): """发送信息到微信""" appid = "" appsecret = "" access_token = "" def get_access_token(self): urlAccessToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + \ SendMessage...
import torchtext.data as data class CMUDict(data.Dataset): def __init__(self, data_lines, g_field, p_field): fields = [('grapheme', g_field), ('phoneme', p_field)] examples = [] # maybe ignore '...-1' grapheme for line in data_lines: grapheme, phoneme = line.split(maxsplit=1)...
# 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...
# Generated by Django 3.1.14 on 2022-03-24 09:47 from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('feedback', '0029_auto_20220324_0944'), ] operations = [ migrations.AddField( model_name='report', name=...
# ========== Thanks https://github.com/Eric-mingjie/rethinking-network-pruning ============ # ========== we adopt the code from the above link and did modifications ============ # ========== the comments as #=== === were added by us, while the comments as # were the original one ============ from __future__ import pri...
from reb import P, PTNode def same(extraction, expected): """Assert that extraction result has the same effect with expected""" assert isinstance(extraction, list) assert isinstance(expected, list) assert len(extraction) == len(expected) for ext, exp in zip(extraction, expected): assert i...
#!/usr/bin/env python3 ### Importing # Importing Common Files from botModule.importCom import * ### Logout Handler @Client.on_message(filters.private & filters.command("revoke")) async def revoke_handler(bot:Update, msg:Message): userid = msg.chat.id query = { 'userid' : userid } # If user ...
import calendar import datetime class UTC(datetime.tzinfo): def utcoffset(self, dt): return datetime.timedelta(0) def tzname(self, dt): return "UTC" def dst(self, dt): return datetime.timedelta(0) utc = UTC() def is_tz_aware(value): return value.tzinfo is not None and valu...
import logging log = logging.getLogger(__name__) handler = logging.StreamHandler() formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) handler.setLevel('DEBUG') log.addHandler(handler)
from expungeservice.models.charge_types.civil_offense import CivilOffense from tests.factories.charge_factory import ChargeFactory from tests.models.test_charge import Dispositions def test_00_is_not_a_civil_offense(): charge = ChargeFactory.create(statute="00", level="N/A", disposition=Dispositions.CONVICTED) ...
from game.common.enums import Upgrades, ObjectType from game.common.stats import GameStats from game.controllers.controller import Controller class UpgradeController(Controller): def __init__(self): super().__init__() def handle_actions(self, client): # if the client wants to drop an item, tr...
import os from flask import Flask, render_template from flask_bootstrap import Bootstrap import config app = Flask(__name__) config_name = os.environ.get('FLASK_CONFIG', 'dev') app.config.from_object(getattr(config, config_name.title() + 'Config')) Bootstrap(app) @app.route('/') def index(): """Serve client-s...
''' goalboost.model package The goalboost model package consists of MongoEngine models along with Marshmallow schemas. MongoEngine is our database ORM to MongoDB, and Marshmallow is a serialization library that helps us validate, consume, and expose these Orm objects for clients that need it at the API layer. For Mon...
import argparse from csat.acquisition import get_factories from csat.acquisition.runner import get_runner_class class ListAction(argparse.Action): def __init__(self, option_strings, dest, const, default=None, required=False, help=None, metavar=None): super(ListAction, self).__init__(opti...
from __future__ import absolute_import from __future__ import print_function import sys import time import ujson from typing import Any, Callable, Dict, List, Set, Text, TypeVar from psycopg2.extensions import cursor CursorObj = TypeVar('CursorObj', bound=cursor) from argparse import ArgumentParser from django.core....
#!/usr/bin/env python import os filename = raw_input('Enter file name: ') fobj = open(filename, 'w') while True: aLine = raw_input("Enter a line ('.' to quit): ") if aLine != ".": fobj.write('%s%s' % (aLine, os.linesep)) else: break fobj.close
"""Api Handler tests.""" import unittest import webapp2 from grow.pods import pods from grow.server import main from grow.testing import testing class ApiHandlerTestCase(unittest.TestCase): """Tests for the server API Handler.""" def test_request(self): """Test that api requests can be completed cor...