text
stringlengths
2
999k
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("UserInfo", "0004_auto_20170318_1107"), ] operations = [ migrations.AlterField( model_name="pledgeclass", ...
import tntbx import tntbx.eigensystem from scitbx.array_family import flex from libtbx.test_utils import approx_equal import random import time def matrix_mul(a, ar, ac, b, br, bc): assert br == ac result = [] for i in xrange(ar): for k in xrange(bc): s = 0 for j in xrange(ac): s += a[i ...
# WARNING: you are on the master branch; please refer to examples on the branch corresponding to your `cortex version` (e.g. for version 0.24.*, run `git checkout -b 0.24` or switch to the `0.24` branch on GitHub) import numpy as np import cv2 from .colors import get_color class BoundBox: def __init__(self, xmin...
from . import _version __version__ = _version.get_versions()['version'] from .impact import Impact from .impact_distgen import run_impact_with_distgen, evaluate_impact_with_distgen from .control import ControlGroup import os # Used to access data directory root, _ = os.path.split(__file__) template_dir = os.path.joi...
from datetime import datetime, timedelta from typing import TypeVar, Generic, Optional, Type T = TypeVar("T") class SimpleCache(Generic[T]): ''' A high performance mini local cache. This cache will not copy the objects on get/put, modification to objects affects cached objects. You can pass a class ...
# -*- coding: utf-8 -*- import os, sys import argparse import numpy as np import torch from torchvision import datasets, transforms from torch import optim from torch.optim import lr_scheduler from model import Net from train_eng import net_train from test_eng import net_test def parse_args(): parser = argparse...
# pull in the default wazimap settings from wazimap.settings import * # noqa # install this app before Wazimap INSTALLED_APPS = ['wazimap_np'] + INSTALLED_APPS DEBUG = False if (os.environ.get('APP_ENV', 'dev') == 'prod') else True DATABASE_URL = os.environ.get('DATABASE_URL', 'postgresql://wazimap_np:wazimap_np@lo...
#!/usr/bin/env python from setuptools import setup from prettytable import __version__ as version def fread(filepath): with open(filepath, 'r') as f: return f.read() setup( name='ptable2', version=version, include_package_data=True, zip_safe=False, entry_points={ 'console_scr...
#!/usr/bin/python3 import argparse parser = argparse.ArgumentParser() parser.add_argument('-i', nargs=1, required=True, help='input gtf file') parser.add_argument('-o', nargs=1, required=True, help='output bed file') args = parser.parse_args() gtf = open(args.i[0]) bed = open(args.o[0], 'w') for line in gtf: chro...
#!/Library/Frameworks/Python.framework/Versions/3.1/bin/python3 import os import sys sys.path.append(os.getcwd().split('slps')[0]+'slps/shared/python') import slpsns import xml.etree.ElementTree as ET if __name__ == '__main__': if len(sys.argv)<3: print('Usage:\n\tcount.py <input-def> <input-file>...') sys.exit(1...
# coding: utf-8 """ Seldon Deploy API API to interact and manage the lifecycle of your machine learning models deployed through Seldon Deploy. # noqa: E501 OpenAPI spec version: v1alpha1 Contact: hello@seldon.io Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint...
# Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # https://aws.amazon.com/apache2.0/ # # or in the "license" file accomp...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** from enum import Enum __all__ = [ 'AacAudioProfile', 'AccountEncryptionKeyType', 'AnalysisResolution', 'AssetContainerPermission', ...
import pickle from sklearn.pipeline import Pipeline from sklearn.preprocessing import LabelEncoder from sklearn.linear_model import SGDClassifier from sklearn.feature_extraction.text import TfidfVectorizer from text_studio.model import Model class Sklearn_SVM(Model): def setup(self, tokenizer=None, lowercase=Fa...
# -*- coding: utf-8 -*- """SPNet v1 model for Keras. """ import numpy as np import sys from keras.models import Model from ..config import ModelConfig from ..losses import pose_regression_loss from ..layers import * from ..utils import * from .blocks import * from .common import residual from .common import downscal...
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright 2013 Kitware 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 cop...
from pubnub.managers import TelemetryManager from pubnub.enums import PNOperationType def test_average_latency(): manager = TelemetryManager() endpointLatencies = [ {"timestamp": 100, "latency": 10}, {"timestamp": 100, "latency": 20}, {"timestamp": 100, "latency": 30}, {"timest...
import setuptools setuptools.setup( name='qrsend', version='2.6.8', py_modules=['qrsend'], entry_points={'console_scripts': ['qrsend = qrsend:main']}, install_requires=['qrcode'], extras_require={'extras': ['netifaces']} )
"""Matrix-based probabilistic linear solvers. Implementations of matrix-based linear solvers which perform inference on the matrix or its inverse given linear observations. """ import abc import warnings import numpy as np import probnum from probnum import linops, randvars class ProbabilisticLinearSolver(abc.ABC)...
from setuptools import find_packages, setup setup( name="pymongo-migrate", version="0.11.0", description="MongoDB data migration tool in Python", url="https://github.com/stxnext/pymongo-migrate", license="Apache", packages=find_packages(where="src"), package_dir={"": "src"}, platforms="...
from __future__ import division import torch import math import random from PIL import Image import cv2 import numpy as np import numbers import types import collections import warnings import matplotlib.pyplot as plt from torchvision.transforms import functional import PIL INTER_MODE = {'NEAREST': cv2.INTER_NEAREST, ...
from __future__ import division, print_function __all__ = ['Experiment', 'load_data', 'load_model', 'load_fit', 'sim_data', 'Parameter', 'FitProblem', 'FreeVariables', 'pmath', 'preview', 'fit', 'np', 'sys', 'sans', 'seed'] # symbols loaded for export import sys import numpy as np from bumps.name...
# Copyright (C) 2018 Pierre Jean Fichet # <pierrejean dot fichet at posteo dot net> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE I...
"""Wordle Terminal""" import random from functools import partial from termcolor import colored with open("words.txt", "r", encoding="utf8") as file: wordList2D = [(line.strip()).split() for line in file] file.close() wordList = [] for i, _ in enumerate(wordList2D): wordList.append(wordList2D[i][0]) word =...
import os import numpy as np import json import tensorflow as tf import keras.backend as k from keras.layers import * from keras.layers import InputLayer, Input from keras.models import Sequential, Model, load_model from keras.layers import concatenate from keras.optimizers import Adam from keras.callbacks import Earl...
import os, time, socket, struct, tempfile, subprocess, ssl __all__ = ['Daemon', 'Datagram', 'DatagramIterator', 'MDConnection', 'ChannelConnection', 'ClientConnection'] class Daemon(object): DAEMON_PATH = './astrond' def __init__(self, config): self.config = config self.daemon = N...
import torch import torch.nn as nn from mmdet.core import bbox2result, bbox2roi, build_assigner, build_sampler from .. import builder from ..registry import DETECTORS from .base import BaseDetector from .test_mixins import BBoxTestMixin, MaskTestMixin, RPNTestMixin @DETECTORS.register_module class TwoStageDetector(B...
"""Split data with multiple labels Split data into multiple datasets Example ------- 2 label columns: >>> python split_data_with_multiple_labels.py ptsd.csv output --split label_included label_abstract_screening --suffix final tiab 3 label columns: >>> python split_data_with_multiple_labels.py ptsd.c...
#!/usr/bin/env python """Writer for PHYLIP sequence format """ from cogent3.format.util import _AlignmentFormatter __author__ = "Gavin Huttley" __copyright__ = "Copyright 2007-2022, The Cogent Project" __credits__ = ["Gavin Huttley", "Thomas La"] __license__ = "BSD-3" __version__ = "2022.4.20a1" __maintainer__ = "Ga...
########################################################################## # If not stated otherwise in this file or this component's Licenses.txt # file the following copyright and licenses apply: # # Copyright 2017 RDK Management # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use th...
"""Pair plot between variables of latent space""" from configparser import ConfigParser, ExtendedInterpolation import glob import time import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from sdss.utils.managefiles import FileDirectory from sdss.utils.configfile import Configu...
import logging import sys import click DEBUG_STRING = click.style("DEBUG", fg="green") LOG_STRING = click.style("manta", fg="blue", bold=True) # same as info LOG_STRING_NOCOLOR = "manta" WARN_STRING = click.style("WARNING", fg="yellow") ERROR_STRING = click.style("ERROR", bg="red", fg="green") CRITICAL_STRING = clic...
# Code modified from https://github.com/kuangliu/pytorch-cifar '''ResNet in PyTorch. BasicBlock and Bottleneck module is from the original ResNet paper: [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. arXiv:1512.03385 PreActBlock and PreActBottleneck module is ...
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2013 OpenStack Foundation # Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this...
#!/usr/bin/env python3 # @Time : 31/5/20 7:49 PM # @Author : fangcheng.ji # @FileName: augmentation.py import numpy as np import random import cv2 import math import albumentations as A import albumentations.augmentations.functional as AF def get_albumentations_train_transforms(): return A.Compose( ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import pickle import pytest import numpy as np import pandas as pd from xarray.core import duck_array_ops, utils from xarray.core.pycompat import OrderedDict from . import TestCase class TestAlias(TestCase):...
from pathlib import Path from tempfile import TemporaryDirectory from h5xrd.main import main def test_main(): with TemporaryDirectory() as csv_dir: main('data', csv_dir) count = 0 for csv_file in Path(csv_dir).iterdir(): count += 1 with csv_file.open("r") as f: ...
#! /usr/bin/python #-*- coding: utf-8 -*- from __future__ import print_function import sys, os import argparse import datetime from pybern.products.codesp3 import get_sp3, list_products from pybern.products.formats.sp3 import Sp3 import pybern.products.fileutils.decompress as dc import pybern.products.fileutils.compre...
#!/usr/bin/python # -*- coding: utf-8 -*- """Tests for the TSK path specification implementation.""" import unittest from tests.path import test_lib from dfvfs.path import tsk_path_spec class TSKPathSpecTest(test_lib.PathSpecTestCase): """Tests for the TSK path specification implementation.""" def testInitiali...
#!/usr/bin/env python from __future__ import print_function import os import subprocess import stretch_body.hello_utils as hu hu.print_stretch_re_use() print('Versions') print("-------------------------------------------------------------------------") import stretch_body import stretch_body.base as base import stretc...
# -*- 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...
import pytest from django.conf import settings from django.contrib import messages from django.contrib.auth.models import AnonymousUser from django.contrib.messages.middleware import MessageMiddleware from django.contrib.sessions.middleware import SessionMiddleware from django.http import HttpRequest, HttpResponseRedir...
# Copyright 2013-2018 CERN for the benefit of the ATLAS collaboration. # # 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...
"""Benchmarks of Lasso regularization path computation using Lars and CD The input data is mostly low rank but is a fat infinite tail. """ from collections import defaultdict import gc import sys from time import time import numpy as np from sklearn.linear_model import lars_path, lars_path_gram from sklearn.linear_m...
import json from abc import ABC, abstractmethod from typing import Any, Dict, Final import toml import yaml from path import Path from .utils.misc import list_to_nested_dicts, merge_nested_dicts class IConfigLoader(ABC): def __init__(self, workdir: Path): self._workdir: Final = workdir @abstractmet...
# 1、现有两元祖 (('a'),('b')),(('c'),('d')) ,请使用Python中的匿名函数生成列表 [ {'a':'c'},{'b':'d'}] t1 = (('a'), ('b')) t2 = (('c'), ('d')) lst = [] for i in range(2): d = lambda t1, t2: {t1[i][0]: t2[i][0]} lst.append(d(t1, t2)) print(lst) # 2、输入一个英文句子,翻转句子中的单词顺序,但单词内字符的顺序不变 source = 'I feel no need for any other faith than my ...
from autograd import grad import autograd.numpy as np #from LineSearch import LineSearch from .BaseOptimizer import Optimizer class DichotomousLineSearch(Optimizer): """Dichotomous search class for line optimization.""" def __init__(self, cost_function, interval, ftol=1e-8, max_iterations=1e3): ...
# Generated by Django 2.1 on 2018-10-02 04:05 import decentmark.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('decentmark', '0005_submission_autofeedback'), ] operations = [ migrations.AddField( model_name='submissio...
import geoacumen_city import maxminddb from flask import current_app IP_ADDR_LOOKUP = maxminddb.open_database( current_app.config.get("GEOIP_DATABASE_PATH", geoacumen_city.db_path) ) def lookup_ip_address(addr): try: response = IP_ADDR_LOOKUP.get(addr) return response["country"]["iso_code"] ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 25 16:03:08 2017 @author: alek """ import json import uuid import logging import sys import threading import asyncio import concurrent from concurrent.futures import _base from concurrent.futures import process from functools import partial from p...
import math import time import warnings from typing import Any, Dict, Optional, Type, Union import gym import numpy as np import torch from gym import spaces from torch import optim from torch.nn import functional as F from paper_rl.architecture.ac.core import ActorCritic, count_vars from paper_rl.common.buffer impor...
# Start the services needed raspi = Runtime.start("raspi","RasPi") hat = Runtime.start("hat","AdafruitMotorHat4Pi") m1 = Runtime.start("m1","MotorHat4Pi") # Attach the HAT to i2c bus 1 and address 0x60 hat.attach("raspi","1","0x60") # Use the M1 motor port and attach the motor to the hat m1.setMotor("M1") m1.attach("ha...
# GENERATED BY KOMAND SDK - DO NOT EDIT from .action import GetOffenseNoteById
import random import matplotlib.pyplot as plt from sklearn.decomposition import PCA from sklearn.manifold import TSNE __author__ = "Marcin Stachowiak" __version__ = "1.0" __email__ = "marcin.stachowiak.ms@gmail.com" def reduce_dim_PCA(X, Y, class_names, n_components=2, visualise=False): if visualise: pri...
'''(Sliding Window using Two Pointers [M]): Given a String, find the longest substring with unique characters. For example: "whatwhywhere" --> "atwhy" ''' def longestSubStringUnique(s): start, end = 0, 0 maxlen = 1 hashMap = {} hashMap[s[0]] = 0 res = [0, 0] while end < len(s) ...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
# Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License # is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
# Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ This module provides a class used to describe the elastic tensor, including methods used to fit the elastic tensor from linear response stress-strain data """ import itertools import warnings import numpy as np import sy...
import string def is_pangram(sentence=""): s = str(sentence) sen = list(set(s.lower())) f = [c for c in sen if c in string.ascii_lowercase] return len(f) == 26
from abc import ( abstractmethod, ) import itertools import logging from types import TracebackType from typing import ( Any, Callable, cast, Dict, List, Optional, Tuple, Type, Union, ) from cached_property import cached_property from eth_typing import ( Address, ) from eth_...
import cv2 import numpy as np import random as rd k = 2 while True : img = np.zeros([768//k,1024//k]) img[rd.randint(0, 768)//k:, rd.randint(0, 1024)//k:] = 1 cv2.imshow("image", img) cv2.waitKey(10)
""" WSGI config for indulgence 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/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_S...
from frappe import _ def get_data(): return { # 'heatmap': True, 'heatmap_message': _('This is based on the Time Sheets created against this project'), 'fieldname': 'design_project', 'transactions': [ { 'label': _('Design'), 'items': ['Task'] }, { 'label': _('Sales'), 'items': ['Sales...
import sentencepiece as spm from sklearn.model_selection import ShuffleSplit from traceback import format_exc as _format_exc s = spm.SentencePieceProcessor('data/jpa_wiki_100000.model') #file1 = open('jyp_train.txt', 'r') #Lines = file1.readlines() # for i in Lines: # print(i) path_input_eng = 'data/English_2....
from dataclasses import dataclass from typing import List, Optional from dogia.types.blockchain_format.sized_bytes import bytes32 from dogia.types.blockchain_format.vdf import VDFInfo, VDFProof from dogia.types.end_of_slot_bundle import EndOfSubSlotBundle from dogia.types.full_block import FullBlock from dogia.types.p...
class MyHashMap: def __init__(self): self.hashMap = {} def put(self, key: int, value: int) -> None: self.hashMap[key] = value def get(self, key: int) -> int: if key in self.hashMap: return self.hashMap[key] return -1 def remove(self, key: in...
import cherrypy # CherryPy lightweight webframework. Install with: sudo pip install cherrypy import datetime import collections # TODO: Expire users who haven't polled in a while, or set their status to 'away'. # TODO: Expire messages older than X days. class Message(object): def __init__(self, sender, r...
"""Support for restoring entity states on startup.""" from __future__ import annotations from abc import abstractmethod import asyncio from datetime import datetime, timedelta import logging from typing import Any, TypeVar, cast from homeassistant.const import ATTR_RESTORED, EVENT_HOMEASSISTANT_STOP from homeassistan...
# -*- coding: utf-8 -*- """ This module provides structures for annotating a given (single image) file with labeled items. """ __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" import logging import time from collections import OrderedDict import os import json from typing import Union, List, Any,...
# from django.urls import path # # from .views import PostList, PostDetail, UserList, UserDetail # # urlpatterns = [ # path('users/', UserList.as_view()), # new # path('users/<int:pk>/', UserDetail.as_view()), # path('<int:pk>/', PostDetail.as_view()), # path('', PostList.as_view()) # ] from rest_fra...
import threading from PyQt4.Qt import (QDialog, QInputDialog, QLineEdit, QVBoxLayout, QLabel, SIGNAL) import PyQt4.QtCore as QtCore from electrum.i18n import _ from .ledger import LedgerPlugin from ..hw_wallet.qt import QtHandlerBase, QtPluginBase from electrum_gui.qt.util import * from btchip....
from conans import ConanFile, Meson, tools from conans.errors import ConanInvalidConfiguration import os required_conan_version = ">=1.33.0" class WaylandProtocolsConan(ConanFile): name = "wayland-protocols" description = "Wayland is a project to define a protocol for a compositor to talk to its clients as w...
import pytest from dynamo.entities import Visitor, itemToVisitor # pylint: disable=wrong-import-position visitor_id = '171a0329-f8b2-499c-867d-1942384ddd5f' def test_default_init(): visitor = Visitor( visitor_id ) assert visitor.id == visitor_id assert visitor.numberSessions == 0 def test_numberSessions_init()...
# coding: utf-8 # Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department # Distributed under the terms of "New BSD License", see the LICENSE file. from ase.io import write as ase_write import copy import numpy as np import warnings from pyiron.atomistics.structure....
from __future__ import absolute_import, print_function, division import os import numpy as np import theano import theano.tensor as T floatX = 'float32' def test_graph_opt_caching(): opt_db_file = os.path.join(theano.config.compiledir, 'optimized_graphs.pkl') if os.path.exists(opt_db_file): os.remove...
from abc import ABC, abstractmethod __all__ = ["CWAttack"] class CWAttack(ABC): @abstractmethod def attack(self, imgs, targets): ...
from blargh.engine import world from .. import exceptions class Instance(): def __init__(self, model, data={}, first=False): '''Create instance with model MODEL. Initial values will be set from DATA. DATA should contain "storage" values. DATA might contain more values, i.e. database column...
import fitz doc = fitz.open("presentazione_cts.pdf") for i in range(len(doc)): for img in doc.getPageImageList(i): xref = img[0] pix = fitz.Pixmap(doc, xref) if pix.n - pix.alpha < 4: # this is GRAY or RGB pix.writePNG("p%s-%s.png" % (i, xref)) else: #...
import math import StringIO import types __pychecker__ = 'no-returnvalues' WS = set([' ', '\t', '\r', '\n', '\x08', '\x0c']) DIGITS = set([str(i) for i in range(0, 10)]) NUMSTART = DIGITS.union(['.', '-', '+']) NUMCHARS = NUMSTART.union(['e', 'E']) ESC_MAP = {'n': '\n', 't': '\t', 'r': '\r', 'b': '\x08', 'f': '\x0c'} R...
"""Support for SimpliSafe alarm control panels.""" import logging import re from simplipy.sensor import SensorTypes from simplipy.system import SystemStates from homeassistant.components.alarm_control_panel import ( FORMAT_NUMBER, FORMAT_TEXT, AlarmControlPanel) from homeassistant.const import ( CONF_CODE, S...
# List and running of tests using pytest framework # (venv) C:\ukautom\t360\kurzus\pycharm\conduit\test_proj> # pytest test_index_1.py --alluredir=./out # allure serve ./out import time time.sleep(1) def time_sl(): time.sleep(1) # tcA001_run = A001 test case - New user registration with user name, email and pa...
# Copyright (C) 2015-2022 by Vd. # This file is part of Rocketgram, the modern Telegram bot framework. # Rocketgram is released under the MIT License (see LICENSE). from dataclasses import dataclass from typing import Optional @dataclass(frozen=True) class PhotoSize: """\ Represents PhotoSize object: ht...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
class ObddManager: def __init__(self,var_count,use_cache=True): # ACACAC: use_cache self.var_count = var_count #self.ordering = ordering # ACAC self.zero = ObddNode(is_terminal=True,sign=0,nid=0) self.one = ObddNode(is_terminal=True,sign=1,nid=1) self.id_counter = 2 #...
class Solution: def findNthDigit(self, n: int) -> int: n -= 1 for digit in range(1, 11): first = 10 ** (digit - 1) if n < 9 * first * digit: return int(str(first + n / digit)[n % digit]) n -= 9 * first * digit
from django.urls import path, re_path, include from .views import blog_home_page,post_detail, posts_categories_partial, posts_by_category, search_posts_view urlpatterns = [ path('blog', blog_home_page), path('tag/<tag_slug>/', blog_home_page), # path('blog/notfound', search_result_none), path('blog/<po...
# ------------------------------------------------------------------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. # -------------------------------------------------------------------...
# ============================================================================= # Automated trading script I - MACD # Author : Mayank Rasu # Please report bug/issues in the Q&A section # ============================================================================= import fxcmpy import numpy as np from stocktrends imp...
from mx.DateTime import ISO class AnyClass: pass date = ISO.ParseDateTime('2002-01-01 00:00:00') rubish = AnyClass() if date == rubish: print "Oh Dear" else: print "hurrah!" class AnyClass: def __coerce__(self, other): print 'coerce %s and %s' % (repr(self), repr(other)) print date + rubish #print ...
# coding: utf-8 """ MIT License """ ''' Axel Masquelin & Sami Connolly Andrea Elhajj & Thayer Alshaabi --- Description: Misceleanous functions to assist in the evaluation of individuals, creating visuals, and csv file save. --- Copyright (c) 2018 ''' # libraries and dependencies # ...
# Copyright 2018 The Cirq Developers # # 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 applicable law or agreed to in ...
from django.apps import AppConfig class UserConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = 'api.user'
# Module to aid with Nanoleaf discovery import socket def discover_devices(timeout=30, debug=False): """ Discovers Nanoleaf devices on the network using SSDP :param timeout: The timeout on the search in seconds (default 30) :param debug: Prints each device string for the SSDP discovery :returns: ...
from unittest.mock import Mock import colander import pytest from h.schemas.validators import Email class TestEmail: @pytest.mark.parametrize( "email", [ "jimsmith@foobar.com", "international@xn--domain.com", "jim.smith@gmail.com", "jim.smith@foo.b...
''' Created on May 25, 2018 @author: nishant.sethi ''' n=5 p=1/3 result=0 for i in range(1,6): result+=(1-p)**(i-1)*p print(round(result,3))
import colorsys import imghdr import os import random from keras import backend as K import numpy as np from PIL import Image, ImageDraw, ImageFont def read_classes(classes_path): with open(classes_path) as f: class_names = f.readlines() class_names = [c.strip() for c in class_names] ...
"""Base driver module to inherit from.""" from selenium.webdriver.common.by import By class BaseDriver(object): """Base driver that will be called from all pages and elements.""" # pylint: disable=too-few-public-methods GENERIC_DIV = (By.TAG_NAME, 'div') DEFAULT_TIMEOUT = 30 def __init__(self, driver): ...
#!/usr/bin/env python3 from pyparsing import * import ebnf ParserElement.enablePackrat() singleRawString = QuotedString(quoteChar='@"', endQuoteChar='"') doubleRawString = QuotedString(quoteChar='@@"', endQuoteChar='"@@', multiline=True) rawString = singleRawString | doubleRawString table = { # Non-greedy trick...
# # Copyright 2019 BrainPad Inc. All Rights Reserved. # # 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 the rights # to use, copy, modify, me...
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains t...