text
stringlengths
2
999k
import datetime from flask import jsonify from flask import request from flask.views import MethodView from chainerui.database import db from chainerui.models.log import Log from chainerui.models.project import Project from chainerui.models.result import Result class LogAPI(MethodView): def post(self, project_...
""" LZ4 frame format definition: https://github.com/lz4/lz4/blob/dev/doc/lz4_Frame_format.md """ import io from typing import Optional from lz4.block import decompress from structlog import get_logger from unblob.extractors import Command from ...file_utils import Endian, convert_int8, convert_int32 from ...models i...
from PIL import Image import os import sys from os import listdir from os.path import isfile, join def main(): folder_path = sys.argv[1] output_folder_path = folder_path + '_png' try: os.mkdir(output_folder_path) except: if not os.listdir(output_folder_path): print('Folder...
# pacman imports from pacman.model.routing_info.\ dict_based_partitioned_partition_n_keys_map import \ DictBasedPartitionedPartitionNKeysMap # spinnMachine imports from spinn_machine.utilities.progress_bar import ProgressBar # front end common imports from spinn_front_end_common.abstract_models.\ abstract...
from cloudant.client import Cloudant from cloudant.error import CloudantException from cloudant.result import Result, ResultByKey client = Cloudant.iam("b3e03381-f624-4db8-a3da-3588bface309-bluemix", "sckyMGqNGv8CX9aIcTDbrhYZYhYBDUfEXAJuXuN8SB1D") client.connect() databaseName = "attendance_toqa" myDatabase = client.cr...
#!/usr/bin/env python3 """This code is the main access point for the majority of users of The-wiZZ. It takes an input subselection of a survey catalog, a The-wiZZ HDF5 data file, and matches the two together to create a resultant clustering redshift estimate that can then be turned into a redshift PDF. This code also ...
# -*- coding: utf-8 -*- import uuid from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.core.validators import MinValueValidator from django.db import models from rest_framework.exceptions import NotAcceptable from apps.authentication...
#!/usr/bin/env python3 # Copyright Istio 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 or ag...
from django.contrib.sites.models import Site, get_current_site from django.core import urlresolvers, paginator from django.core.exceptions import ImproperlyConfigured import urllib PING_URL = "http://www.google.com/webmasters/tools/ping" class SitemapNotFound(Exception): pass def ping_google(sitemap_ur...
# Copyright (c) 2006-2013 Regents of the University of Minnesota. # For licensing terms, see the file LICENSE. import os import sys # Pyserver's conf.py wants the pyserver directory to be the current directory. # And for importing pyserver sub-modules to work, we need the pyserver # directory to be the current direc...
# Copyright 2020-2021, The Autoware Foundation # # 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 agre...
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import sys import time import unittest from telemetry.page import page_test_results class GTestTestResults(page_test_results.PageTestRes...
#! /usr/bin/python from flask import Flask, request, jsonify import boto3 import os from queue import Queue from threading import Thread import time s3 = boto3.client('s3') s3_raw = boto3.resource('s3').Bucket('isitanime-data-raw') s3_dest = boto3.resource('s3').Bucket('isitanime-data-clean') app = Flask(__name__) @...
from wagtail.core import blocks from wagtail.images.blocks import ImageChooserBlock class StandoutItemsBlock(blocks.StructBlock): class LinkBlock(blocks.StreamBlock): internal = blocks.PageChooserBlock() external = blocks.URLBlock() class Meta: required = False max...
import pytest # integration tests requires nomad Vagrant VM or Binary running def test_get_nodes(nomad_setup): assert isinstance(nomad_setup.nodes.get_nodes(), list) == True def test_get_nodes_prefix(nomad_setup): nodes = nomad_setup.nodes.get_nodes() prefix = nodes[0]["ID"][:4] nomad_setup.nodes.ge...
################################################################################ from subprocess import Popen, PIPE, STDOUT from threading import Thread import bz2, json, click from newsroom import jsonl from . import readiter from tqdm import tqdm ###################################################################...
#!/usr/bin/env python # -*- coding:utf-8 -*- """Created with Pycharm IDEA @Create on 2015/9/12 16:31 @my_story models.py @author : OmegaMiao""" from app import db, loginManager from datetime import datetime from werkzeug.security import generate_password_hash, check_password_hash from flask.ext.login import User...
''' The application's Globals object ''' import logging import time from threading import Lock import re from paste.deploy.converters import asbool from pylons import config import ckan import ckan.model as model import ckan.logic as logic log = logging.getLogger(__name__) # mappings translate between config set...
import configparser class BotConfig: def __init__(self, path): parser = configparser.ConfigParser() # open the file implicitly because parser.read() will not fail if file is not readable file = open(path) parser.read_file(file) file.close() if 'Bot' not in parser...
# -*- coding: utf-8 -*- import os from setuptools import find_packages, setup with open('README.rst') as f: readme = f.read() # with open('LICENSE.txt') as f: # licenses = f.read() setup( name='dbestclient', version='2.0', description='Model-based Approximate Query Processing (AQP) engine.', ...
import sympy as sp import cyllene.f_aux as fa import cyllene.f_functionclass as ff import cyllene.f_compare as fc def function(expr): """ Defines a function based on a syntax check and a Function object, using lambda operator. Returns a pure function. """ func = ff.Function(expr) if fun...
from Commander import Commander from gui.UserInterface import UserInterface from log.Replay import Replay
import ast from bluesky.plans import scan, grid_scan import bluesky.preprocessors as bpp import bluesky.plan_stubs as bps from bluesky.preprocessors import SupplementalData from bluesky.callbacks.best_effort import BestEffortCallback def test_hints(RE, hw): motor = hw.motor expected_hint = {'fields': [motor.n...
"""Actor-Critic Algorithm.""" from rllib.util.neural_networks.utilities import broadcast_to_tensor from .abstract_algorithm import AbstractAlgorithm class ActorCritic(AbstractAlgorithm): r"""Implementation of Policy Gradient algorithm. Policy-Gradient is an on-policy model-free control algorithm. Policy...
#!/usr/bin/env python # # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Compile Android resources into an intermediate APK. This can also generate an R.txt, and an .srcjar file containing the prope...
"""diarypro URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-base...
from .dagger import DAgger
# This source code is part of the Biotite package and is distributed # under the 3-Clause BSD License. Please see 'LICENSE.rst' for further # information. __name__ = "biotite.sequence.io.gff" __author__ = "Patrick Kunzmann" __all__ = ["GFFFile"] import copy import string from urllib.parse import quote, unquote import...
# Copyright 2021 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...
from datetime import * class Receipt: def __init__(self, member_number): # Initialize the receipt as a list for future modifications (adding and removing items) self.member_items = [] self.member_number = member_number self.total = 0.0 self.total_tax = 0.0 #...
# -*- coding: utf-8 -*- # Copyright (c) 2020 Nekokatt # Copyright (c) 2021-present davfsa # # 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...
class Node: def __init__(self, data): self.data = data self.next_node = None class LinkedList: def __init__(self): self.head = None self.no_of_nodes = 0 # O(1) for insertion at the start of LL def insert_at_start(self, data): self.no_of_nodes = sel...
from gettybase import Session import unicodedata import os class Getty(): def __init__(self): try: self.s = Session(os.environ['getty_system_id'], os.environ['getty_system_pass'], os.environ['getty_user_name'], ...
from exceptions.exceptions import NGSIUsageError from utils.jsondict import lookup_string_match from flask import request from reporter.reporter import _validate_query_params from translators.crate import CrateTranslatorInstance import logging from .geo_query_handler import handle_geo_query def query_NTNENA(id_=None,...
from typing import Any, Dict import argparse import math import torch import torch.nn as nn import torch.nn.functional as F CONV_DIM = 64 FC_DIM = 128 WINDOW_WIDTH = 28 WINDOW_STRIDE = 28 class ConvBlock(nn.Module): """ Simple 3x3 conv with padding size 1 (to leave the input size unchanged), followed by a Re...
# 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 Li...
from django.contrib.auth import forms as admin_forms from django.contrib.auth import get_user_model from django.utils.translation import gettext_lazy as _ User = get_user_model() class UserChangeForm(admin_forms.UserChangeForm): class Meta(admin_forms.UserChangeForm.Meta): model = User class UserCreati...
from random import shuffle counter=1 #index = None index = [] #indexlist = [] decrypt_list = [] intermediate = [] words = ['B', 'A', 'L', 'K','J','I'] newwords = words.copy() # Copy words shuffle(newwords) # Shuffle newwords for i in range(len(words)): for j in range(len(newwords)): if(words[i...
import numpy as np from sys import argv tobs = int(argv[1]) p0 = np.zeros(10) p2 = np.zeros(10) p1 = np.zeros(10) Zab = np.zeros(10) rate = np.zeros(10) for i in range(10): da = np.loadtxt('tobs%d/reweighted_hist_%d.dat'%(tobs,i)) p0[i] = np.exp(-da[-2,1]) p2[i] = np.exp(-da[-1,1]) p1[i] = np.exp(-da[-...
from pythonforandroid.recipe import CythonRecipe from os.path import join class ShapelyRecipe(CythonRecipe): version = '1.7a1' url = 'https://github.com/Toblerity/Shapely/archive/{version}.tar.gz' depends = ['setuptools', 'libgeos'] # Actually, this recipe seems to compile/install fine for python2, b...
import os import torch from tensorboardX import SummaryWriter import time import glob import re import datetime import argparse from pathlib import Path import torch.distributed as dist from pcdet.datasets import build_dataloader from pcdet.models import build_network from pcdet.utils import common_utils from pcdet.con...
from scripts.bilstm_tagger import bilstm_tagger from scripts.bilstm_tagger_model import build_model
""" Contains data structures designed for manipulating panel (3-dimensional) data """ # pylint: disable=E1103,W0231,W0212,W0621 from __future__ import division import warnings import numpy as np from pandas.types.cast import (_infer_dtype_from_scalar, _possibly_cast_item) from pandas.t...
# Generated by Django 3.0.3 on 2020-02-25 19:30 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('main', '0001_initial'), ...
from __future__ import print_function, absolute_import from six import iteritems, iterkeys, itervalues from six.moves import range from _file_reader import FileReader from f06_table import F06Table class _DummyTable(object): def __init__(self): self.header = [] self.data = [] self.line_n...
from __future__ import print_function #Python 2 & 3 compatibility from __future__ import absolute_import import numpy as np import logging import unittest import os import scipy.linalg as LA import time from pysnptools.snpreader import Bed,Pheno from pysnptools.snpreader import SnpData,SnpReader from pysnptools.kernel...
class Node: def __init__(self, val): self.val = val self.left = None self.right = None self.height = 1 def insert(node, val): if not node: return Node(val) if val <= node.val: node.left = insert(node.left, val) else: node.right = insert(node.rig...
"""Support for Broadlink sensors.""" import logging import voluptuous as vol from homeassistant.components.sensor import ( DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_ILLUMINANCE, DEVICE_CLASS_POWER, DEVICE_CLASS_TEMPERATURE, PLATFORM_SCHEMA, STATE_CLASS_MEASUREMENT, SensorEntity, ) from homeassis...
#!python3 import re from blackmamba.system import Pythonista def _comment_line(line, hash_prefix=''): stripped = line.strip() if stripped.startswith('#'): return line if not stripped: return hash_prefix + '# \n' return hash_prefix + '# ' + line[len(hash_prefix):] _UNCOMMENT_RE = ...
""" <Program Name> test_primary.py <Purpose> Unit testing for uptane/clients/primary.py <Copyright> See LICENSE for licensing information. """ from __future__ import unicode_literals import uptane # Import before TUF modules; may change tuf.conf values. import unittest import os.path import time import copy i...
# -*- coding: utf-8 -*- """Calculate the mobility demand. SPDX-FileCopyrightText: 2016-2019 Uwe Krien <krien@uni-bremen.de> SPDX-License-Identifier: MIT """ __copyright__ = "Uwe Krien <krien@uni-bremen.de>" __license__ = "MIT" import os import pandas as pd from collections import namedtuple from reegis import geo...
_base_ = ['../../../../_base_/datasets/aic.py'] log_level = 'INFO' load_from = None resume_from = None dist_params = dict(backend='nccl') workflow = [('train', 1)] checkpoint_config = dict(interval=50) evaluation = dict(interval=50, metric='mAP', save_best='AP') optimizer = dict( type='Adam', lr=0.0015, ) opti...
import os from rpython.rlib.rpoll import POLLIN, PollError from rpython.rlib import streamio from topaz.coerce import Coerce from topaz.error import error_for_oserror from topaz.module import ClassDef from topaz.modules.fcntl import fcntl from topaz.objects.objectobject import W_Object from topaz.objects.stringobject...
from KOMORANPy.training.model_builder import ModelBuilder # corpus_builder = CorpusBuilder() # # todo : 트레이닝 데이터 위치 ( 실제로는 바이너리 파일만 제공 될 예정 ) # corpus_builder.build_path("/Users/shinjunsoo/shineware/data/komoran_training_data", ".refine.txt") # corpus_builder.save("corpus_build") model_builder = ModelBuilder() model_...
from .common import * DEBUG = False ALLOWED_HOSTS = [os.environ['HOST']] EMAIL_HOST = os.environ['EMAIL_HOST'] EMAIL_PORT = int(os.environ['EMAIL_PORT']) EMAIL_HOST_USER = os.environ['EMAIL_HOST_USER'] EMAIL_HOST_PASSWORD = os.environ['EMAIL_HOST_PASSWORD'] EMAIL_USE_TLS = True LOGGING = { 'version': 1, ...
__author__ = 'mnowotka' try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse import requests import requests_cache from chembl_webresource_client.spore_client import Client, make_spore_function from chembl_webresource_client.query_set import QuerySet from chembl_webresource_...
import pickle from appcore.services import Factory from platforms.base_platform import BasePlatform from platforms.helpers.mysql_connection import MysqlConnection class CountryMapUpdate(BasePlatform): API_URL = 'my.sql.server' DB_SETTINGS = { 'hostname': API_URL, 'username': 'db_user', ...
# quality tests for L1 HfBitCounts trigger objects import FWCore.ParameterSet.Config as cms l1EmulatorObjHfBitCountsQualityTests = cms.EDAnalyzer("QualityTester", qtList=cms.untracked.FileInPath('DQM/L1TMonitorClient/data/L1EmulatorObjHfBitCountsQualityTests.xml'), QualityTestPrescaler=cms.untracked.int32(1)...
from adia.sequence import Module from adia.renderer import ModulePlan, ItemStartPlan, ItemEndPlan, LEFT, RIGHT def test_moduleplan(): p = ModulePlan(Module('foo')) assert repr(p) == 'ModulePlan: foo' def test_itemplans(): class Item: def __repr__(self): return 'foo -> bar' item ...
def XXX(nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ len1 = len(nums1) len2 = len(nums2) if (len1 == 0) & (len2 == 0): return 0 if (len1 != 0) & (len2 == 0): if len1 % 2 == 0: return (nums1[len1 // 2 - 1] + nums1[len1...
import time class TestSflow: speed_rate_table = { "400000": "400000", "200000": "200000", "100000": "100000", "50000": "50000", "40000": "40000", "25000": "25000", "10000": "10000", "1000": "1000" } def setup_sflow(self, dvs): self.ad...
# Copyright (C) 2008 The Android Open Source Project # # 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 bz2 from six.moves.cPickle import load from string import punctuation def offsets_to_token(left, right, offset_array, lemmas, punc=set(punctuation)): token_start, token_end = None, None for i, c in enumerate(offset_array): if left >= c: token_start = i if c > right and toke...
import cv2 import numpy as np import socket if __name__ == '__main__': s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) port = 12345 while True: s.sendto(b'hello world', ("192.168.1.10", 8001))
""" Utilities and base functions for Services. """ import abc import datetime from typing import Any, Dict, List, Optional, Set, Tuple from pydantic import validator from qcelemental.models import ComputeError from ..interface.models import ObjectId, ProtoModel from ..interface.models.rest_models import TaskQueuePOS...
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from nipype.testing import assert_equal from nipype.interfaces.fsl.utils import ImageMeants def test_ImageMeants_inputs(): input_map = dict(args=dict(argstr='%s', ), eig=dict(argstr='--eig', ), environ=dict(nohash=True, usedefault=True, ...
import json import os import boto3 from aws_lambda_powertools import Logger, Metrics, Tracer from shared import ( NotFoundException, generate_ttl, get_cart_id, get_headers, get_user_sub, ) from utils import get_product_from_external_service logger = Logger() tracer = Tracer() metrics = Metrics() ...
import logging import pprint from vnc_api.gen.resource_client import Card from vnc_api.gen.resource_client import Hardware from vnc_api.gen.resource_client import Node from vnc_api.gen.resource_client import NodeProfile from vnc_api.gen.resource_client import Port from vnc_api.gen.resource_client import Tag from vnc_a...
import numpy as np from torchvision import transforms import os from PIL import Image, ImageOps import numbers import torch class ResizeImage(): def __init__(self, size): if isinstance(size, int): self.size = (int(size), int(size)) else: self.size = size def __call__(s...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'UI/cadastro_fornecedor.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 impo...
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options import time import os import sys from glob import glob import re import json import random import shutil import re import codecs dones = [x for x in open("done.txt",'r').read().split("\n...
# -*- coding:utf-8 -*- # -------------------------------------------------------- # Copyright (C), 2016-2020, lizhe, All rights reserved # -------------------------------------------------------- # @Name: usb_can_reader.py # @Author: lizhe # @Created: 2021/5/1 - 23:45 # ---------------------------------...
from django.urls import path, include from .admin import urls as admin_urls app_name = "baserow_premium.api" urlpatterns = [ path("admin/", include(admin_urls, namespace="admin")), ]
from typing import Union, cast import libcst as cst import libcst.matchers as m from .util import CodeMod, runner """ libcst based transformer to convert 'for x in generator: yield x' to 'yield from generator'. """ __author__ = "Gina Häußge <gina@octoprint.org>" __license__ = "MIT" class YieldFromGenerator(CodeMo...
# -*- coding: utf-8 -*- # Copyright 2020 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...
# coding: utf-8 ######################################################################### # 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> # # author yeeku.H.lee kongyeeku@163.com # # # # version 1.0 ...
# Copyright 2015 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 applica...
import os import filecmp from dvc.main import main from dvc.utils import file_md5 from dvc.stage import Stage from dvc.command.run import CmdRun from tests.basic_env import TestDvc class TestRun(TestDvc): def test(self): cmd = 'python {} {} {}'.format(self.CODE, self.FOO, 'out') deps = [self.FOO...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
from Window import Window from Logic import Logic print("Init") logic = Logic() win = Window(logic) win.mainloop() print("End")
import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('localhost', 8080)) sock.listen(1) clientsoc, addr = sock.accept() print('connected:', addr) message = '' while True: clientsoc.sendall(bytes(message + f'Enter two bases and its hight or "exit" to finish the program', "u...
from angr.procedures.stubs.format_parser import FormatParser from cle.backends.externs.simdata.io_file import io_file_data_for_arch class fscanf(FormatParser): #pylint:disable=arguments-differ def run(self, file_ptr): # TODO handle errors fd_offset = io_file_data_for_arch(self.state.arch)['f...
from xml.etree import ElementTree as ET from gomatic.mixins import CommonEqualityMixin def fetch_artifact_src_from(element): if 'srcfile' in element.attrib: return FetchArtifactFile(element.attrib['srcfile']) if 'srcdir' in element.attrib: return FetchArtifactDir(element.attrib['srcdir']) ...
def notebookUI(samplenxs, mtnxs, initdos=None, options=None, load_options_path=None): import yaml if options is not None and load_options_path: raise RuntimeError( "Both options and load_options_path were set: %s, %s" %( options, load_options_path) ) if load_opti...
# Copyright 1999-2021 Alibaba Group Holding 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 a...
def Articles(): return [ { 'id': 1, 'title': 'Article 1', 'body': 'Body of first article', 'author': 'Tom Daley', 'create_date': '07-28-2019' }, { 'id': 2, 'title': 'Article 2', 'body': 'Body of s...
import boto3 import botocore class S3: def __init__(self, key, secret, bucket): self.Key = key self.Secret = secret self.Bucket = bucket return def upload_file(self, local_file, remote_file): s3 = boto3.resource( 's3', aws_access_key_id=self.Ke...
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import os.path import shutil import sys import tempfile import spack.util.environment class Octave(AutotoolsPackage, GNU...
""" WSGI config for travellog project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SET...
from .net_stream_interface import INetStream class NetStream(INetStream): def __init__(self, muxed_stream): self.muxed_stream = muxed_stream self.mplex_conn = muxed_stream.mplex_conn self.protocol_id = None def get_protocol(self): """ :return: protocol id that stream ...
""" common utilities """ import itertools import numpy as np from pandas import ( DataFrame, Float64Index, MultiIndex, Series, UInt64Index, date_range, ) import pandas._testing as tm def _mklbl(prefix, n): return [f"{prefix}{i}" for i in range(n)] def _axify(obj, key, axis): # crea...
def CalculateApacheIpHits(logfile_pathname): # make a dictionary to store Ip's and their hit counts and read the # contents of the logfile line by line IpHitListing = {} Contents = open(logfile_pathname, "r").readlines() # go through each line of the logfile for line in Contents: #spli...
from .base import BaseGrader class SimpleAI(BaseGrader): def grade(self, submission, score): try: points = int(submission.text) except ValueError: points = 0 submission.points = points submission.is_graded = True submission.save() ...
# -------------------------------------------------------------------- # # This example was designed to show the project-level optimization # option in GIAMS. This example was used in the original paper as well # -------------------------------------------------------------------- # import time import ast from Netwo...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import common, Form from odoo.tools import mute_logger class TestDropship(common.TransactionCase): def test_change_qty(self): # enable the dropship and MTO route on the product prod ...
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('imagr_users.urls')) )
import argparse import os import numpy as np import math import itertools import torchvision.transforms as transforms from torchvision.utils import save_image from torch.utils.data import DataLoader from torchvision import datasets from torch.autograd import Variable from mnistm import MNISTM import torch.nn as nn ...
from goalgen import * class NewGuide: def __init__(self, useTFBase, useTFFire, catchArsonist, useMA, prioritizeNew): self.tfBase = useTFBase self.tfFire = useTFFire self.catchArsonist = catchArsonist self.useMA = useMA self.prioritizeNew = prioritizeNew self.step = 0 def init(self, world, mem, memKe...
import numpy as np import matplotlib.patches as patches import matplotlib.pyplot as plt ax = plt.axes(polar = True) theta = np.linspace(0, 2 * np.pi, 8, endpoint = False) radius = .25 + .75 * np.random.random(size = len(theta)) points = np.vstack((theta, radius)).transpose() plt.gca().add_patch(patches.Polygon(points, ...
import os import re import inspect def _get_parser_list(dirname): files = [ f.replace('.py','') for f in os.listdir(dirname) if not f.startswith('__') ] return files def _import_parsers(parserfiles): m = re.compile('.+parsers',re.I) _modules = __import__('weatherterm.parsers',globals(),locals(),pa...