content
stringlengths
5
1.05M
from collections import defaultdict from functools import wraps import importlib.util import inspect import os import re import sys from types import MethodType class IndexingError(Exception): """ Raised for indexing errors """ pass class MonitoringError(Exception): """ Raised for monitorin...
from exception.error_code import ErrorCode class BaseException(Exception): """ カスタム例外の基底クラス """ __status_code: int """ ステータスコード """ __error_code: ErrorCode """ エラーコード """ def __init__(self, status_code: int, error_code: ErrorCode): self.__status_code = status...
import grpc import copy from scannerpy.common import * from scannerpy.op import OpColumn, collect_per_stream_args, check_modules from scannerpy.protobufs import python_to_proto, protobufs, analyze_proto class Sink: def __init__(self, sc, name, inputs, job_args, sink_args={}): self._sc = sc self....
""" Defining Class of custom environment for V-Rep @author: hussein """ # import vrep_env # from vrep_env import vrep import sys import os sys.path.append(os.path.abspath("/home/hussein/Desktop/Multi-agent-path-planning/Reinforcement Learning")) sys.path.append(os.path.abspath("/home/hussein/Desktop/Multi-agent-pat...
from preprocess import preprocesses input_datadir = './train_img' output_datadir = './pre_img' obj = preprocesses(input_datadir, output_datadir) num_images_total, num_successfully_aligned = obj.collect_data() print('Total number of images: %d' % num_images_total) print('Number of successfully aligned images: %d' % n...
# coding=utf-8 from __future__ import absolute_import from config import config from .helpers import connect_mongodb from .migrations import * def migration(cfg_type='default'): print '-----------------' print 'Migration: {}'.format(cfg_type) print '-----------------' cfg = config.get(cfg_type) ...
def test_init(initial_setup): from netnir import __version__ assert isinstance(__version__, str)
import cv2 from HW1helpers import centroid_histogram,plot_colors import numpy as np from matplotlib import pyplot as plt from sklearn.cluster import KMeans from scipy.spatial import distance as dist from scipy import special import glob ##### Question 2: Compute Homography on sample images //DONE # Read source image. ...
from django.dispatch import receiver from django.urls import resolve, reverse from django.utils.translation import gettext_lazy as _ from django.template.loader import get_template from pretix.base.middleware import _parse_csp, _merge_csp, _render_csp from pretix.presale.signals import ( html_head, process_res...
# Copyright 2021 portfolio-robustfpm-framework Authors # Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or # http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or # http://opensource.org/licenses/MIT>, at your option. This file may not be # copied, modified, or distributed except ...
# Copyright 2021 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 unittest import core.cli_utils class CliUtilsTest(unittest.TestCase): def testMergeIndexRanges(self): ranges = [(0, 6), (7, 11), (4, 8), (8, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Tumblr photo downloader """ import sys, os, errno import urllib2 import threading import Queue import time import signal import argparse from xml.dom import minidom __version__ = 0.1 URL_FORMAT = 'http://%s.tumblr.com/api/read?type=photo&num=%d&start=%d' def images...
# coding:utf-8 # 导入pandas并且更名为pd。 import pandas as pd def get_titantic(): titanic = pd.read_csv('../Datasets/titanic.txt') # 分离数据特征与预测目标。 y = titanic['survived'] X = titanic.drop(['row.names', 'name', 'survived'], axis=1) # 对对缺失数据进行填充。 X['age'].fillna(X['age'].mean(), inplace=True) X.fill...
#!/usr/bin/python ''' creates bundle graph from filtered multigraph ''' ### imports ### import sys import os import logging import networkx as nx import numpy as np import scipy.stats as stats import cPickle import helpers.io as io import helpers.misc as misc ### definitions ### ### functions ### def compress_edg...
#!/usr/bin/env python3.5 # coding=utf-8 # Licensed Materials - Property of IBM® # Copyright IBM® Corp. 2015,2017 """Submit for submission of SPL applications. The main function is submitSplApp to submit an SPL Application to a Streaming Analytics service or IBM® Streams instance for execution. usage: submitSPL.py [-h...
"""Defines the logic for handling requests to the `/recs` route""" from dependencies.spotify import Client, SpotifyClient from fastapi import APIRouter, Depends from models.collection import Collection from models.rec import Rec, RecQuery from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvid...
def solution(num): cnt = 0 while num != 1 : if cnt > 500 : cnt = -1 break # 짝수일 경우, if num % 2 == 0 : num = num // 2 # 홀수일 경우, else : num = (num * 3) + 1 cnt += 1 return cnt if __name__ == '__main__': ...
# Copyright 2020 QuantInsti Quantitative Learnings Pvt 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 la...
import os import numpy as np import torch from torch.utils import data from NER_src.Config import max_seq_length class InputExample(object): """A single training/test example for NER.""" def __init__(self, guid, words, labels): """Constructs a InputExample. Args: guid: Unique id f...
from pytest import mark from leetcode.remove_element import Solution from . import read_csv @mark.parametrize( 'nums, val, expect, new_nums', read_csv(__file__, parser=eval), ) def test_two_sum(nums, val, expect, new_nums): assert expect == Solution().removeElement(nums, val) assert nums == new_nums...
# coding=utf-8 import os import unittest from nose.tools import * import pandas as pd import py_entitymatching.catalog.catalog_manager as cm import py_entitymatching.matcher.matcherutils as mu from py_entitymatching.debugmatcher.debug_gui_decisiontree_matcher import _vis_debug_dt, \ vis_tuple_debug_dt_matcher fro...
def fact(x): if x == 0: return 1 return x * fact(x - 1) x=int(input()) print (fact(x))
import json import os import random import xml.dom.minidom as xmldom import re import sys args = sys.argv if (len(args) < 2): sys.exit(1) path = args[1] if(path[-1:] == "/"): path = path[:-1] filename = path + "/command/3/stdout.txt" #filename = "D:/SVN/Ansible02/pargen-IIS/roles/stdout.txt" result = {} ap...
# The MIT License (MIT) # Copyright (c) 2021 by the xcube development team and contributors # # 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...
import yaml class Config(object): with open('./config/config.yaml', encoding='utf-8') as f: __config = yaml.safe_load(f) @staticmethod def getInstance(): return Config.__config
import gym import numpy as np from typing import Dict, Tuple class NoopResetEnv(gym.Wrapper): def __init__(self, env: gym.Wrapper, no_op_max=30, ): """ Samples initial states by performing a random number of no operations on reset. Slight...
from params import * from K2_K2_64x44 import K2_K2_transpose_64x44 p = print def karatsuba_eval(dst, dst_off, coeff, src, t0, t1): """ t1 can overlap with any source register, but not t0 """ p("vmovdqa %ymm{}, {}({})".format(src[0], (dst_off+3*0+coeff)*32, dst)) # a[0:] p("vmovdqa %ymm{}, {}({})".forma...
#!/usr/bin/python """test_Read.py to test the Read class. Requires: python 2 (https://www.python.org/downloads/) nose 1.3 (https://nose.readthedocs.org/en/latest/) Joy-El R.B. Talbot Copyright (c) 2014 The MIT License (MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this...
from setuptools import setup, find_packages from pathlib import Path # see https://packaging.python.org/guides/single-sourcing-package-version/ version_dict = {} with open(Path(__file__).parents[0] / "boltzmanngen/_version.py") as fp: exec(fp.read(), version_dict) version = version_dict["__version__"] del version_...
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.output_reporting import OutputSchedules log = logging.getLogger(__name__) class TestOutputSchedules(unittest.TestCase): def setUp(self): self.fd, self.path = tempfi...
#!/usr/bin/env python3 import sys import struct import opcodes MAGIC_NUMBERS = bytes([int(mv, 0) for mv in ['0xCA', '0xFE', '0xBA', '0xBE']]) JVM_NAMES = {45: 'J2SE 1.1', 46: 'J2SE 1.2', 47: 'J2SE 1.3', 48: 'J2SE 1.4', 49: 'J2SE 5.0', 50: 'J2SE 6.0', ...
import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import argparse import seaborn as sns import pandas as pd import os mpl.rcParams['pdf.fonttype'] = 42 mpl.rcParams['ps.fonttype'] = 42 parser = argparse.ArgumentParser(description='RL') parser.add_argument( '--env', default='cheetah' ...
import typing import unittest import test_runner def test_cases(**_kwargs): import test_cli import test_load import test_unzip cases = list() cases += [ test_cli.CLITest, test_load.LoadTest, test_unzip.UnzipTest, ] return cases def test_suite(**kwargs) -> typin...
from __future__ import print_function, division, absolute_import import time import warnings import sys # unittest only added in 3.4 self.subTest() if sys.version_info[0] < 3 or sys.version_info[1] < 4: import unittest2 as unittest else: import unittest # unittest.mock is not available in 2.7 (though unittest2...
# Deep Neural Network architectures for function approximators # # Import libraries import torch import torch.nn as nn import torch.nn.functional as F # MLP architecture for the state-action value function of the DQN algorithm class QNetwork(nn.Module): """Actor (Policy) Model.""" def __init__(self, state_si...
# pylint: disable=missing-function-docstring # pylint: disable=missing-module-docstring from datetime import datetime, timezone from typing import Dict import pytest from httpx import AsyncClient from sqlalchemy.ext.asyncio import AsyncSession from app import crud from app.core.config import settings from app.schema...
from setuptools import setup import twitch setup(name='twitch.py', description='Twitch API for Python', author='Zakru', authir_email='sakari.leukkunen@gmail.com', url='https://github.com/Zakru/twitch.py', version=twitch.__version__, packages=['twitch'], license='MIT')
class Rect: def __init__(self): self.x = 0 self.y = 0 self.width = 0 self.height = 0
# Copyright 2016 Google Inc. # # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # The Adobe DNG SDK, an API for reading and writing DNG files. { 'variables': { 'other_cflags': [ '-DqDNGBigEndian=0', '-DqDNGReportErrors=0', '-DqDNGThreadSafe=1', '-Dq...
from setuptools import setup, find_packages # read the contents of your README file from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='abstract', version='2021.11.4', license='...
from picamera import PiCamera, Color import time import RPi.GPIO as GPIO from datetime import datetime from datetime import timedelta segCode = [0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71,0x80] camera = PiCamera() BeepPin = 15 BtnPin = 16 # pin12 --- button SDI = 11 RCLK = ...
from django.db import models from django_extensions.db.models import TimeStampedModel from author.decorators import with_author from expressmanage.utils import normalize_string @with_author class Customer(TimeStampedModel): name = models.CharField(max_length=255) firm = models.CharFiel...
#!/usr/bin/env python # vim: tabstop=4 shiftwidth=4 softtabstop=4 import os import sys import logging import eventlet # import json import ujson import yurl currentDir = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.abspath('%s/..' % currentDir)) eventlet.monkey_patch() import utils.cloud_u...
import sys import logging from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter import numpy as NP import pandas as PD from obspy.core.stream import Stream from obspy.core.utcdatetime import UTCDateTime from obspy.core.trace import Trace from fgm2iaga import parse from iaga2hdf import get_dec_tenths_arcm...
from .fhirbase import fhirbase class ValueSet(fhirbase): """ A value set specifies a set of codes drawn from one or more code systems. Attributes: resourceType: This is a ValueSet resource url: An absolute URI that is used to identify this value set when it is referenced i...
# -*- coding: utf-8 -*- """ Created on Wed May 6 21:56:44 2020 @author: sgnodde """ import datetime as dt class Clock: def __init__(self, start_date_time = dt.datetime(2020,1,1)): self.date_time = start_date_time def add_time(self, time_increment = dt.timedelta(days = 1)): """Add...
# inspired by https://nbviewer.jupyter.org/gist/kyamagu/6cff70840c10ca374e069a3a7eb00cb4/dogs-vs-cats.ipynb from caffe2.python import caffe2_pb2 import numpy as np import lmdb, json, skimage from os.path import join from DataHelpers import FetchRowCount, PreprocessImage from DataTransforms import CropCenter# Calculat...
class MouseService: """A mouse service inteface.""" def get_coordinates(self): """Gets the current mouse coordinates as a Point. Returns: Point: An instance of the quest.casting.Point class. """ raise NotImplementedError("not implemented in base class") ...
# BEGIN_COPYRIGHT # # Copyright 2009-2018 CRS4. # # 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 agree...
# Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed # under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Licens...
""" Converter um DataFrame para CSV """ import pandas as pd dataset = pd.DataFrame({'Frutas': ["Abacaxi", "Mamão"], "Nomes": ["Éverton", "Márcia"]}, index=["Linha 1", "Linha 2"]) dataset.to_csv("dataset.csv")
""" Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ from test.testlib.testcase import BaseTestCase from cfnlint import conditions class TestEquals(BaseTestCase): """ Test Equals Logic """ def test_equal_value_string(self): """ Test equals set...
"""account excpetion""" from .duplicate import DuplicateUser from .id import UnknownID from .not_found import UserNotFound __all__ = ["UnknownID", "DuplicateUser", "UserNotFound"]
class Shape: def __init__(self, pos, angle): self.pos = pos self.angle = angle self.offset = [pos[0] * 2, pos[1] * 2, pos[2] * 2] self.points = [] self.edges = [] def add_pos(self, new_pos=(0, 0, 0)): for point in self.points: point[0][0] += new_pos[0...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-08-27 12:29 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Wettbewerbe', '0013_auto_20170827_1228'), ] operat...
allocate_lead(leads,config): leads_list = [{"user_id":1, "size:500", "HQ":"US"}, {"user_id":2, "size:700", "HQ":"US"} {"user_id":3, "size:50", "HQ":"CANADA"} ] User_A[0,500] User_B[0,X] User_c[500,X] User_D class Graph: def __init...
"""add columns to metrics_enrollment_status_cache table Revision ID: 9c957ce496bf Revises: b662c5bb00cc Create Date: 2019-05-31 11:14:30.217021 """ from alembic import op # revision identifiers, used by Alembic. revision = "9c957ce496bf" down_revision = "484c5d15ac06" branch_labels = None depends_on = None def upg...
import tensorflow as tf import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error, r2_score from sklearn.model_selection import train_test_split class LogisticRegressor: def __init__(self, d, n, lr=0.001): ...
# Exercise: Using your first API # API documentation: http://bechdeltest.com/api/v1/doc # Goal 1: # Ask the user for the movie title they want to check # Display all of the details about the movie returned by the API # # Things to keep in mind: # How will your program behave when multiple movies are retur...
import pytest from app.fastapi.database import SessionLocal from app.fastapi.models import Nutrition @pytest.fixture def db_session(): session = SessionLocal() yield session session.rollback() session.close() @pytest.fixture def db_get(db_session): def get(name): db_session.flush() ...
from capybara.helpers import desc, toregex from capybara.queries.base_query import BaseQuery class StyleQuery(BaseQuery): """ Queries for computed style values of a node. Args: expected_styles (Dict[str, str]): The expected style names and values. wait (bool | int | float, optional): Whet...
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: utils.py # Author: Yuxin Wu <ppwwyyxxc@gmail.com> from contextlib import contextmanager import operator import tensorflow as tf __all__ = ['LeastLoadedDeviceSetter', 'OverrideCachingDevice', 'override_to_local_variable', 'allreduc...
def require_non_None(obj, msg=None,msg_supplier=None): """Ensures that obj does not exist or raises TypeError Message is either msg or provided by msg_supplier""" if not obj: raise TypeError(msg or (msg_supplier() if msg_supplier else None))
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-07-25 20:52 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('productdb', '0011_userprofile_regex_search'), ] operations = [ migrations.Al...
# https://stackoverflow.com/questions/48065360/interpolate-polynomial-over-a-finite-field/48067397#48067397 import itertools from sympy.polys.domains import ZZ from sympy.polys.galoistools import (gf_irreducible_p, gf_add, \ gf_sub, gf_mul, gf_rem, gf_gcdex) from sympy.ntheory.prim...
# -*- coding: utf-8 -*- """ A peak element is an element that is greater than its neighbors. Given an input array where num[i] ≠ num[i+1], find a peak element and return its index. The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. You may imagine that num[-1] = num[...
# Copyright (c) 2009-2015 testtools developers. See LICENSE for details. __all__ = [ 'ContainsAll', 'MatchesListwise', 'MatchesSetwise', 'MatchesStructure', ] """Matchers that operate with knowledge of Python data structures.""" from ..helpers import map_values from ._higherorder import ( Ann...
import pandas as pd import os from sklearn.ensemble import RandomForestClassifier from sklearn.datasets import make_classification from sklearn import metrics from sklearn.metrics import classification_report from sklearn.metrics import precision_score, recall_score, f1_score, accuracy_score # from IPython.display imp...
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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 ...
import sys sys.path.append("../../") from drlgeb.ac.model import ActorCriticModel from drlgeb.common import make_game, Agent from collections import deque import queue import threading import gym from multiprocessing import Process, Pipe import multiprocessing as mp import tensorflow as tf import numpy as np from drl...
from litcoin.secp256k1 import POINT_AT_INFINITY, SECP256K1_GENERATOR, SECP256K1_ORDER, \ secp256k1_random_scalar, secp256k1_add, secp256k1_multiply import unittest class TestSecp256k1(unittest.TestCase): def test_secp256k1_random_scalar(self): scalar_1: int = secp256k1_random_scalar() scalar_2...
import geopandas as gpd import numpy as np import pytest from scipy.ndimage.morphology import binary_erosion from shapely.geometry.linestring import LineString from shapely.geometry.multilinestring import MultiLineString from shapely.geometry.multipolygon import MultiPolygon from shapely.geometry.polygon import Polygon...
# -*- coding: utf-8 -*- import click from .openligadb import OpenLigaDB from . import helpers pass_openligadb = click.make_pass_decorator(OpenLigaDB) @click.group(invoke_without_command=True) @click.pass_context def cli(ctx): """ Bundesliga results and stats for hackers. bundesliga-cli is a CLI tool t...
#!/usr/bin/env python # (c) 2016 DevicePilot Ltd. # Definitions from https://github.com/OpenMobileAlliance/OMA-LWM2M-DevKit/blob/master/objects/lwm2m-object-definitions.json objects = { "0": { "id": 0, "name": "LWM2M Security", "instancetype": "multiple", "mandatory": True, "description": "This L...
import collections import json import os import re import subprocess import sys import time import pytest import dcos.util as util from dcos.util import create_schema from dcoscli.test.common import (assert_command, assert_lines, assert_lines_range, exec_command) from dcoscli.test.ma...
from typing import Any, Dict, List from matplotlib.axes import Axes from matplotlib.lines import Line2D def set_legend(axes: Axes, lines: List[Line2D], legend_cfg: Dict[str, Any]): axes.legend(handles=lines, **legend_cfg)
from django.urls import path, include from api import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'player', views.PlayerViewSet) # URL's for create and get dataset, get and filter rows urlpatterns = [ path('team/', views.get_player), path('load/', views.load_play...
from django.core import checks, exceptions from django.db.models import BLANK_CHOICE_DASH, CharField from django.utils import six from django.utils.functional import curry from django.utils.itercompat import is_iterable from django.utils.text import capfirst from lazychoices import forms from .mixins import LazyChoic...
from .dbnet import DBNet from .ocr_mask_rcnn import OCRMaskRCNN from .panet import PANet from .psenet import PSENet from .single_stage_text_detector import SingleStageTextDetector from .text_detector_mixin import TextDetectorMixin from .textsnake import TextSnake __all__ = [ 'TextDetectorMixin', 'SingleStageTextDe...
#!/usr/bin/env python3 """Scans a directory to determine the licenses of its dependancies.""" import argparse import datetime import json import logging import os import pathlib import sys from .kss_prereqs_scanner import KSSPrereqsScanner from .manual_scanner import ManualScanner from .swift_scanner import SwiftMod...
""" The ``mlflow.pytorch`` module provides an API for logging and loading PyTorch models. This module exports PyTorch models with the following flavors: PyTorch (native) format This is the main flavor that can be loaded back into PyTorch. :py:mod:`mlflow.pyfunc` Produced for use by generic pyfunc-based deploym...
import os import sys import numpy as np from numpy.lib import index_tricks import raisimpy as raisim import datetime import time import yaml import random import shutil import pickle import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from xbox360controller import Xbox360Controller...
#!/usr/bin/env python # ============================================================================== # MIT License # # Copyright 2020 Institute for Automotive Engineering of RWTH Aachen University. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated docu...
import os from mayatools import context from mayatools import units from sgfs import SGFS from sgpublish.check import check_paths from maya import cmds steps = [] def _step(func): steps.append(func) return func def _get_reference(namespace): """Get the (ref_node, filename) for a reference with the giv...
from rest_framework.mixins import ( CreateModelMixin, DestroyModelMixin, ListModelMixin ) from rest_framework.request import Request from rest_framework.response import Response from rest_framework.viewsets import GenericViewSet from pydis_site.apps.api.models.bot import BumpedThread from pydis_site.apps.api.seria...
# coding: utf-8 import time import random import logging import threading from Node import node #Para importar a class, em vez do module logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M:%S') l...
from itertools import cycle from json import load import numpy as np import matplotlib.pyplot as plt from matplotlib import rc with open('bgm_anime_dataset.json', 'r', encoding='utf8') as f: data = load(f) scores = np.array( [bangumi['rating']['score'] for bangumi in data], dtype=np.float64 ) count = sc...
from seltest import Base, url, hide window_size = [200, 200] base_url = 'google.com' class GoogleTest(Base): def base(self, driver): pass def title(self, driver): assert driver.title == 'Google', 'title should be "Google"' def bad_title(self, driver): assert driver.title != 'Google', 't...
# -*- coding: utf-8 -*- """ @author: Austin Nicolai """ import sys from sensor import Sensor import math from random import randint class POI_Sensor(Sensor): def __init__(self, sector, location, rover_heading, sensor_range, sensor_noise): super(POI_Sensor, self).__init__(sector, location, rover_headi...
#!/usr/bin/env python # # Copyright 2014 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 o...
#!/usr/bin/python # -*- coding: utf-8 -*- import numpy as np import pulp as lp import re from matplotlib import pyplot as plt from queue import PriorityQueue import pandas as pd def user_definedProb(Charge_Freq,values): totalFreq = sum(Charge_Freq) Charge_Prob = [x / totalFreq for x in Charge_Freq...
from elasticsearch import Elasticsearch, RequestsHttpConnection from elasticsearch import helpers from requests_aws4auth import AWS4Auth import os AWS_ACCESS_KEY = os.environ['AWS_ACCESS_KEY'] AWS_SECRET_KEY = os.environ['AWS_SECRET_KEY'] region = 'ap-northeast-2' service = 'es' awsauth = AWS4Auth(AWS_ACCES...
from main import app,permission import flask,os,tempfile,json from io import BytesIO @app.route('/exportData') @permission.ValidForLogged def exportData(): encObj = app.config['DATA_CONTAINER'] buffer = BytesIO() Data = {} #---------- CONFIG ----- Data['CONFIG'] = {'PASSWORD':encObj.getPasswor...
from . import kafka_interface from . import zeroMQ_interface
import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings_production') from django.conf import settings from celery import Celery app = Celery(app='daisychain', backend='amqp') # This reads, e.g., CELERY_ACCEPT_CONTENT = ['json'] from settings.py: app.config_from_object('django.conf:set...
""" This provides autorecruitment functionality into Ellis. """ import socket import time import json from ellis import config, ellis_modules, ns class Autorecruit(ellis_modules.EllisModule, module_name="Autorecruit"): """ This is the module that providse the core functionality. """ # pylint: disabl...
# T'm "ok" print('T\'m \"ok\"') print("I\'m learning\nPython") print('''line1 line2 line3''') print(True) print(3==2) print(not True) print(9 / 3) # 3.0 print(9 // 3) # 3 print(10 % 3) # 1 s3=r'Hello, "bart"' print(s3) # Hello, "bart" s4=r'''hello, Lisa!''' print(s4)
from urllib.parse import urlparse from re import match from django_filters.views import FilterView from .filters import EquipmentFilter, ReportRequestToRepairFilter, EmployeesFilter from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts...
""" Script to generate data for testing FUV. It must be run in a directory containing ut_FUV.m and ut_constants.mat. ut_FUV.m needs to be modified to load ut_constants.mat at the beginning, in addition to all the intermediate points where it is already being loaded. """ import numpy as np from scipy.io.matlab import ...
from nose import SkipTest from funtests import transport class test_sqla(transport.TransportCase): transport = "sqlalchemy" prefix = "sqlalchemy" event_loop_max = 10 connection_options = {"hostname": "sqlite://"} def before_connect(self): try: import sqlakombu # noqa ...