content
stringlengths
5
1.05M
import os, logging, sys from flask import Flask, render_template, redirect from flask_sqlalchemy import SQLAlchemy from flask_cors import CORS RESOURCES = "resources" app = Flask(__name__, static_folder=f"../{RESOURCES}/static", template_folder=f"../{RESOURCES}/templates", static_url_path='/') CORS(app) # Database ...
# -*- coding: utf-8 -*- import re from bs4 import BeautifulSoup def get_celebrity_info(node): celebrity_nodes = node.next_sibling.next_sibling.find_all('a') celebrities = [ { 'name': celebrity.string, 'douban_id': re.findall(r'\d+', celebrity['href'])[0] ...
import numpy as np import tensorflow as tf from model import PreferenceElicitationModel class TestGaussianProcess(tf.test.TestCase): @classmethod def setUpClass(cls): item_embeddings = np.zeros((2, 2)) cls.model = PreferenceElicitationModel(item_embeddings) def test_gather_subset(self):...
import sqlite3 conn = sqlite3.connect('BD_Dany_trab2AV1.db') cursor = conn.cursor() print('Peças com peso maior que 75 gramas:') cursor.execute(""" SELECT * FROM PECAS WHERE peso_peca > 0.75 ;""") for linha in cursor.fetchall(): print(linha) print('Projetos com orçamento menor que R$ 50.000,00:') cursor.execute...
from django.db import models class Room(models.Model): title = models.CharField(max_length=255) staff_only = models.BooleanField(default=False) def __str__(self): return self.title @property def group_name(self): return "room-%s" % self.id from django.contrib.auth.models import ...
""" BenchExec is a framework for reliable benchmarking. This file is part of BenchExec. Copyright (C) 2015 Daniel Dietsch 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 ...
from flask_restful_swagger import swagger def test_make_class_with_input_class(): class TestClass: pass assert swagger.make_class(TestClass) == TestClass def test_make_class_with_input_instance(): class TestClass: pass test_class = TestClass() assert swagger.make_class(test_cl...
from random import choice import nextcord from nextcord.ext import commands, tasks def get_category() -> str: list = ["playing", "watching", "listening"] return choice(list) def get_watching() -> str: list = [ "Itzy in Paris", "Secret48", "Everglowland", "Anything but Ag...
# -*- coding: utf-8 -*- from datetime import datetime from django.contrib.auth.models import User from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Video(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=25...
import itertools import numpy as np import pandas as pd import scipy.stats as st from mne.stats import fdr_correction def make_table(name, analysis, features, targets): pairs = list(itertools.product(features, targets)) table = pd.DataFrame(pairs, columns=["Feature", "Target"]) scores = [] subjects =...
# Capstone Python bindings, by Nguyen Anh Quynnh <aquynh@gmail.com> import arm, arm64, mips, x86 __all__ = [ 'cs', 'cs_insn', 'cs_disasm_quick', 'cs_version', 'CS_ARCH_ARM', 'CS_ARCH_ARM64', 'CS_ARCH_MIPS', 'CS_ARCH_X86', 'CS_MODE_LITTLE_ENDIAN', 'CS_MODE_BIG_ENDIAN', 'CS_...
from django.conf.urls import url from . import views from rest_framework.routers import DefaultRouter urlpatterns = [ ] router = DefaultRouter() router.register('areas', views.AreaViewSet, base_name='areas') urlpatterns += router.urls
# run in terminal: sudo apt install python3-pip # then run: pip3 install fastbook # also run: pip3 install graphviz import os import random import fastbook fastbook.setup_book() from fastai.vision.all import * path = Path() if len(sys.argv) >= 2: SAMPLE_SIZE = int(sys.argv[1]) else: print('Please input a sample...
import re import random from datetime import datetime, timedelta import time from functools import reduce import traceback import struct import json import urllib from hashlib import blake2b # Copied and Modified from Jumpscale # TODO: Remove def blake2(s, digest_size=32): if isinstance(s, str): # check string di...
from babysitter import *
#! /usr/bin/python import os import sys import json import luigi import numpy as np import nifty.tools as nt import cluster_tools.utils.volume_utils as vu import cluster_tools.utils.function_utils as fu from cluster_tools.utils.task_utils import DummyTask from cluster_tools.cluster_tasks import SlurmTask, LocalTask,...
#!/usr/bin/env python """Tests for the jwcf hawki module. Authors ------- Johannes Sahlmann """ import netrc import os from astropy.table import Table import pytest from ..archive_helpers import get_exoplanet_orbit_database, gacs_list_query local_dir = os.path.dirname(os.path.abspath(__file__)) ON_TRAVIS = os...
import re from abc import abstractmethod from typing import List, Optional, Dict, Pattern, Union import html import serpy from manifest_server.helpers.fields import StaticField from manifest_server.helpers.identifiers import get_identifier, IIIF_V3_CONTEXT from manifest_server.helpers.serializers import ContextDictSe...
"""Auto-generated file, do not edit by hand. RE metadata""" from phonenumbers.phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_RE = PhoneMetadata(id='RE', country_code=262, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='[268]\\d{8}', possible_number...
# coding=utf-8 # Adapted from Ravens - Transporter Networks, Zeng et al., 2021 # https://github.com/google-research/ravens """Transport ablations.""" import numpy as np import torch import torch.optim as optim import torch.nn as nn import torch.nn.functional as F from einops.layers.torch import Rearrange from ravens...
# Generated by Django 2.1.7 on 2019-03-15 01:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('gonderiler', '0001_initial'), ] operations = [ migrations.CreateModel( name='Duyurular', fields=[ ('...
# Copyright 2020, Battelle Energy Alliance, LLC # ALL RIGHTS RESERVED """ Values that are expressed as linear ratios of one another. Primarily intended for transfer functions. """ from .ValuedParam import ValuedParam, InputData, InputTypes # class for custom dynamically-evaluated quantities class Linear(ValuedPar...
################################################################## # BrundleFuzzServer.py # This implements all mutation intelligence ################################################################## from array import array from ConfigParser import SafeConfigParser from datetime import datetime from Queue import Prio...
# -*- coding:UTF-8 -*- # [1*1,2*2,...10*10] L = [x*x for x in list(range(1,11))] print(L) # 我们只想要偶数的平方,不改动range()的情况下,可以加if来筛选 L2 = [x*x for x in list(range(1,11)) if x%2 == 0] print(L2) ''' 编写一个函数,它接受一个list,然后把list中的所有字符串变成大写后返回, 非字符串元素将被忽略 提示: 1.isinstance(x,str)可以判断变量x是否是字符串; 2.字符串的upper()方法可以返回大写的字母 ''' def ...
from selfdrive.controls.lib.pid import PIController from selfdrive.controls.lib.drive_helpers import get_steer_max from cereal import car from cereal import log from selfdrive.virtualZSS import virtualZSS_class class LatControlPID(object): def __init__(self, CP): self.pid = PIController((CP.lateralTuning.pid.kpB...
import copy import uuid from typing import Union from stepist.flow.steps.next_step import call_next_step as stepist_next_step from stepist.flow.utils import validate_handler_data from stairs.core.pipeline.pipeline_objects import (PipelineFlow, PipelineFlowProducer, ...
# -*- coding: utf-8 -*- import numpy as np import pywt # Solves # min 1/2||Ax-b||_2^2 + lmbd||x||_1 # Pass data (A,b,lmbd) to Lasso_NewtonADMM #Objective function def lasso(A,b,x,lmbd): return 0.5 * np.linalg.norm(A.dot(x)-b)**2 \ +lmbd * np.linalg.norm(x,ord=1) #Softthresholding f...
import logging import os from unittest.mock import patch import requests from django.conf import settings from django.test import TestCase, override_settings from eventkit_cloud.utils.geocoding.geocode_auth import ( get_auth_headers, CACHE_COOKIE_KEY, CACHE_TOKEN_KEY, CACHE_TOKEN_TIMEOUT, update_s...
__author__ = 'Max' import mandrill from HRMS.settings import MANDRILL_API_KEY mandrill_client = mandrill.Mandrill(MANDRILL_API_KEY) def send_mail(template_name, email_to, context): message = { 'to': [], 'global_merge_vars': [] } for em in email_to: message['to'].append({'email': e...
from Certmon import app with app.test_client() as c: response = c.get('/') assert response.status_code == 200
n = int(input()) n0 = 2 n1 = 1 if n == 1: print(1) else: for _ in range(1, n): n0, n1 = n1, n0+n1 print(n1)
#importar librerías import scipy.io as sio import numpy as np import matplotlib.pyplot as plt import math from scipy.stats import kurtosis, skew from numpy import mean, sqrt, square rod_sin_falla = sio.loadmat('sano-C-1.mat')['Channel_1'] rod_con_falla_pist_ext = sio.loadmat('pista_externa-C-1.mat')['Channel_1'] rod_...
""" Utils for the library. """
#!/usr/bin/env python import unittest import os import json from app import create_app from app import util class TestHeathenLed(unittest.TestCase): def setUp(self): self.app = create_app(config_name="testing") self.client = self.app.test_client self.util = util def test_load_file_json...
import random from src.Dominion.Cardtypes.Actioncard import Actioncard class Militia(Actioncard): EXPENCES = 4 CARDS = 0 ACTIONS = 0 BUYS = 0 MONEY = 2 # Every other Player discards down to 3 cards in hand def specialAction(self, player, game): if player.canBeAttacked: ...
import sys import h5py from matplotlib import pyplot # Parameters from command-line, type-safe input_fname, ds_x, ds_y, output_fname, x_log, y_log = sys.argv[1:] x_log, y_log = int(x_log), int(y_log) with h5py.File(input_fname) as f: x, y = f[ds_x][()], f[ds_y][()] xlabel, ylabel = ds_x.strip('/'), ds_y.strip('...
### Defined thai letters and numbers thaiAlpha = [' ', 'า', 'บ', 'ซ', 'ด', 'แ', 'ฟ', 'ก', 'ห', 'ิ', 'จ', 'ฅ', 'ล', 'ม', 'น', 'อ', 'ภ', 'ข', 'ร', 'ส', 'ต', 'ึ', 'ฟ', 'ว', 'x', 'ย', 'ฉ'] # th thaiNumber = ['๑', '๒', '๓', '๔', '๕', '๖', '๗', '๘', '๙', '๐'] # th ### Defined lating letters and numbers latinAlpha = [' ', 'a...
# -*- coding: UTF-8 -*- """ .. --------------------------------------------------------------------- ___ __ __ __ ___ / | \ | \ | \ / the automatic \__ |__/ |__/ |___| \__ annotation and \ | | | | \ ...
import discord from discord.ext import commands import random import json import os import asyncio intents = discord.Intents.default() intents.members = True client = commands.Bot(command_prefix='Prefix', intents = intents) f = open("rules.txt","r") rules = f.readlines() filter...
import sys import os.path from pathlib import PosixPath import argparse from .env import Environment from .biome import Biome from .runner import Runner from .stage import build_stages def _exit(status): exit_code = 0 if status else 1 sys.exit(exit_code) TRUTHY = [ 'y', 'yes' ] def _confirm(msg, defau...
"""Test methods for scores.""" import numpy as np from slub_docsa.common.subject import SubjectHierarchy, SubjectNode from slub_docsa.evaluation.score import cesa_bianchi_h_loss def test_cesa_bianchi_h_loss(): """Test h-loss for specific example hierarchy and incidence matrices. Subject Hierarchy - sub...
import time #response collecting function def response(prompt, allowed): resp = input(prompt) #check to see if response is in the set of allowed responses if resp in allowed: #return it if it is return resp else: #call response() again if it is not print('Your answer mus...
import pytest from django.urls import reverse, resolve pytestmark = pytest.mark.django_db def test_index(): assert ( reverse("product_browser:index") == f"/tools/product_browser/" ) assert resolve(f"/tools/product_browser/").view_name == "product_browser:index" def test_detail(pk: int =...
""" The range function returns an iterator which can be used for looping through. Syntax of the range function is range(start (default=0, end required, step default=1) range(10) will loop from 0 to 9 onestep at a time 0,1,2,3,4,5,6,7,8,9, range(n) will go from 0 to n-1 range(2,5) will go 2,3,4, range(start,end) will ...
# Copyright (C) 2012-2015, Alphan Ulusoy (alphan@bu.edu) # # 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 later version. # # This pr...
__author__ = 'Devesh Bajpai' ''' https://codeforces.com/problemset/problem/1244/A Solution: If we have to take m notes and one stationary item can write n notes, the no. of those stationary items needed is ceil(m/n) = (m + n - 1) / n. This way we calculate the minimum pens and pencils needed. If their sum is <= k, we...
# Name: WEH002004 driver # Author: marksard # Version: 2.0 # Python 3.6 or later (maybe) # WinSTAR OLED Display 20x4 WEH002004A (using controller WS0010) # datasheet (http://blog.digit-parts.com/pdf/ws0010.pdf) # Use WS0010 4bit mode # *************************** import RPi.GPIO as GPIO import time ...
""" Manage the Websocket 'opcode' enumerations. Not using enum34 purely to keep dependencies to a minimum. """ from __future__ import print_function from __future__ import unicode_literals class Opcode(object): """Enumeration of websocket opcodes.""" CONTINUATION = 0 TEXT = 1 BINARY = 2 RESE...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/colin/dev/pyQode/pyqode.core/forms/pnl_encoding.ui' # # Created by: PyQt5 UI code generator 5.5.1 # # WARNING! All changes made in this file will be lost! from pyqode.qt import QtCore, QtGui, QtWidgets class Ui_Form(object): def ...
# Copyright 2018 The Cirq Developers # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
# -*- coding: utf-8 -*- ################################################################################ # Copyright (c) 2015-2018 Skymind, Inc. # # This program and the accompanying materials are made available under the # terms of the Apache License, Version 2.0 which is available at # https://www.apache.org/license...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 28 05:43:13 2020 @author: ayman """ from types import SimpleNamespace HYPERPARAMS = {'lander': SimpleNamespace(** {'env_id': 'LunarLanderContinuous-v2', 'n_envs': 8,...
""" Notify the owner of repository of accessibility errors found, through Github issues. """ from django.conf import settings from django.core.management.base import BaseCommand from django.template.loader import get_template from django.utils.translation import gettext as _ from github import Github from wapyce.acc...
import daisy import neuroglancer import numpy as np import sys import zarr from funlib.show.neuroglancer import add_layer, ScalePyramid neuroglancer.set_server_bind_address('0.0.0.0') input_file = sys.argv[1] raw = [ daisy.open_ds(input_file, 'volumes/raw/s%d' % s) for s in range(6) ] relabelled = [ da...
''' High-level functions and classes for solving a wide variety of economic models. The "core" of HARK is a framework for "microeconomic" and "macroeconomic" models. A micro model concerns the dynamic optimization problem for some type of agents, where agents take the inputs to their problem as exogenous. A macro mod...
from django.test import TestCase, RequestFactory from django.contrib.auth.models import AnonymousUser, User from django.contrib.sessions.middleware import SessionMiddleware from .mixins import TwoUserMixin, ProposalGroupMixin, ViewMixin, ProposalMixin from django.utils import timezone from django.core.exceptions import...
from django.shortcuts import render from rest_framework import filters from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from mining.models import * from iitkgp.serializers import * from rest_framework import generics class DepartmentList(ge...
import re import requests content = requests.get('http://www.pythonchallenge.com/pc/def/equality.html').text notes = re.search('<!--(.*?)-->', re.sub('\n', '', content)) if notes: ret = re.findall('[a-z]+[A-Z]{3}([a-z])[A-Z]{3}[a-z]+', notes.group()) print(ret) # 答案:linkedlist
#!/usr/bin/python2 """Module to encode/decode Game Genie codes. The algorithm used to decode was taken from info available at http://tuxnes.sourceforge.net/gamegenie.html See file LICENSE for license information. """ # Mapping and reverse mapping of Game Genie letters to nibbles code2letter = [ 'A', 'P',...
import asyncio import json from typing import List from didsdk.exceptions import TransactionException from didsdk.jwt.jwt import Jwt from iconsdk.builder.transaction_builder import Transaction from iconsdk.exception import JSONRPCException from iconsdk.icon_service import IconService from iconsdk.signed_transaction im...
import random from enum import IntEnum, auto from typing import Union from ..utils.geometry import Vector, Rectangle class Canvas: __slots__ = ('canvas', 'width', 'height') def __init__(self, width, height, default: Union[bool, 'Tile'] = False): self.width = width self.height = height ...
""" Copyright (c) 2017-2019 Starwolf Ltd and Richard Freeman. 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. A copy of the License is located at http://www.apache.org/licenses/LICENSE-2.0 or in the "license" file acc...
import os from django.db.models.signals import pre_delete, post_save, post_init from django.dispatch import receiver from django.conf import settings from maltose.article.build import update_all from .models import FriendLink @receiver(post_save, sender=FriendLink) def post_update_article(sender, instance, **kwarg...
from math import radians, sin, cos, sqrt, atan2, degrees import decimal """ This module contains functions to perform calculations on latitude and longitude coordinates. """ def get_distance(lat1, lon1, lat2, lon2, unit='miles'): """ Calculate the distance between two points on Earth given their latitude and longit...
#subtraction program def sub(a,b): return(a-b) d=sub(4,2) print(d)
# Generated by Django 2.0.2 on 2018-08-12 09:55 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0030_auto_20180811_1620'), ] operations = [ migrations.CreateModel( name='currentData', fiel...
#!/anaconda/bin/python import logging, re, os, sys, threading, time, warnings, subprocess, numpy#, matplotlib import matplotlib.pyplot as plt from scipy import stats as stats from matplotlib.backends.backend_pdf import PdfPages class SaxsPlot(): """Plots saxs data in various ways The SaxsPlot libraries a...
from utils import fm import inquirer from utils.colors import * tasks = fm.get() def textAsk(title, message): questions = [ inquirer.Text(title, message) ] answer = inquirer.prompt(questions) return answer[title] def updateTask(id, description): for task in tasks: if task.id == id: ...
from typing import Union import h5py import numpy as np from tensorflow.keras.models import Model, load_model from utils import load_dataset def save_predictions(model: Union[str, Model], dist: str) -> None: """Save predictions as h5 Args: model (Union[str, Model]): model save location or model ins...
integers = [1, 2, 3, 4, 5] # using lambda print(list(map(lambda x: x + 1, integers))) # using function def increase_by_one(n): return n + 1 print(list(map(increase_by_one, integers)))
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
dia = input("Em que dia você nasceu?") mes = input("Em que mês você nasceu?") ano = input("Em que ano você nasceu?") print("Você nasceu no dia {} do mês {} no ano de {}.".format(dia, mes, ano))
from collections import OrderedDict from typing import Any, Dict, Optional, Union import numpy as np from gym import GoalEnv, spaces from gym.envs.registration import EnvSpec from stable_baselines3.common.type_aliases import GymStepReturn class BitFlippingEnv(GoalEnv): spec = EnvSpec("BitFlippingEnv-v0") d...
import dash # contains widgets that can be dropped into app import dash_core_components as dcc import dash_html_components as html import plotly.graph_objs as go from dash.dependencies import Input, Output, State import pandas as pd import pickle # new imports !pip install basilica import basilica import numpy as np ...
""" Tool for collect artifacts for taxbreak program @author Kamil Luczak """ import sys from os import getcwd from git import Repo from .modules.argument_parser import ArgumentParser from .modules.artifacts_collector import Collector from .modules.writer import Writer def read_user(repo): """ Returns user name...
import logging from discord import Embed from discord.ext.commands import Bot from bot.constants import Channels, DEBUG_MODE log = logging.getLogger(__name__) class Logging: """ Debug logging module """ def __init__(self, bot: Bot): self.bot = bot async def on_ready(self): lo...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import json import warnings import pulumi import pulumi.runtime from typing import Union from .. import utilities, tables class Source...
""" Test output formatting for Series/DataFrame, including to_string & reprs """ from datetime import datetime from io import StringIO import itertools from operator import methodcaller import os from pathlib import Path import re from shutil import get_terminal_size import sys import textwrap import dateutil import ...
import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit, QLabel from PyQt5.QtCore import pyqtSlot from PIL import Image import numpy as np from keras.models import load_model import pickle as pkl import csv model= load_model("trafficModel.h5") labels= pkl.load(open("labels.pickle", "rb")) ...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: doc_details.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _r...
# Find this puzzle at: # https://adventofcode.com/2020/day/11 with open('input.txt', 'r') as file: puzzle_input = file.read().splitlines() occupied = 0 puzzle_input_old = [] def check_seat(y, x, lst): """ Check seat value in a given list. Args: y: The column index of the seat. x: The...
### auto - cut off # ppt文件自动拆条, 打小标题 import time from boto3.session import Session import json import cv2 import numpy from PIL import Image, ImageDraw, ImageFont import boto3 from botocore.config import Config import pandas as pd import os config = Config( read_timeout=120, retries={ 'max_attempts': ...
# Copyright (c) 2001-2008 Twisted Matrix Laboratories. # See LICENSE for details. """ Twisted Protocols: a collection of internet protocol implementations. Many of the protocols found in this package have been moved after the package split in Twisted 2.0. This means you will get a C{DeprecationWarning} if you try to...
#!/usr/bin/env python # -*- coding: utf-8 -*- from disemvoweler import Disemvoweler class TestDisemvoweler: def test_disemvowel_cymbal(self): """ Test 1 """ disem = Disemvoweler() voweled_input = "two drums and a cymbal fall off a cliff" expected = "twdrmsndcymblfll...
""" skeleton word classification model for flask admin app """ from . import db from datetime import datetime class WordClassification(db.Model): __tablename__ = 'word_classification' id = db.Column(db.Integer, primary_key=True, autoincrement=True) classification = db.Column('word_classifica...
import unittest from unittest.mock import patch from tmc import points from tmc.utils import load_module, reload_module, get_stdout from functools import reduce from random import randint exercise = 'src.alphabetically_last' def format_tuple(d : tuple): return str(d).replace("'","") @points('2.alphabetically_la...
# flake8: noqa F401 from .doc_utils import (generate_dirac_images, contour_coefs, gaussian_design, inspector_mtw)
from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static # jwt urls from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, TokenVerifyView ) # end of jwt urls urlpatterns = [ path('admin/', a...
from pathlib import Path from fud.stages import SourceType, Stage from fud.utils import shell class SystolicStage(Stage): """ Stage that invokes the Systolic Array frontend. """ name = "systolic" def __init__(self): super().__init__( src_state="systolic", target_...
from flask import Flask, render_template, request from flask_jsonrpc import JSONRPC from lib import checkName, makeSeed, makeUniqueID application = Flask(__name__) rpc = JSONRPC(application, '/api', enable_web_browsable_api=True) @application.route("/") def index(): return render_template('index.html') @applicat...
import numpy try: import cupy CUPY_CUDA_AVAILABLE = True except ImportError: CUPY_CUDA_AVAILABLE = False global backend backend = numpy def set_backend(name: str): """ Set the backend for the simulations This way, all methods of the backend object will be replaced. Args: name: name of...
from collections import namedtuple RGB = namedtuple("RGB", "red, green, blue") COLORS = { "red": RGB(255, 0, 0), "orange-deep": RGB(255, 40, 0), "orange": RGB(255, 120, 0), "yellow": RGB(255, 200, 0), "yellow-acid": RGB(160, 255, 0), "green": RGB(0, 255, 0), "green-forest": RGB(34, 139, 34...
# coding=utf-8 import os import sys def search(dir, file_list): newDir = dir if os.path.isfile(dir): file_list.append(dir) elif os.path.isdir(dir): for i in os.listdir(dir): newDir = os.path.join(dir, i) search(newDir, file_list) return file_list ...
import logging import os from sys import platform from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait class ResponseExecutor(object): """ This cla...
import argparse as _argparse import re def fix_higgs_paper(path, output='/Users/joelfrederico/Thesis/overleaf/Dissertation.bib'): print('Path: {}'.format(path)) print('Output: {}'.format(output)) punctuation = {0x2018: 0x27, 0x2019: 0x27, 0x201C: 0x22, 0x201D: 0x22} # ===============================...
import bpy import os import platform import sys import webbrowser import re from ..rfb_logger import rfb_log from .prefs_utils import get_pref from .envconfig_utils import envconfig def view_file(file_path): rman_editor = get_pref('rman_editor', '') if rman_editor: rman_editor = get_real_path(rma...
"""Utility functions for strategy detection.""" import datetime import logging import math _LOGGER = logging.getLogger(__name__) def first_building(building, player): """Find when the first building of a given type was constructed.""" for item in player['build']: if item['building'] == building: ...
from ciscoconfparse import CiscoConfParse def main(): cisco_ios = CiscoConfParse("cisco_ipsec.txt") crypto_map = cisco_ios.find_objects(r'crypto map') for child in crypto_map: print child.text for i in child.children: if "AES" in i.text: print i.text if __name__ =...
import os from histomicstk.cli.utils import CLIArgumentParser def main(args2): #cmd = "python3 ../PodoSighter_pix2pix_folder/Complete_Pix2pix_Prediction.py -A0 '{}' -A1 '{}' -A2 '{}' -A3 '{}' -A4 '{}' -A5 '{}' -A6 {} -A7 {} -A8 {} -A9 '{}' -A10 '{}' -A11 {}".format(args2.inputFolder, args2.input...
hash_table = list([0 for i in range(8)]) def get_key(data): return hash(data) def hash_function(key): return key % 8 def save_data(data, value): index_key = get_key(data) hash_address = hash_function(index_key) if hash_table[hash_address] != 0: for index in range(hash_address, len(hash_table)): i...