content
stringlengths
5
1.05M
import csv import sys import urllib3 import json from urllib.parse import quote METAMAP = 'https://knowledge.ncats.io/ks/umls/metamap' DISAPI = 'https://disease-knowledge.ncats.io/api' DISEASE = DISAPI + '/search' def parse_disease_map (codes, data): if len(data) > 0: for d in data: if 'I_CODE...
## # @file elasticsearch.py # @author Lukas Koszegy # @brief Elasticsearch klient ## from elasticsearch import Elasticsearch import json from time import time from database.schemes.mapping import mappingApp, mappingEvent import logging class ElasticsearchClient(): def __init__(self, host="127.0.0.1", port=9200, ss...
from argparse import ArgumentParser import numpy as np import pytorch_lightning as pl from scipy.io import savemat from torch.utils.data import DataLoader from helmnet import IterativeSolver from helmnet.dataloaders import get_dataset class Evaluation: def __init__(self, path, testset, gpus): self.path ...
import cv2 import numpy as np import pandas as pd date=datetime.datetime.now().strftime("%d/%m/20%y") faceDetect = cv2.CascadeClassifier("C:/Users/Administrator/Desktop/haarcascade_frontalface_default.xml") cam = cv2.VideoCapture(0) rec = cv2.face.LBPHFaceRecognizer_create() rec.read("C:/Users/Administrator/Desk...
import numpy as np import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import time import os import shutil import copy import datetime from layers import ConvNet import network_operators import utils # hyperparameters mutation_time_limit_hours = 23 n_models = 8 # ...
import subprocess , os from tkinter import messagebox from tkinter import filedialog class Cmd: def __init__(self,tk, app): self.app = app self.tk = tk self.default_compileur_path_var = os.path.join(os.path.dirname(os.path.abspath(__file__)), "dart-sass\\sass.bat") self.opt...
import math from typing import Optional import torch from torch import nn, Tensor from torch.autograd import grad from torch.nn import functional as F from adv_lib.utils.visdom_logger import VisdomLogger def ddn(model: nn.Module, inputs: Tensor, labels: Tensor, targeted: bool = False, ...
#!/usr/bin/python def get_memory(file_name): # vmstat #procs - ----------memory - --------- ---swap - - -----io - --- -system - - ------cpu - ---- # r;b; swpd;free;buff;cache; si;so; bi;bo; in;cs; us;sy;id;wa;st memory_swpd = list() memory_free = list() memory_buff = ...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import ValidationError class CouponReward(models.Model): _name = 'coupon.reward' _description = "Coupon Reward" _rec_name = 'reward_description' ...
""" ===================== Configuration Manager ===================== """ import os from configparser import ConfigParser from typing import Optional, Dict, TypeVar, Callable from PySide2 import QtWidgets WIDGET = TypeVar('QWidget') ######################################################################## class Con...
import json import yaml from flask import jsonify, Blueprint, redirect from flask_restless import APIManager from flask_restless.helpers import * sqlalchemy_swagger_type = { 'INTEGER': ('integer', 'int32'), 'SMALLINT': ('integer', 'int32'), 'NUMERIC': ('number', 'double'), 'DECIMAL': ('number', 'doubl...
# -*- coding: utf-8 -*- """ Created on Tue Jul 24 12:35:04 2018 @author: Matthias N. """ import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent import asyncio import concurrent.futures import json, codecs async def speedcrawl(pages): data = [] for p in range(...
from .src import dwarfgen def process(*args, **kwargs): return dwarfgen.process(*args, **kwargs)
import tesseract api = tesseract.TessBaseAPI() api.SetOutputName("outputName"); api.Init("E:\\Tesseract-OCR\\test-slim","eng",tesseract.OEM_DEFAULT) api.SetPageSegMode(tesseract.PSM_AUTO) mImgFile = "eurotext.jpg" pixImage=tesseract.pixRead(mImgFile) api.SetImage(pixImage) outText=api.GetUTF8Text() print("OCR output:\n...
import math import torch from torch import Tensor from .optimizer import Optimizer from typing import List, Optional class RAdam(Optimizer): r"""Implements RAdam algorithm. .. math:: \begin{aligned} &\rule{110mm}{0.4pt} \\ ...
""" Author: Darren Date: 30/05/2021 Solving https://adventofcode.com/2016/day/6 Part 1: Need to get most frequent char in each column, given many rows of data. Transpose columns to rows. Find the Counter d:v that has the max value, keyed using v from the k,v tuple. Part 2: As part 1, but using mi...
from flask import Flask, render_template, redirect from flask_pymongo import PyMongo, ObjectId from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import ValidationError, URL app = Flask(__name__) app.config['SECRET_KEY'] = 'test' app.config["MONGO_URI"] = "mongodb://14...
"""added date_read_date Revision ID: a544d948cd1b Revises: 5c5bf645c104 Create Date: 2021-11-28 20:52:31.230691 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'a544d948cd1b' down_revision = '5c5bf645c104' branch_labels = None depends_on = None def upgrade()...
from django.contrib.auth import get_user_model from django.test import TestCase from src.activities.models import Activity from src.questions.models import Question, Answer class QuestionVoteTest(TestCase): def setUp(self): self.user = get_user_model().objects.create_user( username='test_user...
#!/usr/bin/env python import astropy.units as u from typing import Union from dataclasses import dataclass, field, is_dataclass from cached_property import cached_property import copy from typing import ClassVar from schema import Or from tollan.utils.dataclass_schema import add_schema from tollan.utils.log import ge...
from hashlib import md5 def mine(secret: str, zero_count=5) -> int: i = 0 target = '0' * zero_count while True: i += 1 dig = md5((secret + str(i)).encode()).hexdigest() if dig.startswith(target): return i if __name__ == '__main__': key = 'bgvyzdsv' print(f'Par...
import json import os def setAccount( persAcc, money, input=True ): rez = True if input == True: persAcc += money else: if persAcc < money: rez = False else: persAcc -= money return persAcc, rez # ********************************************** def setH...
# Databricks notebook source import pandas as pd import random # COMMAND ---------- # columns = ['id','amount_currency','amount_value','channel','deviceDetails_browser', # 'deviceDetails_device','deviceDetails_deviceIp','merchantRefTransactionId','paymentMethod_apmType', # 'paymentMethod_cardNum...
import numpy as np import cv2 def handle_image(input_image, width=60, height=60): """ Function to preprocess input image and return it in a shape accepted by the model. Default arguments are set for facial landmark model requirements. """ preprocessed_image = cv2.resize(input_image, (width, height...
class Solution: def isPalindrome(self, x: int) -> bool: if x < 0 or (x != 0 and x % 10 == 0): return False res = 0 # 1221 while x > res: res *= 10 res += x % 10 x //= 10 if x == res or x == res // 10: return True ...
from model.contact import Contact from random import randrange def test_delete_some_contact(app): app.contact.ensure_contact_exists(Contact(fname="contact to delete")) old_contacts = app.contact.get_contact_list() index = randrange(len(old_contacts)) app.contact.delete_contact_by_index(index) asse...
""" Number Mind """
#!/usr/bin/env python3 # Up / Down ISC graph for ALL bins # Like SfN Poster Figure 2 # But now for all ROIs in Yeo atlas import tqdm import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import deepdish as dd from HMM_settings import * ISCdir = ISCpath+'shuff_Yeo_outlier_' figdir = figurepath+'up...
""" Created Aug 2020 @author: TheDrDOS """ # Clear the Spyder console and variables try: from IPython import get_ipython #get_ipython().magic('clear') get_ipython().magic('reset -f') except: pass from time import time as now from time import perf_counter as pnow import pickle import numpy as np impo...
# -*- coding: utf-8 -*- import cv2 # トラックバーの値を変更する度にRGBを出力する def changeColor(val): r_min = cv2.getTrackbarPos("R_min", "img") r_max = cv2.getTrackbarPos("R_max", "img") g_min = cv2.getTrackbarPos("G_min", "img") g_max = cv2.getTrackbarPos("G_max", "img") b_min = cv2.getTrackbarPos("B_min", "img") ...
# Developed by Joseph M. Conti and Joseph W. Boardman on 1/21/19 6:29 PM. # Last modified 1/21/19 6:29 PM # Copyright (c) 2019. All rights reserved. import logging import logging.config as lc import os from pathlib import Path from typing import Union, Dict import numpy as np from yaml import load class Singleto...
# -*- coding: utf-8 -*- # Resource object code # # Created by: The Resource Compiler for PyQt5 (Qt v5.15.0) # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore qt_resource_data = b"\ \x00\x00\x07\x10\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x40\x...
#!/usr/bin/python # (c) 2018 Jim Hawkins. MIT licensed, see https://opensource.org/licenses/MIT # Part of Blender Driver, see https://github.com/sjjhsjjh/blender-driver """Path Store unit test module. Tests in this module can be run like: python3 path_store/test.py TestInterceptProperty """ # Exit if run other tha...
from unittest.case import TestCase from responsebot.handlers.base import BaseTweetHandler from responsebot.handlers.event import BaseEventHandler try: from mock import MagicMock, patch except ImportError: from unittest.mock import MagicMock class Handler(BaseTweetHandler): class ValidEventHandler(BaseEv...
# coding: utf-8 from cms.plugin_pool import plugin_pool from cms.plugin_base import CMSPluginBase from cmsplugin_bootstrap_grid.forms import ColumnPluginForm from cmsplugin_bootstrap_grid.models import Row, Column from django.utils.translation import ugettext_lazy as _ class BootstrapRowPlugin(CMSPluginBase): mod...
from scipy import spatial from . import design from .design import * from .fields import * schema = dj.schema('photixxx') @schema class Tissue(dj.Computed): definition = """ -> design.Geometry --- density : float # points per mm^3 margin : float # (um) margin to include on boundaries min_dis...
# Copyright 2017 The KaiJIN 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 applicable ...
import pandas as pd from plotly.subplots import make_subplots import plotly.graph_objects as go import modules.load_data_from_database as ldd from db import connect_db # connection with database rdb = connect_db() def day_figure_update(df, bar): """ Update day figure depends on drop downs """ df_bar = df[df...
import threading import json from socketIO_client import SocketIO, LoggingNamespace class Cliente(): def __init__(self, ip): self.socketIO = SocketIO(ip, 8000) self.errors = '' #thread_rcv= threading.Thread () #thread_rcv.daemon=True #thread_rcv.start() ...
import ctypes import os import warnings from ctypes import ( byref, c_byte, c_int, c_uint, c_char_p, c_size_t, c_void_p, create_string_buffer, CFUNCTYPE, POINTER ) from pycoin.encoding.bytes32 import from_bytes_32, to_bytes_32 from pycoin.intbytes import iterbytes SECP256K1_FLAGS_TYPE_MASK = ((1 << 8) - 1) SECP...
from smach_based_introspection_framework.offline_part.model_training import train_anomaly_classifier from smach_based_introspection_framework._constant import ( anomaly_classification_feature_selection_folder, ) from smach_based_introspection_framework.configurables import model_type, model_config, score_metric imp...
from collections import deque from time import perf_counter def breadthFirstSearch(initialState, goalState, timeout=60): # Initialize iterations counter. iterations = 0 # Initialize visited vertexes as set, because it's faster to check # if an item exists, due to O(1) searching complexity on average ...
/home/runner/.cache/pip/pool/fd/94/44/56b7be5adb54be4e2c5a3aea50daa6f50d6e15a013102374ffe3d729b9
import FWCore.ParameterSet.Config as cms def useTMTT(process): from L1Trigger.TrackerDTC.Producer_Defaults_cfi import TrackerDTCProducer_params from L1Trigger.TrackerDTC.Format_TMTT_cfi import TrackerDTCFormat_params from L1Trigger.TrackerDTC.Analyzer_Defaults_cfi import TrackerDTCAnalyzer_params Track...
from datetime import timedelta import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt import matplotlib.ticker as ticker import numpy as np from matplotlib import rcParams __author__ = 'Ben Dichter' class BrokenAxes: def __init__(self, xlims=None, ylims=None, d=.015, tilt=45, su...
# Copyright 2014-2015 ARM 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 to in w...
from sklearn.cluster import KMeans from sklearn.mixture import GaussianMixture from sklearn.cluster import DBSCAN from .MetadataExtractor import Extractor from .DataCleaner import cleaner, limited_cleaner from joblib import dump, load def predictor(extractor, name): data = cleaner(extractor).drop_duplicates...
# Copyright (c) 2021, Manfred Moitzi # License: MIT License from typing import ( Iterable, List, TYPE_CHECKING, Tuple, Iterator, Sequence, Dict, ) import abc from typing_extensions import Protocol from ezdxf.math import ( Vec2, Vec3, linspace, NULLVEC, Vertex, inter...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/12/30 21:02 # @Author : WIX # @File : 青蛙跳.py """ 青蛙跳台阶, 每次可以跳1级或2级,求青蛙跳上一个n级的台阶一共有多少种跳法? 当n > 2时,第一次跳就有两种选择: 1. 第一次跳1级,后面的跳法相当于剩下n-1级的跳法,即f(n-1) 2. 第一次跳2级,后面的跳法相当于剩下n-2级的跳法,即f(n-2) 即f(n) = f(n-1) + f(n-2) """ class Solution(object): def jumpfrog...
# coding: utf-8 # import models into model package from .error_enveloped import ErrorEnveloped from .health_check_enveloped import HealthCheckEnveloped from .inline_response200 import InlineResponse200 from .inline_response200_data import InlineResponse200Data from .inline_response201 import InlineResponse201 from .in...
__author__ = 'Bohdan Mushkevych' from odm.document import BaseDocument from odm.fields import StringField, ObjectIdField, DateTimeField TIMEPERIOD = 'timeperiod' START_TIMEPERIOD = 'start_timeperiod' END_TIMEPERIOD = 'end_timeperiod' FLOW_NAME = 'flow_name' STATE = 'state' CREATED_AT = 'created_at' STARTED_AT = 'sta...
''' This module generates charts from cohort.pickle rather than from the cumulative csvs. ''' import os import pandas as pd import matplotlib.pyplot as plt from plot_practice_charts import * from ethnicities import high_level_ethnicities wave_column_headings = { "total": "All", "all_priority": "Priority grou...
# nxpy_svn -------------------------------------------------------------------- # Copyright Nicola Musatti 2010 - 2018 # Use, modification, and distribution are subject to the Boost Software # License, Version 1.0. (See accompanying file LICENSE.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # See https://git...
# -*- Python -*- # license # license. """ Files opening and reading/writing functions. """ import sys, os, bz2, lzma, json import logging; module_logger = logging.getLogger(__name__) # ====================================================================== def open_for_reading_binary(filename): """Opens binary fi...
# get largest continues sum def pair_sum(arr, target): seen = set() output = set() for num in arr: diff = target - num if diff not in seen: print('adding diff',diff) seen.add(num) else: print('adding output',diff, seen) outpu...
#!/usr/bin/env python """Archive Now for python""" # import pyhesity wrapper module from pyhesity import * from datetime import datetime # command line arguments import argparse parser = argparse.ArgumentParser() parser.add_argument('-v', '--vip', type=str, required=True) # cluster to connect to parser.add_argu...
# https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem def anagramPairs(s): # Write your code here dic = {} res = 0 for k in range(1, len(s)): for i in range(len(s)-k+1): j = i+k strr = "".join(sorted(s[i:j])) dic[strr] = dic.get(strr,0)+1 f...
""" /****************************************************************************** * * * Name: mylogger.py * * ...
#!/usr/bin/env python """Celery worker to be run as follows: (venv) $ celery worker -A pili.entrypoints.celery.celery --loglevel=info Environment variables (such as MAIL_SERVER, MAIL_USERNAME, etc.) should be set using export: (venv) $ export MAIL_SERVER=smtp.youserver.com 'export' keyword in bash sets a variable t...
import asyncio import http import aiohttp.client import urllib.robotparser import datetime import collections import logging import abc logger = logging.getLogger(__name__) import site_graph class RequestQueue: """A queue of pending HTTP requests, that maintains a minimum interval between outgoing requests I...
import numpy as np from scratch_ml.utils import covariance_matrix class PCA(): """A method for doing dimensionality reduction by transforming the feature space to a lower dimensionality, removing correlation between features and maximizing the variance along each feature axis.""" def transform(self, ...
import logging import argparse from s3push.connector import resource from s3push.uploader import upload from s3push.eraser import erase parser = argparse.ArgumentParser( description='Upload directories and files to AWS S3') parser.add_argument( 'path', type=str, help='Path to a directory of file tha...
# parses vcontrold serial data import struct from scapy.packet import Packet, bind_layers from scapy.fields import * START_BYTE = 0x41 TYPES = { 0x00: "request", 0x01: "response", 0x03: "error" } COMMANDS = { 0x01: "readdata", 0x02: "writedata", 0x07: "functioncall" } class VS2Header(Packet...
import os def exists_or_create_directory(temp_path: str) -> None: directory = os.path.dirname(temp_path) try: os.stat(directory) except Exception as exp: os.mkdir(directory) print(str(exp) + f" -> {directory} created...")
from collections import defaultdict raw_template = [] rules = [] with open("input") as file: raw_template = list(next(file).strip()) for line in file: line = line.strip() if not line: continue left, right = line.split("->") left = left.strip() right = right....
# 쿼드압축 후 개수 세기 def quadtree(arr): l = len(arr) if l == 1: return [1,0] if arr[0][0] == 0 else [0,1] lu = quadtree([a[:l//2] for a in arr[:l//2]]) ru = quadtree([a[l//2:] for a in arr[:l//2]]) ld = quadtree([a[:l//2] for a in arr[l//2:]]) rd = quadtree([a[l//2:] for a in arr[l//2:]]) if l...
# -*- coding: utf-8 -*- """ Created on Thu Nov 11 16:31:58 2021 @author: snoone """ import os import glob import pandas as pd pd.options.mode.chained_assignment = None # default='warn' OUTDIR3= "D:/Python_CDM_conversion/monthly/cdm_out/cdm_head" OUTDIR2= "D:/Python_CDM_conversion/monthly/cdm_out/cdm_ob...
#EsmeeEllson #Help #Class Attributes #You can instantiate with AsciiTable(table_data) or AsciiTable(table_data, 'Table Title'). #These are available after instantiating AsciiTable. Name Description/Notes table_data = List of list of strings. Same object passed to __init__(). title = Table title string....
# -*- coding: utf-8 -*- """ Created on Thu Oct 21 18:32:33 2021 @author: User """ # Expresiones generadoras # El módulo itertools itertools.chain(s1,s2) itertools.count(n) itertools.cycle(s) itertools.dropwhile(predicate, s) itertools.groupby(s) itertools.ifilter(predicate, s) itertools.imap(function, s1, ... sN) ite...
"""Implementation of the Unet in torch. Author: zhangfan Email: zf2016@mail.ustc.edu.cn data: 2020/09/09 """ import torch import torch.nn as nn from network.blocks.residual_blocks import ResFourLayerConvBlock class UNet(nn.Module): """UNet network""" def __init__(self, net_args={"num_class": 1, ...
import re from textwrap import dedent import black import autopep8 from pkg_resources import resource_string def get_snippet(name, decorator=True): 'Get a Python snippet function (as a string) from the snippets directory.' out = resource_string('matflow_defdap', f'snippets/{name}').decode() if not decor...
# -*- coding:utf-8 -*- from timeit import default_timer import numpy as np import matplotlib.pyplot as plt from scipy.misc import face # Importing global thresholding algorithms from .global_th import otsu_threshold, p_tile_threshold,\ two_peaks_threshold, min_err_threshold # Importing global entropy threshold...
#!/usr/bin/python import paho.mqtt.publish as publish import paho.mqtt.client as mqtt import ssl auth = { 'username':"ciscohackhub.azure-devices.net/lora1", 'password':"SharedAccessSignature sr=ciscohackhub.azure-devices.net%2Fdevices%2Flora1&sig=xxxx&se=1463048772" } tls = { 'ca_certs':"/etc/ssl/certs/ca-cert...
def input1(type = int): return type(input()) def input2(type = int): [a, b] = list(map(type, input().split())) return a, b def input3(type = int): [a, b, c] = list(map(type, input().split())) return a, b, c def input_array(type = int): return list(map(type, input().split())) def input_string(): s = in...
from sklearn.base import BaseEstimator, TransformerMixin import re class TextCleaner(BaseEstimator, TransformerMixin): ''' text cleaning : input can be str, list of sring, or pandas Series a minimal version, repacing only '\n' with ' ' ''' def __init__(self): print('') def f...
import torch import torch.optim as optim from torch.optim.lr_scheduler import LambdaLR from allenact.algorithms.onpolicy_sync.losses import PPO from allenact.algorithms.onpolicy_sync.losses.ppo import PPOConfig from allenact.utils.experiment_utils import ( Builder, PipelineStage, TrainingPipeline, Line...
import py.path import pytest from .conftest import TEST_PLAYBOOKS MODULES_PATH = py.path.local(__file__).realpath() / '..' / '..' / 'plugins' / 'modules' def find_all_modules(): for module in MODULES_PATH.listdir(sort=True): module = module.basename if module.endswith('.py') and not module.start...
#!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. 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 # # U...
import os import sys import time import glob import numpy as np import pandas as pd import torch import utils import logging import argparse import torch.nn as nn import torch.utils import torch.nn.functional as F import torchvision.datasets as dset import torch.backends.cudnn as cudnn from copy import deepcopy from nu...
""" hhpy ~~~~~~ The hhpy package - a Python package developed by Henrik Hanssen centered around the idea of providing unified and convenient tools for Data Science """ from hhpy.main import * from hhpy.ds import * from hhpy.ipython import * from hhpy.modelling import * from hhpy.plotting import * from hhpy.regression...
""" Copyright 2017 Nikolay Stanchev 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, softwa...
import importlib from pathlib import Path from airflow.hooks.base import BaseHook from astro.databases.base import BaseDatabase from astro.utils.path import get_class_name, get_dict_with_module_names_to_dot_notations DEFAULT_CONN_TYPE_TO_MODULE_PATH = get_dict_with_module_names_to_dot_notations( Path(__file__) )...
from PySide2 import QtWidgets import maya.cmds as cmds class MyWindow(QtWidgets.QDialog): def __init__(self, parent=None): super(MyWindow, self).__init__(parent) lay = QtWidgets.QHBoxLayout(self) self._line = QtWidgets.QLineEdit('', self) self._line.setPlaceholde...
# Copyright 2021 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...
"""AVMATH Avmath is a Python module for mathematical purposes. It contains functionalities for simple mathematical usage as sine or logarithm functions and submodules for more advanced applied math in the topics of ana- lysis and linear algebra. The module uses a mathematical syntax. The classes and functions are nam...
""" This script deploys all the AWS instances required for a single distributed experiment and runs the docker container on the instances. The experiment is one of inner_product / quadratic / kld / dnn. The user could choose whether to run the coordinator on a strong EC2 instance, or on an ECS Fargate instance. """ imp...
from .models import Answer, Landscape def landscape_boundary(landscape_name): """ Return landscape boundary as GeoJSON :param landscape_name: :return: """ landscape_boundaries = Landscape.objects.raw("""SELECT id, ...
import random, string from datetime import datetime import pytz import json import types from unittest import TestCase from unittest.mock import patch from plaw.wrapper import Plaw, InvalidGrant, InvalidToken class TestPlaw(TestCase): # helper def generate_random_token(self, length=16): return ''.jo...
# encoding: utf-8 # Duke the dog # Este código va destinado al reconocimiento de un perro por su color de pelaje, # eliminando todo ruido causado por el ambiente. # Todo mediante la librería open cv en Python..subl # Programador Sergio Luis Beleño Díaz # Enero.2019 ''' Para empezar se importan las librerías de Open...
from chemlib.chemistry import Combustion, Compound, Reaction from chemlib.utils import reduce_list # TODO: TEMP IMPLEMENTATIONS, NEED TO CONSIDER ADDITIONAL METHODS/CALCULATIONS # INTERFACE? def combustion_analysis(CO2, H2O) -> str: molesC = Compound("CO2").get_amounts(grams = CO2)["moles"] molesH = (Compou...
__all__ = [ 'assign','smart_assign','LCA','linkable', 'Assign','SmartAssign','Linkable', 'join_name', 'Component', 'Input','Output','UInt','SInt','IOGroup','Parameter','Wire','Reg', 'And','Or','Greater','Less','GreaterEqual','LessEqual','NotEqual','Equal', ...
import numpy as np import torch import torch.nn as nn from .anchor_head_template import AnchorHeadTemplate class GradReverse(torch.autograd.Function): def __init__(self, lambd): self.lambd = lambd def forward(self, x): return x.view_as(x) def backward(self, grad_output): return (...
# coding= utf-8 # author= Administrator # date= 2021/3/15 17:38 from bs4 import BeautifulSoup # 创建html字符串 html_doc = """ <!DOCTYPE html><!--STATUS OK--> <html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta content="always...
# Generated by Django 3.0.7 on 2020-06-30 17:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('portfolio', '0005_auto_20200630_1658'), ] operations = [ migrations.AddField( model_name='collection', name='spotlig...
from tool.runners.python import SubmissionPy class DivSubmission(SubmissionPy): def match(self, x): s = str(x) n = len(s) if n != 6: return False # always increasing (or equal) for i in range(n-1): if s[i] > s[i+1]: return False ...
#take file called numbers.txt to start fileName = "numbers.txt" def main(): global fileName fileInput = open(fileName, 'r') numAry = [] for line in fileInput.readlines(): numAry.append(eval(line)) maxInt = findMax(numAry, 0, len(numAry)-1) print("The Max Value Is " + str...
#!/usr/bin/python2.7 # coding:utf-8 import logging from time import sleep from RPi import GPIO from cmdtree import INT from cmdtree import command from cmdtree import entry from cmdtree import group from cmdtree import option GPIO_CONTROL_PORT = 12 FAN_ON_TEMPERATURE = 55 def get_cpu_temp(): ...
from copy import deepcopy from torch import nn import numpy as np import math import torch from torch.utils.data import dataset from torch.utils.data.dataset import Subset from torch.utils.data import DataLoader # def compare_models(model: nn.Module, clients: 'list[Client]', num: int): # def print_params(model...
#!/usr/bin/env python3 # Copyright 2018 Brocade Communications Systems LLC. 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 also obtain a copy of the License at # http://www.apache.org/licenses/LICENS...
import json from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import render...