text stringlengths 3.07k 12.6k |
|---|
"""
functions for calculating theoretical noise levels of LOFAR equipment.
For more information about the math used here read the `sensitivity of the
LOFAR array page
<http://www.astron.nl/radio-observatory/astronomers/lofar-imaging-capabilities-sensitivity/sensitivity-lofar-array/sensiti>`_.
To check the values calc... |
"""Example of using a custom model with batch norm."""
import argparse
import ray
from ray import tune
from ray.rllib.models import ModelCatalog
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.misc import normc_initializer
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.utils... |
"""Module provider for Aliyun"""
import base64
import datetime
import hmac
import logging
import random
import sys
import time
from hashlib import sha1
import requests
from six.moves import urllib
from lexicon.exceptions import AuthenticationError
from lexicon.providers.base import Provider as BaseProvider
LOGGER = ... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 1 20:54:50 2019
Analyzed effect of FFT, NOMP (NOMP better, see May19 slides or workflowy)
@author: gupta
"""
import GAutils.master_simulator3 as ms3
import GAutils.config as cfg
import numpy as np
from datetime import date, datetime
def set_it(itrx, xval, idxa, val):
... |
"""
# Govee domoticz Python Plugin
This plugin allows reading Govee BLE temperature / humidity sensors
## Installation
```bash
cd ~
git clone https://github.com/gaelj/sensor.goveetemp_bt_hci.git domoticz/plugins/Govee
chmod +x domoticz/plugins/Govee/plugin.py
sudo systemctl restart domoticz.service
```
... |
from pathlib import Path
import abc
import inspect
import time
import tensorflow as tf
from synethesia.framework.model_skeleton import Model
class SessionHandler(object):
def __init__(self, model, model_name, checkpoint_dir="./checkpoints", logdir="./logs", max_saves_to_keep=5):
if not isinstance(model... |
import nnpy
import ptf
import ptf.platforms.nn as nn
import ptf.ptfutils as ptfutils
import ptf.packet as scapy
import ptf.mask as mask
from ptf.base_tests import BaseTest
from ptf.dataplane import DataPlane, DataPlanePortNN
from tests.common.utilities import wait_until
class PtfAdapterNNConnectionError(Exception):
... |
#!/usr/bin/env python3
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
#!/usr/bin/env python
#
# Copyright 2007 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 law o... |
import logging
import time
import pytest
import zenko_e2e.conf as conf
from kubernetes import client, config
from kubernetes.client.rest import ApiException
from ..fixtures import *
from .. import util
_log = logging.getLogger('cosmos') # pylint: disable=invalid-name
MD5_HASHES = {
"file1": "b781c1f5179214f6d7f3... |
##############################################################################
# Copyright 2019 IBM Corp.
#
# 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/LI... |
#!/usr/bin/env python
from functools import reduce
from google.cloud.monitoring_v3 import MetricServiceClient
from google.cloud.monitoring_v3.types import LabelDescriptor, MetricDescriptor, TimeSeries
from os import environ
import psutil as ps
import requests
from signal import signal, SIGTERM
from sys import stderr
f... |
# coding:utf-8
'''
python 3.5
mxnet 1.3.0
gluoncv 0.3.0
visdom 0.1.7
gluonbook 0.6.9
auther: helloholmes
'''
import mxnet as mx
import numpy as np
import os
import time
import pickle
import logging
import models
import dataloader
from mxnet import gluon
from mxnet import init
from mxnet import nd
from mxnet import auto... |
"""
:mod:`Imath` --- Support types for OpenEXR library
==================================================
"""
class chromaticity:
"""Store chromaticity coordinates in *x* and *y*."""
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return repr((self.x, self.y))
c... |
import discord
import json, requests
from datetime import datetime
client = discord.Client()
#url = "https://sandbox.iexapis.com/stable" #dev
url = "https://cloud-sse.iexapis.com/stable" # prod
url_iea = "https://api.eia.gov/" # U.S. Energy Information Administration
#Where we store the API keys
class globalVars:
... |
import os
import unittest
import xmlrpclib
import StringIO
#from djangopypi.views import parse_distutils_request, simple
from djangopypi.models import Package, Classifier, Release, PackageInfoField, Distribution
from django.test.client import Client
from django.core.urlresolvers import reverse
from django.contrib.auth.... |
import json
import math
from google.appengine.api import search
"""
Limitations:
1. Providers can only enter a single territory whose set of points does not result in a radius larger than 250 m. So providers need to enter their territories in a piecemeal fashion.
2. When searching for a latitude and lon... |
# Copyright (c) 2020 Sony 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 required by applicabl... |
#
# Implements a wrapper around the Weld API.
#
import copy
import platform
from ctypes import *
import pkg_resources
system = platform.system()
if system == 'Linux':
lib_file = "../weld-latest/target/release/libweld.so"
elif system == 'Windows':
lib_file = "libweld.dll"
elif system == 'Darwin':
lib_file... |
#!/usr/bin/env python
"""
class for handling configuration data files
Reads a .conf file and obtains its metadata
"""
# Copyright (C) 2003, 2004 <NAME>
# Copyright (C) 2003, 2004 <NAME>
#
# SPDX-License-Identifier: GPL-2.0-only
#
import errno
import re
import os
import bb.utils
from bb.parse import ParseErr... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# flake8: noqa
from builtins import _test_sink, _test_source
from typing import Awaitable, Callable, TypeVar
from pyre_extensions import Par... |
#!/usr/bin/env python
"""Command line interface for extending feed effective dates."""
import argparse
import csv
from datetime import datetime, timedelta
import logging
import os
import shutil
import sys
import zipfile
DOWNLOAD_DIRECTORY = 'gtfs'
# extend feed effective date range this far into the past and future
EF... |
# Copyright 2022 The BladeDISC 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 ... |
# pylint: disable=g-bad-file-header
# Copyright 2019 DeepMind Technologies Limited. 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/... |
import cv2
from contextlib import ExitStack
from extraction import loadVideo, dateToFrame,frameToDate, loadMaskCache, HealthExtractor, NicknameExtractor, KillfeedExtractor, UltimateExtractor, TeamnameExtractor
import concurrent.futures
import multiprocessing
from math import floor
def runExtractor(extractor, lock):... |
# -*- coding: utf-8 -*-
"""
WebPV
~~~~~
An EPICS PV client application written with Flask and sqlite3.
:copyright: © 2010 by the Pallets team.
:copyright: © 2018 by the <NAME>.
:license: BSD, see LICENSE for more details.
"""
import os
from multiprocessing import Process
import datetime
impor... |
# Copyright (C) 2019-2021, <NAME>.
# This program is licensed under the Apache License version 2.
# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common opt... |
import sys
sys.path.append("../bayes_opt")
sys.path.append("..")
# Bayesian optimization using classical and lazy_gpr gaussian process
from lazy_gaussian_process.bayesian_optimization import BayesianOptimization
import numpy as np
# import network_training
import pickle
import math
import time
import pandas as pd
imp... |
import os, sys
from pypy.annotation import model as annmodel
from pypy.rpython.controllerentry import Controller
from pypy.rpython.extfunc import register_external
from pypy.rpython.lltypesystem import rffi, lltype
from pypy.rlib import rposix
# ____________________________________________________________
#
# Annotati... |
import albumentations as A
from torch.utils.data import Dataset
import cv2
import numpy as np
import pandas as pd
from sklearn.model_selection import StratifiedKFold
from .commons import config, target_cols
def get_train_data():
train = pd.read_csv('/workspace/train.csv')
train_annotated = pd.read_csv('/wo... |
import logging
import os
from anykeystore import create_store_from_settings
from pyramid.config import Configurator
from pyramid.exceptions import ConfigurationError
from pyramid.response import Response
from velruse.app.utils import generate_token
from velruse.app.utils import redirect_form
log = logging.getLogge... |
from typing import Optional
import numpy as np
from scipy import stats
from scipy.spatial.distance import pdist, squareform
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.exceptions import NotFittedError
from sklearn.metrics.pairwise import rbf_kernel
from sklearn.utils import check_array, check... |
# -*- coding: utf-8 -*-
from six.moves.urllib.parse import urlsplit
from lxml import html
from lxml.html import clean
# XXX move to iktomi.cms?
class Cleaner(clean.Cleaner):
safe_attrs_only = True
remove_unknown_tags = None
drop_empty_tags = frozenset()
dom_callbacks = []
allow_external_src = Fals... |
"""
Scoring server for python model format.
The passed int model is expected to have function:
predict(pandas.Dataframe) -> pandas.DataFrame
Input, expected intext/csv or application/json format,
is parsed into pandas.DataFrame and passed to the model.
Defines two endpoints:
/ping used for health check
/in... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""=================================================================
@Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3
@File : LC-0733-Flood-Fill.py
@Author : [YuweiYin](https://github.com/YuweiYin)
@Date : 2022-01-07
========================================... |
import numpy as np
import cv2, re, os, keras, warnings, time
from keras.models import Model
import keras.layers as L
from keras.optimizers import RMSprop
from keras import models
from keras import optimizers
from keras.applications import VGG16
from mylib.Mailer import Mailer
from mylib import Config
warnings.filterwar... |
"""WsRpc for Shelly."""
from __future__ import annotations
import asyncio
import logging
import pprint
from asyncio import tasks
from dataclasses import dataclass
from typing import Any, Callable, cast
import aiohttp
import async_timeout
from aiohttp import ClientWebSocketResponse, WSMsgType, client_exceptions
from ... |
import os
import re
from enum import Enum
from pathlib import Path
from typing import Union, Optional
from typing import TYPE_CHECKING
from pydantic import BaseSettings, Field
from typhoon import local_config
if TYPE_CHECKING:
from typhoon.core.metadata_store_interface import MetadataStoreInterface
def _join_u... |
import os
import random
from imutils import paths
import numpy as np
import pandas as pd
import skimage as sk
import skimage.transform
from sklearn.model_selection import train_test_split
from tensorflow.keras.preprocessing.image import img_to_array, load_img
from tensorflow.keras.utils import to_categorical
import c... |
#!/usr/bin/python
import argparse
import os
import sys
import time
from tempfile import mkstemp
import rpc_pb2 as rpc
from setup_swrk import setup_swrk
log_file = 'config_file_test.log'
does_not_exist = 'does-not.exist'
def setup_config_file(content):
# Creating a temporary file which will be used as configur... |
import pandas as pd
from sklearn import model_selection
from sklearn.tree import DecisionTreeClassifier
def predict(home_team, away_team, city, toss_winner, toss_decision):
matches_cleaned_data = pd.read_csv('./Dataset/matches_cleaned.csv')
matches_df = matches_cleaned_data[['team1', 'team2', 'city', '... |
"""
Provider implementations
"""
import importlib
from types import LambdaType, ModuleType
from typing import Any
from typing import Callable as CallableType
from typing import Dict, Tuple, Union
from simple_di import (
VT,
Provider,
_inject_args,
_inject_kwargs,
_SentinelClass,
inject,
sen... |
"""Widget to save the state of a WeldxFile and invoke the next step in the pipeline."""
import pathlib
import typing
from os import environ as env
from typing import Any, Dict, Mapping, TypeVar
from urllib.parse import parse_qs, urlencode
import ipywidgets as w
import weldx
import weldx_widgets
import weldx_widgets.w... |
#!/usr/bin/env python3
import sys
import time
import curses
import argparse
import httplib2
import _thread
import colorama
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse
from threading import Thread
from colorama import Fore, Back, Style
class HttpRequest(Thread):
stop... |
# Copyright 2016-2018, Pulumi 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 agreed t... |
#!/usr/bin/python -u
#
# Tests for platypus command line tool
#
import os
import sys
import re
import subprocess
import plistlib
import shutil
CLT_BINARY = os.path.dirname(os.path.realpath(__file__)) + '/platypus'
def profile_plist_for_args(args):
pnargs = [CLT_BINARY]
pnargs.extend(args)
pnargs.extend([... |
from fpdf import FPDF
import pandas as pd
import os
import joblib
from sklearn.metrics import accuracy_score
from sklearn import metrics
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import... |
# -*- coding: utf-8 -*-
'''
This file is part of PyMbs.
PyMbs 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 Software Foundation, either version 3 of
the License, or (at your option) any later version.
PyMbs is distributed... |
# A simple example reading a StochOptFormat file and solving it via Benders
# decomposition.
#
# The code is demonstration only, and does not contain robust checks or many
# nice error messages, preferring to throw assertion errors.
import json
import jsonschema
import math
from pulp import *
def mathoptformat_to_pul... |
import re
from html import unescape
from typing import Dict, List, Union
class CategoryParser():
def __init__(self, html: str):
super().__init__()
self._html = html
self._lines = html.split("\n")
@property
def text(self):
return self._html
def name(self) -> str:
... |
# Copyright 2020 The Flax 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 applicable law or agreed to in wri... |
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required, permission_required, user_passes_test
from django.views import generic
from django.http import Http404
from django.contrib import messages
from django.utils.decorators import method_decorator
from... |
from typing import List
from fastapi_utils.api_model import APIMessage
from fastapi_utils.cbv import cbv
from fastapi_utils.inferring_router import InferringRouter
from fastapi import Depends, status, Response
from odmantic import ObjectId
from app.schema import DatasetPostSchema, DatasetGetSortQuery, \
DatasetTo... |
""" Read DonkeyCar Tub files and write each one to a compressed numpy file (.npz).
Output file will have the same name and location as the tub, with a .npz extension.
Output file will have keys for 'images' (np.int8), 'actions', 'dt_stamps' (unix epoch).
Output file may also have a 'lanes' key for lane auxi... |
# Copyright (c) maiot GmbH 2020. 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... |
import logging
import itertools
from data.logs_model.datatypes import AggregatedLogCount, LogEntriesPage
from data.logs_model.interface import ActionLogsDataInterface
from data.logs_model.shared import SharedModel
logger = logging.getLogger(__name__)
def _merge_aggregated_log_counts(*args):
""" Merge two lists of... |
"""
LLDB AppKit formatters
Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
See https://llvm.org/LICENSE.txt for license information.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""
from __future__ import print_function
# summary provider for CF(Mutable)BitVector
import lldb
i... |
import numpy as np
import logging
from ..common.utils import get_command_args, configure_logger
from ..common.gen_samples import read_anomaly_dataset
from .aad_globals import (
IFOR_SCORE_TYPE_NEG_PATH_LEN, ENSEMBLE_SCORE_LINEAR, AAD_IFOREST, INIT_UNIF
)
from .data_stream import DataStream, IdServer
from .random... |
import os
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from .misc import get_cifar_models
from collections import OrderedDict
__all__ = [
'load_optimizer',
'load_learning_rate_schedule',
'load_checkpoint',
# cifar
'... |
"""The TitleXtract model."""
import string
from collections import defaultdict
import torch
import torch.nn as nn
from citextract.utils.model import load_model_params
class TitleTagging(nn.Module):
"""TitleTagging model."""
def __init__(self, input_size, hidden_size, n_layers, n_classes, device):
""... |
# coding=utf-8
# Copyright 2018 The TF-Agents 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 applicable law... |
import keras
from keras.models import Sequential, Model
from keras.layers import Activation, Merge, Reshape
from keras.layers import Input, Embedding, Dense, dot
from keras.layers.core import Lambda
from keras import optimizers
from keras import backend as K
import numpy as np
import random
import utils.process as pro... |
"""Utility functions used across Caravel"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import functools
import json
import logging
from datetime import datetime
import parsedatetime
from dateutil.parser import pa... |
from torch.nn.modules.loss import _Loss
from package_core.losses import VariationLoss, L1Loss, PerceptualLoss
from package_core.image_proc import *
# L2 loss
def MSE(para):
return nn.MSELoss()
# L1 loss
def L1(para):
return nn.L1Loss()
def MaskedL1(para):
return L1Loss()
# Varianc... |
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
import rospy
import rospkg
import cv2
import tf
import io
import os
import numpy as np
import json
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
class PushestDatasetJsonWriter:
def __init__(self):
... |
# Copyright 2017 Cloudbase Solutions
# 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 json
import copy
import pandas as pd
import spacy
from sklearn.model_selection import train_test_split
class DataSet:
'''Representation of a data set for text classification pipeline
Attributes:
input_: Input dataset if not pre-split in train and test set. This can be a
pandas.DataFrame o... |
import argparse
import os
import re
import unicodedata
import Levenshtein
import pandas
import pandas as pd
import regex
from bz2file import BZ2File
from tqdm import tqdm
from wiktionary_de_parser import Parser
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--wiktionary', type=str, defau... |
# -*- coding: utf-8 -*-
import pickle
import numpy as np
import theano
import theano.tensor as tt
from theano.tests import unittest_tools as utt
from exoplanet.theano_ops.starry import (
GetCl,
GetClRev,
LimbDark,
RadiusFromOccArea,
)
from exoplanet.theano_ops.driver import SimpleLimbDark
class Tes... |
# Lemmatizer for text
import re
import tensorflow as tf
import spacy
from spacy.lang.en import English
from nltk.corpus import stopwords
from libra.data_generation.dataset_labelmatcher import get_similar_column
from libra.data_generation.grammartree import get_value_instruction
def get_target_values(data, instruction... |
import asyncio
import signal
import traceback
from gd.level import Level
from gd.logging import get_logger
from gd.typing import Client, Comment, FriendRequest, Iterable, List, Message, Union
from gd.utils.async_utils import acquire_loop, shutdown_loop, gather
from gd.utils.enums import TimelyType
from gd.utils.filte... |
import cv2
import numpy as np
import time
import math
from Undistort import undistort_chest
from Center import draw_lines,group_lines_and_draw
from Video_stream import LoadStreams
def getAreaMaxContour1(contours): # 返回轮廓 和 轮廓面积
contour_area_temp = 0
contour_area_max = 0
area_max_contour = None
for c... |
#!/usr/bin/env python3
#
# main.py
#
# Command-line utility for interacting with FAN Controller in PDDF mode in SONiC
#
try:
import sys
import os
import click
from tabulate import tabulate
from utilities_common.util_base import UtilHelper
except ImportError as e:
raise ImportError("%s - require... |
from django.conf import settings
from django.utils import translation
import pytest
from mock import Mock, patch
from olympia.amo.tests import TestCase
from olympia.amo.utils import from_string
from olympia.addons.models import Addon
from olympia.translations.templatetags import jinja_helpers
from olympia.translation... |
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
import datasets
import learning
import copy
import argparse
# argparse
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', default='cora', help='Datasets: cora, email, ssets')
parser.a... |
"""Functions that turn a string into a restriction or raise ParseError.
__all__ = ("parse_match", "ParseError",)
@var parse_funcs: dict of the functions that are available.
"""
import re
from ..ebuild import atom, cpv, errors, restricts
from ..restrictions import packages, values
from ..restrictions.util import col... |
from datetime import datetime
from datetime import timedelta
import pytz
import time
import numpy as np
import json
import pandas as pd
from fitness_all import fitnessOfPath
import random
from scipy.stats import truncnorm
from matplotlib import pyplot as plt
def evaluate_fitness_of_all(generation,sessions,travel_time,... |
import re, itertools
from hypertag.nifty.util import unique as unique_list, merge_spaces
from hypertag.core.dom import del_indent
from hypertag.std.registry import Registry
register = Registry()
#########################################################################################################################... |
import os
import pandas as pd
import geopandas as gpd
files = ['prop_urban_2000_2010.csv',
'pop_women_2010.csv',
'pop_men_2010.csv',
'idhm_2000_2010.csv',
'estimativas_pop.csv',
'interest_real.csv',
'num_people_age_gender_AP_2010.csv',
'qualification_APs_... |
# Copyright (c) 2019, Riverbank Computing Limited
# All rights reserved.
#
# This copy of SIP is licensed for use under the terms of the SIP License
# Agreement. See the file LICENSE for more details.
#
# This copy of SIP may also used under the terms of the GNU General Public
# License v2 or v3 as published by the Fr... |
# Copyright 2015 Google Inc. 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 ag... |
##############################################################################
#
# Copyright (c) 2002, 2003, 2018 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution... |
def get_next(currentHead, nextMove):
"""
return the coordinate of the head if our snake goes that way
"""
futureHead = currentHead.copy()
if nextMove == 'left':
futureHead['x'] = currentHead['x'] - 1
if nextMove == 'right':
futureHead['x'] = currentHead['x'] + 1
if nextMove =... |
# ./ida < problems0
import os
# create 10 new problems in file problems0
# from file convert the file to bin moves
# repeat!
PROBLEMS_IN_FILE = 144
def transform_to_bin(path, new_path):
file = open(path, "r+")
new_file = open(new_path, "w+")
line = [
"1000000000000000",
"0100000000000000",
... |
#!/usr/bin/env python
# encoding: utf-8
# The MIT License (MIT)
# Copyright (c) 2012-2016 CNRS
# 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 limita... |
import structlog
import libtaxii.messages_11 as tm11
import libtaxii.messages_10 as tm10
from libtaxii.constants import (
SD_SUPPORTED_CONTENT, ST_UNSUPPORTED_CONTENT_BINDING,
SD_ITEM, ST_NOT_FOUND, ST_BAD_MESSAGE,
ACT_SUBSCRIBE, ACT_UNSUBSCRIBE, ACT_PAUSE,
ACT_RESUME, ACT_STATUS, ACT_TYPES_11,
ACT... |
"""Manage the history_stats data."""
from __future__ import annotations
from dataclasses import dataclass
import datetime
from homeassistant.components.recorder import get_instance, history
from homeassistant.core import Event, HomeAssistant, State
from homeassistant.helpers.template import Template
import homeassist... |
"""
======================================
Gradient Boosting Out-of-Bag estimates
======================================
Out-of-bag (OOB) estimates can be a useful heuristic to estimate
the "optimal" number of boosting iterations.
OOB estimates are almost identical to cross-validation estimates but
they can be compute... |
__all__ = [
'depends',
'config_fields',
'run',
]
"""
The purpose of this target is to 'compile' the regular expressions
found in the regex/ directory and inject them into their respective
Javascript sources in the js/ directory. This is done by invoking a
Python script in regex/ that combines multiple *.re... |
"""
Two constructs to host static sites in aws using S3, cloudfront and Route53.
StaticSitePrivateS3 creates a private S3 bucket and uses S3 API endpoint as
an origin in cloudfront and Origin Access Identity (OAI) to access the s3 objects.
StaticSitePublicS3 creates a public S3 bucket with website enabled and
uses Or... |
import string
from collections import defaultdict
from collections.abc import Callable, Mapping
from functools import partial
from typing import Any, Iterable, Optional
import parse
from arti.fingerprints import Fingerprint
from arti.internal.utils import frozendict
from arti.partitions import CompositeKey, Composite... |
import connexion
import six
from swagger_server.models.schedule_option import ScheduleOption # noqa: E501
from swagger_server import util
from sqlalchemy import exc
def add_schedule_option(body): # noqa: E501
"""Add a schedule_option to the classdeck
# noqa: E501
:param body: ScheduleOption object ... |
"""
Copyright 2020 EUROCONTROL
==========================================
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 conditions
... |
from blazingsql import DataType
from DataBase import createSchema
from Configuration import ExecutionMode
from Configuration import Settings as Settings
from Runner import runTest
from Utils import gpuMemory, skip_test
from EndToEndTests.tpchQueries import get_tpch_query
queryType = "TablesFromSQL"
data_types = [
... |
import os, random
from os import path
import numpy as np
import mxnet as mx
from mxnet import gluon, nd, gpu, autograd
from mxnet.gluon import nn, rnn
from sklearn import preprocessing
"""
Function for data preprocess
"""
def DLPreprocess(dt, cat_feature_list, numeric_feature_list):
### label encode of categorical... |
import edt
import numpy as np
import h5py
from dataset_iterator import MultiChannelIterator
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.losses import mean_squared_error as mse
from dataset_iterator.tile_utils import extract_tile_random_zoom_function
from .data_augmentation import *
from ..model i... |
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from model.models import FewShotModel
import math
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
from itertools import permutations
import scipy.sparse as sp
class GraphConvolution(... |
import os
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Optional
from rich import print
from cookietemple.common.version import load_ct_template_version
from cookietemple.config.config import ConfigCommand
from cookietemple.create.domains.cookietemple_template_struct import ... |
import numpy as np
import keras
from keras.models import Sequential, load_model, Model
from keras.layers import Dense, Dropout, Flatten, GlobalAveragePooling2D, Conv2D, MaxPooling2D, BatchNormalization
from keras.preprocessing.image import ImageDataGenerator
import image_operations
import os
from keras.models import lo... |
import pymongo
from bson.son import SON
import pprint
import json
import requests
import re
import time
from bson.regex import Regex
def connect():
global client
global db
global colKeywordSeedValidated
global colKeywordFirstValidated
global colKeywordSecondValidated
from pymongo import MongoClient
try:
clien... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.