content
stringlengths
5
1.05M
from utils.operator_identifier import * def parse_decomposition(qdmr): """Parses the decomposition into an ordered list of steps Parameters ---------- qdmr : str String representation of the QDMR Returns ------- list returns ordered list of qdmr steps """ # parse ...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
import warnings warnings.filterwarnings('ignore') import torch from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm # from dataset import DataBuilder, Dataset, Vocab, load_embedding from dataset_daily import DataBuilder, Dataset, Vocab, load_embedding from model import Seq2Seq class Trainer: ...
import tensorflow as tf import os import pickle import numpy as np base_seq = [1,1,1,1,2,1,1,1,3,3,1,3,2] + ([0]*95) current_struc = [1,1,1,1,1,1,1,1,1,1,1,1,1] + ([0]*95) target_struc = [2,1,1,2,2,1,1,1,3,3,1,1,3] + ([0]*95) current_energy = [0.0] + ([0]*107) target_energy = [7.9] + ([0]*107) locks = [1,1,1,1,1,2,2,2...
import simplejson import sys import util.net as net import urllib2 from util.primitives import funcs from operator import itemgetter import random import util.callbacks as callbacks import util.threads as threads import common.asynchttp from logging import getLogger log = getLogger('loadbalance') class DigsbyLoadBala...
import os import fire from src.utils.directory import CONFIG_YAML_PATH, EXPENSE_YAML_PATH, INCOME_YAML_PATH, FINAL_PATH from src.utils.io import load_yaml from src.utils.transactions import ( load_transaction, get_accounts, remove_accounts, remove_keywords, map_category, map_description, m...
from django.contrib import admin from .models import Sensor, Order, Employee, Responsable admin.site.site_header = 'Administration Panel' admin.site.site_title = 'Dustbin IoT' admin.site.index_title = 'Admin' admin.site.site_url = '/home/' admin.site.register([Sensor, Order, Employee, Responsable])
#!/usr/bin/env python # -*- coding: utf-8 -*- # # || ____ _ __ # +------+ / __ )(_) /_______________ _____ ___ # | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ # +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ # || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ # # Copyright (C) 20...
""" Copyright 2020 The OneFlow 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 law or agr...
# DO NOT USE THIS MODULE. # This module contians a legacy API, an early approach to composing plans that # was little used and finally deprecated in v0.10.0. It will be removed in a # future release. It should not be used. from functools import wraps from contextlib import contextmanager import warnings from .utils ...
""" NOTE: these functions are copied from "gpu_extract.py" in the hackathon branch; the pieces have not yet been put together into a working GPU extraction in this branch. """ import math import numpy as np import numpy.polynomial.legendre from numba import cuda import cupy as cp import cupy.prof import cupyx import ...
# gridDataFormats --- python modules to read and write gridded data # Copyright (c) 2009-2014 Oliver Beckstein <orbeckst@gmail.com> # Released under the GNU Lesser General Public License, version 3 or later. # See the files COPYING and COPYING.LESSER for details. """ :mod:`gridData` -- Handling grids of data =========...
# Local from .helpers import config import discord from discord.ext import commands class AdminTools(commands.Cog): def __init__(self, client): self.client = client self.prefix = config.load()['bot']['prefix'] @commands.has_permissions(administrator=True) @commands.command(aliases=['conf...
from maya.app.renderSetup.views.lightEditor.lightSource import * from maya.app.renderSetup.views.lightEditor.group import GroupAttributes from maya.app.renderSetup.views.lightEditor.group import Group import PySide2.QtCore as _QtCore class ItemModel(_QtCore.QAbstractItemModel): """ This class defines the vie...
""" 1088. Confusing Number II We can rotate digits by 180 degrees to form new digits. When 0, 1, 6, 8, 9 are rotated 180 degrees, they become 0, 1, 9, 8, 6 respectively. When 2, 3, 4, 5 and 7 are rotated 180 degrees, they become invalid. A confusing number is a number that when rotated 180 degrees becomes a different ...
import numpy import disba import helpers def test_ellipticity(): velocity_model = helpers.velocity_model(5) t = numpy.logspace(0.0, 1.0, 20) ell = disba.Ellipticity(*velocity_model) rel = ell(t) assert numpy.allclose(14.038, rel.ellipticity.sum(), atol=0.001)
"""Support for Axis devices.""" import logging from homeassistant.const import ( CONF_DEVICE, CONF_HOST, CONF_MAC, CONF_PASSWORD, CONF_PORT, CONF_TRIGGER_TIME, CONF_USERNAME, EVENT_HOMEASSISTANT_STOP, ) from .const import CONF_CAMERA, CONF_EVENTS, DEFAULT_TRIGGER_TIME, DOMAIN from .de...
"""plots saliency maps of images to determine which pixels most contriute to the final output""" import os import matplotlib.pyplot as plt import torch import torchvision.transforms as T from PIL import Image import cocpit.config as config plt_params = { "axes.labelsize": "large", "axes.titlesize": "large",...
# -*- coding: iso-8859-1 -*- from sqlalchemy import create_engine import fdb # FORMA SIMPLE ACCESO A DB # con = fdb.connect(dsn='/threads/proyectos/academia/db/ACADEMIA.DB', user='SYSDBA', password='masterkey') # cur = con.cursor() # cur.execute("SELECT CODIGO, NOMBRE FROM UBICACIONES") # print(cur.fetchall(...
######################### ### ACTIVITY CALENDAR ### ######################### SHEET_SERVER_COLUMN = 1 SHEET_TIMESTAMP_COLUMN = 2 SHEET_ACTIVITY_COLUMN = 3 SHEET_DESCRIPTION_COLUMN = 4 SHEET_LINK_COLUMN = 5 ACTIVITY_CALENDAR_CHANNEL_ID = 390394020851089408
"""PatchmatchNet dataset module reference: https://github.com/FangjinhuaWang/PatchmatchNet """
from qutipy.states.MaxEnt_state import MaxEnt_state from qutipy.states.GHZ_state import GHZ_state from qutipy.states.graph_state import graph_state from qutipy.states.isotropic_state import isotropic_state from qutipy.states.isotropic_twirl_state import isotropic_twirl_state from qutipy.states.MaxMix_state import MaxMi...
# -*- coding: utf-8 -*- import os from simmate.conftest import copy_test_files, make_dummy_files from simmate.calculators.vasp.inputs import Incar from simmate.calculators.vasp.error_handlers import Eddrmm def test_eddrmm(tmpdir): copy_test_files( tmpdir, test_directory=__file__, test_fo...
from django.contrib.auth.models import Group, Permission from rest_framework.permissions import IsAdminUser from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from meiduo_admin.serializer.groups import GroupSerializer from meiduo_admin.serializer.permission import PermissionS...
# -*- coding: utf-8 -*- import torch import torch.onnx import torch.onnx.symbolic_helper import torch.onnx.utils import torch.nn as nn import numpy as np from collections import OrderedDict from . import register from . import mask_utils from . import function_module from typing import Dict, List from torchpruner.op...
from dragonfly import (IntegerRef, Integer) from dragonfly.grammar.elements import RuleWrap, Choice from dragonfly.language.base.integer_internal import MapIntBuilder from dragonfly.language.loader import language from castervoice.lib import settings from castervoice.rules.core.numbers_rules.numeric_support import num...
sal = float(input('Digite seu salário atual:\n')) if sal >= 1200: aum = sal + (sal*0.15) print('Seu salário vai de R${} para R${}.'.format(sal, aum)) else: aum = sal + (sal*0.2) print('Seu salário vai de R${} para R${}.'.format(sal, aum)) print('Agora vai lá comemorar comendo umas puta')
"""Kernel density estimate tissue mode normalization CLI Author: Jacob Reinhold (jcreinhold@gmail.com) Created on: 13 Oct 2021 """ __all__ = ["kde_main", "kde_parser"] from intensity_normalization.normalize.kde import KDENormalize # main functions and parsers for CLI kde_parser = KDENormalize.parser() kde_main = KDE...
""" Sum numeric strings a + b without adding them up directly. Examples “123” + "1" = “124” "999" + "1" = "1000" SOLUTION Time O(N) Space O(N): store the result, else O(1). """ from typing import List def solve(a: str, b: str) -> str: res: str = "" digits: List[str] = [str(i) for i in range(10...
import os import time import threading LK = threading.Lock() Ni = 20 + 1 Nj = 20 + 1 Np = 4 FF = [] CC = [] for i in range( Ni ): for j in range( Nj ): CC.append( ( i, j ) ) FF.append( not os.path.isfile( "pes.%d.%d"%( i, j ) ) ) NN = len( FF ) def worker( num ): global LK, CC, FF, NN ...
#!/usr/bin/python # (C) Copyright IBM Corp. 2015, 2016 # The source code for this program is not published or # otherwise divested of its trade secrets, irrespective of # what has been deposited with the US Copyright Office. from abstract_qpylib import AbstractQpylib import json import os import os.path im...
#----------------------------------------------------------------------------- # Copyright (c) 2013-2020, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License (version 2 # or later) with exception for distributing the bootloader. # # The full license is in the file COPYING.txt...
from .app_builder_message import AppBuilderMessage from .app_builder_save_theme import AppBuilderSaveTheme from .app_builder_create_app import AppBuilderCreateApp from .app_builder_settings import Settings from .app_builder_functions import UIFunctions from qt_core import * Gen_Class, Base_Class = loadUiType(UIFunc...
import calendar from datetime import datetime print(calendar.day_name[0]) print(calendar.day_name[1]) print(calendar.day_name[6]) dt = datetime(2019, 8, 17, 6, 00, 00) h = dt.time().hour print(h) # datetime comparison d1 = datetime(2020, 2, 11, 8, 52, 40) d2 = datetime(2020, 2, 11, 9, 52, 40) print(f'{d1} > {d2}') ...
from .feed_filter_tags import * # NOQA
from mamba import describe, included_context, it NEW_EXPORTED_CONTEXT = 'New Exported Context' with describe('Real tests'): with included_context(NEW_EXPORTED_CONTEXT): with it('added example'): pass
from . import pyrender_wrapper # from pyrender_wrapper import CustomShaderCache import numpy as np import pyrender from skimage import io # Camera transform from position and look direction def get_camera_transform(position, look_direction): camera_forward = -look_direction / np.linalg.norm(look_direction) ca...
""" Interfacing with External Environments - Matlab and Octave """ import statsmodels.api as sm from scipy.io import savemat data_loader = sm.datasets.sunspots.load_pandas() df = data_loader.data savemat("sunspots", {"sunspots": df.values})
""" Crie um programa que leia o nome e o preço de varios produtos. O programa devera perguntar se o usuario vai continuar. no final Mostre: A) qual é o total gasto na compra B) quantos produtos custam mais de R$ 1000 C) qual é o nome do produto mais barato. """ total = maior_1000 = cont = menor = 0 nome_mais_barato = ...
from amundsenatlastypes import Initializer init = Initializer() init.create_required_entities() """ DB: [db]@[cluster] Table: [db].[table]@[cluster] Column: [db].[table].[column]@[cluster] TableMetadata: [db].[table].metadata@[clu...
#!/usr/bin/env python import glob import os import markdown import time def get_output_filename(filename): items = os.path.splitext(filename) return items[0] + '.tex' def compile(): os.system("make") files = glob.glob("*.tx") + glob.glob("*/*.tx") + glob.glob("*/*/*.tx") if len(files)==0: print "no ...
FLOWER_FEATURE_CHOICES = ( ("sepal_length", "sepal_length"), ("sepal_width", "sepal_width"), ("petal_length", "petal_length"), ("petal_width", "petal_width"), ("flower_type", "flower_type"), )
from rest_framework.views import APIView from rest_framework.response import Response import logging from .. import utils logger = logging.getLogger(__name__) class ScheduleSettingView(APIView): def get(self, request, format=None): response = { "week_settings": utils.WEEK_CHOICES, ...
from azurlane.common_fight import CommonMap from simulator.win32_tools import rand_click import time import sys s = CommonMap("Games") start_time = time.time() last = {} def check(): global last name = "HandleMark" t = time.time() s.make_screen_shot() found, pos = s.search_resource(name) if n...
from contrastive_learner.contrastive_learner import ContrastiveLearner
# Python 3.0 # Bartosz Wolak # created 23.07.2021 # updated 23.07.2021 """ Module responible for keeping data for buttons,dependent on pygame """ import pygame import src.Drawable import src.loading class Button(pygame.sprite.Sprite): def __init__(self, pos: (int, int), label: str, size: (int, int)...
import ifstool if __name__ == "__main__": ifstool.run()
import torch class TrimHandler: def __init__(self,num_nodes,initial_graph=None,crop_every=100,eps=0.5): self.graph = initial_graph if initial_graph else torch.ones(num_nodes,num_nodes) self.crop_every=crop_every self.num_nodes,self.n=num_nodes,num_nodes**2 self.eps=eps ...
#!/usr/bin/env python3 from datetime import datetime, timedelta from PIL import Image, ImageOps import argparse import re import srt import time import win32print import struct MAXWIDTH = 190 WIDTHCORRECTION = 1.5 ESC = b'\x1B' GS = b'\x1D' RESET = ESC + b'@' SETBOLD = ESC + b'E\x01' EXITBOLD = ESC...
# coding=utf-8 """ Tests for deepreg/model/loss/label.py in pytest style """ from test.unit.util import is_equal_tf import numpy as np import pytest import tensorflow as tf from deepreg.loss.util import ( NegativeLossMixin, cauchy_kernel1d, gaussian_kernel1d_sigma, gaussian_kernel1d_size, rectan...
from task_manager import TaskManager class TaskOpenproject (TaskManager): """Subclass of TaskManager implementing HMGM task management with OpenProject platforms.""" def __init__(self, root_dir): self.root_dir = root_dir # TODO add logic to set up Open Project task manager ...
# Helper Code from collections import defaultdict class Graph: def __init__(self): self.nodes = set() # A set cannot contain duplicate nodes self.neighbours = defaultdict( list) # Defaultdict is a child class of Dictionary that provides a default value for a key that does not exists....
import sys handle = open(sys.argv[1]) data = handle.readlines() handle.close() extracted = [] outputFile = sys.argv[1].replace("opt1","csv") # Keep the original MultEval file handle = open(outputFile, "w") handle.write("id\ttext\tbleu4\tmeteor\tter\n"); for line in data: line = line.replace("\n", "") line = lin...
class PIDController(): """Updated version of PIDController""" def __init__(self, Kp: float = 0.0, Ki: float = 0.0, Kd: float = 0.0, limitMin: float = 0.0, limitMax: float = 0.0, tau: float = 0.0, dt: float = 0.0): """Version 2 of PIDController, with updated math ...
"""Documetação oficial""" variavel_1 = 'valor 1' def soma(x, y): #soma x e y return x + y def multiplica(x, y, z=None): """Soma x, y, z Multiplica x, y, z o programador por omitir a variavel z caso não tenha necessidade de usa-la """ if z: return x * y else: return x * y * z variavel_2 = ...
import requests from flask import url_for, session, Blueprint, redirect from flask import request from apikit import jsonify from nomenklatura import authz from nomenklatura.core import db, github from nomenklatura.model import Account, Dataset section = Blueprint('sessions', __name__) @section.route('/sessions') d...
from django.shortcuts import render, redirect, render_to_response from django.http import HttpResponse from django.contrib.auth import logout as auth_logout from django.contrib.auth.decorators import login_required # Create your views here.
#!/usr/bin/env python3.8 # # Copyright (c) 2020 by Ron Frederick <ronf@timeheart.net> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the...
class MassLevelData(Element,IDisposable): """ MassLevelData is a conceptual representation of an occupiable floor (Mass Floor) in a conceptual building model. It is defined by associating a particular level with a particular mass element in a Revit project. """ def Dispose(self): """ Dispose(self: Elem...
import datetime import six from eventsourcing.domain.model.entity import EventSourcedEntity, EntityRepository from eventsourcing.domain.model.events import publish from quantdsl.priceprocess.base import datetime_from_date class SimulatedPrice(EventSourcedEntity): class Created(EventSourcedEntity.Created): ...
from typing import Optional, Tuple import math __all__ = [ 'Angle', 'Distance', 'Speed', 'Vector3', 'angle_z_to_quaternion', 'Matrix44', 'Quaternion', 'Pose', 'hex_dump', 'hex_load', 'frange', ] class Angle: """ Angle representation. Args: radians (...
from .laundry_cycle_converter import LaundryCycleConverter from .machine_state_converter import MachineStateConverter from .laundry_door_status_converter import LaundryDoorStatusConverter from .laundry_sub_cycle_converter import LaundrySubCycleConverter from .rinse_option_converter import RinseOptionConverter from .tem...
class ValidationError(Exception): """Empty directory exception""" def __init__(self, msg): self.msg = msg super(ValidationError, self).__init__(msg) class MissingDecorator(Exception): """Empty directory exception""" def __init__(self, msg): self.msg = msg super(MissingD...
from __future__ import division import tensorflow as tf import numpy as np from utils import * from sklearn.externals.joblib import Memory from sklearn.model_selection import train_test_split from sklearn.datasets import load_svmlight_file from sklearn import metrics ############# define input options ###############...
""" Preprocess wetlands dataset. TOOTCHI https://doi.org/10.1594/PANGAEA.892657 In: Spatial: 0.066 deg Out: Spatial: 0.033 deg Steps: 1) Harmonize """ import os import xarray as xr import logging from utils.pyutils import rm_existing from dataprocessing.plotting import plot_var from dataprocessing.datasets.con...
import argparse import sys parser = argparse.ArgumentParser() parser.add_argument("-pythonpath", "--pythonpath", type=str) parser.add_argument("-tomo_name", "--tomo_name", type=str) parser.add_argument("-fold", "--fold", type=str, default="None") parser.add_argument("-config_file", "--config_file", help="yaml_file", t...
#!/usr/bin/env python3 # Copyright (c) 2016 Fabian Schuiki # # This script provides the means to prepare, execute, and analyze the results of # a propagation and transition time characterization. import sys, os, argparse from potstill.char.util import * from potstill.char.tpd import Input, Run # Parse the command li...
import unittest import requests from assertpy import assert_that from requests.exceptions import Timeout from unittest.mock import Mock, patch from src.Api import Api class TestApiMonkeyPatch(unittest.TestCase): @patch('src.Api.Api', autospec=True) def test_method_api_put_raises_timeout(self, mock_class): ...
import gym.envs.classic_control as gym_classic import gym.envs.box2d as gym_box from .abstract_environments import * from helpers import sin_and_cos_to_radians class DiscreteActionMountainCar(GroundTruthSupportEnv, DiscreteActionReshaper, gym_classic.MountainCarEnv): goal_state = np.array([[0.5, 0.0]]) goal_...
import os import sys CURRENT_PATH = os.path.dirname(os.path.realpath(__file__)) sys.path.append(CURRENT_PATH) PAR_PATH = os.path.abspath(os.path.join(CURRENT_PATH, os.pardir)) sys.path.append(PAR_PATH) from src.dataset import Dataset from src.server.server import Server from src.algo.baselines.randomP.randomP import ...
# stdlib from typing import Any # relative from ...core.common import UID from ...core.common.serde.serializable import Serializable class PyPrimitive(Serializable): def __init__(self, temporary_box: bool = False) -> None: self._id: UID # sometimes we need to serialize a python primitive in such...
#!/usr/bin/env python # -*- coding: utf-8 -*- import requests import json import csv import os import math import re from hltbapi import HtmlScraper import datetime import parameters os.getcwd() # Export file to JSON def exportJSON(file, name): with open(name + '_data.json', 'w', encoding='utf-8') as jsonfile: ...
from __future__ import print_function from pyspark import SparkContext import sys def mapper(w): arr = w.split(" ") return (arr[0], int(broadcastVectorSmall.value[int(arr[1])-1].split(" ")[1]) * int(arr[2])) if __name__ == "__main__": if len(sys.argv) != 4: print("Usage: matrix_small_c.py vectorf...
#!/usr/bin/python ''' Created on Apr 16, 2014 @author: Lee Khan-Bourne Template for calling Elasticsearch from within a CherryPy website Modify functions 'objects', 'search' and 'setup_routes' to suit your needs ''' import sys sys.stdout = sys.stderr import os, os.path import string import json import atexit i...
import torch import time from collections import OrderedDict # Using ryzen 3600 for benchmark (single core) compare to snapdragon 850 on HL2 # https://gadgetversus.com/processor/qualcomm-sdm850-snapdragon-850-vs-amd-ryzen-5-3600/ def test_cpu_inference(test_generator, model, params, best_model_str=None): # Force ...
# bubble def bubble(list1): tmpLen = len(list1) for i in range(tmpLen): for j in range(1, tmpLen - i): if list1[j] < list1[j-1]: list1[j], list1[j-1] = list1[j-1], list1[j] print(i, j, list1) return list1 # 找出字符串中第一个不重复的字符 def findFirstAlpha(s): tmps...
import bisect import decimal from collections import namedtuple from decimal import Decimal from typing import Counter, Dict, List, Tuple ArithmeticEncodingReturn = namedtuple( "ArithmeticEncodingReturn", "decimal probability_table end_of_sequence") def __init_range_table(probability_table:Dict[str,Decimal]): ...
############################################################################## # Parte do livro Introdução à Programação com Python # Autor: Nilo Ney Coutinho Menezes # Editora Novatec (c) 2010-2020 # Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8 # Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3 # Terce...
import unittest from deep_find_all import DFS, BFS class TestDeepSearch(unittest.TestCase): graph = {'A': ['D', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ...
# -*- coding: utf-8 -*- # # voldemort_manipulate.py # # Jan/27/2012 import voldemort import json import sys # # ------------------------------------------------------------ def voldemort_to_dict_proc (client): keys = {"t3051","t3052","t3053", "t3054","t3055","t3056", "t3057","t3058","t3059"} dict_aa = {} fo...
# this test file takes an encoded emai, decodes it, parese out order information and saves it to the database # also changes the status of the messages db from "need to scrape" to "scraped" # # # #required encoding for scraping, otherwise defaults to unicode and screws things up from bs4 import BeautifulSoup import req...
# APRENDENDO A UTILIZAR EIXOS NO NUMPY import numpy as np def titulo(texto=''): print('-' * 40) print(texto.upper().center(40)) print('-' * 40) ########################## # MATRIZES DE 1 DIMENSÃO # ########################## titulo('uma dimensão') one_dimensional = np.array([1, 1, 2, 3, 5]) print('Ma...
# Dynamic Programming Python implementation of Min Cost Path # problem R = 3 C = 3 def minCost(cost, m, n): # Instead of following line, we can use int tc[m+1][n+1] or # dynamically allocate memoery to save space. The following # line is used to keep te program simple and make it working #...
# encoding: utf-8 """ math ~~~~ This is an example for a parser that parses and evaluates mathematical expressions. :copyright: 2015 by Daniel Neuhäuser :license: BSD, see LICENSE.rst for details """ from __future__ import print_function import re import sys from operator import itemgetter fr...
# -*- coding: utf-8 -*- import sys import random def makerandomline(n = None): if n is None: n = random.randrange(1, 11) s = [random.randrange(100) for i in range(n)] s = [sum(s)] + s s = [str(x) for x in s] return ('\t'.join(s) + '\n').encode('utf-8') def generate(): with open('test1...
from django.db import models class ToDoList(models.Model): name = models.CharField(max_length=256, unique=True, db_index=True) # Natural key. def __str__(self): return self.name class ToDoItem(models.Model): title = models.CharField(max_length=256) # Allowing duplicates in the list. complet...
from . import asynconnect def set_timeout (timeout): for each in (asynconnect.AsynConnect, asynconnect.AsynSSLConnect, asynconnect.AsynSSLProxyConnect): each.keep_alive = timeout each.zombie_timeout = timeout
import os from django.conf import settings import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model, preprocessing import pandas as pd import numpy as np import matplotlib.pyplot as plt import datetime as dt companies_list = [ {'value':"AMBUJACEM", 'name':"Ambuja...
from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileAllowed, FileRequired from wtforms import IntegerField, SubmitField from wtforms.validators import InputRequired, NumberRange class UploadImage(FlaskForm): image = FileField( "Your Image", validators=[ FileRequir...
from django.test import TestCase from dojo.tools.fortify.parser import FortifyXMLParser from dojo.models import Test class TestFortifyParser(TestCase): def test_fortify_many_findings(self): testfile = "dojo/unittests/scans/fortify/fortify_many_findings.xml" parser = FortifyXMLParser(testfile, Tes...
# /*==========================================================*\ # | /=============================================\ | # | || - Code develop to compara two hands at - || | # | || - poker game and print who is the winner - || | # | || - Desafio Python - DATA H - || ...
import numpy as np def calculate_shift(void, wall, field, err_field): ''' Calculate the average and median shifts between the void and wall populations. Parameters: =========== void : astropy table of length n_void Table containing void galaxy parameters wa...
def middle(t): print("Array ", t) if len(t)>1: t.pop(0) t.pop() elif len(t)>0: t.pop() print("Middle of Array ",t) n = int(input("Size of array: ")) arr = [] for _ in range(n): arr.append(int(input("Array Element: "))) middle(arr)
import sys from os.path import dirname, abspath, join path = dirname(dirname(abspath(__file__))) sys.path.append(join(path, 'predict')) from flask import request, render_template, make_response, flash, redirect, url_for from flask import current_app as app from flask import Blueprint from flask_login import login_req...
import json import os.path from json import JSONDecodeError file_path = 'storage\\users.json' def create_user(): if not os.path.exists(file_path): with open(file_path, "w"): pass username = str(input('Username : ')).lower() password = str(input('Password : ')) try: access_l...
import frappe import json def get_context(context): if frappe.session.user != 'Guest': frappe.local.flags.redirect_location = '/' raise frappe.Redirect return context
from enum import Enum class Direction(Enum): LEFT = 1 UP = 2 RIGHT = 3 DOWN = 4 class Packet: xOffsets = { Direction.LEFT: -1, Direction.UP: 0, Direction.RIGHT: 1, Direction.DOWN: 0 } yOffsets = { Direction.LEFT: 0, Direction.UP: -1, Direction.RIGHT: 0, Direction.DOWN: 1 } def __init__(sel...
from django.contrib.auth.models import User from rest_framework import serializers from rest_framework.relations import PrimaryKeyRelatedField from logbook.models import Message, Category, Attachment class CategorySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Category fi...
""" @Time :2020/2/15 21:20 @Author : 梁家熙 @Email: :11849322@mail.sustech.edu.cn """ import json import random import os import logging import collections from pathlib import Path import torch from allennlp.modules.span_extractors import SpanExtractor, EndpointSpanExtractor from tqdm import tqdm from pprint import ...
"""Sigmoid-Bernoulli Restricted Boltzmann Machine. """ from typing import Optional, Tuple import torch import torch.nn.functional as F from learnergy.models.bernoulli import RBM from learnergy.utils import logging logger = logging.get_logger(__name__) class SigmoidRBM(RBM): """A SigmoidRBM class provides the ...