text stringlengths 2 999k |
|---|
# Copyright 2018 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... |
"""
Copyright 2020 The OneFlow 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 law or agr... |
# web_app/classifier.py
import os
import pickle
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression # for example
MODEL_FILEPATH = os.path.join(os.path.dirname(__file__), "..", "models", "latest_model.pkl")
def train_and_save_model():
print("TRAINING THE MODEL...")
X, ... |
# spotify_example.py
from pprint import pprint
import requests
import json
import spotipy
import config
SPOTIPY_REDIRECT_URI = 'http://localhost:8080'
# See authorization scopes descriptions in: https://developer.spotify.com/documentation/general/guides/scopes/
SCOPE = 'user-modify-playback-state user-read-email'
bas... |
app = None
session = None
redis = None
def init_default(_app):
global app, session, redis
app = _app
session = app.Session()
redis = app.Redis
def check_redis():
if redis:
return redis.keys("*")
return 0
def check_app():
if app:
return app.config
return None
de... |
from mcstats import mcstats
mcstats.registry.append(
mcstats.MinecraftStat(
'craft_bookshelf',
{
'title': 'Librarian',
'desc': 'Bookshelves crafted',
'unit': 'int',
},
mcstats.StatReader(['minecraft:crafted','minecraft:bookshelf'])
))
|
import _plotly_utils.basevalidators
class SizeValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="size", parent_name="parcoords.tickfont", **kwargs):
super(SizeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
# -*- coding: utf-8 -*-
# Author: Florian Mayer <florian.mayer@bitsrc.org>
from __future__ import absolute_import, division, print_function
import os
import re
import sys
import shutil
# For Content-Disposition parsing
from sunpy.extern.six.moves.urllib.parse import urlparse, urljoin
from sunpy.extern.six.moves.urlli... |
from .Histogram1D import Histogram1D
from .TimeProfile import TimeProfile
from .Skymap import Skymap
from .FitsSkymap import FitsSkymap
from .Mollview import Mollview
from .DistErrPlot import DistErrPlot
from .ScatterPlot import ScatterPlot
|
# -*- coding: utf-8 -*-
from __future__ import print_function
import itertools
import os
import errno
import sys
from fnmatch import fnmatch
from pkgutil import get_data
from time import time
import certifi
import numpy as np
from .data import iers
from .curvelib import Splines
from .functions import load_bundled_npy... |
import collections
import ConfigSpace
import copy
import json
import openml
import typing
from openml.extensions.sklearn.extension import SklearnExtension
def filter_setup_list(setupid_setup, param_name, min=None, max=None, allowed_values=None):
"""
Removes setups from a dict of setups if the parameter value... |
# coding: utf-8
# Copyright (c) 2016, 2021, 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... |
# stdlib imports
import json
import os
# third-party imports
import pytest
@pytest.fixture
def file_fixture():
def _file_fixture(name):
here = os.path.dirname(os.path.realpath(__file__))
path = os.path.join(here, "fixtures", name)
with open(path, 'r') as f:
fixture = f.read()
... |
import os
import json
import torch
import numpy as np
from pointnetae.config import *
class SceneDataset(torch.utils.data.Dataset):
def __init__(
self,
data_source,
max_num_points,
load_ram=False,
is_testing=False,
):
self.data_source = data_source
self.l... |
from django.contrib import admin
from django.forms import ModelForm
from disturbance.components.main.models import MapLayer, MapColumn
class MyForm(ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['layer_name'].help_text = "Enter the layer... |
#
# 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 us... |
import io
import logging
import socket
import sys
import time
import warnings
import pytest
import mock
from .. import TARPIT_HOST, VALID_SOURCE_ADDRESSES, INVALID_SOURCE_ADDRESSES
from ..port_helpers import find_unused_port
from urllib3 import encode_multipart_formdata, HTTPConnectionPool
from urllib3.exceptions imp... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from scipy import misc
import sys
import os
import argparse
import numpy as np
import mxnet as mx
import random
import sklearn
from sklearn.decomposition import PCA
from time import sleep
from easydict import E... |
from __future__ import division
__author__ = 'David Conant, Jesse Livezey, Ben Dichter'
import re, os
import numpy as np
import pandas as pd
from pynwb.epoch import TimeIntervals
lab_time_conversion = 1e7
def parse(blockpath, blockname):
"""
Find and parse transcript for block.
Parameters
-------... |
from sqlalchemy.sql.expression import _BindParamClause
from sqlalchemy.ext.compiler import compiles
from sqlalchemy import schema, text
from sqlalchemy import types as sqltypes
from ..compat import string_types, text_type, with_metaclass
from .. import util
from . import base
class ImplMeta(type):
def __init__(cl... |
import asyncio
import datetime
import typing
from contextlib import suppress
from enum import IntEnum
from inspect import iscoroutinefunction
import discord
from discord.ext.commands import BucketType, CommandOnCooldown, CooldownMapping
from . import error, http
from .dpy_overrides import ComponentMessage
class Cho... |
# By @TroJanzHEX
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Message
from pyrogram import Client, filters
from script import script # pylint:disable=import-error
@Client.on_message(filters.command(["start"]) & filters.private)
async def start(client: Client, message: Message):
try:
... |
#-*-coding:utf-8-*-
import tensorflow as tf
#输入数据
from tensorflow.examples.tutorials.mnist import input_data
#mnist =input_data.read_data_sets("/tmp/data/mnist",one_hot=True)
#本地路径
MNIST_data_folder="/home/syx/PycharmProjects/NN_Rep/data/mnist"
mnist=input_data.read_data_sets(MNIST_data_folder,one_hot=True)
#定义网络超参数
... |
a = ["a","b","c",1,4,]
b = ["a", "x", 34, "4"]
c = a
def AppendUnique(a, b):
for x in b:
if x not in a:
c.append(x)
print(c)
AppendUnique(a,b)
|
class Solution:
def minJumps(self, arr, n):
jumps = [-1] * n
jumps[0] = 0
front = 0
rear = 0
while rear < n :
remaining_jumps = arr[rear] - (front - rear)
while remaining_jumps > 0 and front < n-1:
front += 1
j... |
import os
import json
from app import api
from app import app
app.config["SERVER_NAME"] = "localhost"
app.app_context().__enter__()
with open('docs/source/_static/swagger.json', 'w', encoding='utf-8') as f:
json.dump(api.__schema__, f, ensure_ascii=False, indent=2)
|
# -*- coding: utf-8 -*-
"""
performCVLLA.py
create profile for nomacs (CVL LA toolkit)
H. Déjean
copyright Xerox 2017
READ project
Developed for the EU project READ. The READ project has received funding
from the European Union's Horizon 2020 research and innovation pr... |
#!/usr/bin/env python
"""Day 11: Corporate Policy -- Advent of Code 2015"""
from typing import List, Iterable, TypeVar
T = TypeVar('T')
ALPHABET = 'abcdefghijklmnopqrstuvwxyz'
ALPHABET_SIZE = len(ALPHABET)
def next_valid_password(data: str) -> str:
"""The next valid password, starting from data."""
passwor... |
import time
import pythoncom
import pywintypes
from manuallogin import *
from PyQt5 import QtWidgets
from multiprocessing import Process
from PyQt5.QAxContainer import QAxWidget
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from utility.static import telegram_msg
from utility.setting impo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-10-20 13:18:34
# @Author : Shanming Liu
import os
import sys
import random
BASEDIR = os.path.dirname(os.path.abspath(__file__))
SRC_DIR = os.path.dirname(BASEDIR)
print(SRC_DIR)
sys.path.append(SRC_DIR)
import pika
from setting import MQ_CONFIG
def ... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2020 Alibaba Group Holding 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 License at
#
# http://www.apache.org/licenses/LICENSE... |
from electroncash.util import NotEnoughFundsSlp, NotEnoughUnfrozenFundsSlp, print_error
from electroncash import slp
from electroncash.slp import SlpParsingError, SlpInvalidOutputMessage, SlpUnsupportedSlpTokenType
from electroncash.transaction import Transaction
from electroncash.address import Address
class SlpTrans... |
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2021 Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free... |
class PlayerDixMille():
player = 0
def __init__(self, name: str = "", human: bool = True):
self._player_number = PlayerDixMille.player
PlayerDixMille.player += 1
if not name:
self._name = f"player {self._player_number}"
else:
self._name = name
... |
# main file
# importing module from the same directory as the main script
import useful2
# importing of modules from external folder
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, 'E:/Documents/GitHub/Grasshopper_vs_Python/lecture 5/1')
import useful
filetemp = useful.some_... |
import pytest
from io import StringIO
import numpy as np
import pandas as pd
import sandy
__author__ = "Luca Fiorito"
#####################
# Test initialization
#####################
def test_from_file_1_column():
vals = '1\n5\n9'
file = StringIO(vals)
with pytest.raises(Exception):
... |
import json
import os
import subprocess
from typing import Any, Dict, Optional, Sequence, Union
import aiohttp
from cli.encoding import get_cairo_calldata, get_ctor_evm_calldata, get_evm_calldata
from starkware.starknet.services.api.gateway.transaction import Transaction
WARP_ROOT = os.path.abspath(os.path.join(__fil... |
from django.test import TestCase, Client
from django.contrib.auth import get_user_model
from django.urls import reverse
class AdminSiteTests(TestCase):
def setUp(self):
self.client = Client()
self.admin_user = get_user_model().objects.create_superuser(
email='admin@sharath.com',
... |
import argparse
import asyncio
import signal
import sys
import time
import traceback
import yaml
import logging
from colorlog import ColoredFormatter
log_fmt = logging.Formatter('%(lineno)-3d %(levelname)7s %(funcName)-16s %(message)s')
log_fmt = ColoredFormatter('%(log_color)s%(levelname)-8s %(lineno)4d ... |
import os
import scipy.signal
import numpy as np
from pyutils.iolib.video import getFFprobeMeta
from pyutils.cmd import runSystemCMD
from scikits.audiolab import Sndfile, Format
import tempfile
import resampy
def load_wav(fname, rate=None):
fp = Sndfile(fname, 'r')
_signal = fp.read_frames(fp.nframes)
_si... |
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
from FiScrape.spiders.FtSpider import FtSpider
from FiScrape.spiders.InsiderSpider import InsiderSpider
from FiScrape.spiders.BBCSpider import BBCSpider
# from FiScrape.spiders.WsjSpider import WsjSpider
# from FiScrape.spi... |
#!/usr/bin/env python
# encoding: utf-8
from .battleship import Game, Board, Ship # noqa
from .version import __version__ # noqa
__all__ = ['Game', 'Board', 'Ship', '__version__']
|
#!/usr/bin/env python
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Tests for Genetic Algorithm classes that provide selection capabilities.
"""
# standard library
import random
import unittest
... |
import os
import sys
sys.path.append("../../../monk/");
import psutil
from pytorch_prototype import prototype
from compare_prototype import compare
from common import print_start
from common import print_status
import torch
import numpy as np
from pytorch.losses.return_loss import load_loss
def test_activation_tanh... |
import plotly.express as px
discrete_colors_0 = ["#e28e31",
"#8a9bde",
"#9f5036",
"#8a5ad2",
"#a2b937",
"#59c8b5",
"#e07d93",
"#406caa",
"#4ab4dd",
"#9d4564",
"#38977f",
"#65c14c",
"#d288c3",
"#d175df",
"#c1303c",
"#bdb466",
"#7a81e0",
"#dd3d72",
"#93a95f",
"#6b8627",
"#e26d69",
"#3f9335",
"#8e6e2e",
"#caa637",
"#72b8... |
#!/usr/bin/env python3
import sys
import argparse
import os
import yt
from yt.units import cm
from enum import Enum
from collections import defaultdict, deque
import numpy as np
################################
# set up parser and parse args #
################################
description = "Script for tracking the p... |
"""Tests using a speaker
"""
import time
import pytest
import mhs5200
def test_both_square(signal_generator):
for frequency in [0.5, 1, 2, 5, 10]:
for channel in signal_generator.channels:
channel.frequency = frequency
channel.amplitude = 20
channel.wave... |
# -*- coding: utf-8 -*-
"""
:author: Grey Li (李辉)
:url: http://greyli.com
:copyright: © 2018 Grey Li
:license: MIT, see LICENSE for more details.
"""
import os
import uuid
from flask import Flask, render_template, flash, redirect, url_for, request, send_from_directory, session
from flask_ckeditor impor... |
# Copyright (c) 2019 Aldo Cortesi
# Copyright (c) 2019 Sean Vig
#
# 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, ... |
def removedupl(lst):
t = list(set(lst))
return t |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "quick_deploy.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django.... |
#!/usr/bin/env python3
import os
import sys
from openvino.inference_engine import IENetwork, IECore
import cv2
import numpy as np
import time
import socket
import json
import logging as log
import paho.mqtt.client as mqtt
import time
import logging
from argparse import ArgumentParser
from inference import Network
... |
from typing import Optional
from dataclasses import dataclass
from auctions.domain.value_objects.money import Money
@dataclass(repr=True)
class Bid:
def __init__(self, id: Optional[int], bidder_id: int, amount: Money):
assert isinstance(amount, Money)
self.id = id
self.bidder_id = bidder_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
import os
import shlex
import sys
extensions = ["sphinx.ext.todo", "sphinx.ext.githubpages", "m2r"]
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# The suffix(es) of source filenames.
# You can specify multipl... |
"""Webhooks for external integrations."""
from __future__ import absolute_import
from django.http import HttpRequest, HttpResponse
from django.utils.translation import ugettext as _
from zerver.lib.actions import check_send_message
from zerver.lib.response import json_success, json_error
from zerver.decorator import ... |
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.cluster import KMeans
from sklearn.cluster import k_means
def assign_undirected_weight(W, i, j, v):
W[i,j] = W[j,i] = v
def unnormalized_L(D,W):
L = D-W
return L
def normalized_... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
from flask import FlaskForm
from .forms import ValidationError, StringField,PasswordField,SubmitField,BooleanField
from . import Required,Email,EqualTo
from ..models import User
class LoginForm(FlaskForm):
username = StringField('Username',validators=[Required()])
password = PasswordField('Password',validators... |
"""
Module: 'ucollections' on micropython-v1.12-pyboard
"""
# MCU: {'ver': 'v1.12', 'port': 'pyboard', 'arch': 'armv7emsp', 'sysname': 'pyboard', 'release': '1.12.0', 'name': 'micropython', 'mpy': 7685, 'version': '1.12.0', 'machine': 'PYBv1.1 with STM32F405RG', 'build': '', 'nodename': 'pyboard', 'platform': 'pyboard'... |
import platform
import random
from functools import partial
from copy import deepcopy
import numpy as np
from mmcv.parallel import collate
from mmcv.runner import get_dist_info
from mmcv.utils import build_from_cfg
from torch.utils.data import DataLoader
from .dataset_wrappers import RepeatDataset
from .registry impo... |
import math
import torch.nn as nn
from onqg.models.Models import OpenNQG
from onqg.models.encoders import RNNEncoder, TransfEncoder
from onqg.models.decoders import RNNDecoder, TransfDecoder
from transformers import AutoConfig, AutoModelWithLMHead, AutoModelForSequenceClassification
from onqg.pytorch_pretrained_bert.m... |
#!/usr/bin/python3
#
# Copyright (C) 2019 Trinity College of Dublin, the University of Dublin.
# Copyright (c) 2019 Li Jian
# Author: Li Jian <lij12@tcd.ie>
# 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 th... |
from caishen_dashboard.dashboard.app import app
if __name__ == "__main__":
app.run_server(debug=True)
|
# model settings
model = dict(
type='FasterRCNN',
pretrained='checkpoints/mmlab/imnet/resnext101_64x4d-ee2c6f71.pth',
backbone=dict(
type='ResNeXt',
depth=101,
groups=64,
base_width=4,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,... |
#!/usr/bin/env python3
"""
Detects and interactively deactivates duplicate Apt source entries.
Usage: sudo python3 apt-remove-duplicate-source-entries.py
"""
from __future__ import print_function
import aptsources.sourceslist
EMPTY_COMPONENT_LIST = (None,)
def get_duplicates(sourceslist):
"""
Detects and re... |
import requests
import json
import time
class CindiHandler:
def __init__(self, url, stepTemplates = []):
self.stepTemplates = stepTemplates
self.url = url
def HandleStep(step):
return step
def start(self, sleep = 3):
jsonList = []
headers = {'content-type': 'application/json'}
for definition in self.s... |
from abc import abstractmethod, ABCMeta
from plenum.common.request import Request
from plenum.server.request_handlers.handler_interfaces.request_handler import RequestHandler
class AbstractRequestManager(metaclass=ABCMeta):
@abstractmethod
def static_validation(self, request: Request):
pass
@ab... |
# 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... |
# coding=utf-8
# *** WARNING: this file was generated by pulumigen. ***
# *** 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
from . import outp... |
import threading
from typing import List, Dict
import requests
class User:
def __init__(self, user_json: dict):
self.raw = user_json
self.id: int = user_json['id']
self.is_bot: bool = user_json['is_bot']
if 'last_name' in user_json:
self.name = f"{user_json['first_name... |
import pygame
class Coordinator:
"""Used from game"""
def __init__(self, game):
self.game = game
def coordinate(self, name):
map_loc = self.game.maps[name].map_loc
map_image = pygame.image.load(map_loc).convert_alpha()
map_image = pygame.transform.scale(map_image, (self.ga... |
# Copyright (c) 2013 Mirantis 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 writi... |
import voluptuous as vol
from esphomeyaml.automation import ACTION_REGISTRY, maybe_simple_id
from esphomeyaml.components import mqtt
from esphomeyaml.components.mqtt import setup_mqtt_component
import esphomeyaml.config_validation as cv
from esphomeyaml.const import CONF_ALPHA, CONF_BLUE, CONF_BRIGHTNESS, CONF_COLORS,... |
import pymysql
import time
import bs4
import requests
import re
import json
import datetime
from multiprocessing import Pool
with open('config.json', 'r') as f:
config = json.load(f)
database = config['database connection']
with open(config['track user path'], 'r') as f:
baseusers = [i.strip('\n') fo... |
from django import forms
from .documents import Project
class ProjectForm(forms.Form):
name = forms.CharField()
class IssueForm(forms.Form):
project = forms.ModelChoiceField(queryset=Project.objects.all())
subject = forms.CharField()
text = forms.CharField(required=False, widget=forms.Textarea)
... |
"""Representations and Inference for Logic (Chapters 7-9, 12)
Covers both Propositional and First-Order Logic. First we have four
important data types:
KB Abstract class holds a knowledge base of logical expressions
KB_Agent Abstract class subclasses agents.Agent
Expr A log... |
parms = []
for t in [1.5,2,2.5]:
parms.append(
{
'LATTICE' : "square lattice",
'T' : t,
'J' : 1 ,
'THERMALIZATION' : 1000,
'SWEEPS' : 100000,
'UPDATE' : "cluster",
'MODEL' : "Ising",
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('django_postges_lookups_any.urls', namespace='django_postges_lookups_any')),
]
|
from django.contrib.sitemaps import Sitemap
from .models import Post
class PostSitemap(Sitemap):
changefreq = 'weekly'
priority = 0.9
def items(self):
return Post.published.all()
def lastmod(self, obj):
return obj.updated
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE.md', which is part of this source code package.
#
import time
from kubernetes import K8sConfig
from kubernetes.K8sContainer import K8sContainer
from kubernetes.K8sExceptions import NotFoundEx... |
#!/usr/bin/env python3
import argparse
import sys
from bstruct_defs import *
def dump_hcc_content(filename):
try:
fp = open(filename, 'rb')
except OSError as e:
print("[ERROR] '%s' raised when tried to read the file '%s'" % (e.strerror, filename))
sys.exit(1)
buf = fp.read... |
import calendar
from flask_appbuilder import ModelView
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_appbuilder.charts.views import GroupByChartView
from flask_appbuilder.models.group import aggregate_count
from flask_babel import lazy_gettext as _
from app import db, appbuilder
from .mo... |
"""FillMargin.
Ensures the margin value is non-null.
"""
import pandas as pd
from prefect import Task
class FillMargin(Task):
"""Ensure the margin is non-null."""
def run(self, pbp: pd.DataFrame) -> pd.DataFrame: # type: ignore
"""Ensure the margin is non-null.
Parameters
--------... |
import os
from os.path import basename, join, exists
import numpy as np
import math
np.random.seed(777)
import tensorflow_addons as tfa
from tensorflow.keras import models
from tensorflow.keras import layers
from tensorflow.keras import models
from tensorflow.keras import optimizers
from tensorflow.keras impo... |
"""
This is the test script for optimizers in the genetic package.
"""
import sys
from typing import Dict
import numpy as np
# from matplotlib import pyplot as plt
sys.path.append("./")
from core.genetic.optimizer import GeneticOptimizer
from core.genetic.tuner import GeneticTuner
def obj_func(param: Dict[str, obje... |
import os
from botbot import envchecks
def test_generic_env_checker():
generic = envchecks._var_check_builder('DOOT',
None,
'PROB_DOOT')
os.environ['DOOT'] = 'thank mr skeltal'
assert generic(important=['thank', 'mr', ... |
from sklearn.feature_extraction.text import HashingVectorizer
import re
import os
import pickle
"""
vectorizer.py imports the vectorizer into the existing session, enabling it's use in the web app.
"""
cur_dir = os.path.dirname(__file__)
stop = pickle.load(open(
os.path.join(cur_dir, 'movie_site',
... |
# Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.14.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
i... |
import numpy as np
import pandas as pd
import seaborn as sns
import scipy.stats as stats
import matplotlib.pyplot as plt
import json, os, progressbar, re, time
from Bio import SeqIO
from Bio import AlignIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from matplotlib_venn import venn3, venn3_circles
from... |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
Run Regression Test Suite
This module calls down into individual test cases via subprocess. It will
... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
import os.path
import re
import sys
import llnl.util.tty as tty
import spack.build_environment
import spack.uti... |
from utils import *
# the IPs of the perf servers for network tests
PERF_SERVER_IPS = ["1.1.1.1", "2.2.2.2"]
def perf_test(
rd_id,
runtime,
mem_size,
thread_no,
sleep_tm,
wait_tm,
log_file="tmp.log"):
func_prex = "perf_test"
aws_id, aws_key, region, role... |
import numpy as np
from task.utils import sample_rand_path
# import pdb
VALID_SAMPLING_MODE = ['enumerative']
KEY_REPRESENTATION = ['node', 'time']
# KEY_REPRESENTATION = ['node', 'time', 'gaussian']
# VALID_SAMPLING_MODE = ['enumerative', 'probabilistic']
# TODO: implement probabilistic sampling mode
# TODO: value sa... |
"""
Module that creates a script that can record all imports of the
module that this function is called from.
"""
import os
import subprocess
def strip_imports(script):
""" Strip out all import statements, including `import as`
and `from ... import`
This is ok for a first pass. But will fail if 'import'... |
# 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'])
Monomer('BaxM', ['BidM', 'BaxA'])
Monomer('Apop', ['C3pro', 'X... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Openbabel(CMakePackage):
"""Open Babel is a chemical toolbox designed to speak the many la... |
import tomodachi
@tomodachi.service
class ExceptionService(tomodachi.Service):
name = "test_exception"
log_level = "DEBUG"
def __init__(self) -> None:
raise Exception("fail in __init__()")
async def _start_service(self) -> None:
raise Exception("fail in _start_service()")
|
# 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
fro... |
# RUN: %{python} %s
#
# END.
import unittest
import platform
import os.path
import tempfile
import lit
from lit.TestRunner import ParserKind, IntegratedTestKeywordParser, \
parseIntegratedTestScript
class TestIntegratedTestKeywordParser(unittest.TestCase):
inputTestCase = None
@... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.