text stringlengths 2 999k |
|---|
from conan.packager import ConanMultiPackager
import platform
if __name__ == "__main__":
builder = ConanMultiPackager()
builder.add_common_builds(shared_option_name="zlib:shared", pure_c=True)
builder.run()
|
from test.lib.testing import assert_raises, assert_raises_message
import sqlalchemy as sa
from sqlalchemy import Integer, PickleType, String, ForeignKey
import operator
from test.lib import testing
from sqlalchemy.util import OrderedSet
from sqlalchemy.orm import mapper, relationship, create_session, PropComparator, \
... |
"""Methods for normalizing/sanitizing steemd account metadata."""
import ujson as json
from hive.utils.normalize import trunc
def get_profile_str(account):
_posting_json_metadata = ""
_json_metadata = ""
if account is not None:
if 'posting_json_metadata' in account:
_posting_json_metadata =... |
from .collections import (
add_contributor,
collection_activate,
collection_change_privacy,
collection_chooser,
collection_explorer,
collection_start,
collection_stats,
collection_stats_detail,
delete_collection,
edit_collection,
edit_contributors,
my_collections,
rem... |
from django.shortcuts import *
from django.conf import settings
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
fro... |
"""
Django settings for project project.
Generated by 'django-admin startproject' using Django 3.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
import d... |
"""
This script takes two input strings and compare them to check if they are anagrams or not.
"""
def mysort(s): #function that splits the letters
d=sorted(s)
s=''.join(d)
return s
s1=input("enter first word ")
n1=mysort(s1) #function invocation /calling the function
s2=input("enter second word ")
n2=mysort(s... |
# -*- encoding: utf-8 -*-
r"""
Display Preferences
This class is used to express display preferences that are not simply
a choice of a particular output format. For example, whether to prefer
vector over raster graphics. By convention, the value ``None`` is
always a valid value for a preference and means no particular... |
# city_separation_2.py
# book p.300
import sys
input = sys.stdin.readline
def find_parent(parent, x):
if parent[x] != x:
parent[x] = find_parent(parent, parent[x])
return parent[x]
def union_parent(parent, a, b):
a = find_parent(parent, a)
b = find_parent(parent, b)
if a < b:
pare... |
from fourier_convolutions import Fourier_ConvNet as Conv2d
import torch
import torch.nn as nn
import torch.nn.functional as F
__all__ = ['MobileNetV3', 'mobilenetv3']
def conv_bn(inp, oup, stride, conv_layer=Conv2d, norm_layer=nn.BatchNorm2d, nlin_layer=nn.ReLU):
return nn.Sequential(
conv_layer(in_chan... |
from tester import assertRaises
# numbers
assert 2 + 2 == 4
assert (50 - 5 * 6) / 4 == 5.0
assert 8 / 4 * 2 == 4.0
assert 8 / 5 == 1.6
assert 7 // 3 == 2
assert 7 // -3 == -3
assert 4 - 2 - 2 == 0
width = 20
height = 5 * 9
assert width * height == 900
x = 6
x += 7 + 8
assert x == 21
x = y = z = 0
assert x == 0
asse... |
# To be run for STK Blender source files before being opened in 2.80+
# Searches for UV textures, creates materials out of them, and assigns
# those materials to all meshes using them
#
# Limitations (most of which can be fixed after migration):
# * Vertex colors are not supported, but they are left intact
# * Decal sh... |
"""
Enable users to merge YAML/Compatible files.
Due to the complexities of merging, users are given deep control over the merge
operation via both default behaviors as well as per YAML Path behaviors.
Copyright 2020, 2021 William W. Kimball, Jr. MBA MSIS
"""
import sys
import argparse
import json
from os import acce... |
import sys
import os
import copy
from pal.cmd_args import parse_cmd_args
from pal.parser import parse_registers
from pal.transform import transforms
from pal.writer.writer_factory import make_writer
from pal.generator.cxx_header_generator import CxxHeaderGenerator
from pal.generator.yaml_data_generator import YamlDat... |
from heapq import heappop, heappush
from collections import defaultdict
import networkx as nx
import numpy as np
def dijkstra(edges, s, t):
"""
Find the shortest path from node s to t in graph G.
:param edges: a list of tuples (i, j, w), where (i,j) is an undirected edge, and w is its weight
:param s:... |
# -*- 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... |
import setuptools
with open("README.md") as fp:
long_description = fp.read()
setuptools.setup(
name="%name.PythonModule%",
version="0.0.1",
description="A sample CDK Python app",
long_description=long_description,
long_description_content_type="text/markdown",
author="author",
pac... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from set_path import set_path
stockrsm_path = set_path()
# PYTHON_ARGCOMPLETE_OK
import argcomplete, argparse
import subprocess
import os
import sys
from argcomplete.completers import ChoicesCompleter
from argcomplete.completers import EnvironCompleter
# Set path and ... |
"""
This module gathers tree-based methods, including decision, regression and
randomized trees. Single and multi-output problems are both handled.
"""
# Authors: Gilles Louppe <g.louppe@gmail.com>
# Peter Prettenhofer <peter.prettenhofer@gmail.com>
# Brian Holt <bdholt1@gmail.com>
# Noel Da... |
from decimal import Decimal as D
from django.utils.translation import gettext_lazy as _
from oscar.core import prices
class BaseSurcharge:
"""
Surcharge interface class
This is the superclass to the classes in surcharges.py. This allows using all
surcharges interchangeably (aka polymorphism).
... |
"""wrapper for ninja build tool"""
import subprocess
import platform
import shutil
name = 'ninja'
platforms = ['linux', 'osx', 'win']
optional = True
not_found = "required for building '*-ninja-*' configs"
#-------------------------------------------------------------------------------
def get_ninja_name() :
if p... |
# Regresión lineal, que peudo correr en collab.
import numpy as np
import matplotlib.pyplot as plt
# Esto son la variabel independiente
x = np.array([0,1,2,4 ])
# Esta es mi dependiente, resutlado de experimentos
y = np.array([1,3,4,5])
# Me permite tomar ecnontrar los cefiioentes lienales para neustra función li... |
# Global Imports
import json
from collections import defaultdict
# Metaparser
from genie.metaparser import MetaParser
# =============================================
# Collection for '/mgmt/tm/cm/device-group' resources
# =============================================
class CmDevicegroupSchema(MetaParser):
sche... |
# -*- coding: utf-8 -*-
'''
Control the Salt command interface
==================================
This state is intended for use from the Salt Master. It provides access to
sending commands down to minions as well as access to executing master-side
modules. These state functions wrap Salt's :ref:`Python API <python-ap... |
# -*- coding: utf-8 -*-
# Copyright 2017-2020 NTT Communications
#
# 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 b... |
#!/usr/bin/env python
import json
import argparse
import mysql_to_bigquery_schema_converter as converter
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Convert mysql schemas to bigquery')
parser.add_argument('Path',
type=str,
h... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""Test da... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2017-08-09 02:47
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('blog', '0030_auto_20170517_1959'),
]
operations = ... |
################################################################################
# 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... |
#!/usr/bin/env python
#
# Copyright (c) 2021 Intel Corporation
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
#
import ros_compatibility.qos
from ros_compatibility.core import get_ros_version
from ros_compatibility.exceptions import *
ROS_VERSIO... |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'My Project',
'author': 'Bjorn Chrisnach',
'url': 'URL to get it at.',
'download_url': 'Where to download it.',
'author_email': 'bjorn.chrisnach@gmail.com',
'version': "0.1",... |
import utils
import config
import os
import feature
import numpy as np
import matplotlib.pyplot as plt
info, wave_data = utils.wavDecode(os.path.join(config.datasetPath, "1_34_1/0/0_0.wav"))
wave_data = wave_data[:, 0]
wave_data = wave_data * 1.0 / (max(abs(wave_data)))
frame_lens = 512
move = 128
frames = utils.fra... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... |
# -*- coding: utf-8 -*-
import os
os.environ['DJANGO_SETTINGS_MODULE']='settings'
import webapp2 as webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
import numpy as np
import cgi
import cgitb
import copy
cgitb.enable()
from loons import loons_model
from... |
# -*- coding: utf-8 -*-
"""
=========================
Abortable tasks overview
=========================
For long-running :class:`Task`'s, it can be desirable to support
aborting during execution. Of course, these tasks should be built to
support abortion specifically.
The :class:`AbortableTask` serves as a base clas... |
import numpy as np
from copy import copy, deepcopy
from ...util.event import Event
from ...util.misc import ensure_iterable
from ...util.status_messages import format_float
from ..base import Layer
from vispy.color import get_color_names
from ._constants import Mode, Box, BACKSPACE, shape_classes, ShapeType
from .shap... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI 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 ... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
@author: Rachid and Kimia
"""
import numpy as np
def gammatone_function(resolution, fc, center, fs=16000, n=4, b=1.019):
"""Define a single gammatone function"""
t = np.linspace(0, resolution-(center+1), resolution-center)/fs
g = np.zeros((resolution,))... |
import copy
import os
import os.path
import pathlib
import shutil
import typing
from fiepipelib.assetdata.data.connection import Connection
from fiepipelib.filerepresentation.data.filerepresentation import AbstractRepresentation, AbstractRepresentationManager
from fiepipelib.fileversion.data.fileversion import Abstrac... |
from django.contrib import admin
from .models import User
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.template.response import TemplateResponse
from django.urls import reverse
from django.utils.html import format_html
from django.utils.http import urlencode
from django... |
# Author: Christian Brodbeck <christianbrodbeck@nyu.edu>
from itertools import product
import pickle
import logging
import pytest
import sys
import numpy as np
from numpy.testing import assert_array_equal, assert_allclose
import eelbrain
from eelbrain import Dataset, NDVar, Categorial, Scalar, UTS, Sensor, configure,... |
# 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... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
from csv import DictReader, unix_dialect, writer
from test import whitelists as wl
mappings = {
"journal_full_title": {},
"publisher": {}
}
def _get_publisher_identity(publisher):
for entry in wl.PUBLISHER_IDENTITY:
if publisher in entry[1]:
... |
#!/usr/bin/env python3
#
# Copyright 2021 Graviti. Licensed under MIT License.
#
"""The implementation of the TensorBay repr."""
from abc import ABC
from enum import Enum, auto
from typing import Any, Callable, Dict, Iterable, Mapping, Sequence, Tuple, Type, TypeVar, Union
class ReprType(Enum):
"""ReprType is a... |
from ml_privacy_meter.attack import meminf, meminf_modules
|
"""Test package metadata"""
import pydrobert.torch
def test_version():
assert pydrobert.torch.__version__ != "inplace"
|
"""
WSGI config for native 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/3.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTIN... |
import logging
from django.utils.unittest import skip
from testconfig import config
from tests.integration.core.chroma_integration_testcase import ChromaIntegrationTestCase
from iml_common.lib.util import ExceptionThrowingThread
log = logging.getLogger(__name__)
class TestCorosync(ChromaIntegrationTestCase):
... |
"""
MIT License
Copyright (c) 2019-2021 akrocynova
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publi... |
import logging
from dataclasses import dataclass, field
from dulwich import porcelain
from dulwich.porcelain import GitStatus
from dulwich.repo import Repo
from itertools import chain
from pathlib import Path
from typing import Any
from .anki_repo import AnkiRepo
logger = logging.getLogger(__name__)
@dataclass
cla... |
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
APP = ['main.py']
DATA_FILES = []
OPTIONS = {'argv_emulation': True, 'resources':'./resources', 'iconfile': './ssnake.icns'}
setup(
app=APP,
data_files=DATA_FILES,
options={'py2app': OP... |
import inspect
import json
from os.path import abspath, dirname, exists, join
from ..test_support import pyfrc_fake_hooks
import hal_impl.functions
import logging
logger = logging.getLogger('pyfrc.sim')
class PyFrcSim:
"""
Executes the robot code using the low fidelity simulator and shows
a tk-... |
"""
Python implementation of Conflict-based search
author: Ashwin Bose (@atb033)
"""
import sys
sys.path.insert(0, '../')
import argparse
import yaml
from math import fabs
from itertools import combinations
from copy import deepcopy
from cbs.a_star_mine import AStar
import time
import signal
from contextlib impor... |
# Reading a TFRecord file
# Serialized tensors can be easily parsed using `tf.train.Example.ParseFromString`
import tensorflow as tf
import numpy as np
filename = "something"
filenames = [filename]
raw_dataset = tf.data.TFRecordDataset(filenames)
print(raw_dataset)
for raw_record in raw_dataset.take(1):
example = ... |
from typing import Optional
import click
from clinica.pipelines import cli_param
pipeline_name = "t1-volume-parcellation"
@click.command(name=pipeline_name)
@cli_param.argument.caps_directory
@cli_param.argument.group_label
@cli_param.option_group.common_pipelines_options
@cli_param.option.subjects_sessions_tsv
@c... |
import sys
pwd = sys.path[0]+'/'
import os
file1 = open(pwd+'datalist.txt','w')
names = os.listdir(pwd+'../Peliculas/noFights')
for name in names:
file1.write('noFights/'+name+' 1\n')
names = os.listdir(pwd+'../Peliculas/fights')
for name in names:
file1.write('fights/'+name+' 2\n')
file1.close()
... |
import numpy as np
import pandas as pd
import pandera as pa
MIN_DATE = pd.Timestamp("2021-10-01")
df = pd.read_csv(
"./ebike_trips.csv",
parse_dates=["start_time", "end_time"],
)
trips_schema = pa.DataFrameSchema(
columns={
"bike_id": pa.Column(
int, checks=pa.Check.ge(0)
), ... |
from typing import NoReturn
from src.contexts.photostore.photo.domain.PhotoRepository import PhotoRepository
from src.contexts.photostore.photo.domain.entities.Photo import Photo
from src.contexts.photostore.photo.domain.errors.PhotoAlreadyExistsError import PhotoAlreadyExistsError
from src.contexts.shared.Infrastruct... |
# Importing the Kratos Library
import KratosMultiphysics
from KratosMultiphysics.json_utilities import read_external_json, write_external_json
def Factory(settings, Model):
if(type(settings) != KratosMultiphysics.Parameters):
raise Exception("Expected input shall be a Parameters object, encapsulating a jso... |
# Copyright 2020 Carlos San Vicente
#
# 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 wr... |
def math():
try:
while True:
test_case, i_d = map(int, input().split())
count = 0
for i in range(test_case):
iid, cs = map(int, input().split())
if iid == i_d and cs == 0:
count += 1
print(count)
except ... |
# define locations to store the rendered data
import boto3
from botocore.exceptions import ClientError
from builtins import range
from enum import Enum
from future.utils import raise_from
import md5
from ModestMaps.Core import Coordinate
import os
from tilequeue.metatile import metatiles_are_equal
from tilequeue.forma... |
# -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import os
impo... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from .. import utilities, tables
class RateBasedRule(pulumi.CustomReso... |
'''
File name: keras-yolo3
Author: minhnc-lab
Date created(MM/DD/YYYY): 2019-05-03
Last modified(MM/DD/YYYY HH:MM): 2019-05-03 10:28
Python Version: 3.6
Other modules: [None]
Copyright = Copyright (C) 2017 of CONG-MINH NGUYEN
Credits = [None] # people who reported bug fixes, made sugges... |
import numpy as np
import raocp.core.cones as core_cones
class AVaR:
"""
Risk item: Average Value at Risk class
"""
def __init__(self, alpha, probabilities):
"""
:param alpha: AVaR risk parameter
:param probabilities: list of probabilities of future events
Note: ambig... |
class Pessoa:
def __init__(self, *filhos, nome=None, idade=35):
self.idade = idade
self.nome = nome
self.filhos = list(filhos)
def cumprimentar(self):
return f'Olá {id(self)}'
if __name__ == '__main__':
brenda = Pessoa(nome='Brenda', idade=26)
ricardo = Pessoa(brenda,no... |
import sys
import cv2
import numpy as np
from tqdm import tqdm
from keras.models import Sequential
from keras.layers import Dropout, Flatten, Dense
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D, GlobalMaxPooling2D
from keras.callbacks import ModelCheckpoint
from keras.preprocessing import ima... |
import re
import sys
MODULE_REGEX = r'^[_a-zA-Z][_a-zA-Z0-9]+$'
module_name = '{{ cookiecutter.project_slug }}'
if not re.match(MODULE_REGEX, module_name):
print(('ERROR: The project slug (%s) is not a valid Python module name. Please do not use'
' a - and use _ instead' % module_name))
# Exit t... |
test = {
'name': 'Question 11',
'points': 2,
'suites': [
{
'cases': [
{
'code': r"""
>>> swap_strategy(9, 21, 8, 6)
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> swap_strategy(30, 54, ... |
# Copyright (c) 2009, 2012-2013, 2015-2020 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation... |
# coding: utf-8
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: api-support@onshape.zendesk.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
im... |
# Copyright (C) 2011 Atsushi Togo
# All rights reserved.
#
# This file is part of phonopy.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notic... |
# coding: utf-8
from __future__ import unicode_literals
import sys
from datetime import datetime
from django.contrib.admin.models import LogEntry, DELETION
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.contenttypes.models import ContentType
from django.views.decorat... |
from collections import namedtuple
from functools import partial
from twisted.internet.defer import succeed
from twisted.trial.unittest import TestCase
from twisted.web import http
from vumi.transports.parlayx.soaputil import (
SOAP_ENV, soap_envelope, unwrap_soap_envelope, soap_fault, tostring,
perform_soap_... |
# coding: utf-8
# Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
#//
#//------------------------------------------------------------------------------
#// Copyright 2007-2010 Mentor Graphics Corporation
#// Copyright 2007-2011 Cadence Design Systems, Inc.
#// Copyright 2010 Synopsys, Inc.
#// Copyright 2014 NVIDIA Corportation
#// Copyright 2019 Tuomas Poikela (tpoikela)
#... |
import numpy as np
from .ReadMGF import ReadMGF
from scipy.interpolate import interp1d
from scipy.ndimage import uniform_filter
import DateTimeTools as TT
def InterpObj(Date,Coords='GSE',Smooth=None):
'''
Return interpolation objects for MGF data.
'''
#read the data in
mag = ReadMGF(Date)
#get continuous t... |
import _plotly_utils.basevalidators
class XValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(self, plotly_name="x", parent_name="histogram2dcontour", **kwargs):
super(XValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
ed... |
"""
Cisco Intersight
Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advan... |
#Um programa que lê vários números até receber 999(condição de parada) Mostra quantos valores foram inseridos e a soma deles
num = 0
count= 0
all = []
sum1 = 0
sum2 = 0
vav = 0
while num != 999:
num = int(input('Digite um número inteiro qualquer (999 para parar) '))
if num != 999:
count += 1
... |
"""
MultiTracker
Multi tracker implementation, with some tricks to make low frame rate work a bit better
"""
from simplesensor.shared import ThreadsafeLogger
from .tracker import Tracker
from time import time
class MultiTracker(object):
def __init__(self, kind="KCF", moduleConfig=None, loggingQueue=None):
""" Creat... |
"""Common operations on Posix pathnames.
Instead of importing this module directly, import os and refer to
this module as os.path. The "os.path" name is an alias for this
module on Posix systems; on other systems (e.g. Mac, Windows),
os.path provides the same operations in a manner specific to that
platform, an... |
# Copyright 2020 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 common import *
from solution import *
import copy
import sys
import datetime
num_test = 100
true, false = True, False
in_0 = []
in_org_0 = []
out = []
def load_test():
f = open('judge/tests/recover-count-array.txt', 'r')
global in_0, in_org_0
in_0 = read_int_matrix(f)
in_org_0 = copy.deepcopy(i... |
import unittest
from openprocurement.framework.cfaua.tests.base import BaseAgreementContentWebTest
from openprocurement.framework.cfaua.tests.data import TEST_AGREEMENT
class AgreementContractsResourceTest(BaseAgreementContentWebTest):
initial_data = TEST_AGREEMENT
def test_get_agreement_contracts(self):
... |
import ast
import errno
import glob
import importlib
import marshal
import os
import py_compile
import stat
import sys
import textwrap
import zipfile
from functools import partial
from pathlib import Path
from typing import Dict
from typing import List
from typing import Mapping
from typing import Optional
from typing ... |
"""Compatibility fixes for older version of python, numpy and scipy
If you add content to this file, please give the version of the package
at which the fixe is no longer needed.
"""
# Authors: Emmanuelle Gouillart <emmanuelle.gouillart@normalesup.org>
# Gael Varoquaux <gael.varoquaux@normalesup.org>
# ... |
from collections import namedtuple
from contextlib import contextmanager
import json
try:
from urllib import quote, quote_plus, unquote_plus
except ImportError:
from urllib.parse import quote, quote_plus, unquote_plus # @UnresolvedImport
import re
import socket
import subprocess
import sys
import threading
im... |
class Solution:
"""
@param s: an expression includes numbers, letters and brackets
@return: a string
"""
def expressionExpand(self, s):
# write your code here
if s is None or len(s) == 0:
return ""
return self.dfs(s)
def dfs(self, s):
... |
import pytest
from loguru import logger
import nest_asyncio
from aiogram.types import ReplyKeyboardMarkup
from settings import config
from app.utils import Secret, JWT
from app.enum import *
from app_bot.utils import Validator, replay_markup_3
config["extra"]["WORKER"] = "PyTest_unit"
logger.configure(**config)
nest_... |
import logging
import subprocess
import threading
from platypush.plugins.camera.model.writer.image import MJPEGStreamWriter
from platypush.plugins.camera.model.writer.preview import PreviewWriter
class FFplayPreviewWriter(PreviewWriter, MJPEGStreamWriter):
"""
General class for managing previews from camera ... |
import tensorflow as tf
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
from dataset import DataGenerator
from encoder import Attentive_encoder
from decoder import Pointer_decoder
from critic import Critic
from config import get_config, print_config
# Tensor summaries for Tenso... |
from itertools import combinations_with_replacement
def find_all(sum_dig, digs):
res=["".join(i) for i in combinations_with_replacement("123456789", digs) if sum(int(j) for j in i)==sum_dig]
return [] if not res else [len(res), int(res[0]), int(res[-1])]
"""
maximum=str(sum_dig//digs)*(digs-sum_dig%digs... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
# -*- 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... |
from plotly.basedatatypes import BaseLayoutHierarchyType as _BaseLayoutHierarchyType
import copy as _copy
class Tickformatstop(_BaseLayoutHierarchyType):
# class properties
# --------------------
_parent_path_str = "layout.scene.xaxis"
_path_str = "layout.scene.xaxis.tickformatstop"
_valid_props ... |
# -*- coding: UTF-8 -*-
import os
import unittest
from mock import Mock
import oca
class TestUserPool(unittest.TestCase):
def setUp(self):
self.client = oca.Client('test:test')
self.xml = open(os.path.join(os.path.dirname(oca.__file__),
'tests/fixtures/userpo... |
import random
from .bot_base import Bot
class RandomBot(Bot):
def __init__(self, dim, name='random_bot'):
super().__init__(dim, name)
""" Example bot that runs randomly. """
def choose_action(self, state):
x = random.randrange(0, self.dim)
y = random.randrange(0, self.dim)
... |
# TODO: define the 'EXPECTED_BAKE_TIME' constant
# TODO: define the 'PREPARATION_TIME' constant
# TODO: define the 'bake_time_remaining()' function
def bake_time_remaining():
"""Calculate the bake time remaining.
:param elapsed_bake_time: int baking time already elapsed.
:return: int remaining bake time ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.