text
stringlengths
1
927k
"""faucetsite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-ba...
from setuptools import setup, find_packages import testpkg setup( name='python-testpkg', version='0.3', description='Run test package.', url='https://github.com/weijarz/python-testpkg', author='weijarz', author_email='weijarz@gmail.com', license='MIT', # See https://pypi.python.org/py...
"""Module for python packaging setup.""" import setuptools # Read README.md for the long description with open('README.md', 'r') as fh: long_description = fh.read() # Setup information setuptools.setup( name='VHDLTest', version='0.2.0', author='Malcolm Nixon', description='VHDL Testbench Runner',...
import random, temp name = input('whats is your name? ') print('good luck ' + name) words = [temp.read()] word = random.choice(words) print('guess the characters') guesses = '' turns = 12 while turns > 0: failed = 0 for char in word: if char in guesses: print(char) else: ...
""" Flask API REST Tutorial Python e Flask - Como Criar Uma API REST Em Minutos Homepage and documentation: https://www.youtube.com/watch?v=N6cZ6aHvLYs&list=PLTzsdf89Lw9wISVTaoCBwk4pRCCgddRZO Copyright (c) 2018, Marcus Mariano. License: MIT (see LICENSE for details) """ from flask import Flask, jsonify, request a...
from django import forms from wiki.models import Page class PageForm(forms.ModelForm): """ Render and process a form based on the Page model. """ class Meta: model = Page fields = ['title', 'author', 'content'] class FriendlyForm(forms.Form): first_name = forms.CharField(max_length=100) ...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/ads/googleads_v2/proto/enums/product_channel_exclusivity.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.prot...
#!/usr/bin/env python3 # This file is covered by the LICENSE file in the root of this project. import argparse import os import yaml import __init__ as booger from common.laserscan import LaserScan, SemLaserScan from common.laserscanvis_uncert import LaserScanVisUncert import glob if __name__ == '__main__': pa...
try: from cytoolz import ( assoc, complement, compose, concat, cons, curry, dicttoolz, dissoc, excepts, functoolz, groupby, identity, itertoolz, merge, partial, pipe, sliding_windo...
# Generated by Django 2.0b1 on 2017-11-13 02:56 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
import time from src.EHs.binaryCounterEH import VarEH def EH_train_epoch(train_loader, network, optimizer, loss_fn, hparams, epoch, taskType='classification'): # custom training with resetting of EHs in each epoch. # Activate the train=True flag inside the model network.train() # reset EHs netwo...
# ยฉ 2019 Nokia # Licensed under the BSD 3 Clause license # SPDX-License-Identifier: BSD-3-Clause from radish_ext.radish.template_with_nested_data_replacer import TemplateForNestedDict from radish_ext.sdk.l import Logging class TestDataBase(object): def __init__(self, cfg) -> None: super().__init__() ...
from types import SimpleNamespace import numpy as np import pandas import pytest from ...execution import DataStore from ...recorders import GenMomentsRecorder from ..datastore_loader import DataStoreLoader1 @pytest.mark.parametrize('num_mom_conds', [1, 2, 12]) def test_record_load(num_mom_conds, tmpdir): datas...
from jax import numpy as jnp from . import Transformer, ViT, TNT, CaiT, MLPMixer def create_trunk( model_name: str, output_dim: int = 1000, dtype: jnp.dtype = jnp.float32 ): if model_name == "txt_b": return Transformer( output_dim=output_dim, num_layers=12, num_he...
#!/usr/bin/python import sys import botan def main(args = None): if args is None: args = sys.argv if len(args) != 3: raise Exception("Usage: <password> <input>"); password = args[1] input = ''.join(open(args[2]).readlines()) rng = botan.RandomNumberGenerator() ciphertext = ...
import dash_bootstrap_components as dbc from dash import html inline_radioitems = html.Div( [ dbc.Label("Choose one"), dbc.RadioItems( options=[ {"label": "Option 1", "value": 1}, {"label": "Option 2", "value": 2}, ], value=1, ...
import aiohttp import pydash import json class ApiWorker(): def __init__(self, httpclient): self._httpclient = httpclient async def find_one_by_uuid(self, uuid): request = self._httpclient.request() url = self._httpclient.scheduler_url('/workers?uuid=' + uuid) async with reque...
# ์ˆ˜๋นˆ์ด๋Š” TV๋ฅผ ๋ณด๊ณ  ์žˆ๋‹ค. ์ˆ˜๋นˆ์ด๋Š” ์ฑ„๋„์„ ๋Œ๋ฆฌ๋ ค๊ณ  ํ–ˆ์ง€๋งŒ, ๋ฒ„ํŠผ์„ ๋„ˆ๋ฌด ์„ธ๊ฒŒ ๋ˆ„๋ฅด๋Š” ๋ฐ”๋žŒ์—, ์ผ๋ถ€ ์ˆซ์ž ๋ฒ„ํŠผ์ด ๊ณ ์žฅ๋‚ฌ๋‹ค. # ๋ฆฌ๋ชจ์ปจ์—๋Š” ๋ฒ„ํŠผ์ด 0๋ถ€ํ„ฐ 9๊นŒ์ง€ ์ˆซ์ž, +์™€ -๊ฐ€ ์žˆ๋‹ค. +๋ฅผ ๋ˆ„๋ฅด๋ฉด ํ˜„์žฌ ๋ณด๊ณ ์žˆ๋Š” ์ฑ„๋„์—์„œ +1๋œ ์ฑ„๋„๋กœ ์ด๋™ํ•˜๊ณ , -๋ฅผ ๋ˆ„๋ฅด๋ฉด -1๋œ ์ฑ„๋„๋กœ ์ด๋™ํ•œ๋‹ค. ์ฑ„๋„ 0์—์„œ -๋ฅผ ๋ˆ„๋ฅธ ๊ฒฝ์šฐ์—๋Š” ์ฑ„๋„์ด ๋ณ€ํ•˜์ง€ ์•Š๊ณ , ์ฑ„๋„์€ ๋ฌดํ•œ๋Œ€ ๋งŒํผ ์žˆ๋‹ค. # ์ˆ˜๋นˆ์ด๊ฐ€ ์ง€๊ธˆ ์ด๋™ํ•˜๋ ค๊ณ  ํ•˜๋Š” ์ฑ„๋„์€ N์ด๋‹ค. ์–ด๋–ค ๋ฒ„ํŠผ์ด ๊ณ ์žฅ๋‚ฌ๋Š”์ง€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ์ฑ„๋„ N์œผ๋กœ ์ด๋™ํ•˜๊ธฐ ์œ„ํ•ด์„œ ๋ฒ„ํŠผ์„ ์ตœ์†Œ ๋ช‡ ๋ฒˆ ๋ˆŒ๋Ÿฌ์•ผํ•˜๋Š”์ง€ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. # ์ˆ˜๋นˆ์ด๊ฐ€ ์ง€๊ธˆ ๋ณด๊ณ  ์žˆ...
# *utf-8* import os import json import numpy as np from tqdm import tqdm import cv2 defect_name2label = { 'red': 1, 'green': 2, 'yellow': 3, 'red_left': 4, 'red_right': 5, 'yellow_left': 6, 'yellow_right': 7, 'green_left': 8, 'green_right': 9, 'red_forward': 10, 'green_forward': 11, 'yellow_forward': 12, '...
def get_script(pid, module, offsets, dtinitOffsets): js = 'var pid = ' + str(pid) + ';' js += 'var module = "' + module + '";' js += 'var pTargets = {};' js += 'var dtInitTargets = {};' for k, v in offsets.items(): js += 'pTargets[' + str(k) + '] = ' + str(k) + ';' for k, v in dtinitOffs...
# ===================================== # Copyright 2017, Andrew Lindesay # Distributed under the terms of the MIT License. # ===================================== # common material related to generation of schema-generated artifacts. import datetime # The possible JSON types JSON_TYPE_STRING = "string" JSON_TYPE_O...
from __future__ import absolute_import, division, print_function from iotbx.pdb import extract_rfactors_resolutions_sigma from libtbx.test_utils import approx_equal example_cns = """ REMARK 2 REMARK 2 RESOLUTION. 2.20 ANGSTROMS. REMARK 3 REMARK 3 REFINEMENT. REMARK 3 PROGRAM : CNS 0.9 REMARK 3 AUTH...
def test_01(value): print value return value * 2 def test_02(value): print value return value * 1.5 def test_03(value): print value return value + ', hello python' def test_04(value): print value return not value def test_05(value): print value if value is None: return None else: raise Exception() d...
""" @author: Patrik Purgai @copyright: Copyright 2019, supervised-translation @license: MIT @email: purgai.patrik@gmail.com @date: 2019.04.04. """ # pylint: disable=no-member # pylint: disable=not-callable import torch import random from torch.nn.modules import ( Module, ModuleList) from torch.nn....
# python3 # Copyright 2021 InstaDeep Ltd. 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 applic...
import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F import torch.utils.data as Data import torch.optim as optim from torch.utils.data import Dataset, DataLoader, WeightedRandomSampler class MultipleRegression(nn.Module): def __init__(self, num_features): s...
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
import copy import ipaddress import itertools import json import logging import pytest import time import os from tests.common.mellanox_data import is_mellanox_device as isMellanoxDevice from tests.common.platform.ssh_utils import prepare_testbed_ssh_keys as prepareTestbedSshKeys from tests.common.reboot import reboot...
#=============================================================================== # Constants #=============================================================================== # vim:set ts=8 sw=4 sts=4 tw=80 et :
#!/usr/bin/env python import os import jinja2 import yaml PATH = os.path.dirname(os.path.abspath(__file__)) TEMPLATE_ENVIRONMENT = jinja2.Environment( autoescape=False, loader=jinja2.FileSystemLoader(os.path.join(PATH, 'data')), trim_blocks=False) def render_template(template_filename, context): ret...
import torch import os import numpy as np from utils import * l2_res = np.zeros([6, 7]) linf_res = np.zeros([6, 7]) resDir = 'res' if not os.path.isdir(resDir): os.mkdir(resDir) for model_file in MODEL_FILE_LIST: task_name = model_file.split('.')[0] for attack_name in ['L2', 'Linf']: avg_res = np...
config = { "interfaces": { "google.ads.googleads.v5.services.KeywordPlanIdeaService": { "retry_codes": { "idempotent": [ "DEADLINE_EXCEEDED", "UNAVAILABLE" ], "non_idempotent": [] }, "retry_params": { "default": { "initial_retry_delay...
import io import urllib.request from PIL import Image, ImageFile from sqlalchemy.dialects.postgresql import JSONB from app.main import db from app.main.lib.image_hash import compute_phash_int, sha256_stream class ImageModel(db.Model): """ Model for storing image related details """ __tablename__ = 'images' id...
# Copyright 2015 - StackStorm, 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 agr...
from dotenv import load_dotenv from pathlib import Path import os env_path = Path('.') / 'data/.env' load_dotenv(dotenv_path=env_path) TOKEN = os.getenv("GITHUB_ACCESS_TOKEN") USERNAME = os.getenv("GITHUB_USERNAME")
from progress_passthrough.iterator_wrappers import ( IteratorWrapper, AttachedLengthIterator, CallbackIterator, wrap_source, wrap_source_len, ) from unittest.mock import Mock def test_iterator_wrapper_on_iterable(): it = range(10) w = IteratorWrapper(it) assert len(w) == len(range(10))...
from kivy import platform import json import random TEST_DEVICE = False SMAC_PLATFORM = None # platform options # android, ESP, RPI, win, linux if TEST_DEVICE: TEST_PLATFORMS = ["android", "win", "linux", "ESP"] try: with open('config.json', 'r') as f: fd = json.load(f) if fd.get("PLATFORM", None) != None:...
import torch.nn as nn import torch.utils.checkpoint as cp from mmcv.cnn import constant_init, kaiming_init from mmcv.runner import load_checkpoint from torch.nn.modules.batchnorm import _BatchNorm from openselfsup.utils import get_root_logger from ..registry import BACKBONES from ..utils import build_conv_layer, build...
import copy import fnmatch from collections import OrderedDict from conans.errors import conanfile_exception_formatter from conans.model.ref import ConanFileReference from conans.model.conan_file import get_env_context_manager from conans.client.graph.printer import print_graph def _apply_build_requires(deps_graph, ...
import logging from django import forms from django.utils.translation import ugettext as _ from ...constants import weekdays, frequency from ...models import RecurrenceRule from ..custom_model_form import CustomModelForm logger = logging.getLogger(__name__) class RecurrenceRuleForm(CustomModelForm): """ Fo...
#!/usr/bin/env python3 # Copyright (c) 2014-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the zapwallettxes functionality. - start two bitrubcoind nodes - create two transactions on node ...
import difflib import re import unicodedata from typing import Tuple, Union from discord import Colour, Embed, utils from discord.ext.commands import BadArgument, Cog, Context, clean_content, command, has_any_role from discord.utils import snowflake_time from bot.bot import Bot from bot.constants import Channels, MOD...
# Standard Library import platform import sys from pathlib import Path current_python_version = "%s.%s" % platform.python_version_tuple()[:2] # when executing pytest cli, the sys.path will be changed. # jsonpath-extractor package's module `jsonpath` same as # the file `jsonpath.py` in f'{sys.prefix}/bin'. # So need ...
from io import BytesIO from math import ceil import numpy as np from PIL import Image from .exception import ParsingError _BLOCK_SIZE = 16 _BLOCK_PIXEL = _BLOCK_SIZE * _BLOCK_SIZE PALETTE_OFFSETS = [ 0xB_EC68, 0xB_EDA8, 0xB_EEE8, 0xB_F028, 0xB_F168, ] def bytes_to_tilemap(data, palette=None, b...
"""Management command that replaces soft-links in content editors and creates redirects.""" import json from django.conf import settings from django.core.management.base import BaseCommand, CommandError from wagtail.core.models import Page from wagtail.contrib.redirects.models import Redirect from wagtail_modeltran...
from fastapi import APIRouter import finviz import requests from urllib.error import HTTPError news_router = APIRouter() @news_router.get("/{stock}/news") async def get_stock_news(stock: str): try: news = finviz.get_news(stock) return {"success": True, "news": news[0:5]} except requests.except...
#!/usr/bin/env python import InstrumentDriver import numpy as np import os import logging from datetime import datetime from PSICT_MultiPulse_tools import delistifyPulseDefs from waveforms_handling import generatePulse, calculateWaveform, gen_pulse_sequence class Driver(InstrumentDriver.InstrumentWorker): """ ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging from typing import Dict, Text, Any logger = logging.getLogger(__name__) EventType = Dict[Text, Any] # noinspection PyPep8Naming def UserUttered(text, p...
# -*- coding: utf-8 -*- # app.py from flask import Flask, request, render_template import pickle import gzip import numpy as np import AiPoems #start up cell -- import necessary metadata for model with open('tokenizer.pickle', 'rb') as handle: tokenizer = pickle.load(handle) with gzip.GzipFile('predictors.npy.gz'...
#!/usr/bin/env python # -*- coding: utf-8 -*- """The setup script.""" from setuptools import setup, find_packages with open('README.md') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ 'wagtail>=1.11.1,<2.5', ] setup_...
#!/usr/bin/python # # Copyright (c) 2019 Zim Kalinowski, (@zikalino) # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
#!/usr/bin/env python3 # encoding: utf-8 """ release_vars.py Created by Jonathan Burke on 2013-02-05. Copyright (c) 2014 University of Washington. All rights reserved. """ # See release_development.html for an explanation of how the release process works # it will be invaluable when trying to understand the scripts ...
from dataclasses import dataclass from typing import Dict import numpy as np from game import Position from game.model.entity.damage import Damageable, Damage, DamageType from game.model.entity.inventory.inventory_keeper import InventoryKeeper from game.model.entity.item.item import Item from .character import Charac...
# -*- coding: utf-8 -*- ''' Template render systems ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import codecs import os import logging import tempfile import traceback import sys # Import 3rd-party libs import jinja2 import jinja2.ext from salt.ext import six if...
#### # channels.py: # # This file captures the HTML endpoint for the events list. This file contains one endpoint which allows for listing # events after a certain time-stamp. # # GET /events: list events # Input Data: { # "start-time": "YYYY-MM-DDTHH:MM:SS.sss" #Start time for event listing ...
import socket import select import logging from crccheck.crc import Crc8, Crc16 def parseData(data): byte_data = bytearray(data) header = byte_data[:26] sop = header[0] camera_id = header[1] image_type = header[2] width = (header[...
#!/usr/bin/env python """ Renames files or directories with "module-triple-here" in their names to use the indicated module triples instead. """ from __future__ import print_function import os import platform import shutil import sys if len(sys.argv) < 3: print('Too few args to ' + sys.argv[0]) print('Usage:...
import json from django.conf import settings from django.db.models import Count from ralph.admin.mixins import RalphTemplateView from ralph.data_center.models.physical import DataCenter class ServerRoomView(RalphTemplateView): template_name = 'dc_view/server_room_view.html' def get_context_data(self, **kwa...
# -*- coding: utf-8 -*- import os import ConfigParser import oss2 import sys from itertools import islice reload(sys) sys.setdefaultencoding('utf-8') # ่Žทๅ–้…็ฝฎ config = ConfigParser.ConfigParser() path = os.path.split(os.path.realpath(__file__))[0] + '/config.conf' config.read(path) ossAccessKeyId = config.get('makelove'...
# Generated by Django 3.2.6 on 2021-08-16 15:21 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('capdb', '0117_extractedcitation_opinion_id'), ] operations = [ migrations.AddField( model_name=...
# flake8: noqa from dataclasses_json.api import (DataClassJsonMixin, LetterCase, dataclass_json) from dataclasses_json.cfg import config, global_config from dataclasses_json.undefined import CatchAll, Undefined
import configparser import json import colorama import pymysql.cursors import telebot from tabulate import tabulate import init colorama.init() config = configparser.ConfigParser() config.read("conf.ini") bot = telebot.TeleBot(config["DATA"]["token"].strip()) connection = pymysql.connect(host=config["DB"]["host"...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import attr import hypothesis import magnum as mn import numpy as np import pytest import quaternion # noqa: F401 from ...
from typing import List, Optional, Union import numpy as np from .ext.dense import ( dense_matvec, dense_rmatvec, dense_sandwich, transpose_square_dot_weights, ) from .matrix_base import MatrixBase from .util import ( check_matvec_out_shape, check_transpose_matvec_out_shape, setup_restrict...
# # This source file is part of the EdgeDB open source project. # # Copyright 2016-present MagicStack Inc. and the EdgeDB authors. # # 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...
import random import sys from os import listdir from os.path import isdir, isfile, join, dirname, realpath # add data to path DATA_DIR = dirname(dirname(realpath(__file__))) sys.path.append(DATA_DIR) from utils import print_progress, execute_bash THIS_DATA_DIR = dirname(realpath(__file__)) # important TEXT_URL = '...
from ..fsGetNumberDescription import fsGetNumberDescription; from mWindowsAPI import oSystemInfo; def fbUpdateReportForNULLPointer( oCdbWrapper, oBugReport, oProcess, oThread, sViolationTypeId, uAccessViolationAddress, sViolationVerb, oVirtualAllocation ): if uAccessViolationAddress == 0: sOffset = ""; elif ...
"""ONVIF event abstraction.""" from __future__ import annotations import asyncio from collections.abc import Callable from contextlib import suppress import datetime as dt from httpx import RemoteProtocolError, TransportError from onvif import ONVIFCamera, ONVIFService from zeep.exceptions import Fault from homeassi...
from django.db import models from tastypie.resources import ModelResource from movies.models import Movie # Create your models here. class MovieResource(ModelResource): class Meta: queryset = Movie.objects.all() resource_name = 'movies' excludes = ['date_created']
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from kinova_msgs/CartesianForce.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class CartesianForce(genpy.Message): _md5sum = "b01974557c40b776cdb7003057779989" _typ...
import logging from library import create_app # disable uvicorn access log logging.getLogger("uvicorn.access").handlers = [] logging.getLogger("uvicorn.access").propagate = False app = create_app()
# -*- coding: utf-8 -*- # Copyright 2014 Rob Ruana # Licensed under the BSD License, see LICENSE file for details. """Sphinx napoleon extension -- support for NumPy and Google style docstrings. """ import sys from six import iteritems from sphinxcontrib.napoleon.docstring import GoogleDocstring, NumpyDocstring from ...
from flask import Flask, request, g, render_template, redirect, flash, url_for, session, abort from flask_sqlalchemy import SQLAlchemy from sqlalchemy.orm import joinedload #from flask import reqparse, fields, Resource, Api, from werkzeug.datastructures import FileStorage from werkzeug.security import check_password_ha...
from flask_restful import Resource import logging as logger from .database import get_user_by_id class UserById(Resource): def get(self, user_id): selected_user = get_user_by_id(user_id) return selected_user, 200
''' Created on Jan 17, 2014 @author: ezulkosk ''' from z3 import Tactic, IntNumRef, BoolRef, is_not, BoolSortRef, Not, simplify import Z3ModelERSNoObjectives as ERS import Z3ModelEShopNoObjectives as SHP import Z3ModelWPTNoObjectives as WPT import sys import z3 class DimacsConverter(): def __init__(self): ...
import operator import pytest from pyconll.util import find_ngrams from pyconll import load_from_file from tests.util import fixture_location def test_ngram_standard(): """ Test if the find_ngram method works for standard situations. """ c = load_from_file(fixture_location('basic.conll')) s, i ...
from consts.notification_type import NotificationType from helpers.model_to_dict import ModelToDict from notifications.base_notification import BaseNotification class MatchScoreNotification(BaseNotification): def __init__(self, match): self.match = match self.event = match.event.get() sel...
import argparse import imaplib import logging import mailbox import os import re import signal import sys import time import mr.config import mr.db class IMAPTool: def __init__(self, imap): self.imap = imap def _check_error(self, status, response): if status != 'OK': raise Runtim...
""" The starlette extension to rate-limit requests """ import asyncio import datetime import functools import inspect import itertools import json import logging import sys import time import warnings from email.utils import formatdate, parsedate_to_datetime from functools import wraps from typing import (Any, Awaitabl...
from utils.argutils import print_args from encoder.train import train from pathlib import Path import argparse if __name__ == "__main__": parser = argparse.ArgumentParser( description="Trains the speaker encoder. You must have run encoder_preprocess.py first.", formatter_class=argparse.ArgumentDef...
import numpy as np import numpy.linalg as la from numpy.testing import assert_allclose import unittest from rlscore.learner import QueryRankRLS from rlscore.kernel import GaussianKernel, PolynomialKernel def mapQids(qids): """Maps qids to running numbering starting from zero, and partitions the training data...
from django.conf.urls import url, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) urlpatterns = [ url(r'^', include(router.urls)), ]
# coding: utf-8 import numpy as np from PIL import Image, ImageDraw from math import sin,cos from numpngw import write_apng W,H = 1024,1024 COLOR_BLACK = (0x00, 0x00, 0x00, 0x00) COLOR_WHITE = (0xF0, 0xF0, 0xE0) COLOR_BLUE = (0x0D, 0x36, 0xFF) COLOR_BLYNK = (0x2E, 0xFF, 0xB9) COLOR_RED = (0xFF, 0x10, 0x...
import qtensor from qtensor import CirqQAOAComposer, QtreeQAOAComposer from qtensor import QAOAQtreeSimulator from qtensor.Simulate import CirqSimulator, QtreeSimulator from qtensor.FeynmanSimulator import FeynmanSimulator import numpy as np import networkx as nx np.random.seed(42) def get_test_problem(n=14, p=2, d=...
# import the basic python packages we need import os import sys import tempfile import pprint import traceback # disable python from generating a .pyc file sys.dont_write_bytecode = True # change me to the path of pytan if this script is not running from EXAMPLES/PYTAN_API pytan_loc = "~/gh/pytan" pytan_static_path =...
# Code for "TSM: Temporal Shift Module for Efficient Video Understanding" # arXiv:1811.08383 # Ji Lin*, Chuang Gan, Song Han # {jilin, songhan}@mit.edu, ganchuang@csail.mit.edu import os ROOT_DATASET = '/media/nas-570-002-nfssamba/rsanford/activity_recognition/' # '/data/jilin/' def return_ucf101(modality): fi...
""" Set your env like the example below: token= mysql= default= dev= """ def temporary_fix(): from shutil import copyfile copyfile("./utils/post.py","/opt/virtualenvs/python3/lib/python3.8/site-packages/instascrape/scrapers/post.py") import os import sys import subprocess sys.path.insert(1,f"{os.getcwd()}...
#! /usr/bin/env python import sys import numpy as np from sensor_msgs.msg import Image def imgmsg_to_cv2(img_msg): if img_msg.encoding != "bgr8": rospy.logerr("This Coral detect node has been hardcoded to the 'bgr8' encoding. Come change the code if you're actually trying to implement a new camera") d...
#-*- coding:utf-8 -*- import sae import sae.const import MySQLdb import time db = MySQLdb.connect(host ="localhost", port =3306, user ="root", passwd ="Sww6416!", db="storychain") cursor =db.cursor() cursor.execute('USE app_storychain') cursor.execute('''CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUT...
from typing import Sequence from weaverbird.exceptions import DuplicateColumnError def validate_unique_columns(columns: Sequence[str]) -> Sequence[str]: if len(set(columns)) < len(columns): raise DuplicateColumnError else: return columns
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
from pandasgui import show show()
from pathlib import Path from typing import List from .cell import Cell import operator import warnings with warnings.catch_warnings(): warnings.filterwarnings("ignore", "Conversion of the second argument of issubdtype") import loompy import numpy as np def write_count_matrix(path: Path, cells: List[Cell]): ...
from typing import List from model.model.topic.factor import Factor from watchmen.pipeline.core.parameter.utils import check_and_convert_value_by_factor # # def get_flatten_field_with_dict(data: dict, factors: dict): # flatten_fields = {} # for factor in factors: # factor_obj = Factor.parse_obj(fact...
# Copyright (c) 2016, Mayo Clinic # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, this # list of conditions and the f...
# -*- coding: utf-8 -*- from django.conf.urls import patterns, url import views from .views import HelloPDFView urlpatterns = patterns('', # URL pattern for the TEST url( r'^~agent/testpdf$', views.testpdf, name='~agent_testpdf' ), # URL pattern for the AgentLandingView url...
from flask import Flask, jsonify, abort, make_response, request, url_for, render_template, redirect from . import app, auth @app.route('/') def root(): return redirect(url_for('.home'), code=302) @app.route('/home') def home(): example = request.args.get('example') or 'Example text' return render_template...
""" test_runner_browndye2.py test runner_browndye2.py script(s) """ import os import glob import seekr2.tests.make_test_model as make_test_model import seekr2.modules.common_sim_browndye2 as sim_browndye2 import seekr2.modules.runner_browndye2 as runner_browndye2 def test_runner_browndye2_b_surface_default(tmp_path...
""" The MIT License (MIT) Copyright (c) 2021 Bang & Olufsen a/s 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, ...