content
stringlengths
5
1.05M
from django.http import HttpResponse, JsonResponse from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework.generics import get_object_or_404 from rest_framework.parsers import JSONParser from .serializers import GameSerializer fr...
import argparse import shlex import greenlet as gl import numpy as np import tensorflow as tf from pong.mechanics.pong import Pong, S from pong.mechanics import policies from pong.mechanics import constants as c from pong.utils import common from pong.utils.tf_machinery import NeuralNetwork class NNPolicy(policies....
from abc import ABC, abstractmethod class MessageParser(ABC): """ Class which provides parsing services """ def __init__(self, input_data): """ Init section taking file with data for parsing :param input_data: string or file with input data """ self.input_data ...
# 17 wordCounts = { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eight...
# -*- coding: utf-8 -*- from csv import reader from pathlib import Path from typing import Dict, List, Tuple from tqdm import tqdm from resources.constants import SECTION_TYPES def load_language_set(ranking_type: List[str], section_type: str, folder_name: str) -> List[str]: print("INFO: Loading language subset...
import math import random import numpy as np import utils from utils import VECTORLENGTH class LT: def __init__(self): # Initialize member fields self._weights = [] # holds probability of the weights self._setWeights() # sets the probability of the weights """if not LT._isBinomCalcul...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Oct 5 17:14:13 2019 @author: avneesh """ import torch.nn as nn import torchvision.models as models import torch.nn.functional as F import torch class Model(nn.Module): def __init__(self): super(Model, self).__init__() # inception_f...
#!/usr/bin/env python # Recal VCF, using likelihood column. # Only if it's a C-T or G-A transition. # # @author: James Boocock # @date: 16/03/2015 # import argparse import sys import vcf import collections import copy def is_ga_or_ct(ref,alt): if(len(ref) == 1 and len(alt) == 1): alt = alt[0] if(r...
from __future__ import unicode_literals import datetime from django.test import TestCase from django.core.urlresolvers import reverse from django.contrib.auth.models import User from django.utils.timezone import make_aware, get_default_timezone from happenings.models import Event from happenings.templatetags.happeni...
# Copyright (c) 2019, IRIS-HEP # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the foll...
__version__ = "1.3.0.1"
import requests from bs4 import BeautifulSoup import locale import json import csv def merge_two_dicts(x, y): """Given two dicts, merge them into a new dict as a shallow copy.""" z = x.copy() z.update(y) return z locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' ) print("\n\nGetting User Page\n\n") page...
import Mask_class as MC import os import time import glob import cv2 as cv import argparse import numpy as np # start = time.clock() # time.sleep(5) # end = time.clock() # print ("times used is : " , end - start) if __name__ == "__main__": net = MC.Mask() parser = argparse.ArgumentParser() pars...
import click from tqdm import tqdm from os.path import join as join_path import skimage.io import torch import os.path import numpy as np import natural.number import models import model_utils import utils import constants as c import image_utils from utils import Params, Timer, ensure_dir_exists @click.command() @c...
# -*- coding: utf-8 -*- from gluon.http import HTTP from gluon.storage import Storage class S3Config(Storage): def __init__(self, T): self.auth = Storage() self.base = Storage() self.database = Storage() self.gis = Storage() self.mail = Storage() self.L10n = Storag...
from model.group import Group from model.contact import Contact import random from random import randrange def test_add_some_contact_to_some_group(app, ormdb): if app.contact.count() == 0: app.contact.create(Contact(firstname="First name", middlename="MiddleName", lastname="LastName")) if app.group.co...
import os import time from shutil import copyfile import captcha_algo_decoder def test(dataset_directory): for filename in os.listdir(dataset_directory): if filename.endswith(".txt"): file_with_captcha_solve = open(os.path.join(dataset_directory, filename), ...
# -*- coding: utf-8 -*- def rhombicuboctahedron(): import vtk # First, you need to store the vertex locations. import numpy as np fu = 1 # full unit hu = 0.5 # half unit d = np.sqrt((fu ** 2) / 2) # diag hh = hu + d # half height # left view faces us import utool as ut ...
import enum import errno import os import platform import socket import traceback from abc import ABCMeta, abstractmethod import mozprocess from ..environment import wait_for_service from ..wptcommandline import require_arg # noqa: F401 here = os.path.dirname(__file__) def cmd_arg(name, value=None): prefix = ...
import os import time from colorama import * from input import * from background import * from paddle import * from ball import * from brick import * from powerup import * from boss import * from laser import * # Windows doesn't support ANSI coloring but Windows API does # init() makes Windows API run these colors i...
import numpy as np def getMinChannel(img,AtomsphericLight): imgGrayNormalization = np.zeros((img.shape[0], img.shape[1]), dtype=np.float16) for i in range(0, img.shape[0]): for j in range(0, img.shape[1]): localMin = 1 for k in range(0, 3): # print('Atomsph...
"""Utilities and helpers useful in other modules """ from typing import Text, Union from six import ensure_binary TextOrBytes = Union[Text, bytes] def text_to_ascii_bytes(text): # type: (TextOrBytes) -> bytes """Convert a text-or-bytes value to ASCII-encoded bytes If the input is already `bytes`, we si...
import math from collections import namedtuple from itertools import chain from math import inf from operator import itemgetter from pathlib import Path from statistics import median from typing import Tuple, Sized, List import cv2 import matplotlib.colors import numpy as np from matplotlib import pyplot as plt from ...
""" A program analyzing 3D protein structures from PDB to generate 2D binding motives. For Further information see https://github.com/Cardypro/StructureAnalyzer """ import math import os from typing import Dict, Tuple, List, Union, Optional from dataclasses import dataclass from collections import defaultd...
from api.views import ShopViewSet, ProductViewSet from rest_framework import routers router = routers.DefaultRouter() router.register('shop', ShopViewSet, basename='Shop') router.register('product', ProductViewSet, basename='Product')
"""steps v.2 Revision ID: d115acfbcb61 Revises: 33f050e2a226 Create Date: 2021-05-07 20:24:39.438596 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'd115acfbcb61' down_revision = '33f050e2a226' branch_labels = None depends_on = None def upgrade(): # ### ...
CapnpLangToolchainInfo = provider(fields = { "lang_shortname": "short name for the toolchain / language, e.g. 'cc', 'java', 'rust', etc.", "plugin": "plugin target to pass to capnp_tool for this language", "plugin_deps": "plugin depepencies to pass to capnp_tool invocation for this language", "runtime":...
class TreeNode: def __init__(self, data): self.data = data self.left = None self.right = None def create_binary_tree(input_list=[]): if input_list is None or len(input_list) == 0: return None data = input_list.pop(0) if data is None: return None node = TreeN...
import torch.nn as nn def _initialize_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') if m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, MeanSpect...
#!/usr/bin/env python # # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import logging from uuid import UUID import azure.functions as func from onefuzztypes.enums import ErrorCode, NodeState from onefuzztypes.models import Error from onefuzztypes.requests import AgentRegistrationGet, AgentRe...
from __future__ import annotations from racketinterpreter.classes import errors as err from racketinterpreter.classes import tokens as t class ParenthesesAnalyzer: PAREN_MAP = { '(': ')', '[': ']', '{': '}' } def __init__(self) -> None: self.paren_stack = [] def rece...
""" This module provides classes for testing RanklistRow object """ import unittest from codeforces import RanklistRow, Party, ProblemResult class RanklistRowTests(unittest.TestCase): def setUp(self): self.row = RanklistRow() def load_from_dict(self): d = { "party": { ...
# pylint:disable=ungrouped-imports from unittest.mock import patch import pytest import activitylogs import auditor import tracker from event_manager.events import permission as permission_events from tests.utils import BaseTest @pytest.mark.auditor_mark class AuditorPermissionTest(BaseTest): """Testing subsc...
# encoding: UTF-8 from __future__ import print_function from .order_type import * class OrderManager(object): ''' Manage/track all the orders ''' def __init__(self): self._internal_order_id = 0 # unique internal_orderid self._order_dict = {} # internal_order to [# ...
import logging import typing import random import heapq import time import asyncio import threading from .actor import Actor from .message import ActorMessage from .state import ActorState, OUTBOX, EXPORT, ERROR, ERROR_NOTRY from .storage import ActorLocalStorage from .registery import ActorRegistery from .builtin_act...
# -*- coding: utf-8 -*- """ Produces fake instrument data for testing. """ from __future__ import print_function from __future__ import absolute_import import functools import os import numpy as np import pandas as pds import pysat from pysat.instruments.methods import testing as test # pysat required parameters pla...
# -*- coding: utf-8 -*- from scake import Scake import logging _logger = logging.getLogger(__name__) class Foo(): def __init__(self, x=1, y=2): self.x = x self.y = y def __call__(self): x = self.x() if isinstance(self.x, Foo) else self.x y = self.y() if isinstance(self.y, Foo...
"""OpenAPI core contrib requests requests module""" from __future__ import absolute_import from werkzeug.datastructures import ImmutableMultiDict from requests import Request from six.moves.urllib.parse import urlparse, parse_qs from openapi_core.validation.request.datatypes import ( RequestParameters, OpenAPIRequ...
# Copyright (c) 2019 Erwin de Haan. 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 applic...
import numpy import ilcs_parser from parseratorvariable import ParseratorType CITATION = ( ('chapter', ('Chapter',)), ('act prefix', ('ActPrefix',)), ('section', ('Section',)), ('subsection', ('SubSection',)), ) class ILCSType(ParseratorType): type = 'ILCS' def tagger(self, field): r...
# -*- coding: utf-8 -*- """ :copyright: (c) 2018 by Neil Jarvis :licence: MIT, see LICENCE for more details """ from __future__ import absolute_import, unicode_literals, print_function def nth(number): if str(number)[-1] == '1': return number + 'st' elif str(number)[-1] == '2': return number +...
from contextlib import contextmanager @contextmanager def assert_raises(expected_exception): ''' unittest.TestCase Python 2.6 compatible assert_raises context manager ''' context = Context() try: yield context except expected_exception as e: context.exception = e except Exc...
from collections import Counter def counter_arithmetic(): sales_day1 = Counter(apple=4, orange=9, banana=10) sales_day2 = Counter({'apple': 10, 'orange': 8, 'banana': 2}) print("sales_day1", sales_day1) print("sales_day2", sales_day2) print("sales_day1 + sales_day2", sales_day1 + sales_day2) p...
""" Status: The algorithm works and an example of using the algorithm is finished, so I am done working on this module. A module that implements the Knuth-Plass text formatting algorithm in Python. """ from typing import List, Callable, Union, Dict, Generator, Tuple from collections import namedtuple class JUSTIF...
import os import imageio import numpy as np from tqdm import tqdm from math import exp import matplotlib.pyplot as plt class HHNeuron(): def __init__(self): self.v = -65 self.vinit = -65 self.gnamax = 1.20 self.gkmax = 0.36 self.vk = -77 self.vna = 50 self...
# Copyright 2019 IBM Corporation # # 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, ...
# Задача 2. Процесори # Да се напише програма, която пресмята каква печалба или загуба ще реализира фирма произвеждаща AND процесори. # Един процесор се изработва за 3 часа. Фирмата има даден брой служители, които работят определен брой дни. # Приема се, че един служител работи 8 часа на ден. Фирмата има за цел да изр...
#coding=utf-8 #author@alingse #2016.08.19 from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout, Activation, Flatten,RepeatVector from keras.layers import Embedding from keras.layers import LSTM from keras.optimizers import SGD, Adadelta, Adagrad,RMSprop from keras.utils...
#-*-coding:utf-8-*- # date:2019-05-20 # Author: X.L.Eric # function: data iter import glob import math import os import random import shutil from pathlib import Path from PIL import Image from tqdm import tqdm import cv2 import numpy as np import torch from torch.utils.data import Dataset from torch.utils.data import D...
# Generated by Django 3.1.2 on 2020-10-26 23:19 import common.models from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('push_notifications', '0006_auto_20200421_2050'), ] operations = [ migrations.CreateModel( name='PathwaysApiKey', ...
# Generated by Django 3.2.2 on 2021-06-18 19:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('schedule', '0004_alter_post_pub_date'), ] operations = [ migrations.AlterField( model_name='post', name='pub_date', ...
#!/usr/bin/env python import argparse import time import numpy as np import torch from trainer import Trainer from models import State from logger import Logger import utils from envs.simulation.robot import SimRobot from utils.config import Config from tensorboardX import SummaryWriter from scipy import ndimage from ...
# Copyright 2019-2021 Canaan Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import random import os def pick(rel_path="human.txt"): script_path = os.path.abspath(__file__) script_dir = os.path.split(script_path)[0] abs_file_path = os.path.join(script_dir, rel_path) with open(abs_file_path, encoding='utf-8') as txt: lines = txt.readlines() ...
#!/usr/bin/python3.6 import numpy as np np.seterr(all="ignore") def continuousScale(*args): """Creates a set of continuous scale data. If provided a filename, returns the indecies for sorting, D0, and D1 If provided a number, just creates and returns the indecies alternating from D0 and D1 indecies If provided 2 nu...
from pydantic import BaseModel from songmam.models.webhook.events.base import BaseMessaging, WithTimestamp class GamePlay(BaseModel): game_id: str player_id: str context_type: str context_id: str score: int payload: str class GamePlayEntries(BaseMessaging, WithTimestamp): game_play: Game...
import datetime import numpy as np import pandas as pd from google.oauth2 import service_account from googleapiclient import discovery SPREADSHEET_ID = "1otVI0JgfuBDJw8jlW_l8vHXyfo5ufJiXOqshDixazZA" # ALL-IN-ONE-LOG-2021 class Spreadsheet: def __init__(self, spreadsheetId): self.spreadsheetId = spreads...
# Copyright 2020 MONAI Consortium import logging import sys import numpy as np import torch from torch.utils.data import DataLoader import monai from monai.data import ImageDataset, decollate_batch from monai.inferers import sliding_window_inference from monai.metrics import DiceMetric from monai.transforms import A...
from unittest.mock import Mock, patch import pytest from firebase_admin import messaging from backend.common.consts.fcm.platform_priority import PlatformPriority from backend.common.models.fcm.platform_config import PlatformConfig from backend.common.models.notifications.requests.fcm_request import ( FCMRequest, ...
from graphviz import Graph import os class ExportReachabilityAnalysisService: def get_height(self, node): h = 0 while len(node.children) > 0: h += 1 node = node.children[-1] return h def get_node_color(self, node): return node.get_color().value def ...
#!/usr/bin/env python3 # vim: textwidth=0 wrapmargin=0 tabstop=2 shiftwidth=2 softtabstop=2 smartindent smarttab import argparse import dateutil.parser import dateutil.utils import logging import os import pathlib import pprint import requests import sys import time import yaml pp = pprint.PrettyPrinter(indent=2, wid...
# # PySNMP MIB module HP-ICF-RATE-LIMIT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-RATE-LIMIT-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:35:10 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
import unittest from .. import * class ScanTestCase(unittest.TestCase): def test_reset(self): scan.reset([player.Player(), player.Player()]) self.assertEqual(len(scan._bin_testing()), 2) def test_binning1(self): p1 = player.Player() p_ref = reference.Reference(p1) scan....
# Generate statistics table of coverage breadth values at the three given coverage depth thresholds def stat_table(coverage_list, RegionNames, validation, phred_score, coverage_phred, X_Cut_off_list, RegionInfo, dataType): Tresh_1 = 0 Tresh_2 = 0 Tresh_3 = 0 index=0 s_table =[] s_table_phred=[] val_l...
from flask import Flask from flask_sqlalchemy import SQLAlchemy import os from flask_cors import CORS; from sqlalchemy import create_engine basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) pw = os.environ['DB_PW'] url = os.environ['DB_URL'] db = os.environ['DB_DB'] db_user = os.environ['DB...
""" Copyright (c) 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 License ...
# sweet_tenant/admin.py # Django modules from django.contrib import admin # Locals from .models import Sweet # Register your models here. admin.site.register(Sweet)
from typing import Text from linebot.models import TextSendMessage from models.message_request import MessageRequest from skills import add_skill @add_skill('/hello') def get(message_request: MessageRequest): return [ TextSendMessage(text=f'Hello World') ]
# # Copyright 2013 Intel Corp # # Authors: Lianhao Lu <[email protected]> # # 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 req...
import MySQLdb # replace mysql.server with "localhost" if you are running via your own server! # server MySQL username MySQL pass Database name. conn = MySQLdb.connect("mysql.server","beginneraccount","cookies","beginneraccount$tutorial") c = conn.cursor() c.execute("SELECT * FR...
# you can read this docs for writing bot # handler reference : https://python-telegram-bot.readthedocs.io/en/stable/telegram.ext.html from telegram import ext from . import views HANDLERS = [ ext.CommandHandler('start', views.start), ext.CommandHandler('getme', views.getme), ext.CommandHandler('clear', vi...
from spacy.lang.en import English nlp = English() tokenizer = nlp.Defaults.create_tokenizer(nlp) class voc: def __init__(self): self.num_words=1 self.num_tags=0 self.tags={} self.index2tags={} self.questions={} self.word2index={} self.response={} ...
if __name__ == "__main__": import argparse import sys parser = argparse.ArgumentParser() parser.add_argument('-v', default=0, type=int, dest='VERTEX', help='Set number of vertices.') parser.add_argument...
from .MultiMatch import MultiMatch from .Range import Range from .Term import Term from .Wildcard import Wildcard __all__ = ["MultiMatch", "Range","Term","Wildcard"]
""" Jeu du 1000 Bornes Quentin Deschamps 2020 """ import pygame from src.interface import Interface from src.sons import Sons from src.couleurs import Couleurs from src.jeu import Jeu import src.selection as selection import src.stats as stats from src.partie import Partie from random import shuffle if __name__ == "__...
class FinisherTemplate(object): def __init__(self, name, description, message, body_message): self.name = name self.description = description self.message = message self.body_message = body_message
import argparse import os import yaml import logging import coloredlogs from pippin.config import mkdirs, get_logger, get_output_dir, chown_file, get_config, chown_dir from pippin.manager import Manager from colorama import init class MessageStore(logging.Handler): store = None def __init__(self, *args, **kwa...
# coding=utf-8 from colorama import Fore import argparse import copy from Putil.data.common_data import CommonDataWithAug import numpy as np import Putil.base.logger as plog logger = plog.PutilLogConfig('dataset').logger() logger.setLevel(plog.DEBUG) COCOLogger = logger.getChild('COCO') COCOLogger.setLevel(plog.DEBUG) ...
import glob from pwn import * """ Modulo in assembly is another interesting concept! x86 allows you to get the remainder after doing a division on something. For instance: 10 / 3 -> remainder = 1 You can get the remainder of a division using the instructions introduced earlier through the div instruction. In most pr...
from django.contrib.auth.views import LoginView class HomePage(LoginView): template_name = 'account/login.html'
# Undergraduate Student: Arturo Burgos # Professor: João Rodrigo Andrade # Federal University of Uberlândia - UFU, Fluid Mechanics Laboratory - MFLab, Block 5P, Uberlândia, MG, Brazil # Fourth exercise: Solving a Linear System --> ax = b # Here I first set conditions import numpy as np from numpy import linalg as l...
# Copyright 2012 OpenStack 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 agreed to in...
length = 10 width = 5 space = length * width print("Space is: %s square meters" % space)
from flask import Blueprint from flask import current_app as app from flask import request, redirect, url_for from functools import wraps from uuid import uuid4 from Models.User import User from Models.Session import Session from datetime import datetime import uuid import hashlib class AuthenticationService(): ...
from __future__ import print_function, division import os,unittest,numpy as np from pyscf.nao import system_vars_c, prod_basis_c, tddft_iter_c dname = os.path.dirname(os.path.abspath(__file__)) sv = system_vars_c().init_siesta_xml(label='water', cd=dname) pb = prod_basis_c().init_prod_basis_pp(sv, jcutoff=7) td = tddf...
from __future__ import absolute_import # import defaults from importlib import import_module from .base import * overrides = import_module('unpp_api.settings.{}'.format(ENV)) # apply imported overrides for attr in dir(overrides): # we only want to import settings (which have to be variables in ALLCAPS) if ...
from os.path import exists, join import numpy as np from nerfactor.util import logging as logutil, io as ioutil, img as imgutil from third_party.xiuminglib import xiuminglib as xm logger = logutil.Logger(loggee="util/vis") def make_frame( view_dir, layout, put_text=True, put_text_param=None, data_root=None,...
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import grad # WGAN-GP with R1-regularization Discriminator Loss function class WGANGP_G(nn.Module): def __init__(self, penalty=None): super(WGANGP_G, self).__init__() def forward(self, preds): return F...
#!/usr/bin/python3 import json import csv import os import argparse """ read in excelint-cli generated JSON files and produce a CSV file, where each line contains the following: Workbook name Sheet name Suspiciousness threshold Formatting threshold Number of suspicious ranges Number of cells in suspicious ranges """...
# Copyright (c) OpenMMLab. All rights reserved. from .base import BaseDataset from .builder import (DATASETS, DATASOURCES, PIPELINES, build_dataloader, build_dataset, build_datasource) from .data_sources import * # noqa: F401,F403 from .dataset_wrappers import ConcatDataset, RepeatDataset from .d...
"""Visualization tooling.""" import itertools from collections import defaultdict import graphviz from monkeys.typing import REGISTERED_TYPES, lookup_rtype, prettify_converted_type def type_graph(simplify=False): """ Render graph of current type system. """ graph = graphviz.Digraph(format='svg') ...
from django.urls import reverse from rest_framework.views import status from authors.apps.base_test import BaseTest class DislikeLikeArticleTestCase(BaseTest): """Tests Like and Dislike articles views""" def test_if_user_cannot_like_article_without_authentication(self): """Test if user cannot like ar...
from __future__ import division import pandas as pd import scipy.io as sio import numpy as np from sklearn import metrics from sklearn.metrics import hamming_loss import torch import numpy as np import pandas as pd def Intersect_set(a, b): countL = 0 for i in range(len(a)): if a[i] == 1 and b[i] == 1: ...
from unittest import TestCase from unittest.mock import patch, MagicMock import sevenbridges from sbg_cwl_upgrader.validator.cwl_validation import CWLValidator import warnings import os import ruamel.yaml from sbg_cwl_upgrader.validator.sbg_validate_js_cwl_v1 import main class TestCWLValidatorLinting(TestCase): ...
""" defines the filesystem model """ import os import glob import types import shutil import autofile.file class DataFile(): """ file manager for a given datatype """ def __init__(self, name, writer_=(lambda _: _), reader_=(lambda _: _)): """ :param name: the file name :type name: str...
import re from factom_did.client.constants import DID_METHOD_NAME from factom_did.client.enums import KeyType, Network def validate_alias(alias): if not re.match("^[a-z0-9-]{1,32}$", alias): raise ValueError( "Alias must not be more than 32 characters long and must contain only lower-case " ...
# Brandon Kupczyk (10/31/16) from pushbullet import Pushbullet class PBAutoRespond: """ Thiis class is used to send actual messages to others using a prebuilt Pushbullet API https://pypi.python.org/pypi/pushbullet.py. """ VCard_file = None pb = None devices = None device = None co...
from .environment import Environment, ENVIRONMENT_VAR_NAME, ENVIRONMENT_NAME_DEFAULT, ENVIRONMENT_NAME_PRODUCTION from .config_manager import ConfigManager
from collections import defaultdict from operator import itemgetter import numpy as np from torch.utils.data import DataLoader from tools.trainer import ModelBase class ModelRCNN(ModelBase): def __init__(self, model, device, metric_iou_treshold=0.75): super().__init__(model, device) self.metric_...
# Copyright (c) 2020, Anders Lervik. # Distributed under the MIT License. See LICENSE for more info. """ PCA Loadings (2D) with xkcd style and centered axes =================================================== This example will plot PCA loadings along two principal axes. Here we employ the `xkcd style <https://matplotl...