text stringlengths 2 999k |
|---|
from rlbot.agents.base_agent import BaseAgent, SimpleControllerState
from rlbot.utils.structures.game_data_struct import GameTickPacket
from behaviour.carry import Carry
from behaviour.clear_ball import ClearBall
from behaviour.defend_goal import DefendGoal
from behaviour.follow_up import PrepareFollowUp
from behaviou... |
import theano
theano.config.compute_test_value = 'off'
from pylearn2.energy_functions.rbm_energy import GRBM_Type_1
import numpy as N
from theano.compat.six.moves import xrange
import theano.tensor as T
from theano import function
from pylearn2.utils import as_floatX
from pylearn2.utils import sharedX
from pylearn2.lin... |
import yaml
import os
from abc import ABC, abstractmethod
from pathlib import Path
from klarify.Parser import YamlParser
class Kustomizer(ABC):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def addDir(self, dir: str):
pass
@abstractmethod
def generateKustomization... |
from __future__ import print_function
import pytest
import six
import sys
from abc import ABCMeta, abstractmethod
from inspect import isabstract
class Foo(object):
pass
class Abstract:
__metaclass__ = ABCMeta
@abstractmethod
def foo(self):
pass
@six.add_metaclass(ABCMeta)
class AbstractSi... |
from okdata.aws.logging import logging_wrapper
from starlette.middleware.base import BaseHTTPMiddleware
def _logging_middleware(request, call_next):
@logging_wrapper("event-stream-api", async_wrapper=True)
async def handler(event, context):
return await call_next(request)
return handler(request.s... |
from __future__ import print_function
import sys
import click
from social_ids.networks import facebook, twitter, instagram
networks = {
'facebook': facebook,
'twitter': twitter,
'instagram': instagram
}
@click.command()
@click.argument('network', type=click.Choice(networks.keys()))
@click.argument('han... |
"""Tests for recovering after errors."""
from pytype.tests import test_base
class RecoveryTests(test_base.BaseTest):
"""Tests for recovering after errors."""
def test_function_with_unknown_decorator(self):
self.InferWithErrors("""
from nowhere import decorator # import-error
@decorator
de... |
import torch
import torch.nn as nn
from tcr_embedding.models.architectures.transformer import TransformerEncoder, TransformerDecoder
from tcr_embedding.models.architectures.mlp import MLP
from tcr_embedding.models.architectures.mlp_scRNA import build_mlp_encoder, build_mlp_decoder
from tcr_embedding.models.vae_base_mo... |
'''
https://codeforces.com/contest/1385/problem/B
1385 B. Restore the Permutation by Merger
File Creation Date: 24-Oct-2020
Author: Biraj(https://github.com/BirajCoder)
'''
for _ in range(int(input())):
n=int(input())
li=list(map(int,input().split()))
new_li=[]
for i in li:
if i... |
'''
Function:
定义游戏精灵类
Author:
Charles
微信公众号:
Charles的皮卡丘
'''
import math
import pygame
import random
from .misc import VelocityVector, VectorAddition
'''猪'''
class Pig(pygame.sprite.Sprite):
def __init__(self, screen, imagepaths, loc_info, velocity=None, **kwargs):
pygame.sprite.Sprite.__init_... |
#!/usr/bin/env python3
# Copyright (c) 2014-2020 The MicroBitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the fundrawtransaction RPC."""
from decimal import Decimal
from itertools import product
fr... |
# Copyright (c) 2015 Michel Oosterhof <michel@oosterhof.net>
"""
Splunk HTTP Event Collector (HEC) Connector.
Not ready for production use.
JSON log file is still recommended way to go
"""
from __future__ import division, absolute_import
from StringIO import StringIO
import json
from twisted.python import log
from... |
import copy
import os
import re
from textwrap import dedent
from typing import Any, Dict, List, Optional, Set, Tuple
from unittest import mock
import orjson
from django.conf import settings
from django.test import override_settings
from markdown import Markdown
from zerver.lib.actions import (
do_add_alert_words,... |
# IMPORTS
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
import matplotlib.style as style
from IPython.core.display import HTML
# PLOTTING CONFIG
%matplotlib inline
style.use('fivethirtyeight')
plt.rcParams["figure.figsize"] = (14, 7)
HTML("""
<style>
.output_png {
display: table-ce... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
__... |
import os
import time
import pytest
import tempfile
import webbrowser
from nilearn.plotting import html_document
from numpy.testing import assert_no_warnings
# Note: html output by nilearn view_* functions
# should validate as html5 using https://validator.w3.org/nu/ with no
# warnings
def _open_mock(f):
print(... |
# Copyright (c) 2021 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 applic... |
#
# ***** ALERTA SERVER DEFAULT SETTINGS -- DO NOT MODIFY THIS FILE *****
#
# To override these settings use /etc/alertad.conf or the contents of the
# configuration file set by the environment variable ALERTA_SVR_CONF_FILE.
#
# Further information on settings can be found at https://docs.alerta.io
from typing import ... |
keyboard.send_keys("<ctrl>+<up>") |
"""drought-metrics.py
Driver that runs the drought metrics evaluation.
Use:
python drought_metrics.py settings_file.yaml
Parameters:
-----------
Parameters are stored in a yaml file provided as the single argument
to this script.
test_path : str
GCM file directory. Can contain multiple files.
... |
import itertools
from ray import tune
from collections import OrderedDict
num_seeds = 10
var_env_configs = OrderedDict(
{
"state_space_size": [8], # , 10, 12, 14] # [2**i for i in range(1,6)]
"action_space_size": [8], # 2, 4, 8, 16] # [2**i for i in range(1,6)]
"delay": [0],
"sequ... |
import re
from astropy.table import vstack
from astroquery.jplhorizons import Horizons
import pandas as pd
pd.options.display.float_format = '{:,.4f}'.format
def decimal_to_hours(dec_time: float) -> (int, float, float):
"""transform decimal time into conventional time"""
hours = int(dec_time)
minutes = (... |
# This file is the entry point.
# First we import the app object, which will get initialised as we do it. Then import methods we're about to use.
from demo.demo.app import app
from demo.demo.blueprints import register_blueprints
from demo.demo.exceptions import register_exception_handlers
from demo.demo.extensions.regi... |
'''
Nome: Luiz Lima Cezario Ra:11201920808
Nesse Programa o objetivo era de criar um contador de pontos para o jogo Fruit Crush
no caso a pessoas escolhe dentre um tabuleiro cheio de frutas uma posicao apartir dessa posicao
a sua pontuacao sera gerada pelo numero de casas de frutas iguais que estiverem conecta... |
# coding: utf-8
"""*****************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* re... |
class SpiderDevice(object):
def __init__(self, data, api):
self.api = api
self.data = data
@property
def id(self):
return self.data.get('id')
@property
def name(self):
return self.data.get('name')
@property
def model(self):
return self.data.get('mod... |
# coding: utf-8
"""
Engine api
Engine APIs # noqa: E501
The version of the OpenAPI document: 1.0.4
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import vtpl_api
from vtpl_api.models.meta_no_seat_belt_event import MetaNoSeatBeltEvent # no... |
"""Auto-generated file, do not edit by hand. RE metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_RE = PhoneMetadata(id='RE', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='1\\d\\d?', possible_length=(2, 3)),
... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'hello_world.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^example', 'exam... |
from typing import Union, List
import demistomock as demisto
from CommonServerPython import *
def pentera_operation_to_incident(full_action_report: list, custom_fields_output: Union[str, bool], context_key: str):
def _init_missing_keys_in_operation_details(operation_details: dict, missing_keys_to_init: set):
... |
# Heavily based on the XML-RPC implementation in python.
# Based on the json-rpc specs: http://json-rpc.org/wiki/specification
# The main deviation is on the error treatment. The official spec
# would set the 'error' attribute to a string. This implementation
# sets it to a dictionary with keys: message/traceback/type
... |
import crnt4sbml
network = crnt4sbml.CRNT("../sbml_files/Fig4C_open.xml")
approach = network.get_semi_diffusive_approach()
bounds = [(1e-2, 1e2)]*10
params_for_global_min, obj_fun_val_for_params = approach.run_optimization(bounds=bounds, iterations=10000,
... |
"""
In principle, one could automate the process for merging data annotations
between binding sites that overlap and need to be merged together. For now, this
function and file does nothing, and merging is handled in other ways.
"""
def generate_merge_func(_):
"""
Returns the identity function
:param _: t... |
"""Class implementation for visible interface.
"""
from typing import Dict
from apysc._type.attr_linking_interface import AttrLinkingInterface
from apysc._type.boolean import Boolean
from apysc._type.revert_interface import RevertInterface
from apysc._type.variable_name_interface import VariableNameInterface
... |
#! usr/bin/env python
# -*- coding: utf-8 -*-
"""
爬取 星座屋 星座运势
https://www.xzw.com/
"""
import re
from functools import reduce
import requests
from bs4 import BeautifulSoup
from everyday_wechat.utils.common import SPIDER_HEADERS
__all__ = ['get_xzw_horoscope', 'get_today_horoscope']
XZW_BASE_URL_TODAY = "https... |
import os
import re
import sys
import unittest2
class TestDiscovery(unittest2.TestCase):
# Heavily mocked tests so I can avoid hitting the filesystem
def test_get_name_from_path(self):
loader = unittest2.TestLoader()
loader._top_level_dir = '/foo'
name = loader._get_name_from_path('... |
from xml.etree.ElementTree import Element, SubElement
from .door import Door
class DoubleSwingDoor(Door):
def __init__(self, door_edge, level_elevation):
super().__init__(door_edge, level_elevation)
motion_degrees = door_edge.params['motion_degrees'].value
self.motion_radians = 3.14 * moti... |
#1.Nested lists are list objects where the elements in the lists can be lists themselves.
#A couple of examples will motivate for nested lists and illustrate the basic operations
#on such lists.
#2.Yes, It can
#3.
#1. Start before Stop, Start + Step to Stop
#2. Two. No.
import turtle
tess = turtle.Turtl... |
from model.contactproperties import ContactProperties
import random
import string
import os.path
import jsonpickle
import getopt
import sys
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of contacts ", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n= 1
f= "data/cont... |
import json
from .oauth import OAuth2Test
class AmazonOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.amazon.AmazonOAuth2'
user_data_url = 'https://api.amazon.com/user/profile'
expected_username = 'FooBar'
access_token_body = json.dumps({
'access_token': 'foobar',
'token_... |
#!/usr/bin/python
## Copyright 2009-2021 Intel Corporation
## SPDX-License-Identifier: Apache-2.0
import sympy as sp
import numpy as np
import math
################################################################################
#### Utils
############################################################################... |
import requests
from tools.keys import get_signing_keys_info
import os
import json
from lightnion import signature
if __name__ == "__main__":
# The url of one of the TOR's authority node to download a consensus
url = "http://154.35.175.225/tor/status-vote/current/consensus"
# HTTP request
print("Reque... |
# coding: utf-8
"""
Iot API
Collection of all public API endpoints. # noqa: E501
The version of the OpenAPI document: 2.0
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
class PropertyValue(object):
"""NOTE: This class is auto generated by O... |
from invoke import Collection
from tasks import (
build,
config,
linting,
)
ns = Collection()
config = Collection.from_module(config, name="config")
linting = Collection.from_module(linting, name="lint")
# Subtasks
ns.add_collection(config)
ns.add_collection(linting)
# Tasks
ns.add_task(build.black)
ns... |
from armulator.armv6.opcodes.abstract_opcodes.teq_immediate import TeqImmediate
from armulator.armv6.opcodes.opcode import Opcode
from armulator.armv6.shift import thumb_expand_imm_c
class TeqImmediateT1(TeqImmediate, Opcode):
def __init__(self, instruction, n, imm32, carry):
Opcode.__init__(self, instruc... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Data pre-processing: build vocabularies and binarize training data.
"""
import argparse
import glob
import os
impor... |
import unittest
from testcypher import TestCypher
from testhelper import TestHelper
from testkeygenerator import TestPseudorandomKey
if __name__ == '__main__':
# Specify test classes
tests = [TestPseudorandomKey, TestHelper, TestCypher]
# Load tests
loader = unittest.TestLoader()
suite = [loader.... |
import platform
from setuptools import setup
from setuptools import find_packages
from setuptools import Extension
extra_compile_args = [
'-std=c++11',
'-O3',
'-Wall',
'-Wextra',
'-Wconversion',
'-fno-strict-aliasing',
'-fno-rtti',
]
extra_link_args = []
if platform.system() == 'Darwin':
... |
# -*- coding: utf-8 -*-
"""Domain Driven Design framework."""
from ddd_base import Entity
from .block import Block
from .location import Location
from .exception.server_error import ServerError
class Server(Entity, Block):
def __init__(self, name):
super().__init__()
self.name = name
self... |
import open3d as o3d
import os
import numpy as np
import h5py
point_clouds = []
for dirpath, dirnames, filenames in os.walk("F:\\cases\\tooth_11_stls"):
for filename in filenames:
print(os.path.splitext(filename)[-1])
if os.path.splitext(filename)[-1] != ".stl":
continue
full_f... |
"""
Django settings for hypercube project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import os
f... |
import brickpi
import time
interface=brickpi.Interface()
interface.initialize()
motors = [0,1]
interface.motorEnable(motors[0])
interface.motorEnable(motors[1])
print("wooo")
motorParams = interface.MotorAngleControllerParameters()
motorParams.maxRotationAcceleration = 6.0
motorParams.maxRotationSpeed = 12.0
motor... |
"""
Django settings for djangoProject 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 project like this: os.path.join(BASE_DIR, .... |
# Copyright (c) 2013-2015 Centre for Advanced Internet Architectures,
# Swinburne University of Technology. All rights reserved.
#
# Author: Sebastian Zander (szander@swin.edu.au)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
... |
#!/usr/bin/env python3
# Copyright (c) 2018-2020 The Ocvcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test wallet group functionality."""
from test_framework.test_framework import OcvcoinTestFramework
fro... |
# @Author: Manuel Rodriguez <vallemrv>
# @Date: 29-Aug-2017
# @Email: valle.mrv@gmail.com
# @Last modified by: vallemrv
# @Last modified time: 30-Aug-2017
# @License: Apache license vesion 2.0
class Constant():
def __init__(self):
self.TIPO_CAMPO = "tipo_campo"
self.TIPO_RELATION = "tipo_relat... |
# Copyright 2013-2020 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 BppPhylOmics(CMakePackage):
"""Bio++ Phylogenetic Omics Library"""
homepage = "http:/... |
import torch
import xml.etree.ElementTree as ET
import os
import cv2
import numpy as np
from torchvision import transforms
from PIL import Image
import random
def flip(img, boxes):
img = img.transpose(Image.FLIP_LEFT_RIGHT)
w = img.width
if boxes.shape[0] != 0:
xmin = w - boxes[:, 2]... |
# -*- coding: utf-8 -*-
##
# Copyright 2017 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 a... |
from mcpi.minecraft import Minecraft
mc = Minecraft.create()
position = mc.player.getTilePos()
x = position.x
y = position.y
z = position.z
# lava block...
blockType = 10
mc.setBlock(x, (y - 1), z, blockType)
|
from django.urls import path, include
from .views import RegisterApi, LoginApi, GetUserApi, ChangePasswordView
from knox import views as knox_views
urlpatterns = [
path("api/auth", include("knox.urls")),
path("api/auth/register", RegisterApi.as_view()),
path("api/auth/login", LoginApi.as_view()),
path(... |
#!/usr/bin/python
# coding: utf-8
# -------------------------------------------------------------------
# Encryption365 AutoRenewal Client For 宝塔Linux面板
# -------------------------------------------------------------------
# Copyright (c) 2020-2099 环智中诚™ All rights reserved.
# ------------------------------------------... |
import numpy as np
import math
try:
import awkward0 as awkward
except ImportError:
import awkward
if awkward.__version__[0] == '1':
raise ImportError('Please install awkward0 with `pip install awkward0`.')
def _concat(arrays, axis=0):
if len(arrays) == 0:
return np.array([])
if is... |
from colorfield.fields import ColorField
from multiselectfield import MultiSelectField
from django.conf import settings
from django.contrib.gis.db import models
from django.db.models import Q
from django.utils.html import escape
from django.utils.translation import gettext_lazy as _
from geotrek.authent.models import S... |
begin_unit
comment|'# Copyright 2015 Hewlett-Packard Development Company, L.P.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# All Rights Reserved.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the ... |
# Copyright 2018 The TensorFlow Probability 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... |
'''
Copyright (c) 2001-2018 by SAP SE, Walldorf, Germany.
All rights reserved. Confidential and proprietary.
'''
import os
import sys
import json
import re
import utils
from urllib.request import urlopen, Request
from urllib.parse import quote
from os.path import join
from string import Template
#'linux-x64-musl': 'L... |
from hazelcast.serialization.bits import *
from hazelcast.protocol.client_message import ClientMessage
from hazelcast.protocol.custom_codec import *
from hazelcast.protocol.codec.map_message_type import *
REQUEST_TYPE = MAP_GETENTRYVIEW
RESPONSE_TYPE = 111
RETRYABLE = True
def calculate_size(name, key, thread_id):
... |
import os
import logging
import functools
import traceback
import time
from datetime import datetime
from docker.errors import APIError
"""
Funcoes para converter as estatisticas de um container,
retiradas deste repositorio: https://github.com/TomasTomecek/sen/blob/master/sen/util.py#L162
"""
# this is tak... |
#exercicio 58
import random
aposta = int(input('aposte um numero entre 1 e 10: '))
r = int(random.randint(1,10))
if r == aposta:
print ('Voce acertou de primeira!!!')
else:
c = 1
while r != aposta:
aposta = int(input('aposte um numero entre 1 e 10: '))
c += 1
print ('Voce precisou de {} tent... |
from http import HTTPStatus
from typing import Optional, Union
from aiohttp_pydantic import PydanticView
from aiohttp_pydantic.oas.typing import r200, r201, r400, r401
from aiohttp.web_response import json_response
from sqlalchemy import select, delete, and_
from sqlalchemy.dialects.postgresql import insert # for <on... |
"""
This is the utils for deep learning, implemented with TensorFlow.
@ Author: Yu Sun. vxallset@outlook.com
@ Date created: Jun 04, 2019
@ Last modified: Jun 06, 2019
"""
import tensorflow as tf
def leaky_Relu(input, name=''):
return tf.nn.leaky_relu(input, alpha=0.1, name=name + '_relu')
def conv_2d(input... |
import theano
import theano.tensor as T
import numpy as np
from utility.utility import *
def activation_init(prefix, params, layer_setting):
#do Nothing
return params
def activation_calc(prefix, params, layer_setting, state_below, mask_below = None):
actFunc = eval(layer_setting['activation'])
flag =... |
# Copyright 2014 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.
from telemetry.page import page as page_module
from telemetry import story
class MseCasesPage(page_module.Page):
def __init__(self, url, page_set):
s... |
# Copyright (C) 2014 VA Linux Systems Japan K.K.
# Copyright (C) 2014 YAMAMOTO Takashi <yamamoto at valinux co jp>
# 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... |
# -*- coding: utf-8 -*-
# Copyright 2022 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... |
from __future__ import unicode_literals
import json
import socket
import time
from functools import partial
from os1.server import RequestHandler, UDPServer, ThreadingUDPServer
from os1.utils import build_trig_table
class OS1ConfigurationError(Exception):
pass
class OS1(object):
MODES = ("512x10", "512x20... |
#%%
from numpy import array
from numpy import hstack
from keras.models import Sequential
from keras.layers import LSTM
from keras.layers import Dense
from keras.layers import RepeatVector
from keras.layers import TimeDistributed
#%%
# split a multivariate sequence into samples
def split_sequences(sequences, n_steps_in,... |
import datetime
import logging
import random
import time
from dbnd._core.task_build.dbnd_decorator import task
from dbnd._core.tracking.metrics import log_metric
logger = logging.getLogger(__name__)
@task
def dbnd_sanity_check(check_time=datetime.datetime.now(), fail_chance=0.0):
# type: (datetime.datetime, fl... |
# Copyright 2018, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the ... |
import abc
import os
from audiomate.utils import jsonfile
class FailedDownloadException(Exception):
pass
class CorpusDownloader(metaclass=abc.ABCMeta):
"""
Abstract class for downloading a corpus.
To implement a downloader for a custom format, programmers are expected to subclass this class and to... |
#!/usr/bin/python2
"""
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"); yo... |
# https://www.codewars.com/kata/551f37452ff852b7bd000139
'''
Instructions :
Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition.
The binary number returned should be a string.
'''
def add_binary(a,b):
return bin(a+b).repl... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import copy
import logging
import numpy as np
from typing import List, Optional, Union
import torch
from detectron2.config import configurable
from . import detection_utils as utils
from . import transforms as T
"""
This file contains the default... |
# 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... |
import os
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from typing import Tuple
class ElectronicSignature:
def __init__(self, read_filename: str, write_filename: str):
self.read_filename = read_filename
self.write_filename = write_filename... |
# Explanation of this file purpose: https://stackoverflow.com/a/16084844/2898283
__version__ = '0.10.0'
|
"""Helper class to implement include/exclude of entities and domains."""
import voluptuous as vol
from homeassistant.core import split_entity_id
from homeassistant.helpers import config_validation as cv
CONF_INCLUDE_DOMAINS = 'include_domains'
CONF_INCLUDE_ENTITIES = 'include_entities'
CONF_EXCLUDE_DOMAINS = 'exclud... |
from django.views.generic import ListView, DetailView, FormView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from djang... |
from collections import namedtuple
from string import Formatter
from django.utils.translation import ugettext as _
import re
from corehq.apps.performance_sms.exceptions import InvalidParameterException
GLOBAL_NAMESPACE = 'global'
USER_NAMESPACE = 'user'
GROUP_NAMESPACE = 'group'
VALID_NAMESPACES = (GLOBAL_NAMESPACE, U... |
# Generated by Django 3.1.7 on 2021-04-07 09:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("main_app", "0002_contact"),
]
operations = [
migrations.AlterField(
model_name="contact",
name="desc",
f... |
# 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, software
# distributed u... |
import re
import string
import functools
def escape_string(s, encoding='utf-8'):
""" escape unicode characters """
if not isinstance(s, bytes):
s = s.encode(encoding=encoding)
return s.decode('unicode-escape', errors='ignore')
def get_list_of_formatter_names(s, return_index_if_empty=True, parse... |
# Copyright 2017 The TensorFlow 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 applica... |
from __future__ import division
import platform
from distutils.version import LooseVersion
import PIL
import pytest
try:
from pathlib import Path
except ImportError: # pragma: no cover
from pathlib2 import Path # python 2
from genbadge import Badge
from genbadge.utils_badge import get_local_badge_templat... |
import streamlit as st
import pandas as pd
import altair as alt
from vega_datasets import data
st.title("Let's analyze some CO2 emission data 🌎")
MAX_WIDTH = 1000
@st.cache # add caching so we load the data only once
def load_data():
climate_url = "https://raw.githubusercontent.com/ZeningQu/World-Bank-Data... |
from sympy import *
import numpy as np
import array as arr
def TongQuat(X, Y):
list ( zip(X , Y ) )
x = symbols('x')
m = len(X)
A = [[X[i] ** j for j in range (m) ] for i in range (m) ]
kq = np.linalg.solve(A,Y)
hamSo = ''
for i in range (len(kq)):
hamSo += '+%d*(x ** %... |
def drawlist():
words = [['प्रतिष्ठा', [('NN', 8)]],
['चलाने', [('VM', 33)]],
['इच्छा', [('NN', 26)]],
['गुरदेव', [('NNP', 1)]],
['90', [('QC', 3)]],
['राजी', [('JJ', 29)]],
['नं', [('NNP', 1)]],
['तेंदुलकर', [('NNP', 13)]],
['निभाना', [('VM', 2)]],
['शेर', [('NNP', 2), ('NN', 4)]],
['सीखे', [('VM', 2)]],
[... |
######################################################################
# Cloud Routes Web Application
# -------------------------------------------------------------------
# HTTP Get Status Code Health Check - Forms Class
######################################################################
from wtforms import TextFi... |
# TO GET DATE TIME USE --
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("Date: %d/%m/%Y Time: %X %p Time: %H[%I]:%M:%S Day: %A[%a] Month: %B[%b]"))
# FREEZE TIME --
import time
k=0
while k<2 :
time.sleep(1) # Freeze Time
print('Hi')
k+=1
#... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.