content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- """ /dms/pool/views_show.py .. zeigt den Inhalt eines Materialpools an Django content Management System Hans Rauch hans.rauch@gmx.net Die Programme des dms-Systems koennen frei genutzt und den spezifischen Beduerfnissen entsprechend angepasst werden. 0.01 28.03.2007 Beginn der Arb...
from django.apps import AppConfig class InfraConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'infra'
import sys import unicodedata if len(sys.argv) < 2: print("USAGE: python3 emojify.py CHARACTER") print("Will output Markdown to render that character as an image.") sys.exit(1) if str is bytes: char = sys.argv[1].decode("UTF-8")[0] # Py2 else: char = sys.argv[1][0] # Py3 try: print("U+%X %s" % (ord(char), unicoded...
from .base import Unit from .prefix import ( Yotta, Zetta, Exa, Peta, Tera, Giga, Mega, Kilo, Hecto, Deca, Base, Centi, Mili, Micro, Nano, Pico, Femto, Atto, Zepto, Yocto ) class Metre( Unit ): name = 'metre' symbol = 'm' valid_prefix = ( Yotta, Zetta, Exa, Peta, Tera, Giga, Mega, Kilo...
from __future__ import print_function, division, absolute_import import sys import pytest from distributed.protocol import (loads, dumps, msgpack, maybe_compress, to_serialize) from distributed.protocol.serialize import Serialize, Serialized, deserialize from distributed.utils_test import slow def test_pro...
import pytest import os from .. import Relic from ..metadata import Metadata from ..storage import FileStorage from unittest.mock import patch import datetime as dt import numpy as np raw_config = """ { "s3": { "storage": { "type": "S3", "args": { ...
import logging from rbtools.api.errors import APIError from rbtools.clients.errors import InvalidRevisionSpecError from rbtools.commands import CommandError from rbtools.utils.match_score import Score from rbtools.utils.repository import get_repository_id from rbtools.utils.users import get_user def get_draft_or_cur...
#!/usr/bin/python import numpy as np import flask from flask_restful import reqparse from flask import request, make_response, current_app from . import valueFromRequest, make_json_response from ..database_support import APIDB, database_cursor from .utils import selection_to_where api_histogram_2d = flask.Blueprint...
import jnius_config import os import inspect from itertools import chain import numpy as np global nd4j nd4j = None global INDArray INDArray = None global transforms transforms = None indexing = None DataBuffer = None system = None Integer = None Float = None Double = None nd4j_index = None serde = None native_ops_ho...
class Solution: # @return an integer def uniquePathsWithObstacles(self, obstacleGrid): y = len(obstacleGrid) x = len(obstacleGrid[0]) pathcount = [[0 for i in xrange(x)] for j in xrange(y)] obstacleFound = False for x_ in range(x): if (obstacleGrid[0][x_]): ...
# -*- coding: utf-8 -*- # ***************************************************************************** # NICOS, the Networked Instrument Control System of the MLZ # Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS) # # This program is free software; you can redistribute it and/or modify it under # the t...
# -------------- # Importing header files import numpy as np # Path of the file has been stored in variable called 'path' #New record new_record=[[50, 9, 4, 1, 0, 0, 40, 0]] #Code starts here data = np.genfromtxt(path,delimiter=",",skip_header=1) print(data) census = np.concatenate((data, new_record)) pr...
# -*- coding: utf-8 -*- """ Created on Sun Jun 28 18:05:37 2020 @author: Karan """ import numpy as np import matplotlib.pyplot as pyplot import pandas as pd dataset=pd.read_csv('train.csv') #Filling null values null=dataset.isnull().sum(axis=0) null2={} for i in range(len(list(null.index))): if list(null)[i]...
# mailstat.analyze # Analysis module for the email analysis project # # Author: Benjamin Bengfort <benjamin@bengfort.com> # Created: Sun Dec 29 23:45:58 2013 -0600 # # Copyright (C) 2013 Bengfort.com # For license information, see LICENSE.txt # # ID: __init__.py [] benjamin@bengfort.com $ """ Analysis module for th...
import numpy as np import os import xml.etree.ElementTree as ET import pickle import json import os from os.path import join, dirname def parse_voc_annotation(ann_dir, img_dir, cache_name, labels=[]): if os.path.exists(cache_name): with open(cache_name, 'rb') as handle: cache = pickle.load(hand...
""" This is the Django template system. How it works: The Lexer.tokenize() method converts a template string (i.e., a string containing markup with custom template tags) to tokens, which can be either plain text (TokenType.TEXT), variables (TokenType.VAR), or block statements (TokenType.BLOCK). The Parser() class ta...
""" AUTOR: Juanjo FECHA DE CREACIÓN: 17/01/2020 """
import datetime import numpy as np from typing import Union def snapshot_maker(param_dict, dir:str): # record <.pth> model infomation snapshot. with open(dir, 'w') as file: for key, value in param_dict.items(): file.write(key + ' : ' + str(value) + '\n') time_now = datetime.datetime...
import sys, os from os.path import abspath, join, isdir, isfile, exists, dirname import logging from .tree import AstProvider from .module import ModuleProvider, PackageResolver from .watcher import DummyMonitor from .calls import CallDB class Project(object): def __init__(self, root, config=None, monitor=None): ...
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. import datetime import os import random import argparse import sys import numpy as np import math from os import listdir fro...
from django.shortcuts import render from django.db import transaction, IntegrityError import pycountry from apiv1.tasks import fetch_mfi_client from haedrian.forms import NewUserForm, EmailUserForm from haedrian.models import Wallet, UserData def index(request): return render(request, 'index.html') @transactio...
# import osm2gmns as og # net = og.getNetFromOSMFile('map.osm', network_type=('railway', 'auto', 'bike', 'walk'), POIs=True, default_lanes=True,default_speed=True) # og.connectPOIWithNet(net) # og.generateNodeActivityInfo(net) # og.outputNetToCSV(net) import grid2demand_0525a as gd import os os.chdir('./Norfolk_VA') ...
""" Scaling tools =================== """ import numpy def linearscaling(x, new_min, new_max, old_min=None, old_max=None, axis=None): """ Linearly rescale input from its original range to a new range. :param scalar-or-array x: scalar or arrays of scalars in ``[old_min, old_max]`` of shape ``(n, *shape)`...
from Configs.app_config import app, db from flask import render_template, request, flash, redirect from Classes.Asset_Class import AssetsData from Classes.People_Class import People from Classes.Roles import Roles customer_name= AssetsData.query.filter_by(name='test').all() @app.route('/', methods=['GET', 'POST']) ...
from django.conf.urls import patterns, url from website import views from website import feeds urlpatterns = patterns('', url(r'^$', views.index, name='index'), url(r'rss/$', feeds.UltimasPublicacoes()), url(r'^index/$', views.index, name='index'), url(r'^empresa/(?P<slug>\S+)$', views.empresa,...
import argparse import numpy as np import wandb import torch import csv from torch import nn from typing import List, Tuple from typing_extensions import Literal from perceptual_advex.utilities import add_dataset_model_arguments, \ get_dataset_model from perceptual_advex.distances import LPIPSDistance, LinfDistan...
#!/usr/bin/env python # coding: utf8 from __future__ import division import logging import numpy as np logger = logging.getLogger(__name__) def basic_test(ndvi, ndsi, swir2, tirs1): """Fundamental test to identify Potential Cloud Pixels (PCPs) Equation 1 (Zhu and Woodcock, 2012) Note: all input array...
from trex.emu.api import * import argparse class Prof1(): def __init__(self): self.def_ns_plugs = None self.def_c_plugs = None def get_template_261_fields(self): return [ { "name": "clientIPv4Address", "type": 45004, ...
#!/usr/bin/env python import encoder import preamble import sys if len(sys.argv) != 3: print('Usage: main.py <shellcode file> <pointer to shellcode>') print("Pointer to shellcode should be an expression that is the address of the start of the shellcode in the victim's address space") print('Example: main....
from torchdistlog import logging import numpy as np import torch.distributed as dist import torch from torchdistlog import logging try: import faiss except ModuleNotFoundError: logging.warning("Faiss Package Not Found!") from ...launcher.misc.utils import distributed_gather_objects """ (Faiss) to multi ...
#!/usr/bin/env python3 from github import Github import json # token needed for authentication at github token = "the_very_secret_token" g = Github(token) repo = g.get_repo('cookiejar/cookietemple') def fetch_ct_pr_issue_stats(gh_item: str) -> None: """ Fetch number of closed and open pull requests to the co...
# -*- coding: utf-8 -*- # pylint: disable=C0111,C0301,R0904 import unittest import os import envitro class TestCore(unittest.TestCase): # test setter/getter def test_isset(self): os.environ['TEST_ISSET_TRUE'] = 'setvar' self.assertTrue(envitro.isset('TEST_ISSET_TRUE')) if 'TEST_ISSE...
from django import forms from .models import Employee class EmployeeModelForm(forms.ModelForm): class Meta: model = Employee fields = ['firstname', 'surname', 'birthdate', 'email'] widgets = { 'firstname': forms.TextInput(attrs={'class': 'form-control'}), 'surname':...
''' https://leetcode.com/problems/reverse-string/description/ input: "hello" output: "olleh" ''' def reverse_string(s): return s[::-1]
import unittest import numpy as np import numpy.testing as npt import pytest from sklearn.base import clone from divik.sampler._core import BaseSampler, ParallelSampler class DummySampler(BaseSampler): def __init__(self, whatever): self.whatever = whatever def get_sample(self, seed): return...
class Util: def __init__(self, _): def qrng() : """ return random 0 or 1 via hadarmard gate param: location_strings: string, node where the q.h is happening, 'Alice' by default """ q=_.PREP() _.H(q) number ...
"All view functions for contentstore, broken out into submodules" from .assets import * from .checklists import * from .component import * from .course import * # lint-amnesty, pylint: disable=redefined-builtin from .entrance_exam import * from .error import * from .export_git import * from .helpers import * from .im...
# This file is part of GridCal. # # GridCal is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # GridCal is distributed in the hope that...
from io import StringIO from pytest_mock import MockerFixture from scrapy_feedexporter_azure.storage import BlobStorageFeedStorage def test_saves_item(mocker: MockerFixture): blob_service = mocker.MagicMock() mocker.patch('scrapy_feedexporter_azure.storage.BlobServiceClient').return_value = blob_service ...
import os from telethon.tl.types import * from KilluaRobot.utils.pluginhelper import runcmd async def convert_to_image(event, borg): lmao = await event.get_reply_message() if not ( lmao.gif or lmao.audio or lmao.voice or lmao.video or lmao.video_note or lmao.p...
class ValueObject: pass
import numpy as np def get_dist_mr_to_stride(idx, stride, st_delta, stdir, maxidx): d = 0 if stdir == 'stay': return d elif stdir == 'left': d += st_delta if stride > idx: acts = maxidx - stride d += 2 * acts else: acts = (stride if stride >= idx else maxidx) - idx d += 2 * act...
"""Parse the output of writelog.sh into info about git commits. """ import argparse import json import sys SEP="@@@@@" def parse_diff(st): """Parse a commit diff from the given string. Args: st: diff string """ D_BEGIN = 1 D_FILES = 2 D_HEADER = 3 D_BODY = 4 state = D_BEGIN def add_diff(): putf = from...
#!/usr/bin/env python import logging import sys import os import signal import conf import core from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol.TBinaryProtocol import TBinaryProtocolAcceleratedFactory from thrift.server import TServer from rpc import RndNodeApi log...
import asyncio import irc import time TWITCH_RATE_LIMITS = { "ALL": [15, 30], "AUTH": [10, 10], "JOIN": [15, 10], } class Client(irc.Client): def __init__(self, endpoint: irc.Endpoint) -> None: super().__init__(endpoint) self._status = { "ALL": [TWITCH_RATE_...
import sublime, sublime_plugin class AngularjsToggleSettingsCommand(sublime_plugin.ApplicationCommand): """Enables/Disables settings""" def run(self, setting): s = sublime.load_settings('AngularJS-sublime-package.sublime-settings') s.set(setting, not s.get(setting, False)) sublime.sa...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # normspace.py # shelly # """ Normalise spaces from the lines on stdin, stripping outer spaces and converting all sequences of spaces or tabs into single spaces. """ import sys import optparse import re def normspace(istream=sys.stdin, ostream=sys.stdout): for l...
from focusnfe.core.base import BaseAPIWrapper class NFe(BaseAPIWrapper): pass
import discord import command_template class Disable(command_template.Command): def __init__(self, handler): super(Disable, self).__init__(handler) self.enabled = True # Should never change self.perm_level = self.permission_levels["owner"] self.cmd_name = "disable" self....
"""Dedup related entities Revision ID: 0361dbb4d96f Revises: a5d97318b751 Create Date: 2016-12-18 22:00:05.397609 """ # revision identifiers, used by Alembic. revision = '0361dbb4d96f' down_revision = 'a5d97318b751' from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by...
""" 680 valid palindrome 2 easy Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. """ class Solution: def validPalindrome(self, s: str) -> bool: def check_removed(m, n): return all([s[k] == s[m+n-k] for k in range(m, n)]) ...
import pytest from fixtures import get_keys, get_children, get_title from craigslist_meta import Country selector = "country" key = "germany" def test_keys(get_keys): """Test `keys` method for country returns valid keys for instantiation.""" country_keys = Country.keys expected_keys = sorted(list(set(get...
# 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 # d...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the masterfile package: https://github.com/uwmadison-chm/masterfile # Copyright (c) 2020 Board of Regents of the University of Wisconsin System # Written by Nate Vack <njvack@wisc.edu> at the Center for Healthy Minds # at the University of Wisconsin-Madison. # Re...
# Copyright (c) 2014 Catalyst IT 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 in writ...
line=input() if 'A' in line or 'B' in line or 'C' in line or 'D' in line or 'E' in line or 'F' in line or 'G' in line or 'J' in line or 'K' in line or 'L' in line or 'M' in line or 'P' in line or 'R' in line or 'Q' in line or 'T' in line or 'U' in line or 'V' in line or 'W' in line or 'Y' in line: print('NO') el...
from sys import argv from argparse import ArgumentParser from csv import reader, writer from numpy import array from collections import deque import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from efficiency import migrations def create_parser(): """Parse com...
import requests, json, cv2, glob, os from playsound import playsound addr = 'http://localhost:5000' test_url = addr + '/audify' content_type = 'image/jpeg' headers = {'content-type': content_type} img = cv2.imread('../assets/book1.jpg') _, img_encoded = cv2.imencode('.jpg', img) response = requests.post(test_url, d...
from django.db import models # Create your models here. class Category(models.Model): title = models.CharField(max_length=50) slug = models.SlugField() class Meta: verbose_name_plural = "Categories" def __str__(self): return self.title class Post(models.Model): title = models.CharF...
#! /usr/bin/python ''' This part of the program is used to manipulate the local directory structure ''' __author__ = "xiaofeng" __date__ = "2019-12-8" import pickle import time from datetime import datetime from ServerLog import ServerLogger #导入服务器端日志库 import logging class OpeDir: def __init__(sel...
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() import notifications from django_project.urls import router urlpatterns = patterns('', url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),...
# Generated from rdsquery.g4 by ANTLR 4.9.2 from antlr4 import * from io import StringIO import sys if sys.version_info[1] > 5: from typing import TextIO else: from typing.io import TextIO def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\...
import random num = random.randrange(1000, 10000) n = int(input("Guess the 4 digit number:")) if (n == num): print("Great! You guessed the number in just 1 try! You're a Mastermind!") else: ctr = 0 while (n != num): ctr += 1 count = 0 n = str(n) num = str(num) correct = ['X']*4 for i in range(0, 4): ...
# -*- coding: utf-8 -*- """ File downloading functions. """ # Authors: Tan Tingyi <5636374@qq.com> import os import shutil import time from urllib import parse, request from urllib.error import HTTPError, URLError from tqdm.auto import tqdm from ._logging import logger from .misc import sizeof_fmt def _get_http(ur...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from ._markdown import \ markdown_autogen, \ markdown_code_block, \ markdown_comment, \ markdown_inline
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2019, WSO2 Inc. (http://wso2.org) All Rights Reserved. # # WSO2 Inc. licenses this file to you 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 ...
from django.apps import AppConfig class LaudosConfig(AppConfig): name = 'laudos'
import numpy as np import pandas as pd def weighted_random_choice(df, p, target_units): """ Proposal selection using weighted random choice. Parameters ---------- df : DataFrame Proposals to select from p : Series Weights for each proposal target_units: int Number ...
from abc import ABC from abc import abstractmethod from dataclasses import dataclass from dataclasses import field from enum import Enum from itertools import groupby from itertools import product from operator import itemgetter from typing import Any from typing import Iterable from typing import List from typing impo...
#!/usr/bin/env python3 ''' NowPlaying as run via python -m ''' #import faulthandler import logging import multiprocessing import os import pathlib import socket import sys from PySide2.QtCore import QCoreApplication, QStandardPaths, Qt # pylint: disable=no-name-in-module from PySide2.QtGui import QIcon # pylint: dis...
#the main aim of this program is to retrive all ASIN's of product import bs4,requests,re print('enter the url of product') prod_url = input() res=requests.get(prod_url) #print(res.text) try: res.raise_for_status() regexobj=re.compile(r'.*?data-asin=("\w\w\w\w\w\w\w\w\w\w").*?') asinlists=regexobj.findall(...
# lilypondpngvideogenerator -- processes lilypond file, scans postscript # file for page boundaries, analyzes tempo # track and generates MP4 video and # subtitle file # # author: Dr. Thomas Tensi, 2006 - 2017 #==================== ...
from lale.lib.sklearn import * from lale.lib.xgboost import * from lale.lib.lightgbm import * #from lale.lib.lale import KeepNumbers, KeepNonNumbers from lale.lib.lale import ConcatFeatures as Concat from lale.lib.lale import NoOp from lale.pretty_print import to_string from lale.lib.lale import Hyperopt from sklearn.d...
#From https://github.com/DerekGloudemans/video-write-utilities/blob/master/combine_frames.py import cv2 import numpy as np import time paths = [ "/media/worklab/data_HDD/cv_data/video/data - test pole 6 cameras july 22/Jul_22_2019_12-05-07/Axis_Camera_10/cam_0_capture_002.avi", "/media/worklab/data_HD...
# Copyright (c) 2020, Oracle and/or its affiliates. # # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ # # connecting from outside directly to server # connecting from outside via router # connecting from inside directly to server - same namespace # connectin...
#! python3 # -*- coding: utf-8 -*- import numpy as np lis = np.array([4, 6]) #L0 Norm print('norm 0') print(np.linalg.norm(lis, ord=0)) #L1 Norm #単純にベクトルの各要素の絶対値を足し合わせる。 #X=4, Y=6の場合、 4+6 となる print('norm 1') print(np.linalg.norm(lis, ord=1)) #L2 Norm #原点からベクトルを終点とした直線距離を求める。←の実際の長さを計算する。 print('norm 2') print(np.li...
"""Replace matched group https://stackoverflow.com/questions/6711567/how-to-use-python-regex-to-replace-using-captured-group/6711631 """ import re text = 'end, Wrong punctuation.' pattern = re.compile(r', ([A-Z])') text = pattern.sub(r'. \1', text) print(text) # end. Wrong punctuation. text = 'excellence, excelle...
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutStrings(Koan): def test_double_quoted_strings_are_strings(self): string = "Hello, world." self.assertEqual(True, isinstance(string, str)) def test_single_quoted_strings_are_also_strings(self): string =...
""" http://3dgep.com/?p=1356 http://3dgep.com/?p=1053 """ import os from collections import namedtuple import numpy from pyglet.gl import * from pyrr import vector from pyrr import quaternion from pyrr import matrix44 from pygly.shader import Shader, ShaderProgram from razorback.mesh import Mesh from razorback.md5....
# -*- coding: utf-8 -*- """ Exceptions module. """ from __future__ import unicode_literals class EventError(Exception): """Using to notify subscribed clients about event failure.""" pass
""" AIS playbox TV addon for kodi. This Kodi addon allows you to play the free TV channels provided by the AIS playbox device. """ import json import random import re import requests import sys import xbmcaddon import xbmcgui import xbmcplugin import zlib from base64 import b64encode from time import strftime from url...
# Workshop: Integrate the AWS Cloud with Responsive Xilinx Machine Learning at the Edge # Copyright (C) 2018 Amazon.com, Inc. and Xilinx 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 ...
import cv2 src = cv2.imread("../res/3.jpg", cv2.IMREAD_COLOR) dst = cv2.bitwise_not(src) cv2.imshow("src", src) cv2.imshow("dst", dst) cv2.waitKey(0) cv2.destroyAllWindows()
from __future__ import print_function import os.path, pickle, time, yaml from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request # If modifying these scopes, delete the file token.pickle. SCOPES = ["https://www.googleapis.com...
from django.shortcuts import render from .serializers import * from rest_framework.renderers import JSONRenderer from management.commands.updatecomponents import send_GET_request from django.http import JsonResponse, HttpResponseServerError from django.contrib.admin.views.decorators import staff_member_required from dj...
import urllib from behave import * from hamcrest import * from eats.pyhamcrest import array_equal_to_by_key, array_equal_to from eats.utils.sitemap import sitemap_parser, replace_env_url_to_prod, SiteMapGen, url_encode from eats.utils.robots import RobotFileEats from eats.utils.google_site_verification import GoogleSit...
"""Example/test script for (stress) testing multiple requests to the bridge.""" import argparse import asyncio import logging from os.path import abspath, dirname from sys import path import time path.insert(1, dirname(dirname(abspath(__file__)))) from aiohue import HueBridgeV2 parser = argparse.ArgumentParser(descr...
# Generated by Django 4.0.1 on 2022-01-07 23:11 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Livros', fields=[ ('id', models.BigAutoFiel...
def string_to_int(list_a): new_list = [] for item in list_a: num = int(item) new_list.append(num) return new_list num_list = input().split() num_list = string_to_int(num_list) maximum = max(num_list) num_set = set(num_list) first_n_num_set = set(range(1, maximum+1)) missing_num_set = first...
from workerpool import WorkerPool """ WARNING: This sample class is obsolete since version 0.9.2. It will be removed or replaced soon. """ class BlockingWorkerPool(WorkerPool): """ Similar to WorkerPool but a result queue is passed in along with each job and the method will block until the queue is fille...
import pytest from jsondaora.exceptions import DeserializationError from jsondaora.schema import IntegerField, StringField def test_should_validate_minimum_integer(): class Integer(IntegerField, minimum=10): ... with pytest.raises(DeserializationError) as exc_info: Integer(9) assert exc...
from django.apps import AppConfig from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ from sui_hei.signals import (add_twitter_on_puzzle_created, add_twitter_on_schedule_created) class SuiHeiConfig(AppConfig): name = 'sui_hei' ve...
from typing import Dict, List, Union import numpy as np def boolean_mask_by_value(mask: np.ndarray, value: int) -> np.ndarray: return boolean_mask_by_values(mask=mask, values=[value]) def boolean_mask_by_values(mask: np.ndarray, values: List[int]) -> np.ndarray: return np.isin(mask, values) def replace_v...
import unittest import numpy as np from random import choice from unittest import mock from aix360.algorithms.rbm import ( BooleanRuleCG, BRCGExplainer, GLRMExplainer, LinearRuleRegression, LogisticRuleRegression ) from pandas import DataFrame from depiction.core import DataType, Task from depiction.interpret...
from django.conf.urls import patterns, include, url from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), #url(r'^e/(?P<path>.*)$', 'django.views.static.serve', # { 'document_root': settings.STATIC_DO...
### TILE SHOWING THE RESULTS from sepal_ui import sepalwidgets as sw from sepal_ui import mapping as sm import ipyvuetify as v from component.message import ms from component.scripts import * from component import parameter as pm # create an empty result tile that will be filled with displayable plot, map, links, t...
import torch X = torch.tensor( [[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]], requires_grad=True ) K = torch.tensor([[0.0, 1.0], [2.0, 3.0]]) def corr2d(X, K): """Compute 2D cross-correlation.""" h, w = K.shape Y = torch.zeros((X.shape[0] - h + 1, X.shape[1] - w + 1)) for i in range(Y.shape...
from collections import deque class Solution: # # Deque (Accepted), O(n) time and space # def diStringMatch(self, s: str) -> List[int]: # queue = deque(range(len(s)+1)) # res = [] # for c in s: # if c == 'I': # res.append(queue.popleft()) # else:...
from typing import Optional, Any, Dict from fastapi import status from starlette.exceptions import HTTPException from conf.const import StatusCode from .schema import SchemaMixin class BaseHTTPException(HTTPException): MESSAGE = None STATUS_CODE = status.HTTP_400_BAD_REQUEST CODE = 40000 def __init...
# -*- coding: utf-8 -*- __author__ = 'yijingping' import time import urllib2 ip_check_url = 'http://api.ipify.org' user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0' socket_timeout = 3 # Get real public IP address def get_real_pip(): req = urllib2.Request(ip_check_url) re...