filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_4199
#!/usr/bin/env python # -*- coding: utf-8 -*- import featuretools as ft import pandas as pd import pytest from numpy import nan from cardea.data_loader import EntitySetLoader from cardea.problem_definition import MissedAppointment @pytest.fixture() def missed_appointment(): return MissedAppointment() @pytest....
the-stack_0_4201
from django.shortcuts import render from vdw.raw.sources.models import Source def sources(request): sources = Source.objects.filter(published=True, archived=False)\ .select_related('stats') return render(request, 'sources/sources.html', { 'sources': sources, })
the-stack_0_4202
from setuptools import find_packages, setup with open('README.md', 'r') as fh: long_description = fh.read() setup( name='backoid', description='backoid', version="0.0.1", long_description=long_description, long_description_content_type="text/markdown", packages=find_packages("src"), p...
the-stack_0_4204
# coding=utf-8 # Copyright 2016 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 os from pants.base.file_system_project_tree import FileSystemProjectTree from pan...
the-stack_0_4207
import json import zipfile import os import sys import pytest from click.testing import CliRunner import mock from chalice import cli from chalice.cli import factory from chalice.config import Config from chalice.utils import record_deployed_values from chalice import local from chalice.constants import DEFAULT_APIGA...
the-stack_0_4208
import os import pandas as pd def read_synchronisation_file(experiment_root): filepath = os.path.join(experiment_root, "labels", "synchronisation.csv") return pd.read_csv(filepath) def convert_timestamps(experiment_root, timestamps, from_reference, to_reference): """ Convert numeric timestamps (seco...
the-stack_0_4209
# coding: utf-8 # Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department # Distributed under the terms of "New BSD License", see the LICENSE file. import unittest from pyiron_base.job.template import PythonTemplateJob from pyiron_base._tests import TestWithProject c...
the-stack_0_4210
""" Calculations that deal with seismic moment tensors. Notes from Lay and Wallace Chapter 8: * Decomposition 1: Mij = isotropic + deviatoric * Decomposition 2: Mij = isotropic + 3 vector dipoles * Decomposition 3: Mij = isotropic + 3 double couples * Decomposition 4: Mij = isotropic + 3 CLVDs * Decomposition 5: Mij =...
the-stack_0_4211
# Copyright 2019 ZTE corporation. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 from typing import Any, Mapping, NamedTuple, Optional, Sequence from itertools import zip_longest from . import utilities from .models.data_format import DataFormat def get_tensor_by_fuzzy_name(graph, name): if ':' in n...
the-stack_0_4212
#!/usr/bin/env python3 # Copyright 2021 The Pigweed 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
the-stack_0_4214
import cv2 import os import scipy as scp import scipy.misc import matplotlib from sklearn.cluster import KMeans import numpy as np import evaluationClass_tools as evTools import random from sklearn import svm from sklearn import preprocessing import pickle import triangle_detection as triang def oneClass(image_seg): ...
the-stack_0_4215
# encoding: utf-8 import datetime from django.test import TestCase from haystack import connections from haystack.inputs import AltParser, Exact from haystack.models import SearchResult from haystack.query import SQ, SearchQuerySet from ..core.models import AnotherMockModel, MockModel class SolrSearchQueryTestCase...
the-stack_0_4216
from select import select from scapy.all import conf, ETH_P_ALL, MTU, plist # Stop sniff() asynchronously # Source: https://github.com/secdev/scapy/issues/989#issuecomment-380044430 def sniff(store=False, prn=None, lfilter=None, stop_event=None, refresh=.1, *args, **kwargs): """Sniff packets sniff([coun...
the-stack_0_4218
import logging as log from django.core.management.base import BaseCommand from django.contrib.auth import get_user_model from django_keycloak.keycloak import Connect class Command(BaseCommand): help = "Synchronize users with keycloak" def handle(self, *args, **options): keycloak = Connect() ...
the-stack_0_4220
import os import logging from functools import partial import pandas as pd from solarforecastarbiter.io.fetch import eia from solarforecastarbiter.io.reference_observations import ( common, default_forecasts) from requests.exceptions import HTTPError logger = logging.getLogger('reference_data') def initialize_...
the-stack_0_4223
import math file = open('day-5.input') result = 0 # F, ==> lower half ==> [min, math.floor((max - min) / 2)] # B,R ==> upper half def get_row(expression): min = 0 max = 127 for i in range(7): selector = expression[i] if selector == 'F': max = math.floor((max+min)/ 2) elif selector == 'B': ...
the-stack_0_4224
# coding: utf-8 """ NiFi Rest Api The Rest Api provides programmatic access to command and control a NiFi instance in real time. Start and stop processors, monitor queues, query provenance data, and more. Each endpoint below includes a description, ...
the-stack_0_4225
#!/usr/bin/env python3 #------------------------------------------------------------------------------- # ============LICENSE_START======================================================= # Copyright (C) 2018 Sven van der Meer. All rights reserved. # ====================================================================...
the-stack_0_4227
""" The Sponge Roll Problem with Columnwise Column Generation for the PuLP Modeller Authors: Antony Phillips, Dr Stuart Mitchell 2008 """ # Import Column Generation functions from CGcolumnwise import * # The Master Problem is created prob, obj, constraints = createMaster() # A list of starting patterns is created...
the-stack_0_4230
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2019-Present Datadog, Inc. import re # noqa: F401 import sys # noqa: F401 from datadog_api_client.v2.model_uti...
the-stack_0_4231
# Copyright 2021, The TensorFlow Federated 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 o...
the-stack_0_4232
#!/usr/bin/env python3 """ Utility functions for testing. """ import copy import numpy as np SEED = 42 def round_dict(d, precision=3): """Round all numerical values in a dictionary recursively.""" d = copy.deepcopy(d) if isinstance(d, dict): for k, v in d.items(): try: ...
the-stack_0_4233
import random import os.path import sys import logging import gtk import gs import gs.ui.rtgraph as rtgraph import gs.config as config LOG = logging.getLogger("graph") class FieldChannel(rtgraph.Channel): def __init__(self, msg, field): rtgraph.Channel.__init__(self) i = 0 for f in msg.f...
the-stack_0_4234
#!/usr/bin/env python3 # coding: utf8 """ Description: Using fasta files (scaffold/chromosme/contig file, protein file), gff file, annotation tsv file and the species name this script writes a genbank file. The annotation tsv file contains association between gene and annotation (EC number, GO term, Interpro) to add ...
the-stack_0_4235
#! /usr/bin/env python # -*- coding: utf-8 -*- from django.conf.urls import url, include from config import views urlpatterns = [ url(r'^$', views.index, name='config'), url(r'^config_save/$', views.config_save, name='config_save'), url(r'^token/', views.get_token, name='token'), ]
the-stack_0_4236
from functools import partial import pandas as pd from cellphonedb.src.core.core_logger import core_logger from cellphonedb.src.core.exceptions.AllCountsFilteredException import AllCountsFilteredException from cellphonedb.src.core.exceptions.NoInteractionsFound import NoInteractionsFound from cellphonedb.src.core.met...
the-stack_0_4237
#!/usr/bin/python # -*- coding:utf-8 -*- """ CNN/Convnets/Convolutional neural networks keras tensorflow """ from keras.datasets import cifar10 from keras.models import Sequential from keras.layers.convolutional import Conv2D from keras.layers.convolutional import MaxPooling2D from keras.layers import Dense from kera...
the-stack_0_4238
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2014, Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # -------------------------------------------------------------------------...
the-stack_0_4240
from icalendar import vCalAddress from app.config import ICAL_VERSION, PRODUCT_ID from app.routers.export import ( create_ical_calendar, create_ical_event, event_to_ical ) class TestExport: def test_create_ical_calendar(self): cal = create_ical_calendar() assert cal.get('version') == ICAL_VE...
the-stack_0_4242
# step 1. imports from sqlalchemy import (create_engine, MetaData, Table, Column, Integer, String, ForeignKey, Float, DateTime) from sqlalchemy.orm import sessionmaker, mapper, relationship from sqlalchemy.ext.horizontal_shard import ShardedSession from sqlalchemy.sql import operators, visitors import datetime #...
the-stack_0_4243
from setuptools import setup import os VERSION = "2.8.3" def get_long_description(): with open( os.path.join(os.path.dirname(os.path.abspath(__file__)), "README.md"), encoding="utf8", ) as fp: return fp.read() setup( name="github-to-sqlite", description="Save data from GitHu...
the-stack_0_4244
class Team: def __init__(self, NO): self.NO = NO self.fighter_list = None self.order = None # previous index of the order self.fight_cnt = 0 @property def fighter_list(self): return self._fighter_list @fighter_list.setter def fighter_l...
the-stack_0_4245
import asyncio import logging import signal import sys from functools import partial from typing import Union, List, Callable, Tuple import serial from bleak import BleakClient from serial_asyncio import open_serial_connection from genki_wave.callbacks import WaveCallback from genki_wave.constants import API_CHAR_UUI...
the-stack_0_4246
# Copyright 2018-2020 Xanadu Quantum Technologies 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 applicabl...
the-stack_0_4248
# Copyright (c) Microsoft 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 wri...
the-stack_0_4249
# -*- coding: utf-8 -*- """ werkzeug ~~~~~~~~ Werkzeug is the Swiss Army knife of Python web development. It provides useful classes and functions for any WSGI application to make the life of a python web developer much easier. All of the provided classes are independent from each ot...
the-stack_0_4255
from django.contrib.auth.models import AnonymousUser from core.models.group import get_user_group from core.models.project import Project from rest_framework import serializers class ProjectsField(serializers.Field): def to_representation(self, project_mgr): request_user = self.parent.request_user ...
the-stack_0_4258
from __future__ import absolute_import import urlparse import boto3 class S3DirectoryGenerator(object): def __init__(self, s3_url): parsed_s3_url = urlparse.urlparse(s3_url) if parsed_s3_url.scheme != 's3': raise SyntaxError('Invalid S3 scheme') self.bucket_name = parsed_s3_ur...
the-stack_0_4259
# qubit number=4 # total number=40 import cirq import qiskit from qiskit import IBMQ from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer, execute, transpile from pprint import pprint from qiskit.test.mock import FakeVigo from ma...
the-stack_0_4260
import json import random import sys from allennlp_reasoning_explainqa.common.constants import CORRECT_OPTION_TAG from allennlp_reasoning_explainqa.training.metrics.confusion_matrix import ( F1MeasureCustomRetrievalEval, ) from allennlp_reasoning_explainqa.training.metrics.explanation_eval import ( Explanation...
the-stack_0_4261
import matplotlib.pyplot as plt import pandas as pd from rich import pretty, print from rich.progress import BarColumn, Progress from sklearn.metrics import ( accuracy_score, auc, classification_report, f1_score, plot_confusion_matrix, roc_auc_score, roc_curve, ) from sklearn.neural_network ...
the-stack_0_4262
import secrets; from app import app; from .rvp import pvr; from .algo import final; from flask import render_template, request, redirect, flash @app.route("/", methods=["GET","POST"]) def index(): secret_key=secrets.token_hex(16) app.config["SECRET_KEY"]=secret_key if(request.method=="POST"): re...
the-stack_0_4263
from __future__ import print_function from builtins import object from pyethapp.eth_protocol import ETHProtocol, TransientBlockBody from devp2p.service import WiredService from devp2p.protocol import BaseProtocol from devp2p.app import BaseApp from ethereum.tools import tester import rlp class PeerMock(object): p...
the-stack_0_4264
"""Provide the Message class.""" from typing import TYPE_CHECKING, Any, Dict from ...const import API_PATH from .base import RedditBase from .mixins import FullnameMixin, InboxableMixin, ReplyableMixin from .redditor import Redditor from .subreddit import Subreddit if TYPE_CHECKING: # pragma: no cover from ... i...
the-stack_0_4265
# Copyright 2013-2019 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 Cmor(AutotoolsPackage): """Climate Model Output Rewriter is used to produce CF-compliant n...
the-stack_0_4266
''' https://blog.csdn.net/xuzhexing/article/details/90729390 https://blog.csdn.net/weixin_44580210/article/details/90314878 粒子滤波定位可以比单纯地利用观测值更精确 步骤: 1.初始:用大量粒子模拟运动状态,这些粒子在整个运动空间内均匀分布 2.预测:根据状态转移方程(运动方程),将每一个粒子带入,得到预测粒子,这里应该包括粒子的速度角速度,以及xy值,进行高维的预测 3.校正:对预测粒子进行评价,这里用下一时刻的观测值(有噪声)与预测粒子的距离作评价 距离越短,则对应粒子的权...
the-stack_0_4270
#!/usr/bin/env python """Package: mininet Test creation and pings for topologies with link and/or CPU options.""" import unittest import sys from functools import partial from mininet.net import Mininet from mininet.node import OVSSwitch, UserSwitch, IVSSwitch from mininet.node import CPULimitedHost from mininet....
the-stack_0_4271
import datetime import posixpath from django import forms from django.core import checks from django.core.files.base import File from django.core.files.images import ImageFile from django.core.files.storage import Storage, default_storage from django.core.files.utils import validate_file_name from django.db.models imp...
the-stack_0_4273
#!/usr/bin/env python3 import argparse import ctypes import os import readline import socket import subprocess import sys import threading readline.get_history_length() # throw this away because we import readline for prompt stuff parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter...
the-stack_0_4274
""" Single-subject data (two sessions) in native space ================================================== The example shows the analysis of an SPM dataset studying face perception. The analysis is performed in native space. Realignment parameters are provided with the input images, but those have not been resampled t...
the-stack_0_4276
""" Exercício Python 113: Reescreva a função leiaInt() que fizemos no desafio 104, incluindo agora a possibilidade da digitação de um número de tipo inválido. Aproveite e crie também uma função leiaFloat() com a mesma funcionalidade. """ def leiaInt(mensagem): value = 0 while True: try: val...
the-stack_0_4277
#!/usr/bin/env python2.5 # # Copyright 2010 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
the-stack_0_4279
from .model import Model from radar.models.geofence import Geofence from radar.models.region import Region from radar.models.place import Place class RadarContext(Model): """Location context Parameters: live (bool) geofences (`list` of :class:`~radar.models.geofence.Geofence`) pla...
the-stack_0_4281
from pprint import pprint import yaml from tabulate import tabulate from funcy import project from wws.commands import utils class Rm: def __init__(self): super().__init__() def process(self, args): """ edits the warp database """ if args['debug']: pprint(args) wit...
the-stack_0_4283
#!/usr/bin/env python3 import asyncio import time from psnawp_api import psnawp from pypresence import Presence from asset_updater import add_game_icon from playstationpresence.lib.files import load_config, load_game_data, load_game_icons from playstationpresence.lib.notifiable import Notifiable from playstationpresenc...
the-stack_0_4284
#! /usr/bin/env python """ based on this quickstart: from https://developers.google.com/google-apps/calendar/quickstart/python Don't forget to put CLIENT_SECRET_FILE in ~/.credentials Note: the above URL redirects to https://developers.google.com/calendar/quickstart/python which has a different sequence for get_crede...
the-stack_0_4285
# coding: utf8 """ Implementation of finite DPP MCMC samplers: - `add_exchange_delete_sampler` - `add_delete_sampler` - `basis_exchange_sampler` - `zonotope_sampler` .. seealso: `Documentation on ReadTheDocs <https://dppy.readthedocs.io/en/latest/finite_dpps/mcmc_sampling.html>`_ """ import time import numpy as...
the-stack_0_4286
def checkPangram(s): List = [] # create list of 26 charecters and set false each entry for i in range(26): List.append(False) # converting the sentence to lowercase and iterating # over the sentence for c in s.lower(): if not c == " ": ...
the-stack_0_4289
import logging import json import os import shutil import subprocess from .base import BaseExporter logger = logging.getLogger(__name__) __all__ = ["JSONExporter"] class JSONExporter(BaseExporter): short_name = "json_file" TESTS_DIR_NAME = "tests" SOLUTION_DIR_NAME = "solutions" VALIDATOR_DIR...
the-stack_0_4290
# -*- 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 or...
the-stack_0_4292
# -*- coding: utf-8 -*- import copy import json from freezegun import freeze_time from mantarray_desktop_app import MICRO_TO_BASE_CONVERSION from mantarray_desktop_app import SERIAL_COMM_DEFAULT_DATA_CHANNEL from mantarray_desktop_app import START_MANAGED_ACQUISITION_COMMUNICATION from mantarray_desktop_app import STO...
the-stack_0_4293
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="findmylibs", version="0.0.1", author="The Nomadic Coder", author_email="atemysemicolon@gmail.com", description="A package to probe installed libraries", long_description=long_descripti...
the-stack_0_4295
import numpy as np trials=10_00_000 dice=int(input("Enter the no of dices :")) for i in np.arange(1*dice,dice*6 + 1): found=0 for _ in np.arange(trials): total=0 for _ in np.arange(dice): total+=np.random.randint(1,7) if(total==i): found+=1 print("Sum Value :"...
the-stack_0_4296
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Find all the common characters in lexicographical order from # # ...
the-stack_0_4297
""" Copyright 2021 Inmanta 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 ...
the-stack_0_4299
#!/usr/bin/python3 # -*- coding: utf-8 -*- import logging import sys import time import _ssl from sleekxmpp import ClientXMPP import config import events from common import VERSION class IdleBot(ClientXMPP): def __init__(self, jid, password, rooms, nick): ClientXMPP.__init__(self, jid, password) ...
the-stack_0_4300
#!/usr/bin/python3 -i # # Copyright (c) 2015-2021 The Khronos Group Inc. # Copyright (c) 2015-2021 Valve Corporation # Copyright (c) 2015-2021 LunarG, Inc. # Copyright (c) 2015-2021 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the ...
the-stack_0_4301
#!/usr/bin/python3 # -*- coding: utf-8 -*- # from trainer import Trainer import pyximport pyximport.install() from cython_train.trainer_cython import Trainer from ssd_v2 import SSD300v2 import keras import argparse def main(): parser = argparse.ArgumentParser(description="Training ssd model with keras") pars...
the-stack_0_4306
#!/usr/bin/env python __copyright__ = 'Copyright 2013-2014, http://radical.rutgers.edu' __license__ = 'MIT' import os import sys verbose = os.environ.get('RADICAL_PILOT_VERBOSE', 'REPORT') os.environ['RADICAL_PILOT_VERBOSE'] = verbose import radical.pilot as rp import radical.utils as ru # --------------------...
the-stack_0_4307
""" File: 1514.py Title: Path with Maximum Probability Difficulty: Medium URL: https://leetcode.com/problems/path-with-maximum-probability/ """ import heapq import unittest from collections import defaultdict, deque from typing import List class Solution: def maxProbability(self, ...
the-stack_0_4308
"""arikefoods URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/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...
the-stack_0_4312
#coding=utf8 import traceback from extensions.database import db from extensions.hueyext import hueyapp from extensions.celeryext import celeryapp from models.asyncmodel import Async from models.warehouse import Warehouse, Area, Workarea, Location from models.inv import Good, Category, Inv from models.auth import Par...
the-stack_0_4313
# -*- coding:utf-8 -*- from __future__ import absolute_import """ 词向量测试 20K 词向量: - 规模: 19527 x 300D - 来源: [Chinese-Word-Vectors: sgns.sikuquanshu.word.bz2](https://github.com/Embedding/Chinese-Word-Vectors) 测试结果: - faiss: load index, 0.82s; search 100 times by word, 1.08s; search 100 times by vec, 1.06s - gensim: lo...
the-stack_0_4314
# Imports from datetime import timedelta from typing import List, Tuple import hypothesis.strategies as st import numpy as np import numpy.testing as npt import pandas as pd import pyarrow as pa import pytest from hypothesis import given, settings from fletcher._algorithms import ( _extract_data_buffer_as_np_arra...
the-stack_0_4317
from __future__ import print_function import gdbremote_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestGdbRemoteAuxvSupport(gdbremote_testcase.GdbRemoteTestCaseBase): mydir = TestBase.compute_mydir(__file__) AUXV_SUPPORT_...
the-stack_0_4322
# -*- coding: utf-8 -*- """This file contains a parser for the Google Drive snapshots. The Google Drive snapshots are stored in SQLite database files named snapshot.db. """ from __future__ import unicode_literals from dfdatetime import posix_time as dfdatetime_posix_time from plaso.containers import events from pla...
the-stack_0_4323
import os import pytest from conda_build import api from .utils import fail_dir, metadata_dir @pytest.mark.parametrize("pkg_format,pkg_ext", [(None, ".tar.bz2"), ("2", ".conda")]) def test_conda_pkg_format( pkg_format, pkg_ext, testing_config, testing_workdir, monkeypatch, capfd ): """Conda package format ...
the-stack_0_4324
from openpyxl import load_workbook from docx import Document from docx.oxml.ns import qn import os # 设置文档字体 def set_font(document): document.styles['Normal'].font.name = u'宋体' document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') def get_ws(file_path): # 读取excel xlsx文件 ...
the-stack_0_4325
import datetime import inspect import json import logging import logging.config import os import pathlib from types import ModuleType from typing import Any, Callable, ContextManager, List, Optional, Union import dotenv import orjson # type: ignore import sentry_sdk import structlog import platform import tempfile f...
the-stack_0_4326
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
the-stack_0_4327
from machine import mem32 # import time import sys import uasyncio from i2c_responder_base import I2CResponderBase import calc_icmpv6_chksum class I2CResponder(I2CResponderBase): """Implementation of a (polled) Raspberry Pico I2C Responder. Subclass of the original I2CResponder class which has been rena...
the-stack_0_4328
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals from unittest import TestCase, skip from docutils.core import Publisher from docutils import io from m2rr import prolog, convert class RendererTestBase(TestCase): def conv(self, src, **kwargs): out =...
the-stack_0_4330
# flake8: noqa import base64 import collections import datetime import inspect import os import os.path as osp import pickle import re import subprocess import sys import cloudpickle import dateutil.tz import numpy as np from garage.core import Serializable class AttrDict(dict): def __init__(self, *args, **kwar...
the-stack_0_4332
# -*- coding: utf-8 -*- # Copyright 2019-2021 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 re...
the-stack_0_4333
import smtplib from smtplib import SMTPServerDisconnected from email.message import EmailMessage import mimetypes import os import logging class MailClient(object): """ Example mail client using SMTPlib Uses config """ def __init__(self, config=None, logger=None): self.mailserver = None ...
the-stack_0_4335
from django.shortcuts import render, HttpResponse from posts.models import Post # Create your views here. def index(request): posts = Post.objects.all().order_by('-registered_at')[:5] context = { 'posts' : posts } return render(request, 'home/index.html', context)
the-stack_0_4336
from elegantrl.agents.AgentSAC import AgentSAC from elegantrl.agents.net import Critic, ActorSAC, ActorFixSAC, CriticREDQ import torch import numpy as np from copy import deepcopy class AgentREDQ(AgentSAC): # [ElegantRL.2021.11.11] """ Bases: ``AgentBase`` Randomized Ensemble Double Q-learning algorithm....
the-stack_0_4338
""" Run a large scale benchmark. We measure: {dataset, encoder, model, train and test accuracy measures, train and test runtimes, feature count}. Note: A reasonably recent version of sklearn is required to run GradientBoostingClassifier and MLPClassifier. """ import os import warnings import pandas as pd import nump...
the-stack_0_4339
#!/usr/bin/python # -*- coding: utf-8 -*- """ Django settings for scrapy_joy project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the pro...
the-stack_0_4341
from fractions import Fraction from unittest import TestCase from musurgia.fractaltree.fractaltree import FractalTree class Test(TestCase): def setUp(self) -> None: self.ft = FractalTree(proportions=[1, 2, 3], tree_permutation_order=[3, 1, 2], value=10) def test_0(self): with self.assertRais...
the-stack_0_4346
import unittest import openfigi class MyTestCase(unittest.TestCase): def test_wkn_ticker_anonymous(self): """Get an ETF by WKN and check if response makes sense""" ofg = openfigi.OpenFigi() ofg.enqueue_request(id_type='ID_WERTPAPIER', id_value='A0YEDG') response = ofg.fetch_respon...
the-stack_0_4348
import numpy as np import scipy.sparse as sp import tensorflow as tf from keras import backend as K modes = { 'S': 1, # Single (rank(A)=2, rank(B)=2) 'M': 2, # Mixed (rank(A)=2, rank(B)=3) 'iM': 3, # Inverted mixed (rank(A)=3, rank(B)=2) 'B': 4, # Batch (rank(A)=3, rank(B)=3) 'UNK': -1 ...
the-stack_0_4350
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals from six.moves import range import json, os from semantic_version import Version import frappe import requests import subprocess # nosec from frappe.utils import cstr from frappe....
the-stack_0_4351
#!/usr/bin/env python # -*- coding: utf-8 -*- import vim import re import os import os.path from functools import wraps from .utils import * from .explorer import * from .manager import * from .mru import * from .devicons import ( webDevIconsGetFileTypeSymbol, webDevIconsStrLen, webDevIconsBytesLen, ma...
the-stack_0_4352
#! /usr/bin/python # -*- coding: utf-8 -*- import base64 import gzip import json import math import os import pickle import re import shutil # import ast import sys import tarfile import time import zipfile import cloudpickle import h5py import numpy as np import scipy.io as sio from six.moves import cPickle import ...
the-stack_0_4353
import logging from typing import Dict from synch.factory import get_reader, get_writer from synch.settings import Settings logger = logging.getLogger("synch.replication.etl") def etl_full( alias: str, schema: str, tables_pk: Dict, renew=False, full=True ): """ full etl """ reader = get_read...
the-stack_0_4354
#! /usr/bin/env python3 import struct import enum def printMessage(s): return ' '.join("{:02x}".format(c) for c in s) class MessageType(enum.Enum): Text = 0 Numeric = 1 Logic = 2 def decodeMessage(s, msgType): payloadSize = struct.unpack_from('<H', s, 0)[0] if payloadSize < 5: # includes...
the-stack_0_4357
# Electrum - Lightweight Bitcoin Client # Copyright (c) 2015 Thomas Voegtlin # # 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 t...
the-stack_0_4359
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import os import sys import json import numpy as np from scipy import misc as scp_misc import tensorflow as tf import facenet import align.detect_face as detect_face # from PIL import Image ...
the-stack_0_4360
from sqlalchemy.testing import eq_, assert_raises, \ assert_raises_message, is_ from sqlalchemy.ext import declarative as decl import sqlalchemy as sa from sqlalchemy import testing from sqlalchemy import Integer, String, ForeignKey from sqlalchemy.testing.schema import Table, Column from sqlalchemy.orm import rel...