text stringlengths 2 999k |
|---|
def preto():
return '\0331;30m'
def vermelho():
return '\033[1;31m'
def verde():
return '\033[1;32m'
def amarelo():
return '\033[1;33m'
def azul():
return '\033[1;34m'
def magenta():
return '\033[1;35m'
def ciano():
return '\033[1;36m'
def cinzaclaro():
return '\033[1;37m'
def ci... |
import os, sys, math
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
# add the FedML root directory to the python path
sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "../../../")))
from fedml_api.model.cv.batchnorm_utils import SynchronizedBatchNorm2d
class Bottleneck(nn.Module):
ex... |
import sh
from dotenv import load_dotenv
import os
load_dotenv()
PASSWORD = os.environ.get("sudo_password")
def get_ansible():
with sh.contrib.sudo(password=PASSWORD, _with=True):
print('Downloading epel-release')
sh.yum('install', 'epel-release', '-y')
print('Downloading Ansible')
... |
import os
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ["MOLECULE_INVENTORY_FILE"]
).get_hosts("default_group")
@pytest.mark.parametrize(
"pkg",
[
"epics-dev",
],
)
def test_default_pkgs(host, pkg):
package ... |
from setuptools import setup, find_packages
setup(
name="aaws",
packages=find_packages(),
python_requires='~=3.7',
)
|
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
# Workaround to encode/decode indexes in protobuf messages
# Based on https://developers.google.com/protocol-buffers/docs/encoding#varints
from io import BytesIO
from karapace.protobuf.exception import IllegalArgumentException
from typing import List
ZERO_BYTE = b"\x00"
def read_varint(bio: BytesIO) -> int:
"""... |
# Add common test utils, which can be used by all test scripts..
from netaddr import IPNetwork
def assertEqual(a, b, error_msg):
'''Assert with error msg'''
assert (a == b), error_msg
def get_ip_list_from_prefix(prefix):
return map(str, IPNetwork(prefix).iter_hosts())
def get_min_max_ip_from_prefix(pref... |
# Copyright The Linux Foundation and each contributor to CommunityBridge.
# SPDX-License-Identifier: MIT
import logging
import unittest
from unittest.mock import Mock, patch, MagicMock
from github import Github
import cla
from cla.models.github_models import get_pull_request_commit_authors, handle_commit_from_user, M... |
from Modules import functions, data
from time import time
last_check_time = 0
# check_punishments unfinished
async def check_punishments(guild):
# iterate through each punishment, ignore if no expiration
for user in functions.get_data("SELECT * FROM punishments", ()):
user_id = user[0]
... |
# engine/base.py
# Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
import contextlib
import sys
import typing
from typing import Any
from typing import ... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "JobGenie.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are... |
# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Fabian Pedregosa <fabian.pedregosa@inria.fr>
# Olivier Grisel <olivier.grisel@ensta.org>
# Gael Varoquaux <gael.varoquaux@inria.fr>
#
# License: BSD 3 clause
import sys
import warnings
from abc import ABCMeta, abstractmethod
import n... |
from models import *
from django.contrib import admin
class GrupoAdmin(admin.ModelAdmin):
pass
admin.site.register(Grupo,GrupoAdmin)
|
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Static()
result.template = "object/static/structure/naboo/shared_arbor_corner_45_s01.iff"
result.attribute_templa... |
import numpy as np
from scipy.ndimage import map_coordinates
from menpo.interpolation.cinterp import interp2
def c_interpolation(ndimage, points_to_sample, mode='bilinear'):
r"""
C-based interpolator that was designed to be identical when
used in both Python and Matlab.
Parameters
----------
... |
"""barcode step."""
import glob
import os
import re
import sys
from collections import Counter, defaultdict
from itertools import combinations, product
import pysam
from xopen import xopen
import celescope.tools.utils as utils
from celescope.tools.__init__ import __PATTERN_DICT__
from celescope.tools.step import Ste... |
from flask import Flask, request, redirect, url_for, render_template, flash
import numpy as np
import tensorflow as tf
import keras
import os
from werkzeug.utils import secure_filename
from keras.models import Sequential
from keras.layers import Dense, Conv2D, MaxPooling2D, UpSampling2D, Input
from keras.prepr... |
from django.apps import AppConfig
class AppencuestaConfig(AppConfig):
name = 'appencuesta'
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Project Schdule Manage',
'version': '1.0',
'category': 'Project',
'summary': 'Project Schdule Manage',
'description': """
This module is for Project Schdule Manage.
========================... |
# Copyright 2015 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... |
""" Formula for building parallel """
from pakit import Archive, Recipe
class Parallel(Recipe):
"""
GNU parallel executes shell jobs in parallel
"""
def __init__(self):
super(Parallel, self).__init__()
self.homepage = 'http://www.gnu.org/software/parallel'
self.repos = {
... |
#!/usr/bin/env python3
# Copyright (C) 2020 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... |
def f(xs, ys):
return [[(x, y) for y in ys] for x in xs] |
# SPDX-License-Identifier: MIT
# Copyright (c) 2019 Intel Corporation
import ast
from io import open
from setuptools import find_packages, setup
with open('dffml/version.py', 'r') as f:
for line in f:
if line.startswith('VERSION'):
version = ast.literal_eval(line.strip().split('=')[-1].strip())... |
from __future__ import print_function, division
import os
from PIL import Image
import numpy as np
from torch.utils.data import Dataset
from ..custom_path import Path
from torchvision import transforms
from ..custom_transforms import FixScaleCrop, RandomHorizontalFlip
from ..custom_transforms import RandomScaleCrop, Ra... |
import math
from dataclasses import dataclass, field
import torch
from torch.distributions.dirichlet import Dirichlet
from fairseq import metrics, utils
from fairseq.criterions import register_criterion
from fairseq.criterions.label_smoothed_cross_entropy import (
LabelSmoothedCrossEntropyCriterion
)
from fairseq.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Crypto rdfvalue tests."""
import hashlib
import os
from builtins import chr # pylint: disable=redefined-builtin
from builtins import range # pylint: disable=redefined-builtin
from future.utils import iterkeys
from grr_response_core import config
from grr_response_co... |
"""Class definitions for corpora"""
from __future__ import annotations
import multiprocessing as mp
import os
import subprocess
import sys
import time
import typing
from abc import ABCMeta
from queue import Empty
from typing import Dict, List, Optional
import sqlalchemy
import tqdm
from sqlalchemy.orm import Session
... |
# 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 python
from wsgiref.simple_server import make_server
import sys
import json
import traceback
import datetime
from multiprocessing import Process
from getopt import getopt, GetoptError
from jsonrpcbase import JSONRPCService, InvalidParamsError, KeywordError,\
JSONRPCError, ServerError, InvalidRequestE... |
def print_two(*args):
arg1, arg2 = args
print ("arg1: %r, arg2: %r" % (arg1, arg2))
def print_two_again(arg1, arg2):
print ("arg1: %r, arg2: %r" % (arg1, arg2))
def print_one(arg1):
print ("arg1: %r" % arg1)
def print_none():
print ("I got nothin'.")
print_two ("Zed", "Shaw")
print_two_again("Zed... |
#!/usr/bin/env python
import sys
from os.path import dirname, abspath
from django.conf import settings
from django.utils.version import get_version
if not settings.configured:
settings.configure(
DATABASE_ENGINE='sqlite3',
INSTALLED_APPS=[
'django.contrib.auth',
'django.con... |
#!/usr/bin/python
import argparse
import logging
import os
import sys
import requests
import json
import base64
import uuid
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "..", "..", "tokens"))
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "... |
from .bonds import FixedRateBond, ZeroCouponBond, FloatingRateBond
from .credit_default_swap import CreditDefaultSwap, Side, PricingModel
from .option import EuropeanExercise, AmericanExercise, VanillaOption
from .option import DividendVanillaOption, EuropeanOption, Put, Call
from .payoffs import PlainVanillaPayoff
fro... |
"""
Unit tests for the unstructured metamodel component.
"""
import numpy as np
import unittest
from openmdao.api import Group, Problem, MetaModelUnStructuredComp, IndepVarComp, ResponseSurface, \
FloatKrigingSurrogate, KrigingSurrogate, ScipyOptimizeDriver
from openmdao.utils.assert_utils import assert_rel_error
... |
# Copyright BigchainDB GmbH and BigchainDB contributors
# SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
# Code is Apache-2.0 and docs are CC-BY-4.0
__version__ = '2.0.0b7'
__short_version__ = '2.0b7'
# supported Tendermint version
__tm_supported_versions__ = ["0.22.8"]
|
# todo 8. Palíndromo. Um palíndromo é uma seqüência de caracteres cuja leitura é idêntica se feita da direita para esquerda ou vice−versa. Por exemplo: OSSO e OVO são palíndromos. Em textos mais complexos os espaços e pontuação são ignorados. A frase SUBI NO ONIBUS é o exemplo de uma frase palíndroma onde os espaços f... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'public.settings')
try:
from django.core.management import execute_from_command_line
except Impor... |
# -*- coding: utf-8 -*-
from . import *
SECRET_KEY = env.str('KOBRA_SECRET_KEY',
'Unsafe_development_key._Never_use_in_production.')
DEBUG = env.bool('KOBRA_DEBUG_MODE', True)
DATABASES = {
'default': env.db_url('KOBRA_DATABASE_URL', 'sqlite:///db.sqlite3')
}
|
# 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... |
"""Ttk wrapper.
This module provides classes to allow using Tk themed widget set.
Ttk is based on a revised and enhanced version of
TIP #48 (http://tip.tcl.tk/48) specified style engine.
Its basic idea is to separate, to the extent possible, the code
implementing a widget's behavior from the code implementing its
ap... |
# coding:utf-8
import datetime
from django.contrib.auth import authenticate
from django import forms
from bootstrap3_datetime.widgets import DateTimePicker
from django.conf import settings
from projects.forms import FormBase, ModelFormBase
from .models import UserProfile
class FormConnection(FormBase):
"""
F... |
from contextlib import contextmanager
from tests.system.tools import waituntil
import logging
log = logging.getLogger(__name__)
@contextmanager
def prepare_bootstrap(manifest, build_server):
if manifest.volume['backing'] == 's3':
credentials = {'access-key': build_server.build_settings['ec2-credentials'][... |
# -*- coding: UTF-8 -*-
"""
cptch.net service
"""
from .base import HTTPService
from .._transport.http_transport import HTTPRequestJSON # type: ignore
from .. import exceptions
from .._captcha import CaptchaType
from ..common import CaptchaAlphabet
__all__ = [
'Service', 'GetBalanceRequest', 'GetStatusRequest',
... |
import torch.nn as nn
from wilds.common.metrics.loss import ElementwiseLoss, Loss, MultiTaskLoss
from wilds.common.metrics.all_metrics import MSE
def initialize_loss(config, d_out):
if config.get('loss_function') == 'cross_entropy':
return ElementwiseLoss(loss_fn=nn.CrossEntropyLoss(reduction='none')... |
def gradient_sample(exp_time):
dets = [pil300KW, pil1M]
sam = ['ZnTi_gradient']
xst = 25500 #step 2000
xsto = -24200
waxs_arc = [2.95, 38.95, 7]
alph_na = ['0.1', '0.2']
alphai = [0.617, 0.717]
det_exposure_time(exp_time, exp_time)
x = xst
while x > xs... |
"""
This is a monkey patched version of the sphinx.apidoc utility. It provides a
modified version of the create_package_file function from apidoc.py available
at https://github.com/sphinx-doc/sphinx
It is subject to the following LICENSE:
Copyright (c) 2014-1017, Christian Schou Oxvig & Patrick Steffen Pedersen
Copyr... |
# Copyright (c) 2016-2017, Neil Booth
# Copyright (c) 2017, the ElectrumX authors
#
# All rights reserved.
#
# The MIT License (MIT)
#
# 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 ... |
#!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'BlogApp.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are ... |
#!/usr/bin/python3
import logging
import os
from shutil import rmtree
from keyman_config.fcitx_util import is_fcitx_running
from keyman_config.get_kmp import InstallLocation, get_keyboard_dir, get_keyman_doc_dir, get_keyman_font_dir
from keyman_config.kmpmetadata import get_metadata
from keyman_config.ibus_util impor... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wildlife.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
"""
Class definitions used in transaction building
Author: Manikandan Dhamodharan, Morgan Stanley
"""
import os
from xpedite.dependencies import Package, DEPENDENCY_LOADER
DEPENDENCY_LOADER.load(Package.Enum, Package.Six)
from enum import Enum # pylint: disable=wrong-import-position
class Counter(object):
"""
S... |
import torch.nn as nn
import torch.nn.functional as F
class Factor1d(nn.Module):
"""Similar to masked attention
"""
def __init__(self, in_features, in_dim, out_features, out_dim, adj_mat=None, bias=True):
super(Factor1d, self).__init__()
self.linear1 = nn.Linear(in_dim, out_dim, bias) # based on intu... |
#!/usr/bin/python2
# Written by Antonio Galea - 2010/11/18
# Distributed under Gnu LGPL 3.0
# see http://www.gnu.org/licenses/lgpl-3.0.txt
#
# Removed ihex functionality and dependency, Bitcraze - 2014-12-11
import sys,struct,zlib,os
from optparse import OptionParser
DEFAULT_DEVICE="0x0483:0xdf11"
def named(tuple,n... |
# Ant-FS
#
# Copyright (c) 2012, Gustav Tiger <gustav@tiger.name>
#
# 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... |
""" This file contains logic for creating files """
from flask import Response
from jinja2 import Template
import json
import csv
from io import StringIO
from application.utils import create_file_response
class FileCreator:
""" Used to create a file with provided data
Attributes:
... |
"""
ActionBus: lightweight action library for ROS framework.
This library is inspired by the existing actionlib package. It aims to reduce the required footprint in implementing
an action system. It follows the convention over configuration principle and it drops the need of having dedicated
action messages. It uses p... |
#!/usr/bin/env python
from telegraf_pyplug.main import print_influxdb_format
def multiple_fields() -> None:
"""
Prints line:
multiple_fields field_float=1,field_int=123i,field_str="two",field_bool=True
"""
print_influxdb_format(
measurement='multiple_fields',
fields={
... |
from distutils.core import setup
setup(name='Mazo',
version='2.0',
description='A low code wrapper for MALLET to generate topic models.',
author='Raf Alvarado',
author_email='ontoligent@gmail.com',
url='https://github.com/ontoligent/mazo',
py_modules=['polite.polite'],
scripts... |
from conans import ConanFile, CMake, tools
import os
class LibeventConan(ConanFile):
name = "libevent"
description = "libevent - an event notification library"
topics = ("conan", "libevent", "event")
url = "https://github.com/conan-io/conan-center-index"
homepage = "https://github.com/libevent/lib... |
_base_ = [
'../_base_/models/flownet2/flownet2css.py',
'../_base_/datasets/flyingthings3d_subset_384x768.py',
'../_base_/schedules/schedule_s_fine.py', '../_base_/default_runtime.py'
]
# Train on FlyingChairs and finetune on FlyingThings3D subset
load_from = 'https://download.openmmlab.com/mmflow/flownet2/... |
#!/usr/bin/env python
# coding: utf-8
#
# Project: Azimuthal integration
# https://github.com/silx-kit/pyFAI
#
# Copyright (C) 2015-2018 European Synchrotron Radiation Facility, Grenoble, France
#
# Principal author: Jérôme Kieffer (Jerome.Kieffer@ESRF.eu)
#
# Permission is hereby granted, fr... |
# 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 toga
import time
import toga
from colosseum import CSS
tab_style = CSS(flex=1, padding=20)
def build(app):
font = toga.Font('Helvetica', 40)
return toga.Box(children=[toga.Button('Button')])
def main():
return toga.App('Test Font', 'org.pybee.font', startup=build)
if __name__ == '__main__':
... |
#!/usr/bin/env python3
################################################
#
# Function to run meta-workflow-run
# with tibanna and patch metadata
#
################################################
################################################
# Libraries
################################################
imp... |
#!/usr/bin/env python3
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.script import *
from test_framework.mininode import *
from test_framework.eurekacoin import *
from test_framework.blocktools import *
from test_framework.key import *
import io
im... |
def test_load_basic_schema(author_schema, author_jsonapi):
"""Tests that loading a basic schema with no relationships works"""
author, errors = author_schema().load(author_jsonapi)
assert errors == {}
assert author.id == int(author_jsonapi['data']['id'])
assert author.name == author_jsonapi['data'][... |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# TODO(dmikurube): Remove this file once Python 2.7 is required.
import os
import sys
try:
from collections import OrderedDict # pylint: disable=E0611,W... |
# 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 use ... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads_v6/proto/errors/invoice_error.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.p... |
import logging
import os
import cloudfiles
from . import settings
logger = logging.getLogger(__name__)
def _init():
"""Connects to the Swift service and returns the specified container"""
if not settings.swift:
logger.error("Unable to connect to swift: Missing configuration")
raise RuntimeEr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_cookiecutter_repo_arg
--------------------------
Tests formerly known from a unittest residing in test_main.py named
TestCookiecutterRepoArg.test_cookiecutter_git
TestCookiecutterRepoArg.test_cookiecutter_mercurial
"""
from __future__ import unicode_literals
imp... |
###############################################################################
# Copyright Maciej Patro (maciej.patro@gmail.com)
# MIT License
###############################################################################
from cmake_tidy.formatting.utils.single_indent import get_single_indent
class FormatSpaces:
... |
"""
This file contains functions that are used to perform data augmentation.
"""
import torch
import numpy as np
import scipy.misc
import cv2
from PIL import Image
import SPIN.constants
def get_transform(center, scale, res, rot=0):
"""Generate transformation matrix."""
h = 200 * scale
t = np.zeros((3, 3))... |
import pathlib
import os
import numpy as np
from nn_analysis import utils, exceptions
from nn_analysis.constants import ENV_CONFIG_PATH, ACTS_CONFIGS_PATH
env_config = utils.load_config(ENV_CONFIG_PATH)
acts_configs = utils.load_config(ACTS_CONFIGS_PATH)
DEFAULT_SAVE_LOC = 'save_acts_path' # If you change this, mak... |
# 1) They are linearly dependent as one can be formed as a linear combination of
# the others (a + b = c). You could also have known this because you have four
#. 3D vectors. You don't need 4 vectors to get anywhere in 3D space!
#.
# 2) The span of a, b, c, and d is all of 3D space (R^3).
# 3) The span of a an... |
# -*- coding: utf-8 -*-
# (C) Copyright 2015 Hewlett Packard Enterprise Development LP
# 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.a... |
#
# 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... |
"""Platform Models."""
from marshmallow import fields, Schema
from marshmallow.validate import OneOf
from ..enums import *
from ..models.BaseSchema import BaseSchema
from .Page import Page
class CursorGetResponse(BaseSchema):
# Feedback swagger.json
items = fields.List(fields.Dict(required=False), r... |
#!/usr/bin/env python3
import sys, os
import networkx as nx
if __name__ == "__main__":
if( len(sys.argv) != 4 ):
print("USAGE: %s <inputfile.gml> <retweets.gml> <mentions.gml>" % sys.argv[0])
sys.exit(1)
inFilename = sys.argv[1]
rtFilename = sys.argv[2]
mentionFilename = sys.argv[3]
orig = nx.read_gml(inFile... |
"""
AWR + SAC from demo experiment
"""
from rlkit.demos.source.dict_to_mdp_path_loader import DictToMDPPathLoader
from rlkit.launchers.experiments.awac.awac_rl import experiment
import rlkit.misc.hyperparameter as hyp
from rlkit.launchers.arglauncher import run_variants
if __name__ == "__main__":
variant = dict(... |
# 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... |
# -*- coding: utf-8 -*-
"""Implements a simple wrapper around urlopen."""
from pytube.compat import urlopen
from urllib.request import Request
def get(
url=None, headers=False,
streaming=False, chunk_size=8 * 1024,
):
"""Send an http GET request.
:param str url:
The URL to perform the GET requ... |
import typing
import numba as nb
import numpy as np
@nb.njit((nb.i8,) * 7, cache=True)
def solve(
n: int,
h: int,
a: int,
b: int,
c: int,
d: int,
e: int,
) -> typing.NoReturn:
inf = 1 << 60
mn = inf
for x in range(n + 1):
y = (n * e - h - (b + e) * x... |
import logging
import ee
import pytest
import openet.disalexi.disalexi as disalexi
import openet.disalexi.utils as utils
# AmeriFlux sites adjusted to nearest Landsat cell centroid
ne1_xy = [-96.47672812080845, 41.16506126041818]
ne2_xy = [-96.46994024736414, 41.16491226772292]
ne3_xy = [-96.43968912903934, 41.17964... |
# Ex: python preprocess.py -csv oasis_cross-sectional.csv -p data/raw_train -mt train -combine_ad
import argparse
from imutils import paths
import matplotlib.pyplot as plt
import numpy as np
import random
import cv2
import os
import csv
from shutil import copyfile
csv_file = ""
data_input_path = ""
img_extensions = ['... |
from django.core.urlresolvers import reverse
from django.contrib import admin
from django.conf import settings
from django import forms
from django_conference.models import (DonationType, ExtraType, Meeting,
MeetingDonation, MeetingExtra, MeetingInstitution, Paper, PaperPresenter,
Registration, RegistrationDon... |
import datetime
import logging
import sys
from contextlib import contextmanager
import dateutil
import lazy_object_proxy
import pendulum
from airflow.models import TaskInstance
from airflow.models.baseoperator import BaseOperator
from airflow.models.dag import DAG
from airflow.models.dagbag import DagBag
from airflow.... |
# -*- coding: utf-8 -*-
import logging
from celery.task import Task, subtask
from pyvac.task.worker import (
WorkerPending,
WorkerPendingNotified,
WorkerAccepted,
WorkerAcceptedNotified,
WorkerDenied,
WorkerApproved,
)
from pyvac.models import DBSession, Request
log = logging.getLogger(__na... |
"""
Django settings for cookbook project.
Generated by 'django-admin startproject' using Django 2.1.4.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 24 20:40:52 2016
Remember to open from terminal in Python 2.7
brew install wget
wget -r -np -c -N -k http://www.physionet.org/pn6/chbmit/
%reset
matlab array -> python numpy array
matlab cell array -> python list
matlab structure -> python dict
@author: heslote1
"... |
import Clean
import pickle
import os
import sys
separator = ""
if sys.platform == 'win32':
separator = '\\'
else:
separator = '/'
with open(os.path.dirname(os.path.abspath(__file__))+separator+'settings.txt', 'rb') as setting_file:
folders = pickle.load(setting_file)
Clean.main(folders)
|
from autots import AutoTS
model = AutoTS(forecast_length=10, frequency='infer', ensemble='simple', drop_data_older_than_periods=200)
model = model.fit(data, date_col='Date', value_col='Close', id_col=None)
prediction = model.predict()
forecast = prediction.forecast
print("DogeCoin Price Prediction")
print(forecast) |
#coding=utf-8
import scrapy
from scrapy.loader import ItemLoader
from scrapy_splash import SplashRequest
from ..items import DLTItem, DLTType
def genJS(jsStr):
"""
var lottery_nums='大乐透|18018|06,08,13,24,28,06,12|2018-02-10|4,824,492,674.96|1~七星彩|18018|3,2,5,9,9,5,8|2018-02-11|1,000,000|2~22选5|13172|08,09,14,... |
######################################################################
#
# File: test/unit/test_base.py
#
# Copyright 2019 Backblaze Inc. All Rights Reserved.
#
# License https://www.backblaze.com/using_b2_code.html
#
######################################################################
from contextlib import context... |
from unittest import TestCase
from api.utils.bar_utils import BARUtils
class UtilsUnitTest(TestCase):
def test_error_exit(self):
msg = "A test error message"
result = BARUtils.error_exit(msg)
expected = {"wasSuccessful": False, "error": msg}
self.assertEqual(result, expected)
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018, Loyalty and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class MarkRange(Document):
pass
|
#!/usr/bin/env python
from pyfoobot import Foobot
import requests
import matplotlib
matplotlib.use('Agg')
import matplotlib.dates
import matplotlib.pyplot
import datetime
from imgurpython import ImgurClient
import ConfigParser
def getSensorReadings(notify):
config = ConfigParser.ConfigParser()
config.read("config.... |
class LinkedList:
"""Defines a Singly Linked List.
attributes: head
"""
def __init__(self):
"""Create a new list with a Sentinel Node"""
self.head=ListNode()
def insert(self,x,p):
"""Insert element x in the position after p"""
temp=ListNode()
temp.data=x
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.