text
stringlengths
3.07k
12.6k
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack 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/...
import datetime import json import os import spotipy from tzlocal import get_localzone class StreamingHistory: def __init__(self, path: str = '.') -> None: self.current_year = datetime.date.today().year self.end = None self.minutes_listened = 0 self.hours_listened = 0 fi...
## ## File: queue_tut.py ## ## Author: <NAME> <<EMAIL>> ## ## Description: Python class that defines a Tutor Queue data structure for ## the server. It makes sense to only ever have one queue of ## tutors and queue probably isn't the best term for Tutor ## management; Tutors c...
import pytest import sys import io import copy import random from gamesbyexample import towerofhanoi def test_constants(): assert towerofhanoi.TOTAL_DISKS == 5 assert towerofhanoi.COMPLETE_TOWER == [5, 4, 3, 2, 1] def test_getPlayerMove(capsys): towers = {'A': copy.copy(towerofhanoi.COMPLETE_TOWER), 'B': ...
import utils from utils import digitutils as dutils import ANN as ann import os import numpy as np import matplotlib.pyplot as plt from multiprocessing import Pool import cv2 from scipy.stats import entropy network_model1 = """ { "input_shape" : [28,28,1], "layers" : [ { "type" : "Conv2D", ...
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 Licen...
import threading import time import weakref from robocorp_ls_core.constants import NULL from robocorp_ls_core.protocols import ITimeoutHandle from robocorp_ls_core.robotframework_log import get_logger _DEBUG = False # Default should be False as this can be very verbose. log = get_logger(__name__) class _TimeoutT...
import numpy as np import tensorflow as tf from util import concrete_shape from transforms import Simplex, Logit """ Utility methods for defining constrained variables as transforms of an unconstrained parameterization. """ def unconstrained(shape=None, init=None, name=None): if init is None: shape = co...
""" Liu et al. "Metric Learning from Relative Comparisons by Minimizing Squared Residual". ICDM 2012. Adapted from https://gist.github.com/kcarnold/5439917 Paper: http://www.cs.ucla.edu/~weiwang/paper/ICDM12.pdf """ from __future__ import print_function, absolute_import, division import numpy as np import scipy.linal...
#!/usr/bin/python """.DBF creation helpers. Note: this is a legacy interface. New code should use Dbf class for table creation (see examples in dbf.py) TODO: - handle Memo fields. - check length of the fields accoring to the `http://www.clicketyclick.dk/databases/xbase/format/data_types.html` """ """His...
''' Created on May 3, 2016 @author: xiao ''' from numpy.random import RandomState from bs4 import BeautifulSoup _words = ''' Lorem ipsum dolor sit amet consectetuer adipiscing elit sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat Ut wisi enim ad minim veniam quis nostrud e...
'''Assortment of fixtures for use in test modules.''' import uuid import os from os.path import join as pjoin from cesium_app.models import (DBSession, User, Project, DatasetFile, Dataset, Featureset, Model, Prediction) from cesium import data_management, featurize, time_series from cesi...
################################################################ # zopyx.smartprintng.lite # (C) 2009, ZOPYX Limited & Co. KG, D-72070 Tuebingen, Germany ################################################################ import os import glob import shutil import tempfile import urllib2 import BeautifulSoup from compa...
from django.contrib.auth.decorators import login_required from django.shortcuts import render, get_object_or_404, redirect from django.template import loader from django.http import HttpResponse, JsonResponse from django_filters.rest_framework import DjangoFilterBackend from rest_framework import generics from rest_fra...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 10 20:16:54 2020 Various preprocessing functions @author: kfinity """ import pandas as pd import numpy as np import json import nltk from youtube_transcript_api import YouTubeTranscriptApi from youtube_transcript_api._errors import TranscriptsDis...
from citywok_ms.auth.models import User import os from datetime import date import click from flask import Blueprint, current_app from flask.cli import AppGroup from citywok_ms import db from citywok_ms.employee.models import Employee from citywok_ms.file.models import EmployeeFile from citywok_ms.supplier.models imp...
import warnings import numpy as np import pandas as pd import scikitplot as skplt from tqdm.notebook import tqdm import matplotlib.pyplot as plt from scipy.stats import chi2_contingency from yellowbrick.classifier import ( ClassificationReport, ConfusionMatrix, DiscriminationThreshold, PrecisionRecal...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2019 Intel 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 # # Un...
"""Support for humidifier and dehumidifier.""" import logging from homeassistant.const import * # noqa: F401 from homeassistant.components.humidifier import ( DOMAIN as ENTITY_DOMAIN, HumidifierEntity, ) from homeassistant.components.humidifier.const import * from . import ( DOMAIN, CONF_MODEL, X...
from decouple import config import requests from django.conf import settings from gingerit.gingerit import GingerIt from .models import Tag, Caption, Picture #similar tag libs from gensim.test.utils import common_texts import gensim.downloader from gensim.models import Word2Vec glove_vectors = gensim.downloader.load(...
import logging import pathlib from tqdm import tqdm import datajoint as dj import pandas as pd import numpy as np from tqdm import tqdm import nrrd import re log = logging.getLogger(__name__) schema = dj.schema() def activate(schema_name, *, create_schema=True, create_tables=True): """ activate(schema_name,...
import ast import os import numpy import pandas from sklearn.feature_selection import VarianceThreshold from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler cpu_numerical_features = ['cpu_# of Cores', 'cpu_# of Threads', 'cpu_Frequency', 'cpu_Turbo Clock', ...
__source__ = 'https://leetcode.com/problems/smallest-rectangle-enclosing-black-pixels/' # Time: O(m long n + n log m) m and nn are the height and width of the image # Space: O(1) # # Description: Leetcode # 302. Smallest Rectangle Enclosing Black Pixels # # An image is represented by a binary matrix with 0 as a white ...
import json from datetime import datetime, timedelta from django.conf import settings from django.core.management import call_command from django.core.management.base import BaseCommand import requests from corehq.util.metrics import create_metrics_event from dimagi.utils.parsing import json_format_datetime from pil...
"""Eval mAP@N metric from inference file.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import app from absl import flags import mean_average_precision_calculator as map_calculator import numpy as np import tensorflow as tf flags.DEFINE_str...
import datetime from typing import Optional from ...orders.models import OrderPositionType, OrderAmountType, IOrderConfirmation class ManualOrderPosition: _hl_vt: str _security_type: str _out_of_hours: bool _sedol: str _account_id: int _available: float _holding: float _holding_value:...
import pytorch_lightning as pl from omegaconf import DictConfig import torch.nn as nn from utils.losses import l2_loss, GANLoss import torch from data import seq_collate from torch.utils.data import DataLoader from utils.utils import re_im from pytorch_lightning import Trainer from utils.visualize import visualize_prob...
from __future__ import absolute_import, division from desispec.io import read_frame from desispec.io import read_fiberflat from desispec.io import read_sky from desispec.io import write_qa_frame from desispec.io.fluxcalibration import read_stdstar_models from desispec.io.fluxcalibration import write_flux_calibration...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import optimization as op from Neural_network import * from keras.datasets import mnist from collections import OrderedDict import matplotlib.pyplot as plt from pylab import mpl import argparse class TwoLayerNet: def __init__(self, input_size, hidden_size...
import cPickle import theano import numpy import csv import logging import theano.tensor as T class DataSet(object): """ Base class for all types of datasets. All dataset classes should have following data members: tr_x, tr_y va_x, va_y te_x, te_y Also: np_tr_x, np_tr_y np_va_x, np...
################################################################################ # A naive bayes classifier for classifying iris data. # # Author: <NAME> # Date: 9/10/2016 # Updated: 9/12/2016 # # Copyright 2016 <NAME> ################################################################################ import csv import ma...
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
# -*- coding: utf-8 -*- # Copyright (c) Los Alamos National Security, LLC, and others. # A note on implementation of ngrams: subclasses should not worry about # ngrams. The base class will assemble ngrams if needed. from abc import ABCMeta, abstractmethod import itertools import operator from pprint import pprint ...
from typing import Any, Dict, Optional, Tuple import numpy as np from great_expectations.core import ExpectationConfiguration from great_expectations.execution_engine import ( ExecutionEngine, PandasExecutionEngine, SparkDFExecutionEngine, ) from great_expectations.execution_engine.execution_engine import...
''' This script serves the purpose of interacting with existing smart contracts on the testnet or mainnet. ''' from brownie import * from brownie.network.contract import InterfaceContainer import json import time; import copy def main(): #load the contracts and acct depending on the network loadConfig()...
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, unicode_literals """ Created on May 1, 2012 """ __author__ = "<NAME>" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "0.1" __maintainer__ = "<NAME>" __...
# -*- coding: utf-8 -*- """ Coursework 4: PCA and Analogous finding References: https://www.esrl.noaa.gov/psd/data/gridded/data.ncep.reanalysis2.pressure.html https://www.esrl.noaa.gov/psd/cgi-bin/db_search/DBListFiles.pl?did=59&tid=81620&vid=1498 https://www.esrl.noaa.gov/psd/cgi-bin/db_se...
# # This code is part of the Blossom project. # # Written by <NAME> <<EMAIL>>, March 2019 # import blossomai as bl import tensorflow as tf from datetime import datetime log_file_location = '../logs/training_sessions.log' feature_list = [ 'masa_all', 'del_asa_all', 'sbr_all', 'rasa_all', 'del_rasa_all', 'blosum_a', '...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function, division import sys import os import argparse import logging import requests.packages.urllib3 import chandl from chandl import util from chandl.downloader import Downloader from chandl.model.thread import Thread fro...
from get_file import * from bb_box import * from add_occlusion import * from overlay import * from get_file_nums import * import numpy as np import random import pickle from math import floor from pathlib import Path import os import scipy.io import sys # jhmdb_gt_path = "MOC-Detector/data/JHMDB/puppet_mask" # jhmdb_r...
from functools import partial from typing import NamedTuple, Dict, List, Optional import torch import torch.nn as nn import torch.nn.functional as F from sacred import Experiment from torch.optim import Optimizer from torch.optim.lr_scheduler import _LRScheduler from torch.utils.data import DataLoader from tqdm import...
''' Used for extracting tag definitions to a format that can be easily read. ''' from reclaimer.field_types import Reflexive from reclaimer.h2.field_types import H2Reflexive from traceback import format_exc from supyr_struct.tag import Tag from supyr_struct.field_types import Union def find_enums(block, nex...
# 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 agreed ...
from .Servo.pwm import PWM from time import sleep """ joint_key convention: R - right, L - left F - front, M - middle, B - back H - hip, K - knee, A - Ankle key : (channel, minimum_pulse_length, maximum_pulse_length) """ joint_properties = { 'LFH': (0, 110, 630), 'LFK': (1, 110, 630), 'LFA': (2, ...
from collections import namedtuple import configparser from globals import CONFIG_FILE from globals import IOTA_DEPTH_VALUE, BROKER_PORT_DEFAULT from globals import VERIFIER_SERVER_HOST_DEFAULT, VERIFIER_SERVER_PORT_DEFAULT class ConfigurationMissing(Exception): def __init__(self, msg=''): self.msg = msg...
#!/usr/bin/env python3 from asyncio import get_event_loop, gather, Semaphore from collections import defaultdict from datetime import datetime from json import dumps from logging import getLogger, basicConfig, INFO from os import environ, cpu_count from pathlib import Path from random import choice from sys import path...
from core import ipcprotocols as ipc from core.stenographer import Stenographer from core.generator import Generator from MessageRegister import MessageSource, MessageCommand import time import os import socket """Methods used for inter-process communications using a file transfer protocol (FTP). """ _server_address ...
from django.http import JsonResponse from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from allauth.socialaccount.models import SocialAccount, SocialApp, SocialToken from api.models import APIKeyProvider, DashboardConfig from api.serializers import APIKeyProviderSerializer,...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2017 <NAME> <<EMAIL>> # # 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 require...
""" Batch geocoding of addresses using the Google Maps Geocoding API. This script utilizes Google Maps' Geocoding API to allow batch geocoding. A CSV file is expected with columns: | Index | Address | Latitude | Longitude | Note: if the data contains a header row, use the --header switch An API key is needed to use...
#!/usr/bin/env python # Copyright 2020 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 ...
""" For the tractogram of a bundle creates two masks: One for startpoints and one for endpoints. Approach: Use DBscan clustering for dividing all endpoints into start and ending. Uses only a subset of all points because of runtime. Then train random forest on those 2 clusters and use random forest to divide all points...
import os from django.conf import settings from django.core.files import File from django.core.files.images import ImageFile from django.test import override_settings from unittest import mock from nose.tools import eq_ import kitsune.upload.tasks from kitsune.questions.tests import QuestionFactory from kitsune.sumo...
import time from math import pi, sin, cos, degrees, hypot, atan2, radians from .game_object import GameObject import pypybox2d SPEED_SCALE_FACTOR = 0.02 MAX_MOTOR_SPEED = 100 GRAB_RADIUS = 0.4 HALF_GRAB_SECTOR_WIDTH = pi / 4 HALF_FOV_WIDTH = pi / 6 GRABBER_OFFSET = 0.25 class AlreadyHoldingSomethingException(Exc...
import polyinterface import os import socket import select import http.client import io from threading import Thread from queue import PriorityQueue, Empty import requests import xmltodict LOGGER = polyinterface.LOGGER class SSDPResponse(object): class _FakeSocket(io.BytesIO): def makefile(self, *args, *...
import numpy as np import torch from torch import nn import copy import random import os ## Distributions def generate_gaussian_parity( n_samples, means=None, cov_scale=1, angle_params=None, random_state=None, ): """ Generate 2-dimensional Gaussian XOR distribution, a mixture of four Ga...
#!/usr/bin/env python from typing import List, Optional from rdkit import Chem from rdkit.Chem import AllChem from rdkit.Chem import rdFMCS from tqdm import tqdm from docopt import docopt from copy import deepcopy import Bio.PDB as PDB # Code borrowed from <NAME> # https://github.com/JoshuaMeyers/Snippets/blob/mast...
#!/usr/bin/env python import rospy import numpy as np import cv2 import matplotlib.pyplot as plt from tf.transformations import euler_from_quaternion from geometry_msgs.msg import PoseStamped , Twist from nav_msgs.msg import Odometry from Astarcodes import astar , reconstract_path , world2maplocation , Save_A_sta...
import tensorflow as tf import numpy as np def load_csv( filename='game_data.csv'): with open(filename, 'r') as f: headers = f.readline().replace('/', '_').split(',') data = f.readlines() return headers, data class DataClass: def __init__(self, headers, data_row): data_row = data...
import pandas as pd from pandas_datareader import data import requests import datetime as dt from pytrends.request import TrendReq def main(stock, years=1): # function to get data from Yahoo Finance end = dt.datetime.today().strftime('%Y-%m-%d') # today as the end date start = (dt.datetime.today() ...
import json import importlib import os import random import hashlib import shutil import google.auth from jinja2 import Template from .config import cfg def import_level(level_path): '''Returns the imported python module of the given level path. Parameters: level_path (str): Relative path of level ...
""" field_parser.py parser for field data """ from __future__ import print_function import os import struct import numpy as np def parse_field_all(fn): """ parse internal field, extract data to numpy.array :param fn: file name :return: numpy array of internal field and boundary ...
# # BSD 3-Clause License # # Copyright (c) 2019, Analog Devices, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, ...
import datetime as dt import functools import inspect import sys import uuid from time import CLOCK_REALTIME from types import GeneratorType from unittest import TestCase, mock from dateutil.parser import parse as parse_datetime import _time_machine NANOSECONDS_PER_SECOND = 1_000_000_000 class Coordinates: def...
''' A DFS search solution to the missionaries and cannibals problem ''' import sys class State(): def __init__(self, c_left, m_left, c_right, m_right, boat_direction, boat_size): self.parent = None self.c_left = c_left self.m_left = m_left self.c_right = c_right self.m_right...
# -*- coding: utf-8 -*- """ @author: HZU """ import pandas as pd import numpy as np from scipy import stats postal_code = pd.read_csv('postal_code_belgium.csv', sep=',') def outliers(df, strategy="Do not remove"): if strategy[:6] =="Remove": df = df[(np.abs(stats.zscore(df['actual_price'])...
#!/usr/bin/env python2.7 # Copyright 2015, ARM Limited # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this li...
#!/usr/bin/env python3 import argparse, os, imageio, sys, semantic_meshes, shutil, subprocess, sqlite3 import numpy as np from tqdm import tqdm from columnar import columnar import scipy.spatial.transform parser = argparse.ArgumentParser(description="Create colmap reconstructions of the scannet dataset") par...
import natcap.invest.habitat_quality import arcpy from arcpy.sa import * import os, glob, shutil, sys, zipfile arcpy.env.overwriteOutput = True workspace_dir = arcpy.env.scratchFolder def isLicensed(): """Set whether tool is licensed to execute.""" try: if arcpy.CheckExtension("Spatial") == "Available": arcpy....
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP # All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE...
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the...
import datetime import functools import weasyprint from io import BytesIO from PyPDF2 import PdfFileMerger from django.conf import settings from django.template.loader import render_to_string from django.core.exceptions import ObjectDoesNotExist from django.db.models import Q from django.utils import translation fro...
import sys import argparse if sys.version_info[:1] == (2,): import mock import unittest else: import unittest2 as unittest from unittest import mock from nose.tools import assert_equals from nose.tools import assert_raises from nose.tools import assert_true from nose.tools import assert_is_instance imp...
# 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...
""" Model of ACC with FCW and IDM+ to take over from Xiao et al. (2017). Creation date: 2020 08 12 Author(s): <NAME> Modifications: """ import numpy as np from .acc import ACC, ACCParameters, ACCState from .idm import IDMParameters from .idmplus import IDMPlus class ACCIDMPlusParameters(ACCParameters): """ Par...
import datetime import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import linear_model from sklearn.metrics import mean_squared_error from exp_data import * from exp_data_utils import RegressionRecord from read_data.utils import dfTypePair, toSingleRowDF import global_config def compu...
# -*- coding: utf-8 -*- # Copyright 2011 Yelp # # 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 ...
from flask import session, redirect, url_for,request from flask_login import current_user from flask_socketio import SocketIO, emit, send, disconnect, join_room, leave_room from classroom_manager import socketio from classroom_manager.models import User, Classroom, Membership, Channel, Message, Note, DirectMessage from...
from django import template from django.template.loader import render_to_string from django.contrib.contenttypes.models import ContentType as CT from django.core.urlresolvers import reverse from valuate.models import Valuation, ValuationType as VT from valuate.forms import ValuationForm register = template.Library() V...
#!/usr/bin/env python import argparse import os import re import time import filecmp import shutil import glob version = 'v2.1.0' ignored = { 'Thumbs.db' } fileNumberPattern = re.compile('([0-9]+)') argParser = argparse.ArgumentParser(prog='savepics', description='Sorts picture files from an input directory into an...
import numpy as np import random import matplotlib.pyplot as plt class board_info(): def __init__(self): self.board = None self.fitness = None def setBoard(self, val): self.board = val def setFitness(self, val): self.fitness = val #returns a randomized chess boar...
import time import logging from ..model import WebUser, WatchedUser, WatchedVideo, Task, TaskStatus,\ ItemOnline, ItemVideoStat, ItemUpStat, ItemRegionActivity,\ TaskFailed,TotalEnabledTask,TotalWatchedUser,TotalWatchedVideo from ..model import TYPE_MAP from ..model import snow from .. ...
from instabot import Bot from skimage.io import imread_collection from glob import glob from win10toast import ToastNotifier import random import json import os import urllib.request import time import requests import smtplib import smtplib from tkinter import * num=0 window = Tk() window.title("Photo...
#!/usr/bin/env python3 # MIT License # # Copyright (c) 2020 FABRIC Testbed # # 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 ...
# Concerning bias in convolutional layer: https://github.com/KaimingHe/deep-residual-networks/issues/10#issuecomment-194037195 import tensorflow as tf import numpy as np import sys from .util import * from . import config def shortcut(shortcut, residual, stride=1, activation=False, name=None, config=config.Co...
import datetime import os import warnings import click import pif import yaml from godaddypy import Client, Account from godaddypy.client import BadResponse class ConfigError(Exception): pass def update_ip(config_file, force): """Update the IP address for the configured domains/subdomains Parameters:...
# Future Imports for py2/3 backwards compat. from __future__ import (absolute_import, division, print_function, unicode_literals) from builtins import range from builtins import object from .nexpose_criteria_operators import * from .nexpose_criteria_constants import * from future import standard...
import json import requests import boto3 import re from operator import itemgetter from .helpers import logger, to_json, cidr_to_netmask, get_gateway_ip, waitfor from . import CITRIX_AWS_PRODUCTS ec2_client = boto3.client('ec2') def send_response(event, context, response_status, response_data, physical_resource_id...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Copyright (c) 2020 Cisco and/or its affiliates. This software is licensed to you under the terms of the Cisco Sample Code License, Version 1.1 (the "License"). You may obtain a copy of the License at https://developer.cisco.com/docs/licenses All use of t...
import re from sys import argv printn = lambda x : print(x, end='') operatorList = ['+', '-', '*', '/'] class Converter(object): opPrecedence = { '+' : 1, '-' : 1, '*' : 2, '/' : 2 } def SetExpression(self, expression): self.expression = expression def __init__(self, expression): self....
import re from creole import Parser from pygments import highlight from pygments.formatters import HtmlFormatter from pygments.lexers import get_lexer_by_name, TextLexer from pygments.util import ClassNotFound from biblion.models import Image class Rules: # For the link targets: proto = r'http|https|ftp|nnt...
#!/usr/bin/python # Copyright (c) 2017 Alibaba Group Holding Limited. <NAME> <<EMAIL>> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General...
"""Tests for settings validation.""" from typing import ClassVar import pytest from pydantic import ValidationError from pudl.settings import (DatasetsSettings, Eia860Settings, Eia923Settings, EiaSettings, EpaCemsSettings, Ferc1Settings, Ferc1ToSqliteSettings, Gen...
# Copyright 2017 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
# -*- coding: utf-8 -*- # # UDP: User Datagram Protocol # # Written in 2020 by Moky <<EMAIL>> # # ============================================================================== # MIT License # # Copyright (c) 2020 <NAME> # # Permission is hereby granted, free of charge, to any person ob...
import torch import itertools from prototype.prototype.model.vit.layers.patch_embedding import Linear_BN class Attention(torch.nn.Module): def __init__(self, dim, key_dim, num_heads=8, attn_ratio=4, activation=None, resolution=14): super().__init__() ...
import json import logging import pathlib from xml.etree import ElementTree from carim.configuration import decorators from carim.global_resources import types, item_type, matching_model, resourcesdir, mission, deploydir, locations from carim.util import file_writing log = logging.getLogger(__name__) _MAX_TIME = 3888...
import os import sys import argparse import numpy as np import torch import torch.optim as optim os_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(os_path) from utils import accuracy from utils import * from utils_plot import * import torch.nn as nn # Training setti...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import json import planetary_test_data import argparse try: import urllib.request as urllib except ImportError: import urllib class PlanetaryTestDataProducts(object): def __init__(self, tags=None, all_products=None, directory=None, ...
import _winreg import struct import datetime handle=_winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) tzparent=_winreg.OpenKey(handle, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones") parentsize=_winreg.QueryInfoKey(tzparent)[0] localkey=_winreg.OpenKey(handle, "SYSTEM\\C...