text stringlengths 2 999k |
|---|
import tensorflow as tf
tf.compat.v1.enable_eager_execution()
# Weight Quantization - Input/Output=float32
converter = tf.lite.TFLiteConverter.from_saved_model('./saved_model')
converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]
tflite_quant_model = converter.convert()
with open('./mobilenet_v3_large_224_d... |
from typing import List
from . import AccessRequest, FileID, PartSpec, PartsGenerator
class NonCorrelatedSchemesGenerator(object):
def __init__(self, number: int, fraction: float) -> None:
self._number: int = number
self._fraction: float = fraction
self._parts_number: int = 2 ** number
@property
def number... |
from __future__ import absolute_import
import six
from sentry.api.serializers import Serializer, register
from sentry.models import Monitor
@register(Monitor)
class MonitorSerializer(Serializer):
def serialize(self, obj, attrs, user):
return {
'id': six.text_type(obj.guid),
'stat... |
import requests
headers = {
'X-Api-Key': '123456789',
}
params = {
'test': '2',
'limit': '100',
'w': '4',
}
response = requests.get('http://localhost:28139/synthetics/api/v3/monitors', params=params, headers=headers)
|
import time
from datetime import datetime
from requests import Response
import json
import os
import TunnelSSH
import Helpers
import SettingsStorage
import sys
def create_tunnel(tun: dict):
timeout_time: datetime = datetime.fromisoformat(tun["timeout_time"])
if timeout_time <= datetime.utcnow():
Help... |
#!/usr/bin/env python
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from cotede.humanqc.humaneval import HumanQC
|
# 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 t... |
# coding: utf-8
#
# Copyright 2014 The Oppia 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 requi... |
import pytest
import os
import os
from collections import defaultdict
from syrupy.extensions.single_file import SingleFileSnapshotExtension
from tempgen.module import Tempgen
from tempgen.parsers import Parsers
from tempgen.transforms import Transforms
from tempgen.tests.helpers import ext_serializer_map
tests_dir = o... |
#!/usr/bin/python3
"""Create class"""
class Square:
"""Square class"""
def __init__(self, size=0, position=(0, 0)):
"""Initialize Square"""
self.__size = size
self.position = position
"""if type(size) is not int:
raise TypeError("size must be an integer")
if... |
#This is a mixin class for signal analyzers to be used by f2_system class
#Todo: Analyzers should be a independent class
#Last modification by Marko Kosunen, marko.kosunen@aalto.fi, 30.07.2018 18:09
import numpy as np
import scipy.signal as sig
import matplotlib as mpl
mpl.use('Agg') #To enble plotting without X
impor... |
"""
McsCMOS
~~~~~~~
Wrapper and Helper to access MCS CMOS Data within H5 Files
:copyright: (c) 2018 by Multi Channel Systems MCS GmbH
:license: see LICENSE for more details
"""
import h5py
import numpy as np
class CMOSData(h5py.File):
"""
Wrapper for a HDF5 File conta... |
import _plotly_utils.basevalidators
class NamelengthsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self,
plotly_name='namelengthsrc',
parent_name='bar.hoverlabel',
**kwargs
):
super(NamelengthsrcValidator, self).__init__(
plotly_name... |
from rest_framework_extensions.key_constructor.constructors import DefaultKeyConstructor
from rest_framework_extensions.key_constructor.constructors import bits
class UserKeyConstructor(DefaultKeyConstructor):
user = bits.UserKeyBit()
|
import numpy as np
from PIL import Image
import sys
def numpy_to_png(source, dest):
image = Image.fromarray(np.load(source))
image.save(dest,"PNG")
if __name__ == "__main__":
source = sys.argv[1]
dest = source.split('.npy')[0] + '.png'
print(source, " to ", dest)
numpy_to_png(source, dest)
|
# -*- coding: utf-8 -*-
from codecs import open
import logging
import colander
import deform
from itsdangerous import BadData, SignatureExpired
from h import i18n, models, validators
from h.accounts import util
from h.services.user import UserNotActivated
from h.models.user import (
EMAIL_MAX_LENGTH,
USERNAME... |
# Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above
# copyright notice, this list of con... |
# 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 ... |
"""
Open Nodes web server
Copyright (c) 2018 Opennodes / Blake Bjorn Anderson
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, c... |
#!/usr/bin/python
import hashlib, re, sys, os, base64, time, random, hmac
# stripped down from https://github.com/vbuterin/pybitcointools/blob/master/bitcoin/main.py
### Elliptic curve parameters
P = 2**256-2**32-2**9-2**8-2**7-2**6-2**4-1
N = 1157920892373161954235709850086879078528375642790749043826051631415181614... |
#
# ovirt-engine-setup -- ovirt engine setup
#
# Copyright oVirt Authors
# SPDX-License-Identifier: Apache-2.0
#
#
"""ovirt-host-setup vmconsole_proxy plugin."""
from otopi import util
from . import config
from . import pki
from . import system
@util.export
def createPlugins(context):
config.Plugin(context=c... |
# Licensed to the StackStorm, Inc ('StackStorm') 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 use th... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
###########################################################
# KivyCalendar (X11/MIT License)
# Calendar & Date picker widgets for Kivy (http://kivy.org)
# https://bitbucket.org/xxblx/kivycalendar
#
# Oleg Kozlov (xxblx), 2015
# https://xxblx.bitbucket.org/
###################... |
"""
Utilities for API Gateway response formatting
"""
import json
def format_response(data, status=200):
return {
'body': json.dumps(data),
'headers': {
'Content-Type': 'application/json'
},
'statusCode': int(status)
}
def format_error(msg, code='BadRequest', stat... |
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2012 VMware, Inc.
# Copyright (c) 2011 Citrix Systems, Inc.
# Copyright 2011 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. Yo... |
from pathlib import Path
import json
# Directory
dir = Path().resolve()
# Configuration
with open(dir/'config.json') as config_file:
CONFIG = json.load(config_file)
def output_dir(config = CONFIG):
"""
Return string for default output directory path.
"""
return(config['output_dir']['path']) |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from scipy.ndimage import map_coordinates
from scipy.ndimage.interpolation import shift
from scipy.optimize import curve_fit, ... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.base.exchange import Exchange
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import A... |
'''
Description:
Shuffle a set of numbers without duplicates.
Example:
// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();
// Rese... |
# Copyright (c) 2019-2021, NVIDIA CORPORATION.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... |
# Given a binary tree, find its maximum depth.
# The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
cla... |
import os
def shell():
inputuser = input("> ")
if (inputuser == "exit"):
exit()
os.system(inputuser)
return shell()
print("Welcome to duckshell (python alpha)")
print("System info: ")
os.system("echo distro: $(uname -o)");
os.system("echo hostname: $(uname -n)");
os.system("echo architecture: ... |
import logging
import subprocess
import click
try:
from instance import settings
APP_ROOT = settings.APP_ROOT
except ImportError:
logging.error('Ensure __init__.py and settings.py both exist in instance/')
exit(1)
except AttributeError:
from config import settings
APP_ROOT = settings.APP_ROO... |
import os
import time
from multiprocessing import Process
from typing import Tuple
import flwr as fl
import numpy as np
import tensorflow as tf
from flwr.server.strategy import FedAvg
import dataset
# generate random integer values
from random import seed
from random import randint
# Make TensorFlow log less verbos... |
#!/usr/bin/env python3
elements = (1, 2, 4)
bitset = 0 # 1. Initialize bitset
# Add elements to bitset
for i in elements:
bitset = bitset | 1<<i # 2. Add element to bitset
# Print contents of bitset
print(bitset)
# Test for elements in bitset
for i in range(6):
if bitset & ... |
'''
The management of salt command line utilities are stored in here
'''
# Import python libs
import os
import sys
# Import salt components
import salt.cli.caller
import salt.cli.cp
import salt.cli.key
import salt.cli.batch
import salt.client
import salt.output
import salt.runner
import optparse
from salt.utils impo... |
# # ⚠ Warning
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIA... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
排序算法:
O(n^2)
冒泡排序
插入排序
选择排序
Q(n log n) 分而治之
快速排序
归并排序
"""
|
from logging import getLogger
from typing import (
List,
Optional,
Set,
)
from pydantic import (
BaseModel,
Extra,
Field,
)
from galaxy import exceptions
from galaxy.datatypes.registry import Registry
from galaxy.managers.collections import DatasetCollectionManager
from galaxy.managers.collect... |
# Generated by Django 2.2.10 on 2020-03-04 23:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dcim', '0101_auto_20200304_1403'),
]
operations = [
migrations.CreateModel(
name='ApplicationType',
fields=[
... |
# -*- coding:utf-8 -*-
"""Test function for vega.run"""
import unittest
def lazy(func):
"""lazy function wrapper
:param func: function name
"""
attr_name = "_lazy_" + func.__name__
def lazy_func(*args, **kwargs):
"""Wrapper of lazy func
:param args: any object
:param kwa... |
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
"""
Almost every FBCodeBuilder string is ultimately passed to a shell. Escaping
too little or too much tends to be the most common error. The utilities in
this file give a systematic way of avoiding such bugs:
- When you write literal strings ... |
"""Assortment of utilities.
"""
from datetime import datetime
from hashlib import sha256, md5
import random
import re
import string
import unicodedata
epoch = datetime.utcfromtimestamp(0)
def unix_time(dt=None):
"""Returns the UNIX time representation for a given date or current UTC."""
dt = dt or datetim... |
"""Copyright (c) 2021, Deep Net. 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 agreed to in... |
print 'Hello World!'
|
# exported from PySB model 'model'
from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD
Model()
Monomer('Ligand', ['Receptor'])
Monomer('ParpU', ['C3A'])
Monomer('C8A', ['BidU', 'C3pro'])
Monomer('SmacM', ['BaxA'])
Monomer('BaxM', ['BidM', '... |
from __future__ import annotations
import typing as t
from functools import singledispatch
from inflection import underscore
from sqlalchemy import Date
from sqlalchemy import DateTime
from sqlalchemy import Text
from sqlalchemy import Time
from sqlalchemy import Unicode
from sqlalchemy import UnicodeText
from sqlalc... |
from .__main__ import create_app
application = create_app()
|
# Copyright 2020 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 required by applicable law or agreed to... |
from features.arduino_features import BlackrockSerialDIORowByte, SerialDIORowByte
from riglib import experiment
class par(object):
def init(self):
pass
class F(BlackrockSerialDIORowByte, par):
pass
f = F()
f.init()
|
import logging
import chevron
import re
from itertools import dropwhile
import snex.util as util
logger = logging.getLogger(__name__)
DEFAULT = {
# :snippet global-default-config lang: python
"output_template": "```{{lang}}\n{{{snippet}}}\n```\n",
"valid_param_keys": ["name", "lang", "lnum", "fname", "pat... |
__all__ = ('modulize',)
import sys
from types import FunctionType, GetSetDescriptorType, MappingProxyType, ModuleType
from .docs import has_docs
NoneType = type(None)
try:
from _weakref import ref as WeakrefType
except ImportError:
from weakref import ref as WeakrefType
# This 2 type can be function
Wrapp... |
import shutil
import tempfile
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.cache import cache
from django.contrib.auth import get_user_model
from django.test import Client, TestCase, override_settings
from django.urls import reverse
from django import... |
from sqlalchemy import Column
from sqlalchemy import Integer
from alembic import command
from alembic import op
from alembic.testing import config
from alembic.testing.env import _no_sql_testing_config
from alembic.testing.env import clear_staging_env
from alembic.testing.env import staging_env
from alembic.testing.en... |
# 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 strax
import straxen
import wfsim
def test_nt_context(register=None, context=None):
"""
Test a context if it is properly setup. To this end, we perform a
simple scan of the field "time" since all plugins should have this
field, if there is some option specified badly, we will quickly f... |
import glob
import datetime
import inference
import numpy as np
flist = []
def run_classifier():
flist = []
list1 = glob.glob("./images/*.jpg")
list1.sort()
print("Printing the time of Interesting Events.....\n\n")
temp = str(inference.run_inference_on_image())
for i in r... |
import re
import sys
import inspect
_py2 = sys.version_info[0] == 2
_py3 = sys.version_info[0] == 3
# noinspection PyPep8Naming
class route(object):
def __init__(self, rule, **options):
"""
Class Initializer - This will only execute if using BottleCBV's original route() style.
"""
... |
#!/usr/bin/python
#
# Logic for computing missing and duplicate files using Postgresql DB.
#
import os
import fnmatch
# from shutil import copy2
# from shutil import copyfile
from dbutils import required as db
MISSING_FROM_COMP_FOLDER = "missing_from_comp"
MISSING_FROM_SRC_FOLDER = "missing_from_source"
FILE_NAME_C... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
"""Decoder portion of the model."""
import torch
import torch.nn.functional as F
from torch import nn
def _build_base_decoder():
"""Builds the base decoder shared by all three decoder types."""
return nn.Sequential(nn.Conv2d(in_channels=1280, out_channels=256, kernel_size=(3, 3), stride=1, padding=1),
... |
class Queue:
"""
A class used to represent an Queue for for storing processes
...
Attributes
----------
processList : list
The list which would store the process currently in line for execution
priority : str
The type of process (Foreground,Background etc)
Sch... |
import numpy as np
import editdistance
class Decoder():
def __init__(self, vocab):
self.vocab_list = [char for char in vocab]
def predict(self, batch_size, logits, y, lengths, y_lengths, n_show=5):
decoded = self.decode(logits, lengths)
cursor = 0
gt = []
n = min(n_sh... |
# MIT License
#
# Copyright (c) 2018-2019 Red Hat, Inc.
# 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, m... |
from django.db import models
from accounts.models import Account
from store.models import Product, Variation
# Create your models here.
class Payment(models.Model):
user = models.ForeignKey(Account, on_delete=models.CASCADE)
payment_id = models.CharField(max_length=100)
payment_method = models.CharField(m... |
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
# set the default Django settings module for the 'celery' program.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Clout9.settings.production")
app = Celery('Clout9')
# Using a string here means the worker wil... |
# blog/asgi.py
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "blog.settings")
from django.conf import settings
django.setup()
from django.core.asgi import get_asgi_application
from channels.security.websocket import OriginValidator
from channels.auth import AuthMiddlewareStack
from channels.r... |
valor = 0
num = [[],[]]
for c in range (0,7):
valor = int(input(f'Digite o {c+1}° valor:'))
if valor % 2 == 0:
num[0].append(valor)
else:
num[1].append(valor)
print('-='*30)
print(f'Os numeros pares foram {num[0]}\nOs numeros ímpares foram {num[1]}.')
|
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... |
import os
import time
from membound_cases import memory_bound_cases_list
from utils import (arch_name, datatime_with_format, dtype2str, dump2json,
geometric_mean, md_table_header, scaled_repeat_times,
size2str)
import taichi as ti
class MemoryBound:
suite_name = 'memoryboun... |
from flask_security.utils import hash_password
from flask_smorest import Blueprint, abort
from ..models.user import User
from ..schemas.paging import PageInSchema, paginate
from ..schemas.user import UserPageOutSchema, UserSchema
from .methodviews import ProtectedMethodView
blueprint = Blueprint('users', 'user')
@b... |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 22 18:44:02 2017
@author: Tirthajyoti Sarkar
Simple selection sort with counter for total number of operations (finding minimum and swapping)
Accepts user input on minimum and maximum bound of the array and the size of the array.
"""
import random
def find_min(array):
... |
###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompar... |
import boto3
import pickle
import logging
from datetime import date
from pyspark.sql.functions import udf
from pyspark.sql.types import ArrayType, StringType
from generate_common_words import dump_pickle
import config as conf
'''
Assign Top 500 Stackoverflow tags to job postings
'''
# ===== Logger Configs =====
TS = da... |
"""
WSGI config for simplerest 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/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_S... |
import json
import os
from mako.template import Template
from models.pomodoro_model import PomodoroModel
from datetime import datetime
class ExportPomsResource:
def on_get(self, req, resp):
"""Handles GET requests"""
resp.content_type = 'text/html'
dir_path = os.path.dirname(os.path.real... |
import csv
import json
def read_data_file(filename):
all_records = []
with open(filename, mode='r') as csv_file:
csv_reader = csv.reader(csv_file)
row_count = 0
for row in csv_reader:
all_records.append(row)
return all_records
def parse_play_fields(play_fields):
pla... |
from rubicon.java.android_events import Handler, PythonRunnable
from rubicon.java.jni import java
from travertino.size import at_least
from ..libs.android import R__color
from ..libs.android.graphics import BitmapFactory, Rect
from ..libs.android.view import Gravity, OnClickListener, View__MeasureSpec
from ..libs.andr... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
#
# Copyright (C) 2021 Graz University of Technology.
#
# Invenio-Records-Marc21 is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
"""Permissions for Invenio Marc21 Records."""
... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "animalRescue.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that... |
import ast
import inspect
import json
import logging
import os
import sys
import tempfile
from functools import wraps
from collections import deque
from execution_trace.constants import RECORD_FN_NAME, RETVAL_NAME, MANGLED_FN_NAME
from execution_trace.utils import strip_indent
# Init logging.
logging.basicConfig()
lo... |
import http.server
import threading
import testPackage
class MyHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
self._set_headers()
... |
import sys
from datetime import datetime
from app import filters
from app.misc.execute import run
def main(args: list[str]):
from app.handlers import dp
# Сохраняем нынешнее время для подсчёта времени безотказной работы
dp.bot['start_time'] = datetime.now()
dp['args'] = args
run(dp)
if __name_... |
import cv2
import threading
class RecordingThread (threading.Thread):
def __init__(self, name, camera):
threading.Thread.__init__(self)
self.name = name
self.isRunning = True
self.cap = camera
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
self.out = cv2.VideoWriter('./st... |
from __future__ import absolute_import
import datetime
import os
from socket import error as SocketError, timeout as SocketTimeout
import socket
import sys
import warnings
from .exceptions import (
NewConnectionError,
ConnectTimeoutError,
SubjectAltNameWarning,
SystemTimeWarning,
)
from .packages impo... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import shutil
import subprocess
from pre_wigs_validation.enums import ValidationEnforcement, ValidationResult
from pre_wigs_validation.instance import ValidationInstance
from pre_wigs_validation.dataclasses impo... |
print 'a.py is executed'
|
from numpy.random import RandomState
from typing import Any, Optional, List
from numpy import arange
from copy import deepcopy
from pydeeprecsys.rl.neural_networks.dueling import DuelingDDQN
from pydeeprecsys.rl.experience_replay.priority_replay_buffer import (
PrioritizedExperienceReplayBuffer,
)
from pydeeprecsys... |
#grad_cam
#[keras-grad-cam/grad-cam.py](https://github.com/jacobgil/keras-grad-cam/blob/master/grad-cam.py)
from keras.applications.vgg16 import (VGG16, preprocess_input, decode_predictions)
from keras.models import Model
from keras.preprocessing import image
from keras.layers.core import Lambda
from keras.models impo... |
import os
import hashlib
from constants import TEX_DIR
from constants import TEX_TEXT_TO_REPLACE
from constants import TEX_USE_CTEX
from constants import TEX_FIX_SVG
def tex_hash(expression, template_tex_file_body):
id_str = str(expression + template_tex_file_body)
hasher = hashlib.sha256()
hasher.updat... |
from django.forms.models import model_to_dict
from django.test import TestCase
from ..forms import EmailChangePasswordForm, ProfileForm
from .factories import StaffFactory, UserFactory
class BaseTestProfileForm(TestCase):
def form_data(self, user, **values):
fields = ProfileForm.Meta.fields
data ... |
from daoRefactor2 import DAO
from rssTickerInfo import rssTickerInfo
import json
import boto3
table = 'CompanyRSSFeed'
dao = DAO(table)
def main():
tickerValues = dao.getRssTickerValues('UNP')
print(tickerValues)
if __name__ == "__main__":
# calling main function
main()
|
##############################################################################
# Copyright (c) 2015 Orange
# guyrodrigue.koffi@orange.com / koffirodrigue@gmail.com
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompani... |
"""Random walk routines
"""
from .._ffi.function import _init_api
from .. import backend as F
from ..base import DGLError
from .. import ndarray as nd
from .. import utils
__all__ = [
'random_walk',
'pack_traces']
def random_walk(g, nodes, *, metapath=None, length=None, prob=None, restart_prob=None):
"""... |
import vdomr as vd
import spikeforest as sf
from cairio import client as ca
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
class AccuracyPlot(vd.components.Pyplot):
def __init__(self, snrs, accuracies):
vd.components.Pyplot.__init__(self)
self._snrs = snrs
self... |
import sys
import unittest
from unittest import mock
from warnings import catch_warnings
from scrapy.exceptions import ScrapyDeprecationWarning
from scrapy.item import ABCMeta, DictItem, Field, Item, ItemMeta
PY36_PLUS = (sys.version_info.major >= 3) and (sys.version_info.minor >= 6)
class ItemTest(unittest.TestCa... |
"""
A CapitalT class and methods that use the Cross class.
Authors: David Mutchler, Vibha Alangar, Dave Fisher, Amanda Stouder,
their colleagues and Xiaolong Chen (Harry).
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
import rosegraphics as rg
import math
def main():
"""
Calls the test funct... |
import time
from collections import deque
from datetime import datetime
import backtrader as bt
from backtrader.feed import DataBase
from backtrader.utils.py3 import with_metaclass
from .cryptostore import CryptoStore
class MetaCryptoFeed(DataBase.__class__):
def __init__(cls, name, bases, dct):
'''Clas... |
"""This script creates some informative graphs on subgroups of income quartile, gender, and race."""
# %%
import os
import matplotlib.pyplot as plt
import seaborn as sns
from pathlib import Path
# %%
# Set up folder path
code_folder = Path(os.path.abspath(''))
print(code_folder)
project_dir = os.path.dirname(code_fol... |
import pytest
import logging
from traitlets.config.loader import PyFileConfigLoader
from traitlets import TraitError
from jupyter_telemetry.eventlog import EventLog
GOOD_CONFIG = """
import logging
c.EventLog.handlers = [
logging.StreamHandler()
]
"""
BAD_CONFIG = """
import logging
c.EventLog.handlers = [
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.