filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_106_29848
# -*- coding: utf-8 -*- """ Script that updates the Siwick Research Group website. Modify the files for the website in the 'website' folder first. See script help: >>> python deploy.py --help You will need to know the Siwick research group's CPM server password. This script requires: - Python 3.3+ - par...
the-stack_106_29849
import tensorflow as tf import keras import skimage import cv2 import numpy as np import mrcnn.visualize as vz from skimage.transform import resize from skimage.color import rgb2grey import warnings def make_image(tensor): """ Convert an numpy representation image to Image protobuf. Copied from https://...
the-stack_106_29850
from redbot.core import commands from redbot.core.utils.chat_formatting import pagify, bold import logging # create log with 'spam_application' log = logging.getLogger("karma.py") log.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatter = logging.Formatter( "%(asctime)s - %(name)s::%(...
the-stack_106_29853
import random from typing import TypeVar def __quicksort(arr: list[TypeVar('T')], left: int, right: int, is_ascending: bool) -> None: if left >= right: return i, j = left, right pivot = arr[random.randint(left, right)] while i <= j: while arr[i] < pivot if is_ascending else arr[i] > ...
the-stack_106_29855
from __future__ import absolute_import, division, print_function from libtbx import test_utils import libtbx.load_env tst_list = [ "$D/tst_cma_es.py", ] def run(): build_dir = libtbx.env.under_build("cma_es") dist_dir = libtbx.env.dist_path("cma_es") test_utils.run_tests(build_dir, dist_dir, tst_list) if (__n...
the-stack_106_29859
# KNN import pandas as pd from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split def trainTest(dftt, x, y): # dftt - DF Train and Test ## SPlit Dataset to train and test x_train, x_test, y_train, y_test = train_test_split(dftt[x], dftt[y], test_size=0.20, r...
the-stack_106_29860
import sys import xml.etree.ElementTree as ET from classes.Feature import * from classes.Extension import * # near and far are defined by windows.h ... :( exceptions = ["GetProcAddress", "near", "far"] class Parameter: def __init__(self, xml): self.name = xml.find("name").text # check for ad...
the-stack_106_29862
from json import dumps from os import getcwd, listdir from os.path import exists, join from pathlib import Path from re import sub class Colors: OK = '\033[92m' WARN = '\033[93m' ERR = '\033[31m' BOLD = '\033[1m' FAIL = ERR + BOLD # Reset color in console. end="" is there so there isnt an extra ...
the-stack_106_29865
# Copyright 2015 Red Hat, 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 agre...
the-stack_106_29868
import os import ast import re import yaml from jinja2 import Environment, BaseLoader, FileSystemLoader, select_autoescape import traceback import functools import time import cProfile import io import pstats import datetime from collections import OrderedDict import appdaemon.utils as ha class Dashboard: def __...
the-stack_106_29869
from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.http import HttpResponse from django.urls import path from django.views import defaults as default_views from django.views.decorators.cache import cache_control from drf_yasg import openapi from drf_...
the-stack_106_29870
# 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 ...
the-stack_106_29871
import datetime import json from pathlib import Path import astropy.units as u from astroplan import Observer from astropy.time import Time from astroplan import moon class Celestial: """Provides information about celestial sightings relative to Virginia. Methods: - get_next_event_after_dt: Get next ris...
the-stack_106_29874
"""Cli process commands""" import os from itertools import chain from functools import partial from operator import attrgetter from multiprocessing.dummy import Pool from vimanga import api, utils def find(search='', threads=3, chapters=None, directory=None, download=False, ...
the-stack_106_29875
import cv2 import glob import random import numpy as np import matplotlib.image as mpimg import matplotlib.pyplot as plt def summarize_data(ds, show_classes=False): print("Number of training examples = ", ds.get_size_of_train()) print("Number of validation examples = ", ds.get_size_of_valid()) print("Numb...
the-stack_106_29878
import sys sys.path.insert(0, '../common_python') import os import pytest import tools def skeleton_jag_reconstruction_loss(cluster, executables, dir_name, compiler_name, weekly, data_reader_percent): if compiler_name not in executables: e = 'skeleton_jag_reconstruction_...
the-stack_106_29879
import numpy as np from .pyscf_rks import rks_pyscf, get_vxc from pydmfet import tools from .fermi import find_efermi, entropy_corr from functools import reduce def kernel(ks): fock = ks.oei + ks.vhxc if ks.vext_1e is not None: fock += ks.vext_1e fock = 0.5*(fock.T + fock) eigenvals, eigenv...
the-stack_106_29880
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.MeterOpenModel import MeterOpenModel class ExerciseItemOpenModelThird(object): def __init__(self): self._desc = None self._external_item_id = No...
the-stack_106_29881
import pytest @pytest.fixture def make_params(tmpdir): p = tmpdir.mkdir("folder").join("test.txt") p.write("test") params = { "dest_mailbox": "TESTMB", "message_location": str(p), "workflow_id": "TESTWF", "message_subject": "TESTSUB", "message_id": "TESTID", ...
the-stack_106_29883
# Mostly based on the code written by Tinghui Zhou: # https://github.com/tinghuiz/SfMLearner/blob/master/utils.py from __future__ import division import numpy as np import tensorflow as tf def euler2mat(z, y, x): """Converts euler angles to rotation matrix TODO: remove the dimension for 'N' (deprecated for conve...
the-stack_106_29885
# MIT License # # Copyright (C) IBM Corporation 2018 # # 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, merge...
the-stack_106_29887
import torch import torch.nn as nn from torch.distributions import MultivariateNormal import gym import numpy as np import torchvision.transforms as transforms from PIL import Image import cv2 import random from tqdm import tqdm import time device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") img_...
the-stack_106_29888
# -*- coding: utf-8 -*- import datetime from functools import reduce import json import operator import os import uuid try: import configparser except ImportError: import ConfigParser as configparser import arrow import click import requests from .config import ConfigParser from .frames import Frames from .u...
the-stack_106_29889
import collections from datetime import timedelta import functools import gc import json import operator import pickle import re from textwrap import dedent from typing import ( TYPE_CHECKING, Any, Callable, Dict, FrozenSet, Hashable, List, Mapping, Optional, Sequence, Set, ...
the-stack_106_29890
# Copyright 2012 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/LICENSE-2.0 # # Unless required by applicable law or agreed t...
the-stack_106_29892
from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.ui import Select from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver import Firefox, Chrome, PhantomJS ...
the-stack_106_29894
# Lint as: python2, python3 # Copyright 2019 Google LLC. 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 req...
the-stack_106_29895
""" Source code for the datetime types that Fourth provides. """ from __future__ import annotations __all__ = ("BaseDatetime", "LocalDatetime", "UTCDatetime") from abc import ABCMeta, abstractmethod from datetime import datetime, timedelta, timezone from operator import ge, gt, le, lt from typing import Any, Callable...
the-stack_106_29897
load("//dart:dart_proto_compile.bzl", "dart_proto_compile") load("@io_bazel_rules_dart//dart/build_rules:core.bzl", "dart_library") def dart_proto_library(**kwargs): name = kwargs.get("name") deps = kwargs.get("deps") verbose = kwargs.get("verbose") visibility = kwargs.get("visibility") name_pb = ...
the-stack_106_29901
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import os import time import argparse import datetime import numpy as np...
the-stack_106_29904
#!/usr/bin/env python3 import os import subprocess from typing import List, Optional from common.basedir import BASEDIR from selfdrive.swaglog import cloudlog def run_cmd(cmd: List[str]) -> str: return subprocess.check_output(cmd, encoding='utf8').strip() def run_cmd_default(cmd: List[str], default: Optional[s...
the-stack_106_29906
# Copyright 2018 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
the-stack_106_29907
#!/usr/bin/env python from pylab import * from numpy import exp, abs, meshgrid, linspace, array, sin, cos, pi, sqrt from mpl_toolkits.mplot3d import Axes3D v0 = array([1, 1, 0]) eta = array([0.2, -0.2, 0]) r = linspace(0, 1, 300) p = linspace(0, 2*pi, 300) R, P = meshgrid(r, p) f = lambda r, p: r*cos(p) + 1 g = lam...
the-stack_106_29911
# -*- coding: utf-8 -*- from cgi import FieldStorage from os import environ #DB_HOST = 'localhost' #DB_USER = 'hablemosdeazucar' #DB_PASS = 'mrqJoBiwECmMCAsPVK4UUxsc' #DB_NAME = 'hablemosdeazucarcgi' #db_data = [DB_HOST, DB_USER, DB_PASS, DB_NAME] POST = FieldStorage() DOCUMENT_ROOT = '/srv/websites/marcoslealsierra/...
the-stack_106_29913
import numpy as np # This is where you can build a decision tree for determining throttle, brake and steer # commands based on the output of the perception_step() function def decision_step(Rover): # Implement conditionals to decide what to do given perception data # Here you're all set up with some basic f...
the-stack_106_29917
import collections import json import six import numpy as np from threading import Thread, Event from ..base import InterfaceBase from ..setupuploadmixin import SetupUploadMixin from ...utilities.async_manager import AsyncManagerMixin from ...utilities.plotly_reporter import create_2d_histogram_plot, create_value_mat...
the-stack_106_29918
import json from datetime import datetime, timedelta from celery import Celery from flask import render_template, request, url_for from sqlalchemy.exc import OperationalError from werkzeug.utils import redirect from bunkmeet import app, db from bunkmeet.one import bunk from bunkmeet.two import covid from bunkmeet.mode...
the-stack_106_29921
from __future__ import absolute_import, division, print_function, unicode_literals SETTINGS_EXCEPTIONS = set(['load', 'map', 'new', 'start']) def _merge_or_diff(old, new, is_merge, require_old_key, path='', require_old_key_exceptions=None): """Merges two dictionaries, mutating the dictionary "o...
the-stack_106_29922
import os from django.contrib.staticfiles import finders from django.core.files.storage import FileSystemStorage from django.test import TestCase from pipeline.collector import default_collector from pipeline.finders import PipelineFinder def local_path(path): return os.path.abspath(os.path.join(os.path.dirname...
the-stack_106_29927
from __future__ import print_function, division import unittest, numpy as np from pyscf import gto, scf from pyscf.nao import gw as gw_c mol = gto.M( verbose = 1, atom = '''Al 0.0 0.0 0.0''', basis = 'cc-pvdz', spin = 1, ) gto_mf = scf.UHF(mol) e_tot = gto_mf.kernel() class KnowValues(unittest.TestCase): def test_...
the-stack_106_29929
import serial import time ser = None def sendData(data): data += "\r\n" ser.write(data.encode()) def main(): global ser ser = serial.Serial('/dev/ttyUSB0', 9600) data = "dorin-is-cool" while 1: #misc code here sendData(data) time.sleep(10) main()
the-stack_106_29931
""" Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ import WhiteBoxMath as whiteBoxMath import WhiteBoxInit as init import azlmbr.legacy.general as general impor...
the-stack_106_29934
#!/usr/bin/env python3 # # Copyright (c) 2017, Linaro Limited # # SPDX-License-Identifier: Apache-2.0 # # vim: ai:ts=4:sw=4 import sys from os import listdir import os, fnmatch import re import yaml import argparse import collections from devicetree import parse_file from extract.globals import * class Loader(yaml....
the-stack_106_29935
import logging import time from pandas import HDFStore import os # Adding logging support logger = logging.getLogger(__name__) def run_radial1d(radial1d_model, history_fname=None): if history_fname: if os.path.exists(history_fname): logger.warn('History file %s exists - it will be overwritten...
the-stack_106_29936
# -*- coding: utf-8 -*- """ Newspaper uses a lot of python-goose's parsing code. View theirlicense: https://github.com/codelucas/newspaper/blob/master/GOOSE-LICENSE.txt Parser objects will only contain operations that manipulate or query an lxml or soup dom object generated from an article's html. """ import logging i...
the-stack_106_29937
#/usr/bin/python import re import os import sys RE_TYPE_NAME = re.compile(r'([\s]*k[A-Za-z0-9]+),.*') CPP_TEMPLATE = ( """std::string type_names[] = {{ {} }}; """ ) def main(*argv): """Parse the MFn header file to generate an array of MFn::Type names.""" cmd, = (argv or [None]) mfn_inl_path = o...
the-stack_106_29938
from settings.default import * SITE_ID = 1 DEBUG = True LOCAL_SERVE = True SOUTH_TESTS_MIGRATE = False # Dummy cache for development CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } # Set session engine to db so that our session doesn't get lost without cache SESS...
the-stack_106_29940
# 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 ...
the-stack_106_29944
# 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 PyScooby(PythonPackage): """A Great Dane turned Python environment detective.""" home...
the-stack_106_29946
from evelink import api, constants from evelink.parsing.assets import parse_assets from evelink.parsing.contact_list import parse_contact_list from evelink.parsing.contract_bids import parse_contract_bids from evelink.parsing.contract_items import parse_contract_items from evelink.parsing.contracts import parse_contrac...
the-stack_106_29948
""" Plot using OceanDataset objects. """ # Instructions for developers: # 1. All funcions must return plt.Axes or xr.plot.FacetGrid objects, # 2. Functions should use the cutout_kwargs argument at the beginning. # 3. Make functions compatible with the animate module, # and create a twin function under animate. # 4....
the-stack_106_29949
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from pathlib import Path import numpy as np import torch import torch.nn as nn from sklearn.cluster import KMeans #from mliv.neuralnet.deepiv_fit import deep_iv_fit from mliv.neuralnet.rbflayer import gaussian, inverse_multiquadric from mliv.neur...
the-stack_106_29951
import tensorflow as tf from baselines.ppo2 import ppo2 from baselines.common.models import build_impala_cnn from baselines.common.mpi_util import setup_mpi_gpus from procgen import ProcgenEnv from baselines.common.vec_env import ( VecExtractDictObs, VecMonitor, VecFrameStack, VecNormalize ) from baseli...
the-stack_106_29956
from typing import Tuple, List from gomoku_enum import Player import itertools import random import logging import sys logger = logging.getLogger("Brain") #logger.setLevel("DEBUG") DEFAULT_NB_LAYER = 1 class Brain: def __init__(self, board, path=None, machine_learning_mode=False): self.board = board # t...
the-stack_106_29958
"""Contains all the Django fields for select2-chained.""" import copy import logging from django_select2.fields import NO_ERR_RESP, AutoModelSelect2Field from .widgets import ChainedAutoSelect2Widget __all__ = ( 'ChainedAutoModelSelect2FieldMixin', 'ChainedAutoModelSelect2Field', 'RequestSpecificAutoMode...
the-stack_106_29959
# coding: utf-8 """Scikit-learn wrapper interface for LightGBM.""" from __future__ import absolute_import import warnings import numpy as np from .basic import Dataset, LightGBMError, _ConfigAliases from .compat import (SKLEARN_INSTALLED, SKLEARN_VERSION, _LGBMClassifierBase, LGBMNotFittedError,...
the-stack_106_29960
""" Django settings for django_get_started project. """ from os import path PROJECT_ROOT = path.dirname(path.abspath(path.dirname(__file__))) DEBUG = False TEMPLATE_DEBUG = DEBUG ALLOWED_HOSTS = ( 'localhost', ) ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'd...
the-stack_106_29962
"""Unsupervised evaluation metrics.""" # Authors: Robert Layton <robertlayton@gmail.com> # Arnaud Fouchet <foucheta@gmail.com> # Thierry Guillemot <thierry.guillemot.work@gmail.com> # License: BSD 3 clause import functools import numpy as np from ...utils import check_random_state from ...utils i...
the-stack_106_29964
# =============================================================================== # # =============================================================================== # It seems that both Pi pins, per segment, are set as output. # LED input pin set '1' and output pin set '0'. # The "digit" pin goes low and the "segment"...
the-stack_106_29966
# SPDX-License-Identifier: Apache-2.0 # Copyright 2021 IBM Corp. import unittest import subprocess import os import filecmp import sys MEM_ERR = 101 SECTOOLS="../secvarctl-cov" SECVARPATH="/sys/firmware/secvar/vars/" goodAuths=[] badAuths=[] goodESLs=[] goodCRTs=[] brokenAuths=[] brokenESLs=[] brokenCrts=[] brokenPkcs7...
the-stack_106_29968
# 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 u...
the-stack_106_29970
import logging from ledfx.devices import Device import voluptuous as vol import numpy as np import sacn import time _LOGGER = logging.getLogger(__name__) class E131Device(Device): """E1.31 device support""" CONFIG_SCHEMA = vol.Schema({ vol.Required('ip_address', description='Hostname or IP address o...
the-stack_106_29971
"""This module includes class to calculate the probability of the ideal hand.""" from dataclasses import dataclass from math import comb from typing import List, Tuple @dataclass class Hand: """Stores hand data, and calculate the probability of given hand. Let d be # of cards in deck, h be # of cards in hand...
the-stack_106_29972
from django import forms from django.db.models import Q from django.utils.translation import npgettext, pgettext_lazy from django_filters import ( CharFilter, ChoiceFilter, DateFromToRangeFilter, ModelMultipleChoiceFilter, OrderingFilter, RangeFilter) from ...core.filters import SortedFilterSet from ...discoun...
the-stack_106_29973
import os import mock import hypothesis as h import hypothesis.strategies as hs import pytest from .. import manifest, item, utils def SourceFileWithTest(path, hash, cls, *args): s = mock.Mock(rel_path=path, hash=hash) test = cls(s, utils.rel_path_to_url(path), *args) s.manifest_items = mock.Mock(retu...
the-stack_106_29974
from .base import AuthenticationBase class GetToken(AuthenticationBase): """/oauth/token related endpoints Args: domain (str): Your auth0 domain (e.g: username.auth0.com) """ def authorization_code(self, client_id, client_secret, code, redirect_uri, grant_type='au...
the-stack_106_29975
# https://www.codewars.com/kata/strings-mix/train/python # My solution from collections import Counter from operator import itemgetter def mix(s1, s2): remove_ones = lambda dict_: {k:v for k,v in dict_.items() if v > 1 } s1 = remove_ones(Counter(filter(str.islower, s1))) s2 = remove_ones(Counter(fi...
the-stack_106_29977
# Copyright (c) 2013 Cloudwatt # 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...
the-stack_106_29978
# 4.3 Using the Data Step to Create an .xdf File from a Data Frame import os import settings as st import pandas as pd import numpy as np from revoscalepy import rx_data_step, rx_get_info np.random.seed(39) x1 = np.random.normal(size = 10000) x2 = np.random.uniform(size = 10000) x3 = x1 + x2 s = np.stack((x1,x2,x3))...
the-stack_106_29981
import demistomock as demisto from CommonServerPython import * import traceback def main(): try: from_date = demisto.args().get('from', '') to_date = demisto.args().get('to', '') query = 'type:"MITRE ATT&CK" and investigationsCount:>0 and -incident.type:"MITRE ATT&CK CoA"' search_i...
the-stack_106_29982
# Software released under the MIT license (see project root for license file) from pyamf import amf3 # ------------------------------------------------------------------------------ suit_arr = [ 'Diamonds', 'Clubs', 'Hearts', 'Spades' ] rank_arr = [ 'Ace', 'Two', 'Three', 'Four', 'Five', 'S...
the-stack_106_29983
import pathlib import numpy as np import pytest import determined as det from determined.tensorboard import SharedFSTensorboardManager, get_base_path, get_sync_path from determined.tensorboard.metric_writers import util as metric_writers_util from determined.tensorboard.util import get_rank_aware_path BASE_PATH = pa...
the-stack_106_29986
import numpy as np def get_hop_distance(num_node, edge, max_hop=1): adj_mat = np.zeros((num_node, num_node)) for i, j in edge: adj_mat[i, j] = 1 adj_mat[j, i] = 1 # compute hop steps hop_dis = np.zeros((num_node, num_node)) + np.inf transfer_mat = [ np.linalg.matrix_power(...
the-stack_106_29988
# -*- coding: utf-8 -*- import logging import pytest from libtmux import exc from libtmux.server import Server from libtmux.test import TEST_SESSION_PREFIX, get_test_session_name, namer logger = logging.getLogger(__name__) @pytest.fixture(scope='function') def server(request): t = Server() t.socket_name =...
the-stack_106_29990
from __future__ import print_function, division import matplotlib.pyplot as plt import math from sklearn.metrics import auc import numpy as np import cv2 import os, sys int_ = lambda x: int(round(x)) def IoU( r1, r2 ): x11, y11, w1, h1 = r1 x21, y21, w2, h2 = r2 x12 = x11 + w1; y12 = y11 + h1 x22 = x...
the-stack_106_29991
#!/usr/bin/env python import os # import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pd from joblib import Memory from . import paths from ..utils import files from . import viz _memory = Memory('./') def _list_csvs(directory): return files.listFilesInDir(directory, en...
the-stack_106_29993
import os import psutil import time def GetOtherMainProcesses(): this_pid = psutil.Process().pid pids = set() for proc in psutil.process_iter(): pid = proc.pid ppid = proc.ppid() if pid == 1 or pid == this_pid or ppid != 0: # ignore the pause container, our own pid, and...
the-stack_106_29994
import os import sys import warnings import logging as log from typing import Union, Optional, List, Dict, Tuple, Iterable from argparse import ArgumentParser import torch import torch.distributed as dist import torch.multiprocessing as mp from torch.utils.data import DataLoader from tqdm.auto import tqdm from torch.o...
the-stack_106_29995
# pylint: disable=too-many-arguments, too-many-locals """ Variational inference """ import math import functools from collections import namedtuple from collections import OrderedDict from scipy.special import gammaln import numpy as np import torch.nn as nn from torch.autograd import Variable from torch.nn.parameter ...
the-stack_106_29996
from __future__ import print_function from __future__ import absolute_import # -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # ----------------------------------------------------...
the-stack_106_29997
from causal_world.task_generators.base_task import BaseTask import numpy as np from causal_world.configs.world_constants import WorldConstants class ReachingTaskGenerator(BaseTask): def __init__(self, variables_space='space_a_b', fractional_reward_weight=1, dense_reward_weights=n...
the-stack_106_30001
#Assignment No: 4 #Problem Statement :Understanding the connectivity of Raspberry-Pi/Beagle board with #temperature sensor. Write an application to read the environment temperature. If temperature #crosses a threshold value, the application indicated user using LEDs. #Name :Sameer Rathod #TE B 58 import RPi.G...
the-stack_106_30004
from __future__ import absolute_import, print_function, division import unittest from pony import orm from pony.orm.tests.testutils import * from pony.orm.tests import setup_database, teardown_database class TestIntConverter1(unittest.TestCase): def setUp(self): self.db = db = orm.Database() cla...
the-stack_106_30005
# Copyright 2020 Alexis Lopez Zubieta # # 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, merge, publi...
the-stack_106_30009
from .nn_layer import NNLayer import tensorflow as tf __all__ = ['LSTMLayer'] class LSTMLayer(NNLayer): """ This layer implements the LSTM cell. """ def __init__(self, input_dim, hidden_layer_size, input_layer): """Initialize LSTMLayer class. Parameters ---------- inpu...
the-stack_106_30011
import turtle instructions = [] with open('day_12.txt') as f: for line in f: line = line.rstrip().lower() instructions.append(line.rstrip()) # PART 1 def move_ship(instructions): ''' Input is array of instructions - letter and number. Letters stand for: n - north, s - south, e - east...
the-stack_106_30013
# -*- coding: utf-8 -*- """ S3 Charting Toolkit @copyright: 2011-12 (c) Sahana Software Foundation @license: MIT @requires: U{B{I{NumPy}} <http://www.numpy.org>} @requires: U{B{I{MatPlotLib}} <http://matplotlib.sourceforge.net>} Permission is hereby granted, free of charge, to any person ...
the-stack_106_30014
import logging import operator import os from datetime import datetime, timedelta from galaxy import util from galaxy.util import unique_id from galaxy.util.bunch import Bunch from galaxy.util.hash_util import new_secure_hash from galaxy.util.dictifiable import Dictifiable import tool_shed.repository_types.util as rt_u...
the-stack_106_30015
import mechanicalsoup as ms import os import re from win10toast import ToastNotifier from time import sleep from sys import exit browser = ms.StatefulBrowser() captive_portal_url = 'http://172.16.40.5:8090/httpclient.html' try: browser.open(captive_portal_url) except: exit(0) #openfile try: accounts =...
the-stack_106_30016
import setuptools with open('README.rst', 'r') as readme_file: long_description = readme_file.read() setuptools.setup( name='django-cpf-cnpj', version='1.0.0', long_description=long_description, long_description_content_type = 'text/x-rst', description='A django model and form field for norm...
the-stack_106_30018
import argparse import os import numpy as np import tensorflow as tf from waymo_toolkit.extractor import ImageExtractor, LabelExtractor, LaserExtractor from waymo_toolkit.utils.logger import setup_logger logger = setup_logger("extractor") def extract(source_dir: str, save_dir: str, args): files = os.listdir(so...
the-stack_106_30021
''' Rice数据集。 图片默认文件夹:./refine_RiceDataset - allData 返回所有数据 - 返回值:(x, y) x: 文件路径 y: 分类 - splitted_data 获取划分好的数据和标签 - 返回值:(x_train, x_test, y_train, y_test) - read_image_tensor 读取图片数据tensor - image_tensor_norm 对图片数据tensor进行规范化 ''' import numpy as np import os import glob import tensorflow as tf ...
the-stack_106_30026
#!/usr/bin/env python # # Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; version 2 of the License. # # This progra...
the-stack_106_30027
answer = 'Y' my_list = [] while answer == 'Y': choice = int(input('Enter a number: ')) if choice not in my_list: my_list.append(choice) print('Number added to list') else: print('Repeated number, not added') answer = input('Do you want to continue? [Y/N] ').upper() print(f'The nu...
the-stack_106_30029
from setuptools import find_packages, setup __version__ = "3.0.0" setup( # package name in pypi name="django-oscar-api", # extract version from module. version=__version__, description="REST API module for django-oscar", long_description=open("README.rst").read(), classifiers=[ "De...
the-stack_106_30030
# Copyright 2019 Google LLC 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...
the-stack_106_30031
import pytest import vtk import pyvista from pyvista import colors @pytest.fixture def default_theme(): return pyvista.themes.DefaultTheme() def test_backwards_compatibility(): try: color = (0.1, 0.4, 0.7) pyvista.rcParams['color'] = color assert pyvista.rcParams['color'] == color ...
the-stack_106_30032
# Time: O(nlogn) # Space: O(n) import bisect class Solution(object): def minimumMountainRemovals(self, nums): """ :type nums: List[int] :rtype: int """ left_lis_len = [0]*len(nums) lis = [] for i in range(len(nums)-1): j = bisect.bisect_left(li...
the-stack_106_30034
#!/usr/bin/python import paho.mqtt.client as paho import os import socket import ssl def on_connect(client, userdata, flags, rc): print("Connection returned result: " + str(rc) ) client.subscribe("#" , 1 ) def on_message(client, userdata, msg): print("topic: "+msg.topic) print("payload: "+str(msg.pay...
the-stack_106_30037
import asyncio import threading import logging import multiprocessing as mp import pytest import msgpack from msgpackio.client import Client from msgpackio.rpc import RPCClient from msgpackio.server import RPCServer from msgpackio.exceptions import RemoteException log = logging.getLogger(__name__) def add(a, b): ...