text
stringlengths
2
999k
import os import time import pytest @pytest.fixture(scope='function', autouse=True) def patched_random_port(mocker): print('using random port fixture...') used_ports = set() from jina.helper import random_port def _random_port(): for i in range(10): _port = random_port() ...
# 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, ...
""" https://leetcode.com/problems/reformat-the-string/ Given alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits). You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two...
#!/usr/bin/env python2 # MIT 6.034 Lab 1: Rule-Based Systems import os import sys import tarfile import traceback import xmlrpclib try: from cStringIO import StringIO except ImportError: from StringIO import StringIO python_version = sys.version_info is_windows = sys.platform in ["win32", "cygwin"] if pytho...
from django import forms from crispy_forms.layout import Layout, Fieldset from core.utils import horizontal_form_helper from labour.forms import AlternativeFormMixin from labour.models import Signup, JobCategory from programme.forms import ( ProgrammeOfferForm as BaseProgrammeOfferForm, AlternativeProgrammeF...
# Nessus.py # A graphical shell/file browser using pygame. # # Simon Heath # 10/2/2003 import pygame from pygame.locals import * # import system data from Nessus_data import * import sys, os # Local/dynamic data all_group = pygame.sprite.RenderClear() # Group for all sprites # Thegroups handle ...
import pickle from hashlib import blake2b from zlib import adler32 def checksum(item: object) -> bytes: """Returns a checksum of the given object.""" return blake2b(pickle.dumps(item, pickle.HIGHEST_PROTOCOL)).digest() def chksum(byte_string: bytes) -> int: """Returns a fast checksum of the given byte s...
import os from setuptools import setup, find_packages # Get version and release info, which is all stored in shablona/version.py ver_file = os.path.join('movie_analysis', 'version.py') with open(ver_file) as f: exec(f.read()) opts = dict(name="movie_analysis", description="finds correlation between ge...
import argparse import logging import torch import torch.nn as nn from torch.nn.modules.conv import _ConvNd multiply_adds = 1 def zero_ops(device): def wrapper(m, x, y): m.total_ops += torch.DoubleTensor([int(0)]).to(device) return wrapper def count_convNd(device): def wrapper(m: _ConvNd, x: ...
# Copyright (c) 2021, Shahzad Naser and Contributors # See license.txt # import frappe import unittest class TestAttendanceTime(unittest.TestCase): pass
# model settings temperature = 0.2 with_norm = True query_dim = 128 model = dict( type='SimSiamBaseSTSNTracker', backbone=dict( type='ResNet', pretrained=None, depth=18, out_indices=(3, ), # strides=(1, 2, 1, 1), norm_cfg=dict(type='SyncBN', requires_grad=True), ...
from django.apps import AppConfig class OrderItemsConfig(AppConfig): name = 'order_items'
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2015-2017 Alex Forencich 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...
""" Square ====== """ import numpy as np from ..topology_graph import Edge from .cof import Cof from .vertices import LinearVertex, NonLinearVertex class Square(Cof): """ Represents a sqaure COF topology graph. Unoptimized construction .. moldoc:: import moldoc.molecule as molecule ...
# coding: utf-8 """ Account Management API API for managing accounts, users, creating API keys, uploading trusted certificates OpenAPI spec version: v3 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class Er...
# -*- coding: utf-8 -*- from __future__ import unicode_literals HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.solr_backend.SolrEngine', 'URL': 'http://localhost:9001/solr/default', 'TIMEOUT': 60 * 5, 'INCLUDE_SPELLING': True, 'BATCH_SIZE': 100, ...
from setuptools import setup, find_packages from distutils.extension import Extension import os.path import sys import numpy # icedagcon has been replaced by pbdagcon since SMRTAnalysis 2.3. # The pseudo namespace 'pbtools' has been removed and the main entry # script has changed from pbtranscript.py to pbtranscript p...
# Generated by Django 3.1.8 on 2021-12-02 07:08 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('problem', '0010_logevent...
# Generated by Django 3.1.8 on 2021-08-24 12:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("permissions", "0005_auto_20210824_1446"), ] operations = [ migrations.AlterField( model_name="responsiblegroup", nam...
from django.db import models from django.db.models.aggregates import Count class ArticleQuerySet(models.query.QuerySet): def get_published(self): """返回已发表的文章""" return self.filter(status="P").select_related('user').order_by('-created_at') def get_drafts(self): """返回草稿箱的文章""" ...
#!/usr/bin/env python3 # Commissioning test. import os import sys from optparse import OptionParser from base import TestTimeout, BaseTestHelper, FailIfNot, logger # The thread network dataset tlv for testing, splited into T-L-V. TEST_THREAD_NETWORK_DATASET_TLV = "0e080000000000010000" + \ "000300000c" + \ "...
# -*- coding: utf-8 -*- from __future__ import print_function import argparse import os import stat import sys # find the import for catkin's python package - either from source space or from an installed underlay if os.path.exists(os.path.join('/opt/ros/melodic/share/catkin/cmake', 'catkinConfig.cmake.in')): sys....
from django.utils.translation import ugettext_lazy as _ INVALID_CREDENTIALS_ERROR = _('Unable to log in with provided credentials.') INACTIVE_ACCOUNT_ERROR = _('User account is disabled.') INVALID_TOKEN_ERROR = _('Invalid token for given user.') INVALID_UID_ERROR = _('Invalid user id or user doesn\'t exist.') STALE_T...
import numpy as np import pandas as pd import os from collections import UserDict def load_data(): """Load the GEFCom 2014 energy load data""" data_dir = 'data/' energy = pd.read_csv(os.path.join(data_dir, 'energy.csv'), parse_dates=['timestamp']) # Reindex the dataframe such that the dataframe has a...
""" =================== Reading an STC file =================== STC files contain activations on cortex ie. source reconstructions """ # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD (3-clause) import matplotlib.pyplot as plt import mne from mne.datasets import sample print(__doc__) dat...
""" Declare the SQLAlchemy model for the Sample data object """ from sqlalchemy import Column, Integer, String, Boolean, JSON, ForeignKey from sqlalchemy.orm import relationship from . import Base class Sample(Base): """SQLAlchemy model for the Sample data object""" __tablename__ = "samples" sample_id...
import tests.periodicities.period_test as per per.buildModel((15 , 'M' , 400));
# Generated by Django 2.2 on 2020-01-15 06:34 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('rates', '0005_auto_20200115_0927'), ] operations = [ migrations.AlterField( model_name='rating', ...
""" Support for HomematicIP alarm control panel. For more details about this component, please refer to the documentation at https://home-assistant.io/components/alarm_control_panel.homematicip_cloud/ """ import logging from homeassistant.const import ( STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM...
from .bases import _ScandinavianStemmer from whoosh.compat import u class NorwegianStemmer(_ScandinavianStemmer): """ The Norwegian Snowball stemmer. :cvar __vowels: The Norwegian vowels. :type __vowels: unicode :cvar __s_ending: Letters that may directly appear before a word final 's'. :ty...
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RImpute(RPackage): """impute: Imputation for microarray data. Imputation for micro...
from biclustering import Bicluster, MSR, DeltaBiclustering __all__ = ['Bicluster', 'MSR', 'DeltaBiclustering']
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2015, René Moser <mail@renemoser.net> # # This file is part of Ansible # # Ansible 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 3 of the Lice...
"""Application Programming Interface.""" from __future__ import annotations from fastapi import APIRouter, Depends, FastAPI, status import imagesecrets from imagesecrets import schemas from imagesecrets.api import dependencies, handlers, openapi, responses, tasks from imagesecrets.api.routers import decode, encode, u...
import torch import torch.nn as nn from gneiss.cluster import random_linkage from gneiss.balances import sparse_balance_basis from scipy.sparse import coo_matrix import numpy as np from torch.distributions import Multinomial, Normal from catvae.composition import ilr from catvae.distributions.mvn import MultivariateNor...
from eth_account import ( Account, ) from eth_utils import ( apply_to_return_value, is_checksum_address, is_string, ) from hexbytes import ( HexBytes, ) from web3._utils.blocks import ( select_method_for_block_identifier, ) from web3._utils.empty import ( empty, ) from web3._utils.encoding ...
__all__ = [ 'vadd2', 'vadd3', 'vdiv2', 'vdiv3', 'vexp', 'vless2', 'vless3', 'vmul2', 'vmul3', 'vneg', 'vnegneg', 'vrand', 'vrepmat', 'vrepmatneg', 'vsquare', 'vsquaresquare', 'vsum' ]
'''LeNet in PyTorch.''' import torch.nn as nn import torch.nn.functional as F class LeNet(nn.Module): def __init__(self, nc=3, h=32, w=32): super(LeNet, self).__init__() self.conv1 = nn.Conv2d(nc, 6, 5) h, w = round((h-4)/2), round((w-4)/2) self.conv2 = nn.Conv2d(6, 16, 5) ...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from sqlalchemy.orm import subqueryload class ConnectorRegistry(object): """ Central Registry for all available datasource engines""" s...
from django.core.management.base import BaseCommand from django.conf import settings from apps.supporters.models import SupportLevel, Supporter import os import glob import csv import re class Command(BaseCommand): def handle(self, *args, **options): csv_dir = os.path.join(settings.SITE_ROOT, 'apps/suppo...
# Copyright 2013 National Technology & Engineering Solutions of Sandia, LLC (NTESS). # Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government # retains certain rights in this software. # # This code does the actual parsing of csv files and matrix files # for VideoSwarm. # # S. Martin # 5/20/2018 im...
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import errno import os import time import unittest from builtins import open, str from co...
# SPDX-License-Identifier: Apache-2.0 """Unit tests using onnx backends.""" # pylint: disable=missing-docstring,unused-import import os import zipfile import numpy as np import tensorflow as tf from onnx import helper from common import check_tf_min_version, unittest_main, requires_custom_ops, check_opset_min_ver...
# -*- coding: utf-8 -*- # Copyright (c) 2015 Jason Power # 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 con...
import json import os import random from logging import Logger, WARNING from time import sleep import pandas as pd from catalyst.assets._assets import TradingPair from logbook import TestHandler from catalyst.exchange.exchange_errors import ExchangeRequestError from catalyst.exchange.exchange_execution import Exchang...
# coding: utf-8 from mock import patch def test_too_many_requests_causes_retry(box_client, mock_box, monkeypatch): monkeypatch.setattr(mock_box, 'RATE_LIMIT_THRESHOLD', 1) with patch('random.uniform', return_value=1): box_client.folder('0').get() box_client.folder('0').get() assert len(mo...
# coding: utf-8 from __future__ import unicode_literals import itertools import json import os.path import random import re import time import traceback from .common import InfoExtractor, SearchInfoExtractor from ..jsinterp import JSInterpreter from ..swfinterp import SWFInterpreter from ..compat import ( compa...
from datetime import datetime from pathlib import Path from .console_logger import ConsoleLogger from .data_logger import DataLogger class Logger(DataLogger, ConsoleLogger): """ This class implements the logging functionality. It can be used to create automatically a log directory, save numpy data array ...
"""extract_wheels extract_wheels resolves and fetches artifacts transitively from the Python Package Index (PyPI) based on a requirements.txt. It generates the required BUILD files to consume these packages as Python libraries. Under the hood, it depends on the `pip wheel` command to do resolution, download, and comp...
from ._WinObject import * from typing import Optional __all__ = ['Bookmark'] class Bookmark(_WinObject): def __init__(self): _WinObject.__init__(self) def isEmpty(self) -> bool: return self.impl.Empty def getStart(self) -> int: return self.impl.Start def g...
import tensorflow as tf ## Layers: follow the naming convention used in the original paper ### Generator layers def c7s1_k(input, k, reuse=False, norm='instance', activation='relu', is_training=True, name='c7s1_k'): """ A 7x7 Convolution-BatchNorm-ReLU layer with k filters and stride 1 Args: input: 4D tenso...
import re import click def test_other_command_invoke(runner): @click.command() @click.pass_context def cli(ctx): return ctx.invoke(other_cmd, arg=42) @click.command() @click.argument("arg", type=click.INT) def other_cmd(arg): click.echo(arg) result = runner.invoke(cli, [...
# engine/cursor.py # Copyright (C) 2005-2021 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: https://www.opensource.org/licenses/mit-license.php """Define cursor-specific result set constructs including :class:`.BaseCursorResul...
from .. import functions as fn from .GraphicsObject import GraphicsObject from .ScatterPlotItem import ScatterPlotItem import pyqtgraph as pg import numpy as np __all__ = ['GraphItem'] class GraphItem(GraphicsObject): """A GraphItem displays graph information as a set of nodes connected by lines (as in 'grap...
# Copyright 2010 OpenStack Foundation # Copyright 2012 University Of Minho # # 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....
""" DistChunky SceneSplitter Python 3 colebob9 This script takes scene files in a "scenes" directory and splits them up based on benchmark scores. TODO: Some extra tweaks to calculating SSP if the benchmark scores are too far from each other Factor in already rendered SSP put benchmark results into another config fil...
import numpy as np import matplotlib.pyplot as plt import math def split_file(file): answer = [[]] j = 0 for i in file: if i == "\n": j += 1 if j == 16: pass else: answer.append([]) elif i[:3] == "VOM": answer[j]...
import numpy as np from . import gaussianprocess as gp import matplotlib.pyplot as plt ##### def findsmoothvariance(y, filtsig= 0.1, nopts= False): ''' Estimates and then smooths the variance over replicates of data Arguments -- y: data - one column for each replicate filtsig: sets the size of...
import csv import io import urllib.request from scipy.cluster.hierarchy import ward, fcluster from scipy.spatial.distance import pdist from scipy.cluster import hierarchy import matplotlib.pyplot as plt import numpy as np data = {} for i in range(1, 73): print(i) url = f"http://demo.spraakdata.gu.se/lsi/clld...
# Copyright 2009-2017 Ram Rachum. # This program is distributed under the MIT license. '''Testing module for `python_toolbox.sleek_reffing`.'''
from . import * from .cvfun import align_vertically import matplotlib.pyplot as plt class Rotater: def rotate_data(self, filename): filename = verify_json_in_filename(filename) data = read(PROCESSED + filename) for field in data: field_id = field["id"] image = cv2...
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : DoubleMA.py @Time : 2021/05/23 @Author : levonwoo @Version : 0.2 @Contact : @License : (C)Copyright 2020-2021 @Desc : 双均线策略示例 ''' # here put the import lib import numpy as np import time import matplotlib.pyplot as plt import talib fr...
#!/usr/bin/env python3 # # Copyright 2021 Graviti. Licensed under MIT License. # """Implementation of gas dataset.""" from typing import Dict import click from .tbrn import TBRN, TBRNType from .utility import error, get_gas def _implement_dataset(obj: Dict[str, str], tbrn: str, is_delete: bool, yes: bool) -> None...
# Copyright (c) 2020, 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 applic...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import time import pandas as pd import stock import baostock as bs def dispatch(row): if 'watch' == row['status']: return handle_watch(row) elif 'pre_buy' == row['status']: return handle_pre_buy(row) elif 'buy' == row['status']: retur...
from modules.rpgsrc import world, typeloader, worldgen import sys if len(sys.argv) == 1: print("Usage: python3 worldgen.py [-w] [-l]") print("-w will generate an entire world and replace the current one.") print("-l will generate and replace the loot of the current world.") else: typeloader.loadAll() if "-w" in ...
def stars_for_rank(rank): if rank >= 21: return 2 if rank >= 16: return 3 if rank >= 11: return 4 return 5 rank = 25 stars = 0 streak = 0 record = list(input()) for game in record: if rank == 0: break if game == "W": streak += 1 stars += (2 if str...
import asyncio import random from functools import partial from aioredis.commands import ( create_redis, Redis, create_redis_pool ) from aioredis.errors import ProtocolError from aioredis.errors import ReplyError, RedisClusterError from aioredis.log import logger from aioredis.util import decode, encode_st...
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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 program is distrib...
"""https://open.kattis.com/problems/icpcawards""" from collections import OrderedDict N = int(input()) rank = OrderedDict() prizes = 12 for _ in range(N): uni, team = input().split() if uni not in rank and prizes != 0: rank[uni] = team prizes -= 1 for uni, team in rank.items(): print(uni...
# 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 or agreed to in writing, s...
from hubbot.moduleinterface import ModuleInterface from hubbot.response import IRCResponse, ResponseType class Do(ModuleInterface): help = "do [channel] <thing> -- do a thing." triggers = ["do"] def on_trigger(self, message): """ @type message: hubbot.message.IRCMessage """ ...
from cloudcafe.identity.v3.common.tokens.behavior import TokensBehavior from cloudcafe.identity.v3.common.tokens.client import TokensClient from cloudcafe.identity.composites import IdentityBaseComposite class IdentityV3Composite(IdentityBaseComposite): def __init__(self, user_config=None): super(Identit...
import torch import torch.nn as nn class StatisticsPooling(torch.nn.Module): """ Mean and Standard deviation pooling """ def __init__(self): """ """ super(StatisticsPooling, self).__init__() pass def forward(self, x): """ :param x: :return:...
# --- # jupyter: # jupytext: # formats: ipynb,py:percent # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.11.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% fro...
from zeeguu.core.model import Text, Bookmark from zeeguu.core.util.hash import text_hash from zeeguu.core import db all_texts = Text.query.order_by(Text.id.desc()).all() removed = 0 for each in all_texts: # print(each.id) dups = Text.query.filter_by(content=each.content).all() if len(dups) > 1: ...
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Member.average_weekly_presence_hours' db.add_column('mks_member', 'average_weekly_presence...
from fastapi import FastAPI from pydantic import BaseModel from typing import Optional, Text from datetime import datetime app = FastAPI() postdb = [] #post model class Post(BaseModel): id: int title: str content: Text created_ay: datetime = datetime.now() published: Optional[bool] = False @app....
import json from typing import List from django.db.models import QuerySet from django.http import HttpRequest, HttpResponse, JsonResponse from django.views.decorators.http import require_GET, require_POST from AOGSbackend.decorators.authenticated_decorator import authenticated from AOGSbackend.utils.http_tools import...
from django.contrib import admin from .models import Question, Choice class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': [ 'p...
nome= input('Qual é o seu nome? ') print('Olá ' + nome + '! Prazer em te conhecer.')
########################################################################### # # Copyright 2018 Google 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 # # https://www.apache.org...
# Generated by Django 3.0.7 on 2020-06-12 10:03 from django.db import migrations def sync_length(apps, schema_editor): for road in apps.get_model("roads", "Road").objects.all(): road.length = len(road.path) road.save() class Migration(migrations.Migration): dependencies = [ ('roads...
Tox21_targets = [ 'NR-AR', 'NR-AR-LBD', 'NR-AhR', 'NR-Aromatase', 'NR-ER', 'NR-ER-LBD', 'NR-PPAR-gamma', 'SR-ARE', 'SR-ATAD5', 'SR-HSE', 'SR-MMP', 'SR-p53'] ToxCast_targets = ['ACEA_T47D_80hr_Negative', 'ACEA_T47D_80hr_Positive', 'APR_HepG2_CellCycleArrest_24h_dn', 'APR_HepG2_CellCycleArrest_24h_up', ...
#codigo, quien emitio la invitacion, quien uso la invitacion, si se a usado o no # y a que circulo pertenece. #Django from django.db import models #Project from cride.utils import CRideModel #Managers from cride.circles.managers import InvitationManager class Invitation(CRideModel): """ A circle invitation...
import os import sys import time import numpy as np from PIL import Image import pickle #if os.path.realpath(os.getcwd()) != os.path.dirname(os.path.realpath(__file__)): # sys.path.append(os.getcwd()) import deephar from keras.utils.data_utils import get_file from deephar.config import ntu_dataconf sys.path.app...
import os import typing as t from typing import TYPE_CHECKING import numpy as np from torch._C import device from simple_di import inject from simple_di import Provide import bentoml from bentoml import Tag from bentoml.exceptions import BentoMLException from bentoml.exceptions import MissingDependencyException from...
import sys if sys.version_info < (3, 7): from ._yref import YrefValidator from ._yanchor import YanchorValidator from ._y import YValidator from ._xref import XrefValidator from ._xanchor import XanchorValidator from ._x import XValidator from ._visible import VisibleValidator from ._te...
from wafw00f.main import WafW00F from n0s3p4ss.config import config CONFIG = config() def detect(url): wafw00f = WafW00F( target=url, proxy=CONFIG.WAFW00F_PROXY ) return wafw00f.identwaf(True)
N, Q = map(int, input().split()) G = [[] for _ in range(N)] from collections import deque for i in range(N - 1): a, b = map(int, input().split()) G[a - 1].append(b - 1) G[b - 1].append(a - 1) dist = [-1] * N dist[0] = 0 d = deque() d.append(0) while d: v = d.popleft() for i in G[v]: if d...
# -*- coding: utf-8 -*- # bing search engine import requests import re import sys import time from urllib import quote from searchEngine import SearchEngine class SEgalaxy(SearchEngine): def __init__(self): super(SEgalaxy, self).__init__() self.engineName = "galaxy" # self.url = "http:/...
from decimal import Decimal import logging, sys, os from shutil import copyfile import sqlalchemy from logic_bank_utils import util as logic_bank_utils (did_fix_path, sys_env_info) = \ logic_bank_utils.add_python_path(project_dir="LogicBank", my_file=__file__) print("\n" + did_fix_path + "\n\n" + sys_env_info + ...
from insertion import random_number_insertion def print_to_screen(element, a_list): ''' Prints element and list to screen, O(n) time with n being the size of the list. It goes through the list two times, but since constants are removed the time is still O(n) ''' print(element) stringified_...
# 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...
from abc import ABC, abstractmethod from ..bitstring_distribution import BitstringDistribution, create_bitstring_distribution_from_probability_distribution from ..circuit import Circuit from ..measurement import ExpectationValues from typing import Optional, List, Tuple from openfermion import QubitOperator from pyquil...
"""The first hint for this problem is the title of the webpage: 'peak hell'. When pronounced, it sounds very similar to 'pickle', which is the builtin python object serialization package. When viewing the the source code of the webpage, there is a 'peakhell' tag that links to a pickle file. We'll download the file (pro...
#!/usr/bin/env python3 from duetwebapi import DuetWebAPI as DWA import json ################################### # Create API link ################################### riley = DWA('http://riley') bruce = DWA('http://bruce') ################################### # REST API methods ################################### riley...
"""IX.IO pastebin like site Syntax: .paste Syntax: .npaste Syntax: .paster Syntax: .iffuci """ import logging logging.basicConfig(format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s', level=logging.WARNING) import asyncio import os from datetime import datetime import requests from telethon...
# # This file is part of pyasn1-modules software. # # Created by Russ Housley # Copyright (c) 2019, Vigil Security, LLC # License: http://snmplabs.com/pyasn1/license.html # import sys import unittest from pyasn1.codec.der.decoder import decode as der_decoder from pyasn1.codec.der.encoder import encode as der_encoder ...
from django import forms class ErrorForm(forms.Form): reason = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control error-form'}), label='Fortell oss hvordan du kom hit:')