content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- # Copyright © 2017 Kevin Thibedeau # Distributed under the terms of the MIT license import os import math import cairo from .shapes import * try: import pango import pangocairo use_pygobject = False except ImportError: import gi gi.require_version('Pango', '1.0') gi.require_versi...
import os import subprocess import pickle import sys #Give input as path to folder contaiing pairs file path=sys.argv[1] def longestSubstringFinder(string1, string2): answer = "" len1, len2 = len(string1), len(string2) for i in range(len1): match = "" for j in range(len2): if (...
import xml.etree.ElementTree as Et class BusLocation: def __init__(self, bus_arrival_item: dict): self.route_id = bus_arrival_item['routeId'] self.station_id = bus_arrival_item['stationId'] self.station_seq = bus_arrival_item['stationSeq'] self.end_bus = bus_arrival_item['endBus'] ...
from django.test import TestCase from django.urls import resolve, reverse from ..models import Post from ..views import PostListView class PageTests(TestCase): """page view tests""" def setUp(self): self.post = Post.objects.create(title='Vasyan', post_text='blog', ...
import logging import asyncio import collections import homeassistant.helpers.config_validation as cv import voluptuous as vol from homeassistant.helpers import aiohttp_client _LOGGER = logging.getLogger(__name__) DOMAIN = 'grohe_sense' CONF_REFRESH_TOKEN = 'refresh_token' CONFIG_SCHEMA = vol.Schema( { ...
# Generated by Django 2.0.9 on 2019-07-19 18:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('maps', '0003_auto_20190716_2152'), ] operations = [ migrations.AlterField( model_name='stop', name='comments', ...
import dash import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc import dash_table import time import datetime import json import pandas as pd import numpy as np import os from dash.dependencies import Input, Output, State # from server import app, server q...
# -*- coding: utf-8 -*- from django.conf import settings from django.core.exceptions import PermissionDenied from django.http import Http404 from django.core.files.base import File from django.core.files.storage import get_storage_class from . import servers import logging logger = logging.getLogger(__name__) from im...
import unittest import os from ..testing import TINYMCE_LATEX_INTEGRATION_TESTING try: from Products.CMFPlone.utils import get_installer except ImportError: get_installer = None class TestSetup(unittest.TestCase): """Test that this is properly installed.""" layer = TINYMCE_LATEX_INTEGRATION_TESTING...
model = { "schema": { "title": { "type": "string", "regex": "^[a-z0-9]+(?:-[a-z0-9]+)*$", "required": True, "unique": True, "minlength": 0, "maxlength": 400, "_metadata": { "order": 1, "help":...
"""Test runway.core.providers.aws.s3._helpers.sync_strategy.base.""" # pylint: disable=no-self-use from __future__ import annotations import datetime from typing import TYPE_CHECKING, List, Optional, cast import pytest from mock import Mock from runway.core.providers.aws.s3._helpers.file_generator import FileStats f...
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import Length, Email, EqualTo, DataRequired, ValidationError from market.models import User class RegisterForm(FlaskForm): username = StringField(label="username", validators=[Length(min=6, max=30),...
# Copyright 2019 Atalaya Tech, Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, ...
from django.contrib import admin from .models import Account, Category admin.site.register(Account) admin.site.register(Category)
from thefuzz import fuzz, process import pandas as pd colors_list = pd.read_csv('colors.csv', names=['Color', 'R', 'G', 'B']) def getFuzzyColor(color_name): # we want a 85% match for thefuzz fuzzyMatch = process.extractOne(color_name.title(), colors_list['Color'], scorer=fuzz.token_sort_ratio) fuzz_color...
from winejournal.blueprints.filters.filters import filters
#-*-coding:utf-8-*- import sys from flask import Flask,request,render_template import json from etc.settings import DEBUG,receiver_file,register_server_port,web_log,LOG_DIRECTORY,RESOURCES_DIRECTORY from threading import Lock from os import remove, devnull from shutil import move from logger import * app=Flask(__name...
from django.conf.urls import url, include from . import views from gallery import views as gallery_views from files import views as files_views urlpatterns = [ url(r'^$', views.GroupListView.as_view(), name='list'), url(r'^(?P<group_id>[0-9]+)/?$', views.GroupFeedView.as_view(), name='feed'), url(r'^(?P<gr...
import json import boto3 import os #required to fetch environment varibles TASK_NAME_FILTER = os.environ['task_name_filter'] ssmclient = boto3.client('ssm') def lambda_handler(event, context): eventdetail = event['detail'] eventmwid = eventdetail['window-id'] eventmwtaskid = eventdetail['window-task...
import numpy as np from nanogui import nanovg as nvg from misc import * import copy def draw_coord_system(ctx): ctx.StrokeColor(nvg.RGB(0, 0, 0)) ctx.StrokeWidth(0.005) for i in range(-100, 101): ctx.BeginPath() ctx.MoveTo(-1000.0, float(i)) ctx.LineTo(+1000.0, float(i)) ct...
from frequency_plan import Frequency from enum import Enum class CN470_510(Frequency): JOIN_ACCEPT_DELAY = 5 MAX_FCNT_GAP = 16384 ADR_ACK_LIMIT = 64 ADR_ACK_DELAY = 32 ACK_TIMEOUT = 2 # 2 +/-1 s random delay between 1 and 3 seconds RF_CH = 0 class DataRate(Enum): SF12BW125 = 0...
#IMPORTS @IMPORTS #GLOBAL @GLOBAL #PARAMETER @PARAMETER #LOCAL @LOCAL #PROCEDURE @PROCEDURE
#!/usr/bin/env python # encoding: utf-8 ################################################################## submit_scripts = { 'Slurm': { # Gaussian09 on C3DDB 'gaussian': """#!/bin/bash -l #SBATCH -p defq #SBATCH -J {name} #SBATCH -N 1 #SBATCH -n 8 #SBATCH --time={t_max} #SBATCH --mem-per-cpu 45...
""" Augmenter that apply operation (word level) to textual input based on back translation. """ import string import os import torch from nlpaug.augmenter.word import WordAugmenter import nlpaug.model.lang_models as nml BACK_TRANSLATION_MODELS = {} def init_back_translatoin_model(model_src, from_model_name, to...
import numpy as np import yfinance as yf import datetime as dt from pandas_datareader import data as pdr yf.pdr_override() # Pulls data[Ticker symbol, market price] for selected stock and appends to data array def getStockData(stock, data): # Set date range for api pull now=dt.datetime.now() if (dt.dateti...
''' MFEM example 3 See c++ version in the MFEM library for more detail ''' from mfem import path import mfem.ser as mfem from mfem.ser import intArray from os.path import expanduser, join import numpy as np from numpy import sin, array freq = 1.0 kappa = np.pi*freq static_cond = False order = 1 meshfile = exp...
# -*- coding: utf-8 -*- """ Created on Sun May 6 22:39:51 2018 @author: fhp7 """ import numpy as np # for each OD pair of nodes: # while not yet at the end of the path # find length of edge between cur_node and prev_node # add the edge length to the total edge length counter # if this...
import yaml import requests import os from slugify import slugify class _DataObject(object): def __getattr__(self, k): return self.data.get(k) class SiteCollection(object): def __init__(self, directory): self.sites = [] for site_file in os.listdir(directory): with open(os.path.join(directory, site_file...
########################################################################### ## Class hydroshare_resource_editor ########################################################################### import wx import wx.xrc from Utilities.HydroShareUtility import HydroShareAccountDetails, HydroShareUtility from WxUtilities import...
import json import logging import os import parmed import yaml from simtk import unit from simtk.openmm import app from blues import reporters, utils class Settings(object): """ Function that will parse the YAML configuration file for setup and running BLUES simulations. Parameters ---------- ...
f = open("input.txt", "r") input = f.read() floor = 0 for i in range(len(input)): if input[i] == '(': floor += 1 elif input[i] == ')': floor -= 1 if floor == -1: print "part 2: floor -1 at", i + 1 print floor
#!/usr/bin/env python from lobe import ImageModel model = ImageModel.load('path/to/exported/model') # Predict from an image file result = model.predict_from_file('path/to/file.jpg') # Predict from an image url result = model.predict_from_url('http://url/to/file.jpg') # Predict from Pillow image from PIL import Imag...
import datetime from constants.common_constants import DEFAULT_FALSE_FLAG, DEFAULT_TRUE_FLAG from models import session from models.book import Book, UserBookMapping, BookType from utils.log_handler import function_logger def get_number_of_books_charge(user_id=None): now = datetime.datetime.now() book_detail...
from snovault import ( calculated_property, collection, load_schema, ) from .base import ( Item ) @collection( name='individuals', unique_key='accession', properties={ 'title': 'Individuals', 'description': 'Listing of Individuals', }) class Individual(Item): item_t...
from typing import Dict, List, Tuple day_num = "03" day_title = "Spiral Memory" INPUT = 312051 up = 1 left = 2 down = 3 right = 4 def rotateLeft(dir: int) -> int: if dir == up: return left elif dir == left: return down elif dir == down: return right elif dir == right: ...
import sys def get_number(seq): return int("".join(map(str, seq))) def run_phase(input_seq): sums = [0] for n in input_seq: sums.append(sums[-1] + n) out = [] for digit_idx in range(len(input_seq)): multiplier = 1 group_start = digit_idx group_size = digit_idx + 1...
import numpy as np import nltk import re import pandas as pd import os import pickle import csv from pythainlp import word_tokenize from pythainlp.corpus import thai_stopwords from nltk.stem.porter import PorterStemmer from stop_words import get_stop_words from string import punctuation from sklearn.preprocessing im...
"""JSPEC Testing Module for matching JSPEC documents errors. """ from test.matcher import JSPECTestMatcher from jspec.entity import ( JSPEC, JSPECObject, JSPECArray, JSPECIntPlaceholder, JSPECRealPlaceholder, JSPECNumberPlaceholder, ) class JSPECTestMatcherError(JSPECTestMatcher): """Clas...
from lib import actions class SetFanAction(actions.BaseAction): def run(self, state, structure=None, device=None): target_state = True if state == 'on' else False if structure and device: nest = self._get_device(structure, device) nest.fan = target_state else: ...
###################################################### # # BioSignalML Management in Python # # Copyright (c) 2010-2013 David Brooks # # 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 # # ...
import traceback import sys class ConsistentHashing(object): def __init__(self,hash_func=hash, num_replicas=1): self.__hash=hash_func self.__numReplicas=num_replicas self.__hashCircle={} self.__keys=[] def keys(self): return self.__keys def hash_circles(self): return self.__hashCircle def node_size(se...
from django.db.models import Max from django.shortcuts import render def index(request): return render(request, 'core/index.html') def mapa(request): return render(request, 'core/mapa.html')
"""Syntax highlighter for Markdown markup language.""" from __future__ import annotations from prettyqt import core, gui, syntaxhighlighters BASE_FONT = 12.0 class Rule(syntaxhighlighters.HighlightRule): font_size = BASE_FONT class Link(Rule): regex = r'\[(.+)\]\(([^ ]+)( "(.+)")?\)' color = "#61AFE...
import praw # fill in your reddit stuff here. reddit = praw.Reddit(client_id='', client_secret='', user_agent='', username='') def scrap(sub): subreddit = reddit.subreddit(sub) meme = subreddit.random() return meme.url, meme.author, meme.permalink
from datetime import datetime, timedelta, time from pyiso.base import BaseClient import copy import re from bs4 import BeautifulSoup import time import pdb # PRC_LMP # PRC_HASP_LMP # PRC_RTPD_LMP # PRC_INTVL_LMP # PRC_AS - All Ancillary Services for Region and Sub-Regional Partition. Posted hourly in $/MW for the DAM ...
from re_calc.util import is_number, every import unittest class TestInputProcessing(unittest.TestCase): def test_is_number(self): self.assertTrue(is_number('4.0')) self.assertFalse(is_number('*')) def test_every(self): numbers_list = [1, 2, 4, 5] result = every(lambda x: x % ...
""" Dovecot dict proxy implementation """ import asyncio import logging import json class DictProtocol(asyncio.Protocol): """ Protocol to answer Dovecot dict requests, as implemented in Dict proxy. Only a subset of operations is handled properly by this proxy: hello, lookup and transaction-based set. ...
import numpy as np import matplotlib.pyplot as plt def ROC_plot(state, scores, threshold=None, color=None, legend_on=True, label="predict", base_line=True, linewidth=1.0): """ Plot ROC curve and calculate the Area under the curve (AUC) from the with the prediction scores and true labels. ...
import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * ''' IMPORTS ''' import json import requests from typing import List, Dict # Disable insecure warnings requests.packages.urllib3.disable_warnings() ''' GLOBALS/PARAMS ''' USERNAME = demisto.params().get('credentials'...
import unittest from awstin.dynamodb.orm import Attr, DynamoModel, Key, list_append from awstin.dynamodb.testing import temporary_dynamodb_table class MyModel(DynamoModel): _table_name_ = "temp" pkey = Key() an_attr = Attr() another_attr = Attr() set_attr = Attr() third_attr = Attr() ...
from dnnv.properties import * import numpy as np N = Network("N") x = Image(__path__.parent / "dave_small_image9.npy")[None] / 255.0 input_layer = 0 output_layer = -2 epsilon = Parameter("epsilon", type=float) / 255.0 gamma = Parameter("gamma", type=float, default=15.0) * np.pi / 180 output = N[input_layer:](x) gamma...
# Copyright (c) 2014 Evalf # # 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 rights # to use, copy, modify, merge, publish, distribute, s...
import numpy as np from openiva.commons.facial import get_transform_mat,warp_img,l2_norm,face_distance,sub_feature MEAN_PTS_5=np.array([[0.34191607, 0.46157411], [0.65653392, 0.45983393], [0.500225 , 0.64050538], [0.3709759 , 0.82469198], [0.63151697, 0.82325091]]) INDS_68_5=[36, 45, 3...
def f(x): """ :rtype: object """ pass def g(x): y = x f(x) # (1) f(y) # (2)
import dash_html_components as html import dash_core_components as dcc import pandas as pd import pathlib import io import requests def get_code(): code = html.Div( [ html.H1("Example Static Tab"), dcc.Graph( id='example-graph', figure={ ...
""" cs_modals.py - Creates modal dialogs for the child support slash command. Copyright (c) 2020 by Thomas J. Daley, J.D. """ import json import math import re class CsModals(object): @staticmethod def param_modal(trigger_id: str) -> dict: return CsModals.load_view('cs_params_view', trigger_id) ...
from pymongo import MongoClient import os from influxdb import InfluxDBClient import time import datetime mongopwd = os.environ["MONGOPASS"] mongourl = "mongodb://pax:{}@xenon1t-daq.lngs.infn.it:27017/run".format(mongopwd) client = InfluxDBClient(host='influxdb', port=8086,) dbs = client.get_list_database() print(d...
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' \file genCompileScript.py \brief Python script to generate the compile script for unix systems. \copyright Copyright (c) 2018 Visual Computing group of Ulm University, Germany. See the LICENSE file at the...
# -*- coding: utf-8 -*- """ Generate metadata and bag for a resource from Django """ import os import requests from django.conf import settings from django.core.management.base import BaseCommand from hs_core.models import BaseResource from hs_core.hydroshare import hs_requests from hs_core.hydroshare.hs_bagit impor...
import rospy from roboy_middleware_msgs.msg import MagneticSensor import numpy as np import matplotlib.pyplot as plt from magpylib.source.magnet import Box,Cylinder from magpylib import Collection, displaySystem, Sensor from scipy.optimize import fsolve, least_squares import matplotlib.animation as manimation import ra...
import rcbu.client.report as report from rcbu.utils.bytes import dehumanize_bytes import rcbu.common.duration as duration def _args_from_dict(body): args = { '_backup_id': body['BackupConfigurationId'], '_restored': { 'files': int(body['NumFilesRestored']), 'bytes': body['N...
##################################################################### # Python script to run ModelSim simulations for all the post-pnr testbenches # in a project directory # This script will # - Collect all the testbenches in a given directory # For instance: # ../k4_arch/pre_pnr/verilog_testbenches/and2_post_pnr...
from fvcore.common.registry import Registry from collections import OrderedDict import numpy as np import torch from torch import nn import torch.nn.functional as F from clip import Bottleneck from clip import QuickGELU, LayerNorm ENCODER_MODULES_REGISTRY = Registry("ENCODER_MODULES") ENCODER_MODULES_REGISTRY.__doc...
''' Created on Aug, 12 2015 @author: mlaptev ''' from base_serialization import Base_Serialization import json import os class JSON_Serialization(Base_Serialization): ''' This class will be used to demonstration of both serialization and de-serialization capabilities with using JSON ''' def __i...
#!/usr/bin/python """ get_spectrum.py Jordan Fox , 2016 this program extracts the energy speactrum from an input file (arg 1) and prints the energies to STDOUT The input file must be a .res file from BIGSTICK 7.7.0 or similar Works for BIGSTICK options n, d """ import sys import os """ get input file """ if (len(...
''' This function gives you the possibility to concatenate multiple videos. ''' import moviepy.editor as mp from scripts import style import os def create_concatenation(): videos = [] all_video_file_paths = [] all_filenames = [] color = style.bcolors() while True: try: vi...
#!/usr/bin/python # build_native.py # Build native codes # # Please use cocos console instead import sys import os, os.path import shutil import urllib import webbrowser from optparse import OptionParser os.system('cls') current_dir = os.path.dirname(os.path.realpath(__file__)) command = 'php artisan serve' print ...
from .base import Experiment from .dnn import DNNExperiment from .train import TrainingExperiment from .prune import PruningExperiment from .attack import AttackExperiment from .quantize import QuantizeExperiment
""" 问题描述: 牛牛的作业薄上有一个长度为 n 的排列 A,这个排列包含了从1到n的n个数,但是因为一些原因, 其中有一些位置(不超过 10 个)看不清了,但是牛牛记得这个数列顺序对的数量是 k,顺序对是指满足 i < j 且 A[i] < A[j] 的对数,请帮助牛牛计算出,符合这个要求的合法排列的数目。 输入描述: 每个输入包含一个测试用例。每个测试用例的第一行包含两个整数 n 和 k(1 <= n <= 100, 0 <= k <= 1000000000), 接下来的 1 行,包含 n 个数字表示排列 A,其中等于0的项表示看不清的位置(不超过 10 个)。 输出描述: 输出一行表示合法的排列数目。 示例1 输入 5...
from __future__ import unicode_literals import logging import os import signal import socket import sys from optparse import make_option from django.conf import settings from django.core.management.base import BaseCommand from mesos.interface import mesos_pb2 try: from mesos.native import MesosSchedulerDriver ex...
try: import galsim except ImportError: class GalSimWCS(object): def __init__(self, *args, **kwargs): raise NotImplementedError( 'Unable to import galsim. The GalSimWCS interface is not available.') else: from .decaminfo import DECamInfo from .PixelMapCollection impo...
#! python3 from time import perf_counter import re from curriculummapper import Course, Curriculum def main(): ''' An example scraper for the case western MS Data Science program webpage ''' # initiating an empty curriculum object true_start_time = perf_counter() school_name = "Case Western"...
import re import datetime from commands.core import Command class Note: def __init__(self): self.name = '' self.dz = '' self.date = datetime.datetime.today() def __str__(self): tt = self.date.timetuple() weekday = self.weekday(self.get_calendar()[2]) return '\n...
import logging from crl.interactivesessions.shells.remotemodules import servers from crl.interactivesessions.shells.remotemodules.msgs import ( ExecCommandErrorObj) from crl.interactivesessions.shells.remotemodules.compatibility import to_bytes from .serverterminal import ( LineServerBase, LineServerExit) ...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import typing from bravado_core.spec import Spec from swagger_spec_compatibility.rules.common import BaseRule from swagger_spec_compatibility.rules.common import Level from swa...
import os import subprocess import sys import shutil import json import argparse import jinja2 as jinja import platform import git PKG_ROOT = 'ansibledriver' PKG_INFO = 'pkg_info.json' DIST_DIR = 'dist' WHL_FORMAT = 'ansible_lifecycle_driver-{version}-py3-none-any.whl' DOCS_FORMAT = 'ansible-lifecycle-driver-{version...
from milvus import Milvus, Prepare, IndexType, Status import random milvus = Milvus() # Connect Milvus server, please change HOST and PORT to correct one milvus.connect(host='localhost', port='33001') # Table name is defined table_name = 'table_'+str(random.randint(0,100)) # Create table: table name, vector dimens...
#!/usr/bin/env python3 import aocd YEAR = 2021 DAY = 8 DIGIT_SEGS = { 0: 'abcefg', 1: 'cf', 2: 'acdeg', 3: 'acdfg', 4: 'bcdf', 5: 'abdfg', 6: 'abdefg', 7: 'acf', 8: 'abcdefg', 9: 'abcdfg', } SEG_DIGITS = {v: k for k, v in DIGIT_SEGS.items()} def part_a(inlist): count = 0...
from fr_api import * import glob if __name__ == '__main__': file_names = glob.glob(r'./dataset/pic/*.jpg') file_names.sort() print(file_names) for file in file_names: save_path = "".join("./dataset/ha/{}.png".format(file[14:18])) print(save_path) face_image = FacesImage(file...
# ------------------------------------------------------------------------- # Copyright (c) Thomas Waldinger. All rights reserved. # Licensed under the Apache License, Version 2.0. See # License.txt in the project root for license # information. # --------------- """ ArchiveEntry The archive entry represents one archi...
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ This script takes the path to a directory, and looks for any Turtle files (https://www.w3.org/TeamSubmission/turtle/), then uses RDFLib to check if they're valid TTL. It exits with code 0 if all files are valid, 1 if not. """ import logging import os import sys imp...
import scipy import numpy as np import cv2 import argparse import json from keras.applications import inception_v3 from keras import backend as K from keras.preprocessing import image from utils import * #Set learning phase = 0 (test mode). Prevent model learning for safety reasons. K.set_learning_phase(0) model = in...
""" Copyright 2020 Huawei Technologies Co., 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/LICENSE-2.0 Unless required by applicable...
"""empty message Revision ID: d28e299dee4e Revises: 4eb2629c7a29 Create Date: 2021-02-01 10:17:23.264719 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = 'd28e299dee4e' down_revision = '4eb2629c7a29' branch_labels = None...
# TODO: This is the entry routine for your monero miner. # NOTE: If you are creating a new GIT repo and you are going to put the data_location_json and/or settings.json file in your repo directory then be sure # to add these to the your .gitignore file. # The first thing you need is a way to read configuration f...
from django.db import models import datetime from django.db.models.constraints import UniqueConstraint from random import randint from django.apps import apps import datetime from django.utils import timezone # Create your models here. ''' The is the place where the structure of database goes ''' class Game(models.Mo...
#! /usr/bin/ipython import numpy as np import ke from gplot import * from pause import * ke._Ecs(0.0001, 1., n=15) ke.E(0.0001, 1., n=15, typ='atr') x=np.arange(0,10,0.001); y=1*x; ke._ke_newton.v_cos(x,y, x.size); gplot(x,y-np.cos(x)) x=np.arange(0,10,0.001); y=1*x; ke._ke_newton.v_sin(x,y, x.size); gplot(x,y-np.si...
""" Defines a dummy socket implementing (part of) the zmq.Socket interface. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import abc import warnings try: from queue import Queue # Py 3 except ImportError: from Queue import Queue # Py 2 import zmq ...
""" Define various utility functions. """ import numpy as np from typing import Sequence def rle_encode(seq: Sequence) -> list: """ Run-length-encode a sequence. Converts a sequence to a list of runs of the same element. Parameters ---------- seq Sequence to convert. Returns a lis...
from .missing_element_base import MissingElementBase from . import missing_empty from . import missing_field from . import missing_fieldset from . import missing_list from . import missing_section_element class MissingSection(MissingElementBase): def __repr__(self): if self._key: return f"<clas...
# -*- coding:utf-8 -*- import coremltools import logging import os if __name__ == '__main__': logFmt = '%(asctime)s %(lineno)04d %(levelname)-8s %(message)s' logging.basicConfig(level=logging.DEBUG, format=logFmt, datefmt='%H:%M',) modelFilePath = os.getcwd() modelFilePath += '/MarsHabitatPr...
from Messages.Message import Message class Error (Message): def get_text(self): return "ERROR: " + self.text
import aredis import asyncio import uvloop import time import sys from functools import wraps from argparse import ArgumentParser if sys.version_info[0] == 3: long = int def parse_args(): parser = ArgumentParser() parser.add_argument('-n', type=int, help='T...
#!/usr/bin/env python # svmap.py - SIPvicious SIP scanner __GPL__ = """ SIPvicious SIP scanner searches for SIP devices on a given network Copyright (C) 2012 Sandro Gauci <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Genera...
from django.conf.urls.defaults import patterns, url from django.views.decorators.csrf import csrf_exempt from mozdns.mozbind.views import build_debug_soa urlpatterns = patterns('', url(r'^build_debug/(?P<soa_pk>[\w-]+)/$', csrf_exempt(build_debug_soa)), ...
# We use three flags: met_dot, met_e, met_digit, mark if we have met ., e or any digit so far. First we strip the string, then go through each char and make sure: # If char == + or char == -, then prev char (if there is) must be e # . cannot appear twice or after e # e cannot appear twice, and there must be at least o...
#coding=utf8 from uliweb import expose @expose('/') def index(): return redirect('/yesno/list')
import tensorflow as tf train, test = tf.keras.datasets.fashion_mnist.load_data() trainImages, trainLabels = train testImages, testLabels = test model = tf.keras.Sequential([ tf.keras.layers.Flatten(input_shape=(28,28)), tf.keras.layers.Dense(units=128, activation=tf.nn.relu), tf.keras.layers.Dense(units...
# Copyright 2017 st--, Mark van der Wilk # # 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...
import os from dotenv import load_dotenv from os import environ load_dotenv(".env") BOT_TOKEN = os.environ["BOT_TOKEN"] DATABASE = os.environ["DATABASE"] admins = [ 381252111, ] async def load_admins() -> tuple: return tuple(map(int, environ["ADMINS"].split(",")))