text stringlengths 1 927k |
|---|
import logging
import os
import errno
import six
import importlib
import copy
import re
from collections import OrderedDict
from great_expectations.exceptions import (
PluginModuleNotFoundError,
PluginClassNotFoundError,
)
logger = logging.getLogger(__name__)
def safe_mmkdir(directory, exist_ok=True):
"... |
# 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 under ... |
#!/usr/bin/env python
def brute_force_search(l, value):
for i in range(len(l)):
if l[i] == value:
return i
return -1
if __name__ == "__main__":
array = range(42)
found = brute_force_search(array, 20) |
from __future__ import division
import time
import iotbx.pdb
import mmtbx.model
from cctbx.array_family import flex
from libtbx.test_utils import approx_equal
#-----------------------------------------------------------------------------
# This finite difference test checks transformation of riding H gradients
# for n... |
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
APP = ['test.py']
DATA_FILES = []
OPTIONS = {}
setup(
app=APP,
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
) |
"""Open an arbitrary URL.
See the following document for more info on URLs:
"Names and Addresses, URIs, URLs, URNs, URCs", at
http://www.w3.org/pub/WWW/Addressing/Overview.html
See also the HTTP spec (from which the error codes are derived):
"HTTP - Hypertext Transfer Protocol", at
http://www.w3.org/pub/WWW/Protocols... |
# -*- coding: utf-8 -*-
from django.utils import timezone
from modularodm import Q
from website import settings
def no_addon(email):
return len(email.user.get_addons()) == 0
def no_login(email):
from website.models import QueuedMail
from website.mails import NO_LOGIN_TYPE
sent = QueuedMail.find(Q('us... |
from . import type_checker
class DTODescriptor:
__slots__ = "_immutable", "_type", "_field", "_validator", "_dto_class_name", "_coerce"
def __init__(self, dto_class_name: str, field: str, type_: type, immutable: bool = True,
validator: callable = None, coerce: callable = None):
self.... |
#!/usr/bin/python
#
# Copyright 2018-2020 Polyaxon, 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 ... |
import json
HTML_TEMPLATE = {
'vega-lite': """
<!DOCTYPE html>
<html>
<head>
<style>
.vega-actions a {{
margin-right: 12px;
color: #757575;
font-weight: normal;
font-size: 13px;
}}
</style>
<script src="{base_url}/vega@{vega_version}"></script>
<script src="{base_url}/v... |
# 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! ***
from .. import _utilities
import typing
# Export this package's modules as members:
from .scalable_target import *
from .scaling_policy import *
from .... |
#!/usr/bin/python2.5
# Copyright (C) 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 la... |
# time limit exceeded
# slug = find-substring-with-given-hash-value
class Solution:
def subStrHash(self, s: str, power: int, modulo: int, k: int, hashValue: int) -> str:
n = len(s)
curr = 0
for i in range(k):
curr = ((ord(s[n-i-1]) - ord('a') + 1) + (power%modul... |
import time
import logging
import torch
import torch.nn as nn
import torch.nn.parallel
from torch.nn.utils import clip_grad_norm_
from utils.meters import AverageMeter, accuracy
def _flatten_duplicates(inputs, target, batch_first=True):
if batch_first:
target = target.view(-1, 1).expand(-1, inputs.size(1)... |
# __author: Administrator
# date: 2020/7/14
product_list = [
('Mac', 9000),
('kindle', 800),
('tesla', 900000),
('python book', 105),
('bike', 2000)
]
shopping_car = []
saving = input("please input your money:")
if saving.isdigit():
saving = int(saving)
while True:
for i, (v, j)... |
from ctypes import byref, Structure, c_char, c_buffer, string_at, windll, c_void_p, c_uint32, POINTER, c_wchar_p, WinError
LPWSTR = c_wchar_p
LPVOID = c_void_p
PVOID = LPVOID
PPVOID = POINTER(PVOID)
DWORD = c_uint32
def RaiseIfZero(result, func = None, arguments = ()):
"""
Error che... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import account_move
from . import account_journal
from . import res_partner |
from pybaum.registry_entries import FUNC_DICT
def get_registry(types=None, include_defaults=True):
"""Create a pytree registry.
Args:
types (list): A list strings with the names of types that should be included in
the registry, i.e. considered containers and not leaves by the functions
... |
from anchorecli.cli import repo |
# -*- coding: utf-8 -*-
from datetime import datetime, time, timedelta
from plotly.offline import plot
from plotly.graph_objs import Bar, Scatter
from ..report import Report
from health_stats.models.events import *
from health_stats.database import DBSession
from health_stats.dataset import DataSet
class DailyCar... |
# Copyright 2020 Kaggle 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 law or agreed to in writing, ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-12-14 16:15
from __future__ import unicode_literals
import ckeditor_uploader.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('goods', '0008_auto_20181213_0915'),
]
operations = [
... |
__author__ = 'hudaiber'
import os
import sys
if sys.platform == 'darwin':
sys.path.append(os.path.join(os.path.expanduser('~'),'Projects/lib/BioPy/'))
sys.path.append(os.path.join(os.path.expanduser('~'),'Projects/SystemFiles/'))
elif sys.platform == 'linux2':
sys.path.append(os.path.join(os.path.expanduse... |
import numpy as np
def solve_hazard_eqn(fn, val, minval=10.0, maxval=900.0, interval=1.0):
'''
Finds the approximate point where a function crosses a value from below.
'''
prev_val = fn(minval)
for i in np.arange(minval+interval, maxval, interval):
next_val = fn(i)
if next_val < val and val < prev_val:
r... |
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2021 richardHaw
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, m... |
import pandas as pd
import mlflow.sklearn
from sqlalchemy import create_engine
from config import DATABASE_URI
from predictions.common_predictor import CommonPredictor
from config import ROOT_DIR
pd.set_option("display.width", 1000)
pd.set_option("display.max_columns", 50)
class LoLPredictor(CommonPredictor):
d... |
import os
import yaml
import datetime
def checkOutputDirectoryAndCreate(output_folder):
if not os.path.exists('result/' + output_folder):
os.makedirs('result/' + output_folder)
def loadConfig(path):
f = open(path)
config = yaml.load(f, Loader=yaml.FullLoader)
tz = datetime.timezone(datetime.ti... |
# coding: utf-8
"""
LUSID API
FINBOURNE Technology # noqa: E501
The version of the OpenAPI document: 0.11.4425
Contact: info@finbourne.com
Generated by: https://openapi-generator.tech
"""
try:
from inspect import getfullargspec
except ImportError:
from inspect import getargspec as getf... |
# Write a function named substring_between_letters that takes a string named word, a single character named start,
# and another character named end. This function should return the substring between the first occurrence of start and end in word.
# If start or end are not in word, the function should return word.
# F... |
#============================================
__author__ = "Sachin Mehta"
__maintainer__ = "Sachin Mehta"
#============================================
import torch
from torch import nn
import torch.nn.functional as F
from nn_layers.cnn_utils import activation_fn, CBR, Shuffle, BR
import math
class EffDWSepConv(nn.Mo... |
# Copyright 2017 The Bazel 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 applicable la... |
import json
import logging
import re
import time
from flask import render_template, request, redirect, jsonify, url_for, session, Blueprint, abort
from sqlalchemy.sql import or_
from CTFd.models import db, Challenges, Files, Solves, WrongKeys, Keys, Tags, Teams, Awards, Hints, Unlocks
from CTFd.plugins.keys import ge... |
import logging
import warnings
import uuid
from sanic import Blueprint, response
from sanic.request import Request
from sanic.response import HTTPResponse
from socketio import AsyncServer
from typing import Optional, Text, Any, List, Dict, Iterable, Callable, Awaitable
from rasa.core.channels.channel import InputChann... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayOpenServicemarketOrderRejectResponse(AlipayResponse):
def __init__(self):
super(AlipayOpenServicemarketOrderRejectResponse, self).__init__()
def par... |
import numpy as np
from pytorch_drl.utils.schedule import LinearSchedule
class OrnsteinUhlenbeck:
def __init__(self, x_size, mu=0,
sigma_init=0.2, sigma_final=0.2,
sigma_horizon=1, theta=0.2, dt=1e-2):
self.mu = mu
self.x_size = x_size
self.dt = dt
... |
"""
Generic file-handing functions for SPH data
"""
from yt.utilities.io_handler import BaseIOHandler
class IOHandlerSPH(BaseIOHandler):
"""IOHandler implementation specifically for SPH data
This exists to handle particles with smoothing lengths, which require us
to read in smoothing lengths along wi... |
from django.core.management.base import BaseCommand, CommandError
from scores.models import Team, League, Player
import json, shutil, time, hashlib, glob, os
class Command(BaseCommand):
def handle(self, *args, **options):
Player.objects.all().delete()
allplayers = json.load(open("players.current.json")... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Constant-Q transforms'''
from __future__ import division
import numpy as np
import scipy.fftpack as fft
from . import audio
from .time_frequency import cqt_frequencies, note_to_hz
from .spectrum import stft
from .pitch import estimate_tuning
from .. import cache
from .... |
# coding: utf-8
from __future__ import absolute_import
from bitmovin_api_sdk.common import BaseApi, BitmovinApiLoggerBase
from bitmovin_api_sdk.common.poscheck import poscheck_except
from bitmovin_api_sdk.models.bitmovin_response import BitmovinResponse
from bitmovin_api_sdk.models.response_envelope import ResponseEn... |
a = float(input(""))
b = float(input(""))
c = float(input(""))
x = ((a * 2.0)+ (b*3.0) + (c*5.0))/10.0
print("MEDIA = %.1f" %x) |
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... |
"""
查询本地数据
尽管`bcolz`最终会丢失时区信息,但写入时依旧将时间列转换为UTC时区。
除asof_date、timestamp列外,其余时间列无需转换
"""
import re
import warnings
from concurrent.futures.thread import ThreadPoolExecutor
from functools import partial
import numpy as np
import pandas as pd
from cnswd.cninfo.utils import _rename
from cnswd.mongodb import get_db
fro... |
# qubit number=3
# total number=12
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
import networkx as nx
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collectio... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
students = []
def add():
name = input("Фамилия и инициалы? ")
number = input("Номер телефона? ")
print("Дата рождения:")
day = input("день")
month = input("Месяц")
year = input("Год")
student = {
'name': name,
'number': numbe... |
import ray.experimental.client as ray
ray.connect("localhost:50051")
objectref = ray.put("hello world")
print(objectref)
print(ray.get(objectref)) |
# 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 flask import render_template
from <%= appName %> import app
@app.route('/')
def index():
return render_template('index.html') |
# 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
# d... |
from flask import current_app as app
from typing import List
from .abstracts.AbcHighscoreRankRepository import AbcHighscoreRankRepository
from .Repository import Repository
from ..models.highscore.HighscoreRank import HighscoreRank
class HighscoreRankRepository(Repository, AbcHighscoreRankRepository):
DEFAULT_RE... |
from flask import Flask, jsonify
from elementae import azar, expresser
app = Flask(__name__)
@app.route('/', methods=['GET'])
def randomization():
mood = azar([0, 1], 1)
output = expresser(mood)
return jsonify(output)
if __name__ == '__main__':
app.run(port=5005, host='0.0.0.0', debug=True) |
# coding=utf-8
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... |
# import basehash
# hash_fn = basehash.base62() # you can initialize a 36, 52, 56, 58, 62 and 94 base fn
# password = int("1")
# hash_value = hash_fn.hash(password)
# unhashed = hash_fn.unhash(hash_value)
# print(hash_value)
# print(unhashed)
# alphabets="abcdefghijklmnopqrsdt"
# message=input("Enter the message ... |
# coding: utf-8
"""
convertapi
Convert API lets you effortlessly convert file formats and types. # noqa: E501
OpenAPI spec version: v1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class GetDocxCommentsHierarchicalResp... |
from insights import add_filter
from insights.parsers.messages import Messages
from insights.specs import Specs
from insights.tests import context_wrap
MSGINFO = """
May 18 15:13:34 lxc-rhel68-sat56 jabberd/sm[11057]: session started: jid=rhn-dispatcher-sat@lxc-rhel6-sat56.redhat.com/superclient
May 18 15:13:36 lxc-rh... |
import re
import sys
import os
import logging
sys.path.insert(1, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from tools import shared
from tools import line_endings
logger = logging.getLogger('minimal_runtime_shell')
def generate_minimal_runtime_load_statement(target_basename):
prefix_statements... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from celery.utils.imports import symbol_by_name
ALIASES = {
"processes": "celery.concurrency.processes:TaskPool",
"eventlet": "celery.concurrency.eventlet:TaskPool",
"gevent": "celery.concurrency.gevent:TaskPool",
"threads": "celery.concur... |
# import tensorflow as tf
from onnx_darknet.handlers.backend_handler import BackendHandler
from onnx_darknet.handlers.handler import onnx_op
@onnx_op("HardSigmoid")
class HardSigmoid(BackendHandler):
@classmethod
def _common(cls, node, **kwargs):
x = kwargs["tensor_dict"][node.inputs[0]]
if "alpha" not ... |
# Copyright (c) 2016 Citrix System.
# 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 requir... |
from corehq.apps.locations.models import SQLLocation
from custom.icds_reports.models.aggregate import AggregateInactiveAWW
from custom.icds_reports.utils import india_now, DATA_NOT_ENTERED
class AwwActivityExport(object):
title = 'AWW Activity Report'
def __init__(self, config, loc_level=0, show_test=False, ... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from google.longrunning import operations_pb2 as google_dot_longrunning_dot_operations__pb2
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empt... |
# coding=utf-8
#
# Copyright 2014 Red Hat, Inc.
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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
#
# ... |
import environ
from tradingdb.chainevents.abis import abi_file_path, load_json_file
env = environ.Env()
# ------------------------------------------------------------------------------
# ETH EVENTS - Set a list of addresses the Event Listener has to listen to
# ------------------------------------------------------... |
import os
import sys
import zipfile
import pytest
from mountequist import installers
from mountequist.util import get_root_mountebank_path
from tests.defaults import DEFAULT_TEST_PATH
windows_only = pytest.mark.skipif(sys.platform != "win32", reason="Windows Only")
@windows_only
def test_windows_can_download(mark_... |
#!/usr/bin/env python3
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2012 thomasv@gitorious
#
# 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 with... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2015 clowwindy
#
# 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... |
from flask import Flask, request, jsonify
from flask_graphql import GraphQLView
from extensions import bcrypt, auth, jwt
from schema import auth_required_schema, schema
from dotenv import load_dotenv
from flask_jwt_extended import (
create_access_token,
create_refresh_token, get_jwt_identity,
jwt_required
)... |
#!/usr/bin/env python3.8
# Copyright 2019 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import datetime
import os
import unittest
import test_env
from test_case import TestCaseWithFuzzer
class CorpusTest(TestCaseWithFu... |
# Copyright (c) 2019 Horizon Robotics. 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 applicab... |
'''
onshape
======
Provides access to the Onshape REST API
'''
from onshape_api import utils
import os
import random
import string
import json
import hmac
import hashlib
import base64
import urllib
import datetime
import requests
from urllib.parse import urlparse
from urllib.parse import parse_qs
__all__ = [
'O... |
# Maior e Menor valor na lista
listanum = []
maior = 0
menor = 0
for c in range(0 ,5):
listanum.append(int(input(f'Digite um valor para a posição {c}: ')))
if c == 0 :
maior = menor = listanum[c]
else:
if listanum[c] > maior:
maior = listanum[c]
if listanum[c] < men... |
import json
import setuptools
kwargs = json.loads(
"""
{
"name": "jsii-calc",
"version": "0.0.0",
"description": "A simple calcuator built on JSII.",
"license": "Apache-2.0",
"url": "https://github.com/aws/jsii",
"long_description_content_type": "text/markdown",
"author": "Amazon Web Se... |
# 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
__... |
#!/usr/bin/env python
import re
from pathlib import Path
from setuptools import setup
with (Path(__file__).parent / "aiodocker" / "__init__.py").open() as fp:
try:
version = re.findall(r'^__version__ = "([^"]+)"\r?$', fp.read(), re.M)[0]
except IndexError:
raise RuntimeError("Unable to deter... |
### Script to pull and update data tracking
### import packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import requests
import io
import pathlib
from bs4 import BeautifulSoup
def dataset_load() -> pd.DataFrame():
"""
Function to load and save data regarding... |
import reframe as rfm
import reframe.utility.sanity as sn
class SlurmSimpleBaseCheck(rfm.RunOnlyRegressionTest):
'''Base class for Slurm simple binary tests'''
def __init__(self):
self.valid_systems = ['daint:gpu', 'daint:mc',
'dom:gpu', 'dom:mc',
... |
#!/usr/bin/env python3
from __future__ import print_function
from utils import *
import json
import os
import sys
import subprocess
import copy
from collections import OrderedDict
class Dependency(object):
def __init__(self, name, repository_url, base_state, path):
if path is None:
path = os.... |
#
# Collective Knowledge
#
# See CK LICENSE.txt for licensing details.
# See CK Copyright.txt for copyright details.
#
import sys
import os
import re
import ck.net
############################################################
try:
from io import open
except ImportError:
pass
try:
from setuptools import se... |
"""Module configuring Certbot in a snap environment"""
import logging
import socket
from typing import List
from requests import Session
from requests.adapters import HTTPAdapter
from requests.exceptions import HTTPError
from requests.exceptions import RequestException
from certbot.compat import os
from certbot.error... |
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "LinearTrend", cycle_length = 5, transform = "Difference", sigma = 0.0, exog_count = 0, ar_order = 0); |
from .base import AlgoBase
from .torch.ddpg_impl import DDPGImpl
class DDPG(AlgoBase):
""" Deep Deterministic Policy Gradients algorithm.
DDPG is an actor-critic algorithm that trains a Q function parametrized
with :math:`\\theta` and a policy function parametrized with :math:`\\phi`.
.. math::
... |
# Generated by Django 2.1.15 on 2020-11-27 19:22
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0002_tag'),
]
operations = [
migrations.CreateModel(
... |
#!/usr/bin/env python
"""
bbox_utils.py
=============
A set of utilities for bounding box lookups.
"""
import os
import sys
import logging
logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
def is_in_range(i, start, end):
"Returns a boolean. True if i is inside (or equal to e... |
import torch
import torch.backends.cudnn as cudnn
from collections import OrderedDict
from .modules.utils import yaml_loader, create_model_for_provider
from .modules.craft import CRAFT
def copy_state_dict(state_dict):
if list(state_dict.keys())[0].startswith("module"):
start_idx = 1
else:
sta... |
'''
Copyright 2019 The Microsoft DeepSpeed Team
'''
import time
import psutil
import torch
from deepspeed.pt.log_utils import logger
def print_rank_0(message):
if torch.distributed.is_initialized():
if torch.distributed.get_rank() == 0:
logger.info(message)
else:
logger.info(mess... |
from __future__ import absolute_import, division, print_function
import tensorflow as tf
from tensorflow import keras
import numpy as np
print(tf.__version__)
imdb = keras.datasets.imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
print("Training entries: {}, labels: {}... |
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from textwrap import dedent
from typing import TYPE_CHECKING
from pathvalidate.error import ErrorReason, ValidationError
from ._common import extract_table_metadata
from ._logger import logger
from ._validator import validate_sqlite_attr_name, v... |
import os
import torch
import torch.nn as nn
import numpy as np
import math
import PIL
import matplotlib.pyplot as plt
def show_images(images, in_row=True):
'''
Helper function to show 3 images
'''
total_images = len(images)
rc_tuple = (1, total_images)
if not in_row:
rc_tuple = (total... |
from common_files.utils import MetricLogger, colorize, load_hyperparams
hyperparams = load_hyperparams()
AGENT = hyperparams['algo']['agent']
if 'cnn' in AGENT:
# For headless rendering
import os
os.environ['PYOPENGL_PLATFORM'] = 'egl'
import gym
if AGENT == 'td3':
from td3.agent import Agent
elif A... |
# Copyright 2011 Andrew Bogott for the Wikimedia 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-... |
"""Module for processing and packing sprites."""
import logging
from pathlib import Path
from typing import List, Dict, Any
import pyxel
from bansoko import LEVEL_NUM_LAYERS
from bansoko.graphics import Rect, Size, IMAGE_BANK_HEIGHT, IMAGE_BANK_WIDTH
from resbuilder import ResourceError
from resbuilder.resources.box_... |
# coding: utf-8
"""
UltraCart Rest API V2
UltraCart REST API Version 2 # noqa: E501
OpenAPI spec version: 2.0.0
Contact: support@ultracart.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class CouponsRequest(object):
... |
# 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 ... |
#!/usr/bin/env python
__author__ = 'Sergei F. Kliver'
import argparse
from RouToolPa.Routines import EggNOGRoutines
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input", action="store", dest="input", required=True,
help="Eggnog tsv file")
parser.add_argument("-o", "--output_pref... |
# 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
from ... import _utilities, _tables
__a... |
import unittest
import pathlib
import cpptypeinfo
HERE = pathlib.Path(__file__).absolute().parent
CIMGUI_H = HERE.parent / 'libs/cimgui/cimgui.h'
class CImguiTest(unittest.TestCase):
def test_cimgui(self) -> None:
parser = cpptypeinfo.TypeParser()
cpptypeinfo.parse_files(
parser, CIMG... |
# Modified based on the HRNet repo.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import logging
from collections import namedtuple
import torch
import torch.nn as nn
def get_model_summary(model, *input_tensors, item_length=26, verbose=False):... |
# Copyright (c) 2010-2020, sikuli.org, sikulix.com - MIT license
#
# 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... |
import abc
import os
import tarfile
# https://github.com/google/pytype/issues/128
from six import with_metaclass # pytype: disable=pyi-error
# pytype: disable=ignored-abstractmethod
class FileSystemError(Exception):
pass
class FileSystem(with_metaclass(abc.ABCMeta, object)):
"""Interface for file systems.... |
# Crie um programa que tenha uma Tupla unica com nomes de produtos e seus respectivos preços na sequencia.
# No final, mostre uma listagem de preços, organizando os dados em forma tabular.
'''Dá para fazer em 2 linhas...
for i in range(0, len(prod), 2):
print(f'{prod[i]:.<30}R${prod[i + 1]:7.2f}')'''
produtos = (... |
# Generated by Django 3.0.11 on 2021-10-18 08:21
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('tt_storage', '0005_auto_20190417_1852'),
]
operations = [
migrations.AlterField(
model_name... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.