text stringlengths 1 927k |
|---|
"""
Set up the demo environment that mimics interaction with devices.
For more details about this component, please refer to the documentation
https://home-assistant.io/components/demo/
"""
import asyncio
import time
import homeassistant.bootstrap as bootstrap
import homeassistant.core as ha
import homeassistant.load... |
# THIS FILE IS AUTO-GENERATED. DO NOT EDIT
from verta._swagger.base_type import BaseType
class ModeldbGetExperimentRunByNameResponse(BaseType):
def __init__(self, experiment_run=None):
required = {
"experiment_run": False,
}
self.experiment_run = experiment_run
for k, v in required.items():
... |
import pytest
from rest_framework.test import APIClient
from friendship.models import Friend, FriendshipRequest
from .factories import UserFactory, User
# from tests.serializers import UserTestSerializer
# Add tests for serializers and settings import.
@pytest.mark.django_db(transaction=True)
def test_create_friend_r... |
#!/usr/bin/env python3
# encoding: utf-8
"""
ARC's settings
"""
import os
import string
##################################################################
# If ARC communication with remote servers is desired, complete the following server dictionary.
# Instructions for RSA key generation can be found here:
# https... |
#!/usr/bin/env python2
"""
= Hash length extension attacks
== Challenge
=== Challenge facts
Must have 0
result = int(md5(self.nonce + self.user_nonces[-1]).hexdigest(),16)&((2<<(self.odds-1))-1)
* Faut que le hash & odds == 0
* odds donne `2**input - 1`
* nonce is 16 bytes
* user_nonce max length 1024
* large... |
class _DoublyLinkedBase:
class _Node:
__slots__ = '_element', '_prev', '_next'
def __init__(self, element, prev, next):
self._element = element
self._prev = prev
self._next = next
def __init__(self):
self._header = self._Node(None, None, None)
... |
#!/usr/bin/env python3
# coding: utf-8
# Copyright 2019 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... |
"""
Parsers
"""
from rest_framework import parsers
from rest_framework.exceptions import ParseError
from rest_framework_json_api import exceptions, renderers
from rest_framework_json_api.utils import get_resource_name, undo_format_field_names
class JSONParser(parsers.JSONParser):
"""
Similar to `JSONRenderer... |
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# 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 us... |
from copy import copy
from typing import List, Tuple, Union, Iterator, Iterable
import numpy as np
class Size:
def __init__(self, size: Union[int, None]):
"""
Create a Size object with the given size. If the size passed
in is None, then it is treated as infinite
:param size: ... |
# Generated by Django 3.0.7 on 2020-06-30 00:02
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0002_site_owner'),
]
operations = [
migrations.AlterModelOptions(
name='event',
options={'ordering': ('-created_at',... |
# coding: utf8
from __future__ import unicode_literals
"""
Example sentences to test spaCy and its language models.
>>> from spacy.lang.ro import Romanian
>>> from spacy.lang.ro.examples import sentences
>>> nlp = Romanian()
>>> docs = nlp.pipe(sentences)
"""
sentences = [
"Apple plănuiește să cumpere o compan... |
class Solution:
def findPairs(self, nums: List[int], k: int) -> int:
if k < 0:
return 0
counter = collections.Counter(nums)
cnt = 0
for num in counter:
if (k != 0 and counter[num] and counter[num + k]) or (k == 0 and counter[num] > 1):
cnt += 1... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from .youtube import YoutubeIE
from ..utils import (
parse_iso8601,
str_to_int,
)
class CrackedIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?cracked\.com/video_(?P<id>\d+)_[\da-z-]+\.html'
_TESTS = [{
... |
from setuptools import setup, find_namespace_packages
from setup_helper import find_resource_files
# -- Apps Definition -- #
app_package = 'water_data_explorer'
release_package = 'tethysapp-' + app_package
# -- Python Dependencies -- #
dependencies = []
# -- Get Resource File -- #
resource_files = find_resource_file... |
from utils import utils
class ServerTokenMessageSerializer:
data_dict = [
{'name': 'rtid', 'n_bytes': 1, 'cast': None},
{'name': 'len', 'n_bytes': 2, 'cast': utils.bytes_to_int_little}
]
def serialize(self, data: bytes):
raise Exception('Unimplemented Handler: ServerTokenMessageSer... |
#!/usr/bin/env python
"""Certbot Apache configuration submission script"""
from __future__ import print_function
import argparse
import atexit
import os
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import textwrap
import six
_DESCRIPTION = """
Let's Help is a simple script you... |
"""
WSGI config for ticketdesk project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SE... |
#!/usr/bin/python
import subprocess as sb
import sys
import os
import stegall as stg
prog = 'hexcurse'
def launch(arg2):
if os.path.isfile(arg2):
os.system(prog +' ' +arg2)
else:
stg.io_error()
exit()
def hedit(arg2):
try :
launch(arg2)
except OSError as e:
if e.errno == os.errno.ENOENT:
stg.p... |
# Copyright 2018-2019 QuantumBlack Visual Analytics Limited
#
# 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
#
# THE SOFTWARE IS PROVIDED "AS IS"... |
from typing import List
from pandas._typing import FilePathOrBuffer, Scalar, StorageOptions
from pandas.compat._optional import import_optional_dependency
from pandas.io.excel._base import BaseExcelReader
class PyxlsbReader(BaseExcelReader):
def __init__(
self,
filepath_or_buffer: FilePathOrBuff... |
from unittest import TestCase
from unittest.mock import MagicMock, patch
class TestS3BucketObjectFinder(TestCase):
@patch('boto3.client')
@patch('justmltools.s3.aws_credentials.AwsCredentials', autospec=True)
def test_get_matching_s3_objects(
self,
aws_credentials_mock: MagicMock,
... |
# --------------------------------------------------------------------------
# Source file provided under Apache License, Version 2.0, January 2004,
# http://www.apache.org/licenses/
# (c) Copyright IBM Corp. 2015, 2016, 2017, 2018
# --------------------------------------------------------------------------
# Author: O... |
class ElementIntersectsElementFilter(ElementIntersectsFilter, IDisposable):
"""
A filter to find elements that intersect the solid geometry of a given element.
ElementIntersectsElementFilter(element: Element,inverted: bool)
ElementIntersectsElementFilter(element: Element)
"""
def Dispose(self):
... |
from django.conf.urls import url
from django.urls import path
from django.views.generic import TemplateView
from . import views
from .models import GPXTrack
app_name = 'geoloc_data'
urlpatterns = [
# city detail view
#url(r'^city/(?P<pk>[0-9]+)$', views.SpotsDetailView.as_view(), name='city-detail'),
# u... |
#
# PySNMP MIB module ENGENIUS-MESH-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENGENIUS-MESH-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:48:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
# -*- coding: utf-8 -*-
# Copyright (C) Canux CHENG <canuxcheng@gmail.com>
#
# 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 ... |
from pymol import cmd
def ligandNeighbors(prot, chain, ligand):
print ligand
# set some string names for temporary objects/selections
tmpObj = cmd.get_unused_name("_tmp")
tmpObj2 = cmd.get_unused_name("_bla")
# operate on a new object & turn off the original
sel = "{} and chain {}".format(prot... |
from baremetal import *
from math import log, pi
from matplotlib import pyplot as plt
import numpy as np
import sys
from math import log, ceil
from settings import Settings
from measure_magnitude import measure_magnitude
from calculate_gain import calculate_gain
from slow_barrel_shifter import slow_barrel_shifter
def... |
# -*- coding: utf-8 -*-
from wtforms.form import Form
from superset.forms import (
CommaSeparatedListField, filter_not_empty_values)
from tests.base_tests import SupersetTestCase
class FormTestCase(SupersetTestCase):
def test_comma_separated_list_field(self):
field = CommaSeparatedListField().bind(F... |
import logging
from bson import ObjectId
from flask_restful import Resource, reqparse
from sintel.db import DBExplorer, schema
from sintel.resources.auth_utils import requires_auth
from sintel.resources.computing.utils.layout import tsne
from sintel.resources.experiment import validate_experiment_id
LOGGER = logging... |
"""deCONZ service tests."""
from asynctest import Mock, patch
import pytest
import voluptuous as vol
from homeassistant.components import deconz
from homeassistant.components.deconz.const import CONF_BRIDGEID
from .test_gateway import BRIDGEID, setup_deconz_integration
GROUP = {
"1": {
"id": "Group 1 id... |
# Copyright (c) ZenML GmbH 2021. 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 applica... |
#!/usr/bin/env python
#========================================================================================
# File: gen_app_config_files.py
# Author: Jose F Martinez/GSFC
# Date: 2016-06-29
#
# Modification History:
# Date | Author | Description
# ---------------------------
# 06/29/16 | Jose F Martine... |
#!/usr/bin/env python
from setuptools import setup
setup(name='rrcf',
version='0.4.1',
description='Robust random cut forest for anomaly detection',
author='Matt Bartos, Abhiram Mullapudi, Sara Troutman',
author_email='mdbartos@umich.edu, abhiramm@umich.edu, stroutm@umich.edu',
url='http... |
from financialmodelingprep.decorator import get_json_data
BASE_URL = 'https://financialmodelingprep.com'
class calendars():
BASE_URL = 'https://financialmodelingprep.com'
API_KEY = ''
def __init__(self, API_KEY):
self.API = API_KEY
@get_json_data
def earning_calendar(self):
'''
... |
from dataclasses import dataclass
from typing import Iterable, Optional, Sequence, Set
from di.core.element import Dependency, Value
class Matcher:
def iterate(self, dependency: Dependency, values: Set[Value]) -> Iterable[Value]:
raise NotImplementedError
class ValuesMapper:
def map(self, objects: ... |
import tensorflow as tf
import tensorflow_addons as tfa
tfk = tf.keras
tfkl = tfk.layers
tfm = tf.math
class AddPositionEmbs(tfkl.Layer):
"""Adds (optionally learned) positional embeddings to the inputs."""
def __init__(self, trainable=True, **kwargs):
super().__init__(trainable=trainable, **kwargs)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
**Project Name:** MakeHuman
**Product Home Page:** http://www.makehumancommunity.org/
**Github Code Home Page:** https://github.com/makehumancommunity/
**Authors:** Thomas Larsson, Jonas Hauquier
**Copyright(c):** MakeHuman Team 2001-2019
*... |
_base_ = [
'../retinanet/retinanet_r50_fpn_2x_coco.py'
]
model = dict(
type='Distilling_Single',
distill = dict(
teacher_cfg='./configs/retinanet/retinanet_x101_64x4d_fpn_1x_coco.py',
teacher_model_path='/lustre/S/duzhixing/workspace/model/retinanet_x101_64x4d_fpn_2x_coco_20200131-bca068ab... |
# -*- coding:utf-8 -*-
#
# Copyright (C) 2008 The Android Open Source Project
#
# 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... |
import logging
import time
import gym
from aivle_gym.agent_env import AgentEnv
from judge import CartPoleEnvSerializer
class CartPoleAgentEnv(AgentEnv):
def __init__(self, port):
base_env = gym.make("CartPole-v0")
super().__init__(
CartPoleEnvSerializer(),
base_env.action... |
from datetime import (
datetime,
timedelta,
)
import numpy as np
import pytest
from pandas import (
DataFrame,
Index,
MultiIndex,
Series,
isna,
)
import pandas._testing as tm
def assert_series_or_index_equal(left, right):
if isinstance(left, Series):
tm.assert_series_equal(le... |
import numpy as np
from . import _libwarpx
class PGroup(object):
"""Implements a class that has the same API as a warp ParticleGroup instance.
"""
def __init__(self, igroup, ispecie, level=0):
self.igroup = igroup
self.ispecie = ispecie
self.level = level
self.ns = 1 # Numb... |
"""
Configuration values for transition process.
"""
BROKER_URL = 'amqp://localhost//'
CELERY_RESULT_BACKEND = 'amqp://'
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT = ['json']
CELERYD_PREFETCH_MULTIPLIER = 1
CELERY_TASK_RESULT_EXPIRES = 7200 # 2 Hours |
from datetime import datetime
import pandas as pd
import numpy as np
import json
df = pd.read_csv('/home/josh/python/SNLP/src/truncate_data/epoch_rev.json')
df = df[df.epoch_time < 1483142400.0]
df = df[df.epoch_time > 1419984000.0]
with open('epoch_fil.json', 'w+') as f:
f.write(out) |
# 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 RStatnetCommon(RPackage):
"""Common R Scripts and Utilities Used by the Statnet Project So... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 12 11:26:41 2019
@author: omaier
"""
import pyqmri
try:
import unittest2 as unittest
except ImportError:
import unittest
from pyqmri._helper_fun import CLProgram as Program
from pkg_resources import resource_filename
import pyopencl.array a... |
# Copyright (c) 2015-2020 The Decred developers
# Copyright (c) 2019-2020 The atomicswap-qt developers
#
# 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 witho... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('Contacts/', views.Contacts.as_view(), name='contact'),
path('Profile/', views.profile.as_view(), name='profile'),
] |
#!/usr/bin/env python
import concurrent.futures
import os
import subprocess
import sys
from absl import flags
from absl.testing import absltest
from grr_response_client.unprivileged.windows import process_test
from grr_response_client.unprivileged.windows import sandbox
flags.DEFINE_bool(
"set_inheritance",
... |
import unittest
import os
from simpleh5.utilities.search_utilities import _build_search_string
class TestBuildString(unittest.TestCase):
def test_string_single(self):
query = ['strs', '==', 'abc']
match_string, uservars = _build_search_string(query)
self.assertEqual(match_string, "(n0==b... |
"""
Script.
Use it to add an application to the system startup (WINDOWS)
""" |
# Copyright 2018 University of Groningen
#
# 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 i... |
import binascii
import os
import pytest
from sanic import Sanic
from sanic.response import json
from sanic_jwt import exceptions, Initialize
from sanic_jwt.decorators import protected
class User(object):
def __init__(self, id, username, password):
self.id = id
self.username = username
se... |
'''OpenGL extension EXT.secondary_color
This module customises the behaviour of the
OpenGL.raw.GL.EXT.secondary_color to provide a more
Python-friendly API
Overview (from the spec)
This extension allows specifying the RGB components of the secondary
color used in the Color Sum stage, instead of using the defaul... |
"""
Creates a MobileNetV2 Model as defined in:
Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen. (2018).
MobileNetV2: Inverted Residuals and Linear Bottlenecks
arXiv preprint arXiv:1801.04381.
import from https://github.com/tonylins/pytorch-mobilenet-v2
"""
import logging
import math
impor... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# env libs
import os
from dotenv import load_dotenv
from pathlib import Path
# dash libs
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objs as pgo
# pydata stack
import... |
#!/usr/bin/env python3
import datetime
import os
import signal
import subprocess
import sys
import traceback
from multiprocessing import Process
import cereal.messaging as messaging
import selfdrive.crash as crash
from common.basedir import BASEDIR
from common.params import Params, ParamKeyType
from common.text_window... |
# Load library
import numpy as np
# Create a vector as a row
vector_row = np.array([1, 2, 3])
# Create a vector as a column
vector_column = np.array([[1],[2],[3]]) |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django_autoslugfield.utils import unique_slugify
from django_sample_generator import fields, generator
from .models import Tweet
from accounts.models import User
from common_utils import generator_fields as extra_gen... |
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 7, transform = "None", sigma = 0.0, exog_count = 100, ar_order = 12); |
"""Support for Lutron Caseta Occupancy/Vacancy Sensors."""
from pylutron_caseta import OCCUPANCY_GROUP_OCCUPIED
from openpeerpower.components.binary_sensor import (
DEVICE_CLASS_OCCUPANCY,
BinarySensorEntity,
)
from . import DOMAIN as CASETA_DOMAIN, LutronCasetaDevice
from .const import BRIDGE_DEVICE, BRIDGE_... |
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph
from gui.objects.graph.hitobject_plot import HitobjectPlot
from gui.objects.graph.line_plot import LinePlot
from misc.callback import callback
from analysis.osu.std.map_data import StdMapData
from generic.switcher import Switcher
class Timeline(pyqtgraph.PlotW... |
# Deep Q Network in pytorch
# Atharv Sonwane <atharvs.twm@gmail.com>
# References -
# https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf
import copy
import random
import time
from collections import deque, namedtuple
from itertools import count
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch... |
from sklearn.metrics import accuracy_score, precision_score, f1_score, recall_score, confusion_matrix
import pandas as pd
def getClassification_scores(true_classes, predicted_classes):
acc = accuracy_score(true_classes, predicted_classes)
prec = precision_score(true_classes, predicted_classes,average="macro")
... |
#!/usr/bin/env python2
""" The annotation class """
# upconverty - A universal hardware design file format converter using
# Format: upverter.com/resources/open-json-format/
# Development: github.com/upverter/schematic-file-converter
#
# Copyright 2011 Upverter, Inc.
#
# Licensed under the Apache License, Versi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 1.0.2.7202 on 2019-05-14.
# 2019, SMART Health IT.
import io
import json
import os
import unittest
from . import paymentreconciliation
from .fhirdate import FHIRDate
class PaymentReconciliationTests(unittest.TestCase):
def instantiate_from... |
# Copyright 2016 Twitter. 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 applicable law or agree... |
#!/usr/bin/env python3
"""
*twist_runtime.py*
Most of it is copied from the Lambda python3.7 runtime (bootstrap.py)
The section at the bottom contains the modifications.
"""
import json
import logging
import os
import site
import sys
import time
import traceback
import warnings
sys.path.insert(0, "/var/runtime") # F... |
# Thomas Hilton Johnson III
# text_cleaner.py
# Utilizing regex to clean out unnecessary parts of the text
# Reference: https://stackabuse.com/using-regex-for-text-manipulation-in-python/
# Reference: https://stackoverflow.com/questions/11469228/python-replace-and-overwrite-instead-of-appending/11469328
# Not necessary... |
"""Python module which parses and emits TOML.
Released under the MIT license.
"""
from toml import encoder
from toml import decoder
__version__ = "0.10.2"
_spec_ = "0.5.0"
load = decoder.load
loads = decoder.loads
TomlDecoder = decoder.TomlDecoder
TomlDecodeError = decoder.TomlDecodeError
TomlPreserveCommentDecoder... |
import pytest
from jina.drivers.evaluate import RankEvaluateDriver
from jina.drivers.helper import DocGroundtruthPair
from jina.executors.evaluators.rank.precision import PrecisionEvaluator
from jina.proto import jina_pb2
class SimpleRankEvaluateDriver(RankEvaluateDriver):
def __init__(self, field: str, *args, ... |
#!/usr/bin/env python3
import typing # noqa F401
import warnings
import torch
from torch import Tensor
from ..exceptions.warnings import BadInitialCandidatesWarning
def initialize_q_batch(X: Tensor, Y: Tensor, n: int, eta: float = 1.0) -> Tensor:
r"""Heuristic for selecting initial conditions for candidate ge... |
# -*- coding: utf-8 -*-
"""Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2016, 2017, 2018, 2019, 2020 Caleb Bell
<Caleb.Andrew.Bell@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (t... |
# Copyright (c) 2011 OpenStack Foundation
# 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 ... |
import unittest
import math
import numpy
import pytest
import cupy
import cupy.core._accelerator as _acc
from cupy.core import _cub_reduction
from cupy import testing
@testing.gpu
class TestSumprod(unittest.TestCase):
def tearDown(self):
# Free huge memory for slow test
cupy.get_default_memory_... |
#!/usr/bin/env python3
# coding: utf-8
"""
Tools to work with Path str / instances.
"""
import os
from typing import Union
from pathlib import Path
import logging
import shutil
from hashlib import sha1
import uuid
import re
from fnmatch import fnmatch
import operator
from functools import reduce
PTYPE = getattr(re,... |
"""
CS 229 Machine Learning
Question: Reinforcement Learning - The Inverted Pendulum
"""
from __future__ import division, print_function
import matplotlib
matplotlib.use('TkAgg')
from env import CartPole, Physics
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import lfilter
"""
Parts of the code... |
#!/usr/bin/env python
"""
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");... |
class Solution:
def grayCode(self, n: int) -> List[int]:
if n == 0: return [0]
if n == 1: return [0, 1]
res = self.grayCode(n - 1)
for i in range(len(res) - 1, -1, -1): res.append((2 ** (n - 1)) + res[i])
return res |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Manages subcommands in a script.
Each subcommand should look like this:
@usage('[pet name]')
def CMDpet(parser, args):
'''Prints a pet.
Many... |
#!/usr/bin/env python
# coding=utf-8
'''
Author: JiangJi
Email: johnjim0816@gmail.com
Date: 2021-12-22 10:40:05
LastEditor: JiangJi
LastEditTime: 2021-12-22 10:43:55
Discription:
'''
import copy
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from TD3.memory import ReplayBuffer
c... |
# 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... |
config = {}
def process_logic_message(message):
type = message.get("type", None)
if type == "initialize":
return __initialize__(message)
elif type == "turn_off":
return __set_state__("off")
elif type == "turn_on":
return __set_state__("on")
elif type == "toggle":
i... |
# coding=utf-8
"""
audfprint_match.py
Fingerprint matching code for audfprint
2014-05-26 Dan Ellis dpwe@ee.columbia.edu
"""
from __future__ import division, print_function
import os
import time
import psutil
import matplotlib.pyplot as plt
import librosa
import numpy as np
import scipy.signal
from . import audfprin... |
#!/usr/bin/env python
"""
title: A CLI tool for exporting data from Elasticsearch into a CSV file.
description: Command line utility, written in Python, for querying Elasticsearch in Lucene query syntax or Query DSL syntax and exporting result as documents into a CSV file.
usage: es2csv -q '*' -... |
# qubit number=5
# total number=55
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... |
#!/usr/bin/env python3
import argparse
import asyncio
import os
import socket
import ssl
import capnp
import calculator_capnp
this_dir = os.path.dirname(os.path.abspath(__file__))
class PowerFunction(calculator_capnp.Calculator.Function.Server):
'''An implementation of the Function interface wrapping pow(). ... |
import streamlit as st
from utils import retrieve_doc
from annotated_text import annotated_text
def annotate_answer(answer,context):
start_idx = context.find(answer)
end_idx = start_idx+len(answer)
annotated_text(context[:start_idx],(answer,"ANSWER","#8ef"),context[end_idx:])
st.write("# Haystack De... |
import numpy as np
from numpy.linalg import inv
# Kalman Filter Class
class KalmanFilter:
"""
Simple Kalman filter
"""
def __init__(self, XY, B=np.array([0]), M=np.array([0])):
stateMatrix = np.zeros((4, 1), np.float32) # [x, y, delta_x, delta_y]
if XY != 0:
stateMatrix = ... |
# TODO :demand:用于补充某种类型的链接,将抽象机场信息实例化
# 1. 遍历所有"可用"机场实例
# 2. 审核授权
# if 该机场不具备该类型链接的采集权限,剔除。
# elif 该机场同时具备其他类型的采集权限,权限收缩(改写),实例入队。
# else 该机场仅具备该类型任务的采集权限,实例入队。
__all__ = ["ActionShunt", "devil_king_armed", "reset_task"]
from src.BusinessCentralLayer.setting import CRAWLER_SEQUENCE, CHROMEDRIVER_PATH
from .maste... |
# !/usr/bin/env python
'''
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"... |
from .model import Model
from .nbow_model import NeuralBoWModel
from .rnn_model import RNNModel
from .self_att_model import SelfAttentionModel
from .conv_model import ConvolutionalModel
from .conv_self_att_model import ConvSelfAttentionModel
from .elmo_model import ElmoModel
from .cbow_model import ContinuousBoWModel |
# Copyright (c) 2018 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... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-21 13:57
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Creat... |
import argparse
import json
import logging.config
from keystoneauth1.exceptions import Unauthorized
from sdk.softfire.os_utils import OSClient
log = logging.getLogger(__name__)
def image_list():
file_path = '/net/u/dsa/Projects/Softfire/check-os/etc/images_list.json'
image_names = []
with open(file_path... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == "__main__":
print("In __main__")
import numpy as np
import matplotlib.pyplot as plt
import model_functions as mf
### 4)
luminosities = np.arange(0.5, 1.6, 0.002) # Stelar luminosities
alphaw_out = np.ones(len(luminosities)) * n... |
class AppLinks:
types = {
'login': bool
}
def __init__(self):
self.login = None # bool |
# -*- coding: utf-8 -*-
"""CCXT: CryptoCurrency eXchange Trading Library (Async)"""
# -----------------------------------------------------------------------------
__version__ = '1.41.4'
# -----------------------------------------------------------------------------
from ccxt.async_support.base.exchange import Exc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.