text
stringlengths
2
999k
import collections from . import base class MiniBatcher(base.Optimizer): """Wrapper class for doing mini-batch gradient descent. This will accumulate successive gradients until ``batch_size`` have been observed. Once the current mini-batch is full, the underlying optimizer will update the weights using ...
"""Configurations of the program.""" import json import ORCSchlange.sql class Config: """Main config object as an singleton""" class SingeltonObject: """Enclosed class that hold the information.""" def __init__(self, args): """Initialization of the class.""" self.client...
"""COAP implementation using aiocoap.""" from __future__ import annotations import asyncio import json import logging from typing import Callable from aiocoap import Context, Message from aiocoap.credentials import CredentialsMissingError from aiocoap.error import ( ConstructionRenderableError, Error, Lib...
from __future__ import absolute_import, division, print_function import glob import os import py_compile import stat import sys import textwrap import zipfile import py import pytest import six import _pytest._code from _pytest.assertion import util from _pytest.assertion.rewrite import ( rewrite_asserts, PYT...
_BLANK_LINE = "" _HEADING_LABEL = 'Heading' _COLUMN_LABEL = 'Column' _DATA_LABEL = 'Data' _DELIMITER = "\t" _LINE_BREAK = "\n" def _get_slice(name, text_lines, start_condition, end_condition): section_start = None section_end = None for count, text in enumerate(text_lines): if start_condition(text,...
import pandas as pd import numpy as np import sys from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression # from math import exp def meanAbsolutePercentageError(yTrue, yPredict): yTrue, yPredict = np.array(yTrue), np.array(yPredict) return np.mean(np....
# coding=utf-8 # Copyright 2018 The Tensor2Tensor 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://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
print("multumiriiiii cristinaaa")
from __future__ import unicode_literals import logging from django.utils.translation import pgettext_lazy logger = logging.getLogger(__name__) class CartStatus: OPEN = 'open' SAVED = 'saved' WAITING_FOR_PAYMENT = 'payment' ORDERED = 'ordered' CHECKOUT = 'checkout' CANCELED = ...
import json import pytest from indra.statements import Statement, Evidence from indra_cogex.client.queries import * from indra_cogex.client.queries import ( _filter_out_medscan_evidence, _get_ev_dict_from_hash_ev_query, ) from indra_cogex.representation import Node from .test_neo4j_client import _get_client ...
from flask import Flask from flask import request from flask_restful import Resource, Api from kubernetes import client, config from flask_cors import CORS from datetime import datetime import json app = Flask(__name__) api = Api(app) CORS(app) config.load_incluster_config() with open("/var/run/secrets/kubernetes.i...
# # Copyright 2016 The BigDL 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://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
from nltk.corpus import wordnet as wn from tqdm import tqdm with open('all_synset_names') as in_f: with open('all_paths', 'w') as out_f: max_len = 0 for line in tqdm(in_f.readlines()): l = line.strip() paths = wn.synset(l).hypernym_paths() ''' try: ...
import os import pickle from numpy.random import RandomState from rlai.agents.mdp import StochasticMdpAgent from rlai.environments.gridworld import Gridworld from rlai.gpi.monte_carlo.evaluation import evaluate_v_pi, evaluate_q_pi from rlai.policies.tabular import TabularPolicy from rlai.q_S_A.tabular import TabularS...
""" Script som laster ned fire rapporttyper fra NVDB rapporter API til angitt mappe Rapporttyper som lastes ned: V1_Vegnettsrapport.xlsx V2_AggregertMengdePerVegkategori.xlsx V3_AggregertMengdePerVegnr.xlsx V4_Detaljert_mengde.xlsx Tilstandsrapport.xlsx Disse lagres i mappen <mappenavn>_<Navn kon...
import time from json import dumps from typing import List, Optional, Union import datadog import re from urllib.parse import ParseResult, parse_qsl, unquote, urlencode, urljoin, urlparse from unidecode import unidecode from nephrogo import settings def str_to_ascii(s: str) -> str: return unidecode(s) def onl...
# coding: utf-8 import os import unittest import mock from mako.template import Template from tornado.escape import to_unicode class UINamespaceTest(unittest.TestCase): def setUp(self): path = os.path.join(os.path.dirname(__file__), 'templates') self.tpl = Template(filename=os.path.join(path, 'ui...
print('1. int') # 除法 得到一个浮点数 print(2 / 4) # 除法 得到一个整数 print(5 // 4) print(7 // 4) print(2 // 4) # 乘方 print(2 ** 4) # 取余 print(17 % 3) print('1.1 要点') ## 要点 # 1. py3 可以同时为多个变量赋值 # 2. 查看数据类型 a, b = 2, 3 print(a ** 3) print(type(a)) print('2. string') str = 'hello world' print(str.index('o')) print(str[0]) print(str[-1...
import gym from stable_baselines3 import PPO, SAC from stable_baselines3.ppo import MlpPolicy as PPOMLP from stable_baselines3.sac import MlpPolicy as SACMLP from gym_anm.envs import SimplEnv, GenToGridEnv, DelayedSellEnv from .callbacks import ProgressBarManager, EvalCallback from .hyperparameters import * from .uti...
from .functions import * from .functions import chain as C, flat as F FEATURES = { 'feat_calls_count_family_relative': { 'inputs': [ 'feat_calls_count_family_weekly', 'feat_calls_count_family_total', ], 'function': relative_qualitative, 'window': '1d', ...
# -*- coding: utf-8 -*- # Copyright 2019 The Matrix.org Foundation C.I.C. # # 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 require...
class Solution: def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int: m = len(nums1) n = len(nums2) dp = [[float('-inf') for i in range(m)] for j in range(n)] for i in range(n): for j in range(m): if i == 0: if j == 0: ...
# Copyright 2015 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Module to upload your homebrew ChromeOS image as a GCE image. Use this script if you have a GCE targeted CrOS image (currently, lakitu_mobbuild) that ...
# Copyright 2021-present MongoDB, 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 wri...
# -*- coding: utf-8 -*- from RISJbot.spiders.newssitemapspider import NewsSitemapSpider from RISJbot.loaders import NewsLoader # Note: mutate_selector_del_xpath is somewhat naughty. Read its docstring. from RISJbot.utils import mutate_selector_del_xpath from itemloaders.processors import Identity, TakeFirst from itemlo...
with open("pytorochka.txt") as f: with open("pytorochka_parsed.txt", "w") as fw: fw.write("\n".join(f.read().split("\n")[::2]))
# -*- encoding: utf-8 -*- # """ # License: MIT # Copyright (c) 2020 - Pizarra # """ # taken from https://github.com/hackersandslackers/paramiko-tutorial import logging from flask import current_app from paramiko import SSHClient, AutoAddPolicy, RSAKey from paramiko.auth_handler import AuthenticationException, SS...
""" 佐々木実験17のスクリプト EMAEarlyStoppingを採用 EMAES_PATIENCE = 10 SCALEを調整 学習用 $ python3 filament.py train 検証用 $ python3 filament.py evaluate --model=last --eval_type=xxxx --year=xxxxx predict画像出力はinspect*.pyを実行 """ import os import sys import time import math import numpy as np import imgaug import json import collections...
import pytest from whatlies.language import GensimLanguage @pytest.fixture() def lang(): return GensimLanguage("tests/cache/custom_gensim_vectors.kv") def test_missing_retreival(lang): assert lang["doesnotexist"].vector.shape == (10,) def test_spaces_retreival(lang): assert lang["graph trees"].vector...
import copy import itertools from typing import TYPE_CHECKING, Optional, List import torch from torch.optim import Optimizer from avalanche.benchmarks.utils import AvalancheConcatDataset, \ AvalancheTensorDataset, AvalancheSubset from math import ceil from avalanche.models import TrainEvalModel, NCMClassifier fro...
from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField(verbose_name="카테고리 명", max_length=50, unique=True) parent = TreeForeignKey('self', verbose_name="상위 카테고리", on_delete=models.CASCADE, null=True, blank=True, related_name='children') ...
# 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 u...
# Copyright (c) 2020-2021, NVIDIA CORPORATION. # # 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 agre...
#!/usr/bin/env python """ This module contains the :class:`Analysis` class, which is used for creating optimized, repeatable data processing workflows. An analysis can be created from a function or any other callable object. Dependent analyses can then be created using the :meth:`Analysis.then` method. Each function m...
import os import unittest from simple_salesforce import Salesforce from simple_salesforce.exceptions import ( SalesforceMalformedRequest, SalesforceResourceNotFound, ) @unittest.skipIf( any(["INSTANCE_URL" not in os.environ, "ACCESS_TOKEN" not in os.environ]), "environment not configured for integrat...
# Copyright (c) 2012-2013 ARM Limited # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functiona...
# -*- coding: utf-8 -*- """pyjstat is a python module for JSON-stat formatted data manipulation. This module allows reading and writing JSON-stat [1]_ format with python, using data frame structures provided by the widely accepted pandas library [2]_. The JSON-stat format is a simple lightweight JSON format for data d...
<<<<<<< HEAD ONOS_VERSION = "2.4.1-SNAPSHOT" ======= ONOS_VERSION = "2.5.0-SNAPSHOT" >>>>>>> origin/master ONOS_ARTIFACT_BASE = "onos-" ONOS_GROUP_ID = "org.onosproject" ONOS_ORIGIN = "ONOS Community" APP_PREFIX = ONOS_GROUP_ID + "." DEFAULT_APP_CATEGORY = "Utility" DEFAULT_JAVA_VERSION = "11"
# Copyright 2019 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
#! /usr/bin/env python3 class TestClass: greeting = 'hello' instance = TestClass() print( TestClass.greeting ) # =>> hello print( TestClass.greeting is instance.greeting ) # =>> True # removing class attributes del TestClass.greeting print( hasattr(instance, 'greeting') ) # =>> False # and ad...
# -*- coding:utf-8 -*- # author : alexloser # note : python3.4+ """ Bace3 is my python3.x module which contains some utilities and toolkits. """ __author__ = 'alexloser' __version__ = '1.0' __git__ = 'https://github/alexloser/bace3' __optional__ = ('numpy', 'mako', 'requests')
from unittest import TestCase, main from psycopg2 import DataError from src.TransactionManager import TransactionManager from src.utils import get_fly_book, get_hotel_book, \ get_fly_connection, get_hotel_connection, fly, hotel class TransactionManagerBase(TestCase): def setUp(self): ...
import os import copy import asyncio import logging from io import StringIO from datetime import datetime from functools import partial from operator import itemgetter from collections import defaultdict from binascii import hexlify, unhexlify from typing import Dict, Tuple, Type, Iterable, List, Optional, DefaultDict,...
from dataclasses import dataclass from typing import Any, List from src.types.blockchain_format.sized_bytes import bytes32 from src.util.clvm import int_to_bytes, int_from_bytes from src.util.hash import std_hash from src.util.ints import uint64 from src.util.streamable import streamable, Streamable @dataclass(froze...
# coding: utf-8 # # Copyright 2018 The Oppia 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 requi...
# vim: set fileencoding=utf-8 : from __future__ import absolute_import, print_function, unicode_literals import abc import json import types import logbook import requests import six import stethoscope.configurator import stethoscope.utils logger = logbook.Logger(__name__) @six.add_metaclass(abc.ABCMeta) class ...
import PyQt5.QtWidgets as qtw import PyQt5.QtGui as qtg import PyQt5.QtCore as qc class MainWindow(qtw.QWidget): def __init__(self): super().__init__() self.setWindowTitle("Hellow") self.setLayout(qtw.QVBoxLayout()) self.setupUI() def setupUI(self): self.entry=qtw.QLineEdit(self,placeholderText="Hi") ...
r""" Morphisms on affine varieties A morphism of schemes determined by rational functions that define \ what the morphism does on points in the ambient affine space. AUTHORS: - David Kohel, William Stein - Volker Braun (2011-08-08): Renamed classes, more documentation, misc cleanups. - Ben Hutz (2013-03) iterat...
''' Created on 20 May, 2011 This module shows how you can use vensim models directly instead of coding the model in Python. The underlying case is the same as used in fluExample .. codeauthor:: jhkwakkel <j.h.kwakkel (at) tudelft (dot) nl> epruyt <e.pruyt (at) tudelft (dot) nl> ''' from __future__ imp...
import glob import numpy as np import os import time start = time.time() valid = open("/home/longhn/Annotation_2906/valid.txt", "w", encoding="utf8") all_files = [] for ext in ["*.png", "*.jpeg", "*.jpg"]: images = glob.glob(os.path.join("/home/longhn/Annotation_2906/train", ext)) all_files += images num_img = le...
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt import frappe, unittest from frappe.widgets.form.meta import get_meta from frappe.widgets.form.load import getdoctype, getdoc class TestFormLoad(unittest.TestCase): def test_load(self): getdoctype("DocType") m...
from tkinter import Tk, Frame, BOTH, Menu, TclError, Label, RAISED, SUNKEN, SOLID, messagebox class Copapy(Frame): def __init__(self, parent=None): self.parent = parent Frame.__init__(self, parent, height=800, width=600) parent.title("copapy - copy & paste history") # parent.resizab...
import sys import time from django.conf import settings from django.db.backends.creation import BaseDatabaseCreation from django.utils.six.moves import input TEST_DATABASE_PREFIX = 'test_' PASSWORD = 'Im_a_lumberjack' class DatabaseCreation(BaseDatabaseCreation): # This dictionary maps Field objects to their a...
""" https://projecteuler.net/problem=2 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find th...
""" Test for the remove.py module in the vcontrol/rest/providers directory """ from os import remove as delete_file from web import threadeddict from vcontrol.rest.providers import remove PROVIDERS_FILE_PATH = "../vcontrol/rest/providers/providers.txt" class ContextDummy(): env = threadeddict() env['HTTP_HO...
""" Defines arguments manipulation utilities, like checking if an argument is iterable, flattening a nested arguments list, etc. These utility functions can be used by other util modules and are imported in util's main namespace for use by other pymel modules """ from collections import deque as _deque import sys, ope...
from rest_framework import generics, authentication, permissions from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.settings import api_settings from .serializers import UserSerializer, AuthTokenSerializer # Create your views here. class CreateUserView(generics.CreateAPIView): """ Cr...
import torch from torch import nn def get_activation(activation): activation_func = None if activation == 'tanh': activation_func = nn.Tanh() elif activation == 'sigmoid': activation_func = nn.Sigmoid() elif activation == 'relu': activation_func = nn.ReLU() elif activation ...
# from napari_mosquito_bb_annotations import threshold, image_arithmetic # add your tests here...
import os import boto3 from getpass import getpass from dotenv import load_dotenv dotenv_path = os.path.join(os.path.dirname(__file__), ".env") load_dotenv(dotenv_path) REGION_NAME = os.getenv("REGION_NAME") CLIENT_ID = os.getenv("CLIENT_ID") client = boto3.client("cognito-idp", region_name=REGION_NAME) username = i...
# Copyright 2021 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 or agreed to in writing, s...
"""Maintains a write-only copy of our usernotes for archival purposes""" from base64 import b64decode import json import os import time from zlib import decompress import praw import prawcore from slack_python_logging import slack_logger class UsernoteArchiver: """Main bot class""" def __init__(self): ...
#!/usr/bin/env python # Copyright 2017 gRPC 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://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
# SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries # # SPDX-License-Identifier: MIT """Pin definitions for the Coral Dev Board Mini.""" from adafruit_blinka.microcontroller.mt8167 import pin # Board name = RPI name [= alias] = pin name GPIO22 = D4 = pin.GPIO22 # Pin 7 GPIO9 = D17 = pin.G...
# Copyright (c) 2019 NVIDIA CORPORATION. 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 applicabl...
from oldowan.mtconvert import seq2sites, sites2seq, str2sites from string import translate import pandas as pd import numpy as np import sys import csv sys.path.append('../../scripts') from utils import * ## load metadata metadata = pd.read_csv('metadata.csv', index_col=0) region = range2region(metadata.ix[0,'SeqRang...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import ivfunctions import nnetivfunctions from mcpy import metrics from mcpy import plotting from mliv.dgps import fn_dict from raw_plots import raw_metric, plot_raw CONFIG = { "target_dir": "one_z_one_t_nnet", "rel...
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Prepare the build; do --help for more info, or try the test/prepare_build.txt file. ''' import argparse import re # Templates PATTERN_BUILD = '%s = (\d+)' # E.g: PROJECT_BUILD = 3 PATTERN_BUILD_TARGET = '%s = %d' PATTERN_STAGE = '%s = \'(\w+)\'' # E.g: PROJECT_STAGE = ...
from spec import Spec, skip, ok_, eq_, raises, trap from invoke.parser import Parser, Context, Argument, ParseError from invoke.collection import Collection class Parser_(Spec): def can_take_initial_context(self): c = Context() p = Parser(initial=c) eq_(p.initial, c) def can_take_ini...
# -*- coding: utf-8 -*- import sys import os import random import re import time import torch from torch.autograd import Variable from torch import optim import torch.nn as nn #sys.path.append('../') from hybrid_t2_model import Seq2Seq from hybrid_data_utils import * import psutil proc = psutil.Process...
# 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 # ATTENTION: all required packages must be configured to be installed during the onlin...
""" Copyright (c) 2020 Intel Corporation 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 writin...
"""webappexample URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Cl...
import click from graviteeio_cli.http_client.apim.api import ApiClient from ....exeptions import GraviteeioError @click.command() @click.option('--api', 'api_id', help='API id', required=True) @click.pass_obj def start(obj, api_id): """Starts an API.""" api_client: ApiClient = obj...
from django import forms from django.utils import timezone from django.utils.translation import ugettext as _ from django.utils.translation import ungettext from wagtail.admin import widgets from wagtail.core.models import Page, PageViewRestriction from .models import WagtailAdminModelForm from .view_restrictions imp...
# Generated by Django 3.0.5 on 2020-08-01 04:59 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('subscriptions', '0004_message'), ] operations = [ migrations.AddField( model_name='program', ...
import os import pickle from pprint import pformat from _pytest.fixtures import pytest_fixture_setup as fixture_result def pytest_addoption(parser): """ Add option to store/load fixture results into file """ parser.addoption( "--store", action="store", default=False, help="Store config") ...
# Copyright (c) 2016 Shotgun Software Inc. # # CONFIDENTIAL AND PROPRIETARY # # This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit # Source Code License included in this distribution package. See LICENSE. # By accessing, using, copying or modifying this work you indicate your # agreement to the S...
import logging from logging.handlers import TimedRotatingFileHandler from cryptocoinsinfo.reply_markups import * from cryptocoinsinfo.config import * # start logging to the file of current directory or º it to console # logging.basicConfig(level=logging.INFO, # format='%(asctime)s - %(name)s - %(l...
from typing import Union import pandas as pd import torch from torch.utils.data import Dataset class DiabetesDataset(Dataset): def __init__( self, data: Union[str, pd.DataFrame], transform = None, target_transform = None ) -> None: super().__init__() if isinst...
import argparse import gc import numpy as np import sys import json import time import torch import torch.backends.cudnn as cudnn sys.path.append('..') import pretrainedmodels import pretrainedmodels.utils as utils model_names = sorted(name for name in pretrainedmodels.__dict__ if not name.startswith("__") and name...
from django.shortcuts import render # Create your views here. from django.shortcuts import render def index(request): return render(request, 'chat/index.html') def room(request, room_name): return render(request, 'chat/room.html', { 'room_name': room_name })
# Run example on single image and two vessel masks (should run out of the box for a the example image and masks) #...............................Imports.................................................................. import numpy as np import torch import Visuallization as vis import Net as NetBuild import os import ...
import numpy import six import cupy from cupy import core from cupy.core import internal from cupy.linalg.solve import inv from cupy import util from cupy.util import collections_abc matmul = core.matmul def dot(a, b, out=None): """Returns a dot product of two arrays. For arrays with more than one axis, i...
from sympy import symbols, simplify, pprint import sympy as sp pU = symbols('pU') pB = symbols('pB') pUx = symbols('pUx') pUy = symbols('pUy') pBx = symbols('pBx') pBy = symbols('pBy') tau = symbols('tau') delta = symbols('delta') quadratic = \ (pUx + (tau - 1)*(pBx - pUx))**2 + \ (pUy + (tau - 1)*(pBy - pUy)...
from typing import Dict from eth_utils import decode_hex from web3.utils.filters import Filter from raiden_contracts.constants import EVENT_CHANNEL_OPENED, CONTRACT_TOKEN_NETWORK from raiden_contracts.contract_manager import CONTRACT_MANAGER from raiden.utils import typing from raiden.utils.filters import ( get_f...
"""Internal settings and definitions and functions for getting them.""" import collections class HeaderDict(collections.UserDict): """Sub-classing dict to allow for tab-completion.""" def __setitem__(self, key, value): if key == "data": raise KeyError("protected key") super().__s...
# Copyright (c) 2021 Matt Colligan # # 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, distr...
#!/usr/bin/env python """ Created on 13/01/2019 Author pacellig This class provides utilities for creating and importing JWK, either starting form existing RSA keys and x509 certificates, or creating them as needed. Each JWK might contain: alg: is the algorithm for the key kty: is the key type use: is ho...
# do not add future boilerplate to this plugin # specifically, do not add absolute_import, as the purpose of this plugin is to test implicit relative imports on Python 2.x __metaclass__ = type from ansible.plugins.lookup import LookupBase class LookupModule(LookupBase): def run(self, terms, variables, **kwargs):...
import sys import pygame from .colors import Colors from .utils import generate_random_values, scale_list SCREEN_HEIGHT, SCREEN_WIDTH = 500, 450 GAP = 10 ARRAY = [25, 38, 80, 31, 62, 52, 36, 11, 73, 51, 43, 32, 37, 8, 14, 26, 58, 23, 13, 20] class Quicksort: TICKS = 10 VALUE_COUNT = 20 ARRAY = ARRAY.c...
from pymongo import MongoClient from os import environ from dotenv import load_dotenv load_dotenv() def get_db(): client = MongoClient(environ.get("DATABASE_URL")) db = client['esharing-database'] return db
rows = 5 i = 0 while i <= rows - 1: j = 0 while j < i: # display space print('', end=' ') j += 1 k = i while k <= rows - 1: print('*', end=' ') k += 1 print() i += 1 i = rows - 1 while i >= 0: j = 0 while j < i: print('', end=' ') ...
# -*- coding: utf-8 -*- import scrapy class FerdosiShahnameSpider(scrapy.Spider): name = "nozar" allowed_domains = ["ganjoor.net"] start_urls = ["https://ganjoor.net/ferdousi/shahname/nozar/sh1/"] order = 1 def parse(self, response): sh = dict() sh["type"] = "masnavi" sh["...
# Copyright (c) 2020 PaddlePaddle 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 appli...
#!/usr/bin/env python import os import rospkg import roslib, rospy import subprocess, shlex from datetime import datetime from std_msgs.msg import String from radio_services.srv import InstructionAndStringWithAnswer first_standing_time = 0 last_sitting_time = 0 ros_visual_topic = '' sitting = False running = False ros...
#!/usr/bin/env python import base_filters COPY_GOOGLE_DOC_KEY = '1_-iPgi5Lk3hQsoJS8BKgngBStYA7rWC2wFXeIgb1eEw' USE_ASSETS = False # Use these variables to override the default cache timeouts for this graphic # DEFAULT_MAX_AGE = 20 # ASSETS_MAX_AGE = 300 JINJA_FILTER_FUNCTIONS = base_filters.FILTERS
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.base.exchange import Exchange # ----------------------------------------------------------------------------- try: basestri...
# MIT License # # Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020 # # 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 # r...
import os import pandas as pd import numpy as np import keras from keras.models import Sequential from keras.layers import * from keras.utils import to_categorical train_dataset = pd.read_csv('datasets/train.csv') test_dataset = pd.read_csv('datasets/test.csv') train_dataset.head() train_images = train_dataset.iloc[...