content
stringlengths
5
1.05M
import re def remove_escapes(msg) -> str: """ Returns a filtered string removing \r """ filtered = msg.replace(r'\r', '') return filtered def pretty_print(msg) -> str: """ Returns a fully cleaned message after filtering through a regex """ ansi_escape = re.compile(r'\x1B(...
import numpy as np import matplotlib.pyplot as plt from scipy import integrate import itertools, operator, random, math from scipy.sparse.linalg import spsolve_triangular from sklearn import linear_model import pandas as pd def random_sampling(data, porpotion): sampled_data = np.empty(data.shape) sampled_data[...
# django libs from django.http import FileResponse from django.core.serializers import serialize from django.utils import translation from django.utils.translation import gettext # deepeye setting & models & form from main.models import Project from .models import ClassificationModel, Dataset, Result, Weight ...
from rest_framework import generics, viewsets from django.http import HttpResponse import requests from .models import Game from .serializers import GameSerializer API_KEY = 'f88969b6f429963a6b586bd5966c7b80' # class ListGame(generics.ListAPIView): # queryset = Game.objects.all() # serializer_class = GameSeriali...
#This class is here to maintain the occurrance of of two words together and marks this as phrase class chains: def __init__(self, text): self.library = {} self.text = text def addChain(self,index, wordLevel = 3): compound = "" for i in range(wordLevel): if ((i+index) <= len(self.text)-1): compound +=...
#!/usr/bin/env python # -*- coding: utf-8 -*- """abloop.py: Skeleton operations of the abductive loop.""" __author__ = "Brian J. Goode" import pandas as pd import numpy as np from scipy.stats import chi2 from sklearn.metrics import mutual_info_score import seaborn as sns from matplotlib import pyplot as plt c...
# -*- coding: utf-8 -*- """ Created on Fri Jul 6 23:20:56 2018 @author: Gaurav """ import numpy as np import numba as nb import matplotlib.pyplot as plt import matplotlib.cm as cm import os ############################CLASS SPACE######################################## class Boundary: def __init__(...
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
''' This module provides a clingo.Theory class for a LPX theory. ''' from clingo.theory import Theory from ._clingolpx import lib as _lib, ffi as _ffi __all__ = ['ClingoLPXTheory'] class ClingoLPXTheory(Theory): ''' The DL theory. ''' def __init__(self): super().__init__("clingolpx", _lib, _f...
from distutils.core import setup, Extension import glob cppstring = Extension( 'cppstring', define_macros=[], include_dirs=['include', '/usr/local/include'], libraries=[], library_dirs=['/usr/local/lib'], sources=glob.glob('src/*.cpp'), extra_compile_args=['-MMD', '-MP', '-g', '-std=c++11']...
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json from alipay.aop.api.constant.ParamConstants import * class AlipaySocialGiftOrderRefundModel(object): def __init__(self): self._mid = None self._order_id = None self._refund_price = None self._refund_type = No...
import torch import torch.nn as nn import torch.nn.functional as F from .base_net import BaseNet from .pointseg_modules import Fire, FireDeconv, SELayer, ASPP class PSEncoder(BaseNet): def __init__(self, input_shape, cfg, bn_d = 0.1): super(PSEncoder, self).__init__() bn_d = bn_d self.byp...
import pandas as pd import itertools ############################ # Display ############################ def pd_print_all(df): with pd.option_context('display.max_rows', None, 'display.max_columns', None): # more options can be specified also print(df) ############################ # Search ###########...
import os from flask import request, redirect, Flask, send_file from pathlib import Path app = Flask(__name__) root = Path.cwd() / "__files__" root.mkdir(exist_ok=True) css = """ form { display: flex; flex-direction: column; gap: 1rem; width: max-content; } """ @app.route("/upload/<path:name>", meth...
import numpy from src.dcf import (combine_cash_flow_simulations, compute_dcf, get_random_numbers, simulate_cash_flow_values, simulate_dcf) def test_compute_dcf(): cash_flow_values = [1000000, 1000000, 4000000, 4000000, 6000000] discount_rate = .05 expected = 1330...
#!/usr/bin/python # (c) 2020, NetApp, Inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = """ --- module: na_santricity_discover short_description: NetApp E-Series discov...
# 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__ = [ 'PrivateEndpointServiceConnectionStatus', 'PublicNetworkAccessType', ] class PrivateEndpointServiceConnect...
import pytest import numpy as np import random import cv2 from proyecto2.io import IO from proyecto2.image import Image class TestIO: TEST1 = [[[124, 177, 144, 255], [ 54, 104, 72, 255], [151, 192, 165, 255], [200, 236, 214, 255], [103, 129, 116, 255]], [[ 96, 133, 99, 255], [ 7, 37, 12, 255], [113, 1...
""" Copyright © - 2020 - UMONS CONQUESTO of University of Mons - Jonathan Joertz, Dorian Labeeuw, and Gaëtan Staquet - is free software : you can redistribute it and/or modify it under the terms of the BSD-3 Clause license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; wi...
###################################### # Import and initialize the librarys # ###################################### from code.pygame_objects import * ################# # Setup logging # ################# filename = os.path.basename(__file__).split('.')[0] logger = log.get_logger(filename) logger.info('Loading up {}....
from .wrapper import Querier __all__ = [Querier]
import board import busio import time import math import adafruit_hcsr04 sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.D11, echo_pin=board.D10) from sphero_rvr import RVRDrive rvr = RVRDrive(uart = busio.UART(board.TX, board.RX, baudrate=115200)) ***************************************************************...
import json import unittest import pyyoutube.models as models class ChannelSectionModelTest(unittest.TestCase): BASE_PATH = "testdata/modeldata/channel_sections/" with open(BASE_PATH + "channel_section_info.json", "rb") as f: CHANNEL_SECTION_INFO = json.loads(f.read().decode("utf-8")) with open(...
import importlib from ptoken.cache.backend import Backend class Frontend: """ Frontend of cache """ __backend_ = None # type: Backend def __init__(self, backend, **backend_kwargs): """ :param backend: type: string """ module = importlib.import_mo...
# Copyright 2018-2021 Faculty Science Limited # # 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...
import cupy from cupy import core def flip(a, axis): """Reverse the order of elements in an array along the given axis. Note that ``flip`` function has been introduced since NumPy v1.12. The contents of this document is the same as the original one. Args: a (~cupy.ndarray): Input array. ...
""" Contains application configuration for django """ from django.apps import AppConfig class PermissionsConfig(AppConfig): """Configuration of the application""" name = 'permissions'
"""fifth migration Revision ID: 7edeef2ab637 Revises: 5595ad14bcf5 Create Date: 2020-05-13 05:14:43.748249 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '7edeef2ab637' down_revision = '5595ad14bcf5' branch_labels = None depends_on = None def upgrade(): ...
#!/usr/bin/python3 # -*-coding:utf-8-*- from urllib.parse import urlencode param = {"birthday":"生日快乐", "mingxing":"huangbo"} result = urlencode(param) print(result)
from __future__ import absolute_import from django.conf.urls import url from talks.contributors.views import (contributors_home, contributors_events, contributors_eventgroups, contributors_persons) urlpatterns = [ url(r'^$', contributors_home, name='contributors-home'), u...
""" Clean up Ravel and Mininet. """ import os import mininet.clean from ravel.log import logger def clean(): "Try to kill Pox controller and clean Mininet" logger.info("killing Pox controller instance") os.system("pkill -9 -f pox.py") logger.info("cleaning Mininet") mininet.clean.cleanup()
import data import math import random import time import torch import torch.nn as nn from datetime import timedelta from evaluate import compute_many2one_acc, compute_v_measure class Control(nn.Module): def __init__(self, model, model_path, batch_size, device, logger): super(Control, self).__init__() ...
import pytest import os import shutil from gtmcore.dataset import Manifest from lmsrvlabbook.tests.fixtures import fixture_single_dataset from gtmcore.fixtures.datasets import helper_append_file class TestDatasetOverviewQueries(object): def test_num_files(self, fixture_single_dataset): """Test getting t...
"""Training a face recognizer with TensorFlow based on the FaceNet paper FaceNet: A Unified Embedding for Face Recognition and Clustering: http://arxiv.org/abs/1503.03832 """ # MIT License # # Copyright (c) 2016 David Sandberg # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this ...
# Global configuration information used across all the # translations of documentation. # # Import the base theme configuration from cakephpsphinx.config.all import * # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout t...
# -*- coding: utf-8 -*- """Tests for schools.views.""" import unittest import django.test from schools import models from schools import views import users.models class ViewsTestCase(django.test.TestCase): def setUp(self): self.request_factory = django.test.RequestFactory() self.student = users...
#!/usr/bin/python #medallion,hack_license,vendor_id,rate_code,store_and_fwd_flag,pickup_datetime,dropoff_datetime,passenger_count,trip_time_in_secs #89D227B655E5C82AECF13C3F540D4CF4,BA96DE419E711691B9445D6A...
from collections import OrderedDict from cnamedtuple._namedtuple import namedtuple, _register_asdict __all__ = [ 'namedtuple' ] __version__ = '0.1.6' # Register `OrderedDict` as the constructor to use when calling `_asdict`. # This step exists because at one point there was work being done to move # this projec...
from sqlalchemy import * from sqlalchemy.orm import * from migrate import * import sys, logging log = logging.getLogger( __name__ ) log.setLevel(logging.DEBUG) handler = logging.StreamHandler( sys.stdout ) format = "%(name)s %(levelname)s %(asctime)s %(message)s" formatter = logging.Formatter( format ) handler.setForm...
import sys, os, cv2, time, heapq, argparse from PIL import Image, ImageFont, ImageDraw from vidgear.gears import NetGear import numpy as np, math try: from armv7l.openvino.inference_engine import IENetwork, IEPlugin except: from openvino.inference_engine import IENetwork, IEPlugin import multiprocessing as mp f...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return a ListNode def deleteDuplicates(self, head): if head == None: return None temp = [] while head !=...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ------------------------------------------------- @ Author : pengj @ date : 2018/11/23 12:02 @ IDE : PyCharm @ GitHub : https://github.com/JackyPJB @ Contact : pengjianbiao@hotmail.com ---------------...
from tensorflow.keras.layers import (Conv2D, Dense, Flatten, MaxPooling2D, TimeDistributed) def VGG16(inputs): x = Conv2D(64,(3,3),activation = 'relu',padding = 'same',name = 'block1_conv1')(inputs) x = Conv2D(64,(3,3),activation = 'relu',padding = 'same', name = 'bl...
## ## Author Michel F. Sanner Jan 2009 ## import types, weakref from Scenario2.actions import Actions from Scenario2.keyframes import KF, Interval from Scenario2.datatypes import DataType from Scenario2.interpolators import Interpolator, BehaviorList class Actor: """ An Actor is an object that will modify an ...
numbers = [int(n) for n in input().split(', ')] number_beggars = int(input()) result = [] for beggar in range(number_beggars): beggar_result = 0 for index in range(beggar, len(numbers), number_beggars): if index < len(numbers): beggar_result += numbers[index] result.append(...
""" Copyright 2017 Steven Diamond 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 wr...
from memesv4 import do_experiment import argparse parser = argparse.ArgumentParser(description='') parser.add_argument("seed") args = parser.parse_args() seed = int(args.seed) params = { "sigma": 4, "RES": 32, "mutation": 0.0, "select": False, "uniform_init": True, "output_dir": "no_sel_no_m...
import torch import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import numpy as np import random import copy from utils import OUNoise # random seed np.random.seed(1) class Actor_TD3(nn.Module): def __init__(self, state_dim, action_dim, max_action): super(Actor_TD3, self)._...
# Copyright 2019 DeepMind Technologies Limited. 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 ...
from datetime import datetime import handle_json.handle_weather_json import nonebot import pytz from aiocqhttp.exceptions import Error as CQHttpError city = '绵阳' msg = handle_json.handle_weather_json.get_weather_dict(city) @nonebot.scheduler.scheduled_job('cron',day='*', hour='7', minute='20') async def _(): bot...
from gundala import EPP, Contact from config import config, contacts, nameserver data = { 'id': '7654323', 'name': 'Admin 3', 'org': 'Biznetgio', 'street': 'Jl. Sudirman', 'city': 'Jakarta Pusat', 'sp': '', 'pc': '', 'cc': 'ID', 'voice': '', 'fax': '', 'email': 'admin@biznet...
""" Script to export matplotlib plots from training to tikz """ from hierarchical_policy.decision_maker.ppo_decision_maker import PPO from hierarchical_policy.updraft_exploiter import model_updraft_exploiter from policy_evaluation import run_episode from hierarchical_policy.vertex_tracker.waypoint_controller import Co...
# -*- coding: utf-8 -*- """ jinja2.exceptions ~~~~~~~~~~~~~~~~~ Jinja exceptions. :copyright: (c) 2009 by the Jinja Team. :license: BSD, see LICENSE for more details. """ class TemplateError(Exception): """Baseclass for all template errors.""" def __init__(self, message=None): i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (c) Camille Scott, 2019 # File : server.py # License: MIT # Author : Camille Scott <camille.scott.w@gmail.com> # Date : 05.09.2019 '''The core sensor server. This handles sensor reporting and timing and makes the collected data available over UNIX socket and WebSock...
# ------------------------------------------------------------------ # Copyright (c) 2020 PyInstaller Development Team. # # This file is distributed under the terms of the GNU General Public # License (version 2.0 or later). # # The full license is available in LICENSE.GPL.txt, distributed with # this software. # # SPD...
# Copyright 2018 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 or agreed to in writing,...
#!/usr/bin/env python2 # Copyright (c) 2014-2015 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # Base class for RPC testing # Add python-bitcoinrpc to module search path: import os import sys import...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'menderLoginGUI.ui' # # Created by: PyQt5 UI code generator 5.10.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): M...
import matplotlib #matplotlib.use("Agg") from mirnylib.plotting import nicePlot import os import pickle from openmmlib import contactmaps from mirnylib.numutils import zoomArray from openmmlib import polymerutils import matplotlib.pyplot as plt import numpy as np from mirnylib.h5dict import h5dict from mirnylib.genom...
from django.apps import AppConfig class SignaldataConfig(AppConfig): name = 'signalData'
# coding: utf-8 """ Justap API 欢迎阅读 Justap Api 文档 Justap 是为移动端应用和PC端应用打造的下一代聚合支付SAAS服务平台,通过一个 SDK 即可快速的支持各种形式的应用,并且一次接口完成多个不同支付渠道的接入。平台除了支持服务商子商户模式,同时还对商家自有商户(即自己前往微信、支付宝等机构开户)提供了完整的支持。 感谢您的支持,我们将不断探索,为您提供更优质的服务!如需技术支持可前往商户中心提交工单,支持工程师会尽快与您取得联系! # 文档说明 采用 REST 风格设计。所有接口请求地址都是可预期的以及面向资源的。使用规范的 HTTP 响应代码来表示请...
# -*- coding: utf-8 -*- # @Brief: iou相关 import tensorflow as tf import math def box_iou(b1, b2): """ 计算iou :param b1: :param b2: :return: """ # 13,13,3,1,4 # 计算左上角的坐标和右下角的坐标 b1 = tf.expand_dims(b1, -2) b1_xy = b1[..., :2] b1_wh = b1[..., 2:4] b1_wh_half = b1_wh/2. ...
import numpy as np import matplotlib.pyplot as pp from mpl_toolkits.mplot3d import Axes3D from fenics import Mesh from static import run_static from visualisation import * from axes_world import one_by_one # ============================================================================= # Mesh #name = 'strai...
# -*- coding: utf-8 -*- from __future__ import print_function # (at top of module) import sys, requests import uuid from props.localtest_mapper import * import lib.obp # test payment workflow # prerequisites: # 1 run OBP-API and run OBP-Kafka_Python # 2 in props # connector=mapped # 3 prepare your own accounts...
X = int(input()) f = False i = 0 while i < 3000: if f: break j = i-1 while X > (i**5-j**5): if X == (i**5-j**5): print(i, j) f = True break j -= 1 i += 1
import json from dojo.models import Finding class GitlabDepScanParser(object): def get_scan_types(self): return ["GitLab Dependency Scanning Report"] def get_label_for_scan_types(self, scan_type): return scan_type # no custom label for now def get_description_for_scan_types(self, scan...
import logging from yapsy.IPlugin import IPlugin from modules.common.Downloads import Downloads logger = logging.getLogger(__name__) """ """ class GO(IPlugin): def __init__(self): self._logger = logging.getLogger(__name__) def process(self, conf, output, cmd_conf): self._logger.info("GO step"...
# -*- coding: utf-8 -*- import redis import re ''' Usage: moon.py -u redis http://127.0.0.1:6379 redis未授权访问漏洞 ''' def attack(URL): print('[+]开始检测-Redis未授权访问漏洞。[+]') #print(re.findall('//(.*?):',URL)[0])#获取IP #print(re.findall(':(\w*?)$',URL)[0])#获取端口 try: r = redis.StrictRedis(host=re...
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI Limited # # 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 ...
from abc import * from pandas import DataFrame from Common.Measures.Time.TimeSpan import TimeSpan class AbstractPlotter(ABC): _data_frame: DataFrame _src: str _col: str _legend_place: str _ticker: str _time_span: TimeSpan
#!/usr/bin/python from sys import argv, stdout from os.path import basename from struct import pack, unpack def clamp( x, low, high ): if x < low: x = low if x > high: x = high return x class BitStream: def __init__( self ): self.bits=[] def add_int( self, x, bits ): for n in range( bits ): bit = ( x ...
import re mapping_units = { "0":"", "zero":"zero", "1":"um", "2":"dois", "3":"três", "4":"quatro", "5":"cinco", "6":"seis", "7":"sete", "8":"oito", "9":"nove" } mapping_dozens = { "0":"", "10":"dez", "11":"onze", "12":"doze", "13":"treze", "14":"cato...
import os from iconsdk.builder.transaction_builder import DeployTransactionBuilder from iconsdk.builder.call_builder import CallBuilder from iconsdk.icon_service import IconService from iconsdk.libs.in_memory_zip import gen_deploy_data_content from iconsdk.providers.http_provider import HTTPProvider from iconsd...
# Copyright (C) 2010 Google Inc. 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 f...
import torch import torch.nn as nn import torch.nn.functional as F from loss.Dist import Dist class GCPLoss(nn.CrossEntropyLoss): def __init__(self, **options): super(GCPLoss, self).__init__() self.weight_pl = options['weight_pl'] self.temp = options['temp'] self.Dist = Dist(num_cla...
import jwt from fastapi import Security from fastapi.exceptions import HTTPException from fastapi.security.api_key import APIKeyHeader from starlette.status import HTTP_401_UNAUTHORIZED from settings import config api_key_header = APIKeyHeader( scheme_name=config.API_KEY_SCHEME, name=config.API_KEY_NAME, ...
import unittest from numpy.testing import assert_array_equal import numpy as np import torchvision.transforms as transforms import torchvision.datasets as datasets from imbalanceddl.dataset.imbalance_svhn import IMBALANCESVHN class TestCIFAR10(unittest.TestCase): def test_svhn10_exp100(self): train_data...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys, re, json from xml.etree import ElementTree as ET import common as beerlib curl_ua = 'curl/7.54.1' # first we need the post ID html = beerlib.download_html('https://m.facebook.com/page_content_list_view/more/?page_id=1871132519814729&start_cursor=10000&num_to...
import numpy as np from pqdict import pqdict def mins(df): ''' Function for exploring a bidimensional PES in order to find minima in the surface. ''' lims = list(df.shape) #shape is a tuple containing the (y,x) shape mins = dict() for x in range(lims[0]): for y in range(lims[1]):...
#!/usr/bin/python # ex:set fileencoding=utf-8: from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from djangobmf.categories import SALES from djangobmf.currencies import BaseCurrenc...
import os import pandas as pd from typing import Any, List, Dict def extract_data_from(root: str, system: str) -> pd.DataFrame: tests: List[Dict[str, Any]] = list() path: str = os.path.join(root, system) files: List[str] = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))] for f in...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # ************* 1 ********** EtabsAPI illustration: 0.0.1 Autor: Francisco J.Mucho Date: 25/03/21 Time: satrt 10:10am finish 12:00pm # ************* 1 ********** """ from collections import OrderedDict import os, sys # import EtabsAPIFile from coreapi.EA...
"""Test suite of unit tests for simple PyBind module""" import unittest import numpy as np # import module created using PyBind import utils class UtilsTest(unittest.TestCase): """Test utility functions""" def setUp(self) -> None: """Provide some local variables for each test""" self.i3 = 3 ...
from modules.Load import * from modules.SpikeTracker import * from modules.Plotter import * # test via manual selection of data source ( explicit run of this file alone ) if __name__ == "__main__": run = LoadMultiRun() ad_accel = run["accel"] ad_omega = run["omega"] # for automated testing via t...
# -*- coding: utf-8 -*- ''' List Functions Created on Sun Jul 07 14:23:47 2013 @author: Will Rhodes ''' import math,operator from collections import OrderedDict import itertools def convertAllToFloat(lst): ''' utility method that can convert all in list to float without throwing exceptions ''' fltLst ...
from importlib import reload #python3 only import markhov import numpy as np import random a="a" aaa = ['a','a a','a a a'] ops = {'S':{'NotCL':['mg']}, # from start we have to merge 'NotCL':{'NotCL':['mg','copy'], # this state is the state in which the last "special" operation was *not* Clear. Either we've...
import django from . import views from django.conf.urls import url from django.contrib.auth import views as auth_views urlpatterns = [ # post views # url(r'^login/$', views.user_login, name='login'), # login / logout urls url(r'^login/$', django.contrib.auth.views.login, name='login'), url(r'^logo...
# Blueprints provide a nice API for encapsulating a group of related routes # and templates. When an application has distinct components, blueprints # can be used to separate the various moving parts. from flask import Blueprint from helpers import object_list from models import Entry, Tag entries = Blueprint('entri...
import json import typing import factory from flask import Flask, url_for from flask.testing import FlaskClient from app.extensions import get_session from auth.models import User from .helpers import LoggedInState, random_password class UserFactory(factory.alchemy.SQLAlchemyModelFactory): first_name = factory...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def assign_creator(apps, schema_editor): Quest = apps.get_model("coordination", "Quest") for quest in Quest.objects.all(): quest.creator = quest.organizer quest.save() def move_organizer_and_pla...
from sqlalchemy import MetaData, Table, Column, Integer, NVARCHAR, BOOLEAN meta = MetaData() t = Table( "task_status_type", meta, Column("id", Integer, primary_key=True), Column("name", NVARCHAR(255)), Column("is_complete", BOOLEAN), Column("is_active", BOOLEAN), ) def upgrade(migrate_engin...
import numpy as np import matplotlib import matplotlib.pyplot as plt from scipy.stats import gaussian_kde #Set up plot style font = {'size' : 12} matplotlib.rc('font', **font) matplotlib.rc('font', serif='Computer Modern Roman') #Define colours martaRed = "#c24c51" martaGreen = "#54a666" martaBlue = "#4c70b0" ...
import os import itertools as it import numpy as np import conv_cart_internal_geoms as trimerGeom def getE0DataObjFromCalcObjs(calcObjList, geomRepStr): allDeltaE0 = list() allGeoms = list() for x in calcObjList: allDeltaE0.append( x.e0Diff ) for x in calcObjList: allGeoms.append( x.trimerGeom ) return ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2019/5/8 @Author : AnNing """ from __future__ import print_function import os import numpy as np import sys from hdf5 import write_hdf5_and_compress from initialize import load_yaml_file from load import LoadH8Ndvi def main(yaml_file): """ :param...
from PySide2.QtWidgets import QApplication, QWidget, QSplitter, QTextEdit, QVBoxLayout, QToolButton from PySide2.QtCore import Qt class CustomSplitter(QWidget): def __init__(self): QWidget.__init__(self) self.splitter = QSplitter(self) self.splitter.addWidget(QTextEdit(self)) self.s...
#!/usr/bin/env python # encoding: utf-8 from __future__ import unicode_literals import json import re import datetime # Regex pattern definitions from jrnl.util import date2string, datetime2string DATE_PATTERN = r'\d\d\d\d\-\d\d\-\d\d' # YEAR-MONTH-DAY e.g. 1984-01-24 STATUS_REGEX_DICT = { r'\[ \]': 'incomple...
__author__ = 'royrusso' import jmespath class TestNodes_v2: def test_get_node_stats(self, fixture): response = fixture.app.get('/api/nodes/%s/_stats' % fixture.cluster_v2_name) assert 200 == response.status_code res = fixture.get_response_data(response) assert fixture.has_all_k...
############################################################################### # Copyright 2012-2014 The University of Texas at Austin # # # # Licensed under the Apache License, Version 2.0 (the "License"); #...
from random import randint class Task(object): def __init__(self, env, start): self.env = env self.env.new_game() self.start = self.env.load_state('./rl/game_state_ckpts/{}.npy'.format(start)) def finished(): pass def reached_pos(self, x_, y_): x, y = self.env.agent_pos() return (x_ - 5...
# @lc app=leetcode id=322 lang=python3 # # [322] Coin Change # # https://leetcode.com/problems/coin-change/description/ # # algorithms # Medium (38.38%) # Likes: 7686 # Dislikes: 210 # Total Accepted: 699.3K # Total Submissions: 1.8M # Testcase Example: '[1,2,5]\n11' # # You are given an integer array coins repr...