text
stringlengths
2
999k
# -*- coding: utf-8 -*- # # (c) Copyright 2003-2015 HP Development Company, L.P. # # This program 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 2 of the License, or # (at your option) any late...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from cfg import * from region_loss import RegionLoss from yolo_layer import YoloLayer #from layers.batchnorm.bn import BN2d class MaxPoolStride1(nn.Module): def __init__(self): super(MaxPoolStride1, self).__init__() ...
# -*- coding: utf-8 -*- from .factory import WsFactory from .resource import WsResource from bouser.helpers.plugin_helpers import BouserPlugin, Dependency __author__ = 'viruzzz-kun' class WsService(BouserPlugin): signal_name = 'bouser.ws' web = Dependency('bouser.web') cas = Dependency('bouser.castiel') ...
# coding: utf-8 # filename: loss_deform.py import torch import torch.nn as nn from torch.nn import SmoothL1Loss from dataloader.bw2deform import deform2bw_tensor_batch from dataloader.data_process import reprocess_t2t_auto from dataloader.bw_mapping import bw_mapping_tensor_batch from evaluater.eval_ssim import cal_te...
#!/usr/bin/env python3 import unittest import sys import random sys.path.append('../src') import config from config import ConfigParameter from config import ConfigDatabase from config import CommandLineArgumentsLoader from config import DefaultValueLoader from config import ConfigFileLoader from config import Confi...
import os import shutil import matplotlib.pyplot as plt import matplotlib import numpy as np import scipy.stats as stats import scipy.optimize as opt import pandas as pd import random import xlrd import seaborn as sns from pprint import pprint from pandas.core.frame import DataFrame import sys import i...
# -*- coding: utf-8 -*- # Copyright 2015 - 2016 OpenMarket Ltd # Copyright 2017 Vector Creations 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/LIC...
n, t = map(int, input().split()) a = [int(input()) for _ in [0] * n] s = 0 for i in range(n-1): if a[i+1] - a[i] < t: s += a[i+1] - a[i] else: s += t else: s += t print(s)
# Copyright (c) 2016. Mount Sinai School of Medicine # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
import pytest from instpector import endpoints @pytest.mark.incremental class TestApi: user_id = None story_id = None def test_profile(self, instance, username): profile = endpoints.factory.create("profile", instance) user = profile.of_user(username) assert type(user).__name__ == "T...
from .data import RawData class Sample(): """ Representation of a MS sample contain in an experiment. Contains, peak and feature lists, raw_data object to store raw file and connect to appropriate backend reader. """ # Sample counter to automatically assign sample ids sample_counter = 0 ...
''' 主程序 @author: PurePeace @time: 2020年2月10日 02:03:09 ''' import time, datetime, re, requests, random, json from bs4 import BeautifulSoup requests.adapters.DEFAULT_RETRIES = 999 # 增加重连次数 # get now timeString or timeStamp def getTime(needFormat=0, formatMS=True): if needFormat != 0: return datetime.date...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Author: Daniel J. Umpierrez import argparse from pprint import pprint from model import FlightCollector def load_airports_info(): cwd: Path = Path(__file__).resolve(True).parent data_file = cwd.joinpath('data', 'airports-code-min.csv') if data_file.is_file...
#!/usr/bin/env python # coding: utf8 """Export spaCy model vectors for use in TensorBoard's standalone embedding projector. https://github.com/tensorflow/embedding-projector-standalone Usage: python vectors_tensorboard_standalone.py ./myVectorModel ./output [name] This outputs two files that have to be cop...
# -*- coding: utf-8 -*- # # This class was auto-generated. # from onlinepayments.sdk.data_object import DataObject from onlinepayments.sdk.domain.mandate_redirect_data import MandateRedirectData class MandateMerchantAction(DataObject): """ | Object that contains the action, including the needed data, that you...
from django.apps import AppConfig class ControllerandsensorConfig(AppConfig): name = 'ControllerAndSensor'
''' A split, horizontal stacked bar chart using plain Python lists. .. bokeh-example-metadata:: :apis: bokeh.plotting.Figure.hbar_stack :refs: :ref:`userguide_categorical` > :ref:`userguide_categorical_bars` > :ref:`userguide_categorical_bars_stacked` :keywords: bars, categorical, stacked ''' from bokeh.m...
import numpy as np import os import cv2 import time from object_detection.utils import label_map_util from object_detection.utils import visualization_utils as vis_util from graphpipe import remote label_file='mscoco_label_map.pbtxt' category_index = label_map_util.create_category_index_from_labelmap(os.path.join('d...
""" @author: Sze "Ron" Chau @e-mail: chaus3@wit.edu @source: https://github.com/wodiesan/sweet-skoomabot @desc Night sensor-->RPi for Senior Design 1 """ import logging import os import RPi.GPIO as GPIO import serial import subprocess import sys import time import traceback # GPIO pins. Uses the BC...
from unicodedata import name from django.urls import path from . import views urlpatterns = [ path("", views.StartingPageView.as_view(), name="starting-page"), path("posts", views.AllPostsView.as_view(), name="posts-page"), path("posts/<slug:slug>", views.SinglePostView.as_view(), name="post-deta...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.contrib import admin from paypal.standard.ipn.models import PayPalIPN class PayPalIPNAdmin(admin.ModelAdmin): date_hierarchy = 'payment_date' fieldsets = ( (None, { "fields": [ "flag", "txn_id", "txn_type", "payment_...
"""Extract reference documentation from the NumPy source tree. """ from __future__ import absolute_import from __future__ import print_function import inspect import textwrap import re import pydoc from warnings import warn from sphinx.pycode import ModuleAnalyzer class Reader(object): """A line-based string re...
# Copyright (c) 2016 Tzutalin # Create by TzuTaLin <tzu.ta.lin@gmail.com> try: from PyQt5.QtGui import QImage except ImportError: from PyQt4.QtGui import QImage from base64 import b64encode, b64decode from libs.pascal_voc_io import PascalVocWriter from libs.yolo_io import YOLOWriter from libs.pascal_voc_io im...
from os.path import dirname, abspath, join as pjoin import tarfile from testpath import modified_env, assert_isfile from testpath.tempdir import TemporaryDirectory try: from unittest.mock import patch, call except ImportError: from mock import patch, call # Python 2 fallback import zipfile from pep517.envbuil...
# Execution time : 8.871481 seconds # Solution Explanation # Generate all the permutations of { 1, 2, ... , 9 } # And simplily add the ones that verify the conditions import time width = 40 from itertools import permutations def solution(): prime = [0,2,3,5,7,11,13,17] ans = 0 for v in permutations('01...
import os import re import sys import subprocess import paramiko import zipfile PLATFORMS = ['win32', 'x64'] CONFIGURATIONS = ['Release', 'netcdf_Release', 'MPI_Release', 'MPI_netcdf_Release'] class SSHClient: '''Dummy object to bypass paramiko''' def __init__(self, workdir): self.workdir = workdir...
# -*- coding: utf-8 -*- __author__ = "苦叶子" """ 公众号: 开源优测 Email: lymking@foxmail.com """ from flask import current_app, session from flask_restful import Resource, reqparse import json import os import codecs from utils.file import list_dir, mk_dirs, exists_path, rename_file, remove_dir, get_splitext class Proj...
import logging import numpy as np from smac.configspace import ConfigurationSpace from ConfigSpace.hyperparameters import IntegerHyperparameter, FloatHyperparameter, CategoricalHyperparameter, \ OrdinalHyperparameter from smac.facade.smac_facade import SMAC from smac.scenario.scenario import Scenario from d3m_ta2_n...
from distutils.dir_util import copy_tree import os import platform import subprocess import sys class DirUtils: @staticmethod def cp(source_dir, target_dir): """ Copy the contents of one directory to another Arguments: source_dir {str} -- Source directory to copy from ...
from django.urls import path from .views import classify, detect, segment app_name = "inference" urlpatterns = [ path('classify/', view=classify, name="classify"), path('detect/', view=detect, name="detect"), path('segment/', view=segment, name="segment"), ]
from datasets.load import load_dataset, load_metric from transformers import ( AutoTokenizer, DataCollatorWithPadding, EvalPrediction, default_data_collator, ) import numpy as np import logging from collections import defaultdict task_to_keys = { "boolq": ("question", "passage"), "cb": ("premis...
# To download TIF Files import os from requests.api import request from tqdm import tqdm import requests with open("Forest Loss APIs.txt") as f: urls = f.read().split() for url in tqdm(urls): r = requests.get(url) with open(os.path.join("..", "..", "data", "forest", url.split("/")[-1]), "wb") as fout: ...
# from ATRequests import requests from usim800_hamilkar.Sms import sms from usim800_hamilkar.Communicate import communicate from usim800_hamilkar.Request import request from usim800_hamilkar.Info import info import serial class sim800(communicate): TIMMEOUT = 1 def __init__(self, baudrate, path): sel...
"""Parse OpenGL feature definitions.""" from enum import Enum from typing import MutableMapping, Iterable import xml.etree.ElementTree as xml import attr from gladiator.mixins import StringToEnumMixin from gladiator.optional import OptionalValue class FeatureApi(StringToEnumMixin, Enum): """An OpenGL feature A...
import AppKit from PyObjCTools.TestSupport import TestCase class TestAppKitErrors(TestCase): def testConstants(self): self.assertEqual(AppKit.NSTextReadInapplicableDocumentTypeError, 65806) self.assertEqual(AppKit.NSTextWriteInapplicableDocumentTypeError, 66062) self.assertEqual(AppKit.NST...
""" This script prepares data in the format for the testing algorithms to run Author: Anton Yeshchenko """ from __future__ import division import copy import csv import re import time # from collections import Counter from datetime import datetime from itertools import izip import numpy as np import shared_variabl...
#### # CODE TAKEN FROM https://github.com/mgrankin/over9000 #### import torch, math from torch.optim.optimizer import Optimizer # RAdam + LARS class Ralamb(Optimizer): def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0): defaults = dict(lr=lr, betas=betas, eps=eps, weight_de...
# Copyright (c) 2021, Aakvatech and contributors # For license information, please see license.txt import frappe from frappe.model.document import Document class BackgroundDocumentPosting(Document): def on_submit(self): post_doc = frappe.get_doc(self.document_type, self.document_name) post_doc.queue_action(self....
from ..tree.expr import Binary, Assign, Dot from ..tree.expr import Unary, Self from ..tree.expr import Constant, This, Var from ..tree.expr import Access, Creator, FuncCall from ..fakecode import Const from ..fakecode.inst import Call, Malloc, Alloca, Branch, Jump from ..fakecode.inst import Arith, Logic, Load, Store...
import _plotly_utils.basevalidators class LayerValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="layer", parent_name="layout.smith.imaginaryaxis", **kwargs ): super(LayerValidator, self).__init__( plotly_name=plotly_name, pare...
import torch.utils.data as data import numpy as np from imageio import imread from path import Path import random import os def load_as_float(path): return imread(path).astype(np.float32) class PairFolder(data.Dataset): """A sequence data loader where the files are arranged in this way: root/scene_1...
#!/usr/bin/env python # Copyright (c) 2018 Sony Pictures Imageworks 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 req...
import sys import os import numpy as np import argparse import time import json from pathlib import Path import argparse import os import shutil import sys import numpy as np import torch import random random.seed(42) import torch.nn as nn import torch.optim as optim import torch.utils.data from torch.utils.data imp...
import os import pwd import sys def check_venv(filename): # type: (str) -> None try: import django import ujson import yakkl django ujson yakkl except ImportError: print("You need to run %s inside a Yakkl dev environment." % (filename,)) user_...
"""empty message Revision ID: 9d1918d542b5 Revises: 5b1f4c9d0d43 Create Date: 2021-11-03 20:18:06.598898 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '9d1918d542b5' down_revision = '5b1f4c9d0d43' branch_labels = None depends_on = None def upgrade(): op...
from app.workspace_management_api.sample_model import DataPoint, DataPointsPerSensor, SampleFromWorkspace, Timeframe from typing import List from app.workspace_management_api.data_source import ExternalDataSource from bson.objectid import ObjectId import random class WorkspaceDataSource(ExternalDataSource): @stat...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import traceback import signal from fairdiplomacy.utils.multiprocessing_spawn_context import get_multiprocessing_ctx mp = get_multiprocessin...
# vi: set shiftwidth=4 tabstop=4 expandtab: import datetime import math def get_grid_from_file(file_path="day10_input.txt"): with open(file_path) as f: return [l.strip() for l in f] def get_asteroids(grid): for i, line in enumerate(grid): for j, val in enumerate(line): if val == ...
from model.contact import Contact import random def test_modify_contact(app, db, check_ui): if len(db.get_contact_list()) == 0: app.contact.create(Contact(firstname="Dara", middlename="Test", lastname="Bozhenko", username="dbozhenko", title="TestContact", company="Compan...
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013, John McNamara, jmcnamara@cpan.org # import unittest import os from ...workbook import Workbook from ..helperfunctions import _compare_xlsx_files class TestCompareXLSXFiles(unittest.TestC...
# from pytest import capfd import pytest from bin.dna import DNA from bin.dna import NotDNAError def test_init(): dna = DNA('ACTGACTGACTA') assert all(c in "ACGT" for c in dna.seq), 'DNA sequence does not exists only of ACTG' assert len(dna.seq) % 3 ==0, 'DNA sequence is not a multiple of three' def ...
"""Database table models for the audiobook library.""" from datetime import date from decimal import Decimal from typing import TypeVar from sqlalchemy.ext.hybrid import hybrid_property from audiobooks.database import Model from audiobooks.extensions import db from .utils import clean_name LibraryModelType = TypeV...
from typing import Callable, Tuple import numpy as np from odyssey.distribution import Distribution from iliad.integrators.info import CoupledInfo from iliad.integrators.vectors import coupled_leapfrog from iliad.integrators.vectors.vector_fields import riemannian_vector_field, softabs_vector_field from iliad.integr...
# 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! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from...
''' >>> data = '{"username": "oscar", "password": "trashcan", "account": 1234, "amount": 12.03}' >>> deposit(data) 'OK' >>> data = '{"username": "oscar", "password": "trash", "account": 1234, "amount": 14.98}' >>> deposit(data) 'Invalid Password' >>> data = '{"username": "oscar", "password": "trashcan", "account": 1234...
#!/usr/bin/env python3 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "L...
# The MIT License # Copyright (c) 2021- Nordic Institute for Interoperability Solutions (NIIS) # Copyright (c) 2017-2020 Estonian Information System Authority (RIA) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # # py parlai/chat_service/tasks/overworld_demo/run.py --debug --verbose from parlai.core.worlds import World from parla...
from flask import Flask from flask_bootstrap import Bootstrap from config import config_options from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_uploads import UploadSet,configure_uploads,IMAGES from flask_mail import Mail from flask_simplemde import SimpleMDE simple = SimpleMDE(...
""" circonus.util ~~~~~~~~~~~~~ Utility functions that other modules depend upon. """ from calendar import timegm from posixpath import sep as pathsep from colour import Color def datetime_to_int(dt): """Convert date and time to seconds since the epoch. :param datetime.datetime dt: The date and time to...
#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. import sys from zope.interface import implementer from twisted.conch import avatar from twisted.conch.checkers import InMemorySSHKeyDB, SSHPublicKeyChecker from twisted.conch.ssh import connection, factory, keys, session, ...
#------------------------------------------------------------- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under...
""" Experimental manager based on storing a collection of 1D arrays """ from __future__ import annotations from typing import ( TYPE_CHECKING, Any, Callable, Hashable, TypeVar, ) import numpy as np from pandas._libs import ( NaT, lib, ) from pandas._typing import ( ArrayLike, Dtyp...
from django.db import models from django.contrib.auth.models import User class Machines(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,related_name="machine") instance_id = models.TextField() instance_name = models.TextField() def __str__(self): return f"{self.instance_name}"
from pynyzo.hashutil import HashUtil from pynyzo.messageobject import MessageObject from pynyzo.fieldbytesize import FieldByteSize import json import struct class Transaction(MessageObject): """Transaction message""" nyzos_in_system = 100000000 micronyzo_multiplier_ratio = 1000000 micronyzos_in_syst...
""" This document contains the tree widget used to display the editor document outline. """ from pyqode.core.widgets import OutlineTreeWidget class PyOutlineTreeWidget(OutlineTreeWidget): """ Deprecated, use pyqode.core.widgets.OutlineTreeWidget instead. """ pass
#!/usr/bin/python3 import itertools import os import subprocess import xml.dom.minidom import MySQLdb from tqdm import tqdm from config import database from gpxlen import getTrackLength db = MySQLdb.connect(database["host"], database["user"], database["passwd"], ...
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. '''Unit tests for grit.xtb_reader''' from __future__ import print_function import io import os import sys if __name__ == '__main_...
""" Demonstrates using OBJECTS via Turtle Graphics. Concepts include: -- CONSTRUCT an INSTANCE of a CLASS (we call such instances OBJECTS). -- Make an object ** DO ** something by using a METHOD. -- Reference an object's ** DATA ** by using an INSTANCE VARIABLE. Also: -- ASSIGNING a VALUE to a NAME (V...
import subprocess def get_hdd_info(hdd): r = subprocess.run(["hdparm", "-I", hdd], capture_output=True) output = r.stdout.decode().splitlines() model_index = [i for i, s in enumerate(output) if 'Model Number:' in s] serial_index = [i for i, s in enumerate(output) if 'Serial Number:' in s] try: ...
'''OpenGL extension SGIX.texture_multi_buffer Overview (from the spec) This extension provides an API for the application to specify that the OpenGL should handle multiple textures in such a way that, wherever possible, a texture definition or redefinition can occur in parallel with rendering that uses a differe...
def bar(data: dict, title: str = "Bar", x_legend: str = "", y_legend: str = ""): import plotly.graph_objects as go keys, values = zip(*data.items()) fig = go.Figure(data=go.Bar(y=values, x=keys)) fig.update_layout( title=title, xaxis_title=x_legend, yaxis_title=y_legend, ) ...
""" Models ====== `models.py` contains every relations regarding nekoyume blockchain and game moves. """ import datetime from hashlib import sha256 as h import os import re from bencode import bencode from flask_caching import Cache from flask_sqlalchemy import SQLAlchemy from keccak import sha3_256 import requests ...
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import re from textwrap import dedent from typing import Iterable, cast import pytest from pants.base.exceptions import ResolveError from pants.base.s...
import torch import cv2 import imageio import pickle import os from tqdm import tqdm from numpy.linalg import norm from Encoder_BH2MANO import Encoder_BH2MANO from gen_3d_pose_flow import * from manopth.manolayer import ManoLayer from opendr.renderer import ColoredRenderer from opendr.camera import ProjectPoints f...
# -*- coding: utf-8 -*- """ Created on Thu Feb 11 13:31:22 2021 @author: dv516 """ import numpy as np from scipy.integrate import solve_ivp import matplotlib.pyplot as plt def sys_model(t, x, u): """Function modelling the dynamic behaviour of the system in question with a control term u. Returns the sta...
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class DemoSpiderItem(scrapy.Item): title = scrapy.Field() summary = scrapy.Field() url = scrapy.Field() tags = scrapy.Field() catal...
# Aula de estrutura de repetição com variavel de controle for c in range(0, 6): print('oi') print('fim') for a in range(0, 10, 2): # o primeiro argumento e o segundo é o range de contagem, o terceiro é o metodo da contagem print(a) print('fim') # Outro exemplo for a in range(10, 0, -1): # Com uma condição d...
import testinfra def test_make_installed(host): cmd = host.run("make --version") assert cmd.rc == 0, "it is required for all the Beats projects" def test_python_installed(host): cmd = host.run("python --version") assert cmd.rc == 0, "it is required for the Beats" def test_tar_installed(host): cmd = host.ru...
import socket HOST = '' # Server IP Address PORT = 15000 # Server port tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp.bind((HOST, PORT)) tcp.listen(1) print ('\nConnection OK ') while True: connection, client = tcp.accept() print ('Connection made by', client) msg = ...
# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ''' Algorithms to compute confounds in :abbr:`fMRI (functional MRI)` ''' from __future__ import (print_function, division, unicode_literals, absolute_import) ...
import six import requests from django.conf import settings from django.core.mail.backends.base import BaseEmailBackend from django.core.mail.message import sanitize_address from django.utils.encoding import force_text from requests.packages.urllib3.filepost import encode_multipart_formdata __version__ = '0.8.0' ve...
# pylint: disable=too-many-lines # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -----------------------------------...
###################################################################### # Author: Dr. Scott Heggen TODO: Change this to your name # Username: heggens TODO: Change this to your username # # Assignment: A01 # # Purpose: A program that returns your Chinese Zodiac animal given a # birth year between 1988 an...
import sys import os import copy import json import datetime opt = dict() opt['dataset'] = '../data/pubmed' opt['hidden_dim'] = 16 opt['input_dropout'] = 0.5 opt['dropout'] = 0 opt['optimizer'] = 'adam' opt['lr'] = 0.01 opt['decay'] = 5e-4 opt['self_link_weight'] = 1.0 opt['pre_epoch'] = 200 opt['epoch'] = 100 opt['i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Utility functions ================= Functions that helps with formatting shape and converting between object types. """ import mpmath import numpy as np dB = lambda X : 20*np.log10(np.abs(X)) def args_to_str(**args): ''' Converts dictionary entries into s...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import hashlib import re import uuid class NameCreator: @staticmethod def get_valid_file_name(file_name: str): return re.sub(r"[\\/*?:\"<>|]", "_", file_name) @staticmethod def create_name_with_uuid(prefix: str, uuid_l...
from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'u...
# ################################ # From paper: "End-to-End Waveform Utterance Enhancement for Direct Evaluation # Metrics Optimization by Fully Convolutional Neural Networks", TASLP, 2018 # Authors: Szu-Wei, Fu 2020 # ################################ import torch import torchaudio import numpy as np from sp...
# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ''' Created on 20 Apr 2010 logging options : INFO, DEBUG hash_method : content, timestamp @author: Chris Filo Gorgolewski ''' from __future__ import (print_function, division, unic...
# Generated by Django 3.0.8 on 2020-07-12 07:36 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
# Ex073 tabela = ('Flamengo', 'Internacional', 'Atlético', 'São Paulo', 'Fluminense', 'Grêmio', 'Palmeiras', 'Santos', 'Atlético Paranaense', 'Red Bull Bragantino', 'Ceará', 'Conrinthians', 'Atlético GO', 'Bahia', 'Sport', 'Fortaleza', 'Vasco da Gama', 'Goias', 'Coritiba', 'Botafogo') cont = 0 while...
import logging import numpy as np import re from LoopStructural.utils import getLogger logger = getLogger(__name__) def strike_symbol(strike): R = np.zeros((2, 2)) R[0, 0] = np.cos(np.deg2rad(-strike)) R[0, 1] = -np.sin(np.deg2rad(-strike)) R[1, 0] = np.sin(np.deg2rad(-strike)) R[1, 1] = np.cos(n...
import flask_pytest
#!/usr/bin/env python # # Use the raw transactions API to spend Aikis received on particular addresses, # and send any change back to that same address. # # Example usage: # spendfrom.py # Lists available funds # spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00 # # Assumes it will talk to a aikid or aiki-Qt r...
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import import logging import os import shutil from six.moves import input # pylint: disable=redefined-builtin from telemetry...
class Parent(): def override(self): print('PARENT override()') def implicit(self): print('PARENT implicit()') def altered(self): print('PARENT altered()') class Child(Parent): def override(self): print('CHILD override()') def altered(self): print('CHILD, ...
''' small script to plot cpp output ''' import csv from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import import matplotlib.pyplot as plt from matplotlib import cm import numpy as np import pandas as pd import time from src import utils plt.style.use("kitish") def main(): # Plot normalized Data ...
import os import torch import torch.nn as nn import torch.nn.functional as F from torchsummary import summary class UNet3D(nn.Module): def __init__(self, in_channels, out_channels, interpolate=True, conv_layer_order='cbr', init_ch=16): super(UNet3D, self).__init__() self.no_class = out_c...
# -*- coding: utf-8 -*- # Import Section from dotenv import load_dotenv, find_dotenv import os import requests from requests import session as ss from cryptography.fernet import Fernet import ast, logging # Get Params dotenv_path = find_dotenv() load_dotenv(dotenv_path) auth_key = ast.literal_eval(os.environ.get("AU...