filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_13788
from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ class PhasmaDevice(models.Model): mac = models.CharField(_('media access control address'), max_length=127, primary_key=True, ...
the-stack_0_13790
__author__ = 'bptripp' import numpy as np import matplotlib.pyplot as plt import cPickle from quaternion import angle_between_quaterions # def interpolate(point, angle, points, angles, values, sigma_p=.01, sigma_a=(4*np.pi/180)): # """ # Gaussian kernel smoothing. # """ # # q = to_quaternion(get_rotat...
the-stack_0_13792
"""Represents a Concrete Strategy Object class for parsing PDF files. References: Lesson 4, Concept 8: Exercise - Strategy Objects https://classroom.udacity.com/nanodegrees/nd303/parts/bdd52131-b22e-4c57-b3f2-a03951c9d514/modules/5fe343a0-2926-4953-81bc-485ee835e1c6/lessons/cac8a587-58ea-44d2-927f-0c9badb7a8e9/con...
the-stack_0_13793
from six.moves import xrange import tensorflow as tf from .var_layer import VarLayer from ..tf import sparse_tensor_diag_matmul def conv(features, adj, weights): degree = tf.sparse_reduce_sum(adj, axis=1) + 1 degree = tf.cast(degree, tf.float32) degree = tf.pow(degree, -0.5) adj = sparse_tensor_dia...
the-stack_0_13795
#!/usr/bin/env python # Copyright 2015-2017 Yelp 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 ...
the-stack_0_13796
# Copyright (c) 2016, Matt Layman import os import sys import tempfile import unittest try: from unittest import mock except ImportError: import mock from tap import TAPTestRunner from tap.runner import TAPTestResult, _tracker class TestTAPTestRunner(unittest.TestCase): def test_has_tap_test_result(se...
the-stack_0_13799
# Aggregator class # : contains aggregate methods import logging from Queue import Empty from threading import Thread, Event from user_agents import parse logger = logging.getLogger('pwstat_aggregator') class Aggregator(Thread): def __init__(self, queue, writer, stat_list): Thread.__init__(self) ...
the-stack_0_13800
def is_prime(n): if n <= 1: return False elif n <= 3: return True elif n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True p = int(input().strip()) for _ in range(p)...
the-stack_0_13801
# # 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...
the-stack_0_13802
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Tests exercising the various classes in xmppserver.py.""" import unittest import base64 import xmppserver class XmlUtilsTest(unit...
the-stack_0_13803
# -*- coding: utf-8 -*- import torch import random import inspect import numpy as np from itertools import islice, repeat import os def check_path(path, exist_ok=False, log=print): """Check if `path` exists, makedirs if not else warning/IOError.""" if os.path.exists(path): if exist_ok: lo...
the-stack_0_13804
# Copyright 2020 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...
the-stack_0_13807
""" Devices. """ import attr import anyio from typing import List from .event import DeviceLocated, DeviceNotFound, DeviceValue, DeviceException from .error import IsDirError import logging logger = logging.getLogger(__name__) __all__ = ["Device"] @attr.s class NoLocationKnown(RuntimeError): device = attr.ib...
the-stack_0_13808
import torch from .observation_type import ObservationType def get_tensorrt_backend_config_dict(): """ Get the backend config dictionary for tensorrt backend NOTE: Current api will change in the future, it's just to unblock experimentation for new backends, please don't use it right now. """ weight...
the-stack_0_13811
# -*- coding: utf-8 -*- """ Copyright (c) 2018 Deepomatic SAS http://www.deepomatic.com/ 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 right...
the-stack_0_13813
#!/usr/bin/env python from tornado import httpclient, simple_httpclient, netutil from tornado.escape import json_decode, utf8, _unicode, recursive_unicode, native_str from tornado.httpserver import HTTPServer from tornado.httputil import HTTPHeaders from tornado.iostream import IOStream from tornado.simple_httpclient ...
the-stack_0_13814
#!/usr/bin/env python3 import os from torch.utils.data import Dataset, ConcatDataset from torchvision.datasets.omniglot import Omniglot import numpy as np import torch from torchvision import transforms class TripletOmniglot(Dataset): """ [[Source]]() **Description** This class provides an interfac...
the-stack_0_13815
import django_filters import netaddr from django.core.exceptions import ValidationError from django.db.models import Q from netaddr.core import AddrFormatError from nautobot.dcim.models import Device, Interface, Region, Site from nautobot.extras.filters import ( CustomFieldModelFilterSet, CreatedUpdatedFilterS...
the-stack_0_13816
"""Support for monitoring if a sensor value is below/above a threshold.""" import logging import voluptuous as vol from homeassistant.components.binary_sensor import ( DEVICE_CLASSES_SCHEMA, PLATFORM_SCHEMA, BinarySensorEntity, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_DEVICE_CLASS,...
the-stack_0_13820
#!/usr/bin/env python3 # # Copyright 2019 PSB # # 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 agree...
the-stack_0_13821
# Copyright (C) 2020 # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. """ Get detailed info about...
the-stack_0_13823
import os import shutil from collections import OrderedDict from shaper import manager, libs def test_create_folder(): temp_dir_name = 'test_folder' manager.create_folders(temp_dir_name) assert os.path.isdir(temp_dir_name) shutil.rmtree(temp_dir_name) def test_read_properties(test_assets_root): ...
the-stack_0_13825
import logging from unittest import TestCase import requests_mock from parameterized import parameterized from hvac.adapters import JSONAdapter from hvac.api.auth_methods import Okta class TestOkta(TestCase): TEST_MOUNT_POINT = "okta-test" TEST_USERNAME = "hvac-person" @parameterized.expand( [ ...
the-stack_0_13827
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the psort CLI tool.""" from __future__ import unicode_literals import argparse import os import unittest try: import resource except ImportError: resource = None from plaso.cli import psort_tool from plaso.cli.helpers import interface as helpers_interfa...
the-stack_0_13829
from optimism.JaxConfig import * from optimism import ReadMesh from optimism.material import Neohookean from optimism.material import LinearElastic from optimism import EquationSolver from optimism.SparseCholesky import SparseCholesky as Cholesky from optimism import SparseMatrixAssembler from optimism import Functio...
the-stack_0_13831
import logging from datetime import time from calendar_view.core.config import CalendarConfig from calendar_view.core.event import Event class InputData(object): def __init__(self, config: CalendarConfig, events: list): self.config = config self.events = events def validate_config(config: Calen...
the-stack_0_13833
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2010 Radim Rehurek <radimrehurek@seznam.cz> # Copyright (C) 2012 Lars Buitinck <larsmans@gmail.com> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """ Construct a corpus from a Wikipedia (or other MediaWiki-based) database dum...
the-stack_0_13835
import torch import torch.nn as nn from models.deconv import * from torchvision.models.utils import load_state_dict_from_url __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152', 'resnext50_32x4d', 'resnext101_32x8d', 'wide_resnet50_2', 'wide_resnet101_2'] model_ur...
the-stack_0_13836
import logging import os import click from cligj import ( precision_opt, indent_opt, compact_opt, projection_geographic_opt, projection_mercator_opt, projection_projected_opt, use_rs_opt, geojson_type_feature_opt, geojson_type_bbox_opt, geojson_type_collection_opt) from .helpers import write_features,...
the-stack_0_13837
import sys import selectors import socket import os sys.path.insert(0, "../") from messages.dns_request_message import * from messages.dns_response_message import * from messages.client_req_lb_message import * from messages.client_res_lb_message import * from messages.content_related_messages import * from config imp...
the-stack_0_13838
# coding=utf-8 # Copyright 2019 The Google UDA Team Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
the-stack_0_13839
from decimal import Decimal from django.contrib.auth import get_user_model from django.core.validators import MaxLengthValidator, MinValueValidator from rest_framework import serializers from snippets.models import LANGUAGE_CHOICES, STYLE_CHOICES, Snippet, SnippetViewer class LanguageSerializer(serializers.Serializ...
the-stack_0_13840
from datetime import date from django.db import models from django import forms from django.forms import ModelForm, Textarea, TextInput, NumberInput #from django.forms.extras.widgets import Select, SelectDateWidget from django.forms.widgets import EmailInput from django.conf import settings from django.core.exceptions ...
the-stack_0_13841
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # Copyright 2020 Huawei Technologies Co., Ltd # # 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....
the-stack_0_13842
# -*- coding: utf-8 -*- import re import scrapy import json from locations.items import GeojsonPointItem class StopAndShopSpider(scrapy.Spider): #download_delay = 0.2 name = "stop_and_shop" item_attributes = {'brand': "Stop and Shop"} allowed_domains = ["stopandshop.com"] start_urls = ( '...
the-stack_0_13845
# filter.py from pyspark import SparkContext sc = SparkContext("local", "Filter app") words = sc.parallelize( ["scala", "java", "hadoop", "spark", "akka", "spark vs hadoop", "pyspark", "pyspark and spark"] ) # words_filter = words.filter(lambda x: 'spark' in x) def g(x): for...
the-stack_0_13847
"""Compatibility fixes for older version of python, numpy and scipy If you add content to this file, please give the version of the package at which the fix is no longer needed. """ # Authors: Emmanuelle Gouillart <emmanuelle.gouillart@normalesup.org> # Gael Varoquaux <gael.varoquaux@normalesup.org> # ...
the-stack_0_13848
# vim:ts=4:sw=4:sts=4:et # -*- coding: utf-8 -*- """Additional auxiliary data types""" from itertools import islice class Matrix: """Simple matrix data type. Of course there are much more advanced matrix data types for Python (for instance, the C{ndarray} data type of Numeric Python) and this implementa...
the-stack_0_13851
from __future__ import unicode_literals import pytest from toolz import dissoc, merge from eth_utils import ( encode_hex, ) from eth_tester.exceptions import ( ValidationError, ) from eth_tester.validation import DefaultValidator @pytest.fixture def validator(): _validator = DefaultValidator() retu...
the-stack_0_13852
import torch from . import iou3d_cuda def boxes_iou_bev(boxes_a, boxes_b): """Calculate boxes IoU in the bird view. Args: boxes_a (torch.Tensor): Input boxes a with shape (M, 5). boxes_b (torch.Tensor): Input boxes b with shape (N, 5). Returns: ans_iou (torch.Tensor): IoU result...
the-stack_0_13853
# Copyright (c) 2021 PaddlePaddle 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 appli...
the-stack_0_13855
from dataclasses import asdict, dataclass from enum import Enum from typing import Any, Dict, List, Optional, Tuple from .regime import Regime class ClassementState(Enum): ACTIVE = 'ACTIVE' SUPPRIMEE = 'SUPPRIMEE' @dataclass class Classement: rubrique: str regime: Regime alinea: Optional[str] =...
the-stack_0_13856
from __future__ import print_function import argparse import os import time import numpy as np import torch import torch.optim as optim import torchvision.datasets as dset import torchvision.transforms as tforms from torchvision.utils import save_image import torch.utils.data as data from torch.utils.data import Dat...
the-stack_0_13858
#!/usr/bin/env python # -*- coding: UTF-8 -*- import rospy import math import numpy as np import matplotlib.pyplot as plt from std_msgs.msg import Bool from sensor_msgs.msg import LaserScan from geometry_msgs.msg import Twist class rplidarnav: def __init__(self): self.stop_flag = False rospy.init_...
the-stack_0_13859
from kipoiseq.dataloaders import SingleVariantUTRDataLoader class SingleVariantFramepoolDataloader(SingleVariantUTRDataLoader): def __init__( self, gtf_file, fasta_file, vcf_file, feature_type="5UTR", vcf_file_tbi=None, infer_from_cds=False, on_error_...
the-stack_0_13860
#!/usr/bin/python import math import datetime import dateutil.parser import dateutil.tz import csv import json DEBUG = True def void(): pass def log(x): print(x) debug_log = log if DEBUG else void def avg(items): return float(sum(items)) / max(len(items), 1) ISO_8601_UTC_MEAN = dateutil.tz.tzoffset(No...
the-stack_0_13863
import os import errno import fire import json import yaml import shutil from time import sleep import logging from boto3 import session from botocore.exceptions import ClientError logging.basicConfig( format='%(asctime)s|%(name).10s|%(levelname).5s: %(message)s', level=logging.WARNING) log = logging.getLogger...
the-stack_0_13864
""" Pontoon requires a very specific subset of functionality implemented in django allauth. Because of concerns related to the security concerns it's a better to keep only selected views and don't allow user to tamper with the state of an account. """ import importlib from django.urls import path from django.conf impo...
the-stack_0_13865
# -*- coding: utf-8 -*- ''' Support for YUM/DNF .. important:: If you feel that Salt should be using this module to manage packages on a minion, and it is using a different module (or gives an error similar to *'pkg.install' is not available*), see :ref:`here <module-provider-override>`. .. note:: ...
the-stack_0_13866
""" calc.py Core calculation logic for the runoff calculator. """ import math from collections import OrderedDict # dependencies (numpy included with ArcPy) import numpy # dependencies (3rd party) import petl as etl from .utils import msg QP_HEADER=['Y1','Y2','Y5','Y10','Y25','Y50','Y100','Y200','Y500','Y1000'] d...
the-stack_0_13867
# Copyright 2017 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 # # Unless required by applicable law or agreed to in wri...
the-stack_0_13868
import os import sys import json def read(): config = None default_config = { "DEFAULT": { "NETWORK_API_URL": "https://network.satnogs.org/api/", "DB_API_URL": "https://db.satnogs.org/api/", "DB_API_KEY": "", "HTTPS_PROXY": "", "HTTP_PROXY": ...
the-stack_0_13869
# Copyright (c) 2018 Pablo Moreno-Munoz # Universidad Carlos III de Madrid and University of Sheffield from GPy import kern from GPy.util import linalg import random import warnings import numpy as np import climin from functools import partial import matplotlib.pyplot as plt import VariationalOptimization as vo de...
the-stack_0_13870
#! /usr/bin/python3 import sys def resolve_overlap(o, n): if (o.x0 > n.x1 or o.x1 < n.x0 or o.y0 > n.y1 or o.y1 < n.y0 or o.z0 > n.z1 or o.z1 < n.z0): return {o, n} # No overlap if o.x0 < n.x0: if o.x1 > n.x1: # n sits fully within o on the x axis oa = Region(o.sta...
the-stack_0_13871
import os import json if __name__ == "__main__": total = 0 for data_file in os.listdir("./data/raw"): path = os.path.join("./data/raw", data_file) with open(path, "r") as f: data = json.loads(f.read()) total += len(data) print(total)
the-stack_0_13873
import Adafruit_GPIO.SPI as SPI import Adafruit_MCP3008 import RPi.GPIO as GPIO from time import sleep import urllib.request import time GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO_TRIGGER = 14 GPIO_ECHO = 15 ir = 16 CLK = 11 MISO = 9 MOSI = 10 CS = 8 GPIO.setup(GPIO_TRIGGER, GPIO.OUT) GPIO.setup(GPIO...
the-stack_0_13876
from datetime import timedelta from django.core.urlresolvers import reverse from django.utils.timezone import now import mock from funfactory.helpers import urlparams from nose.tools import eq_, ok_ from remo.base.tests import RemoTestCase from remo.base.utils import month2number from remo.profiles.tests import User...
the-stack_0_13877
# 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 agreed to in writing, s...
the-stack_0_13879
#!/usr/bin/env python """ Add face index attribute to mesh. """ import argparse import pymesh def parse_args(): parser = argparse.ArgumentParser( description=__doc__); parser.add_argument("input_mesh", help="input mesh"); parser.add_argument("output_mesh", help="output mesh"); return pars...
the-stack_0_13880
import argparse import os from datetime import datetime from ais import stream from pymongo import MongoClient, errors from src.functions import more_processing client = MongoClient('mongodb://useradmin:SOh3TbdfdgPxmt1@bigdata4.research.cs.dal.ca:27011/ais') # save to mongo def save_mongo(result): try: ...
the-stack_0_13883
__author__ = "Radical.Utils Development Team" __copyright__ = "Copyright 2016, RADICAL@Rutgers" __license__ = "MIT" # ------------------------------------------------------------------------------ # # We provide a json based config file parser with following properties # # - system config files will be merged...
the-stack_0_13884
# -*- coding: utf-8 -*- ''' Operations on regular files, special files, directories, and symlinks ===================================================================== Salt States can aggressively manipulate files on a system. There are a number of ways in which files can be managed. Regular files can be enforced wit...
the-stack_0_13886
# ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # --------------------------------------------...
the-stack_0_13893
from fastjsonschema import JsonSchemaException from src.utils.errors import SDerror def validate_body(data, validator): try: validator(data) except JsonSchemaException as e: raise SDerror( message="Invalid request body", status_code=400, error_type="JsonSc...
the-stack_0_13895
import logging from xml.etree.ElementTree import Element from jmeter_api.basics.config.elements import BasicConfig from jmeter_api.basics.utils import Renderable, FileEncoding, tree_to_str class Counter(BasicConfig, Renderable): root_element_name = 'CounterConfig' def __init__(self, *, st...
the-stack_0_13897
# Copyright 2013-2014 Massachusetts Open Cloud Contributors # # 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 applicab...
the-stack_0_13898
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil; coding: utf-8 -*- # ex: set sts=4 ts=4 sw=4 et: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and license terms. ...
the-stack_0_13899
import time from handler.base_plugin import BasePlugin class AntifloodPlugin(BasePlugin): __slots__ = ("users", "delay", "absolute", "absolute_time") def __init__(self, delay=1, absolute=False): """ Forbids users to send messages to bot more often than delay `delay`. If `absolute` is True, bot ...
the-stack_0_13902
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 # # 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 wit...
the-stack_0_13903
"""Config flow for ReCollect Waste integration.""" from __future__ import annotations from aiorecollect.client import Client from aiorecollect.errors import RecollectError import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_FRIENDLY_NAME from homeassistant.core impor...
the-stack_0_13905
#!/usr/bin/env python """ Extract outline edges of a given mesh and save them into '<original path>/edge_<original mesh file name>.vtk' or into a user defined output file. The outline edge is an edge for which norm(nvec1 - nvec2) < eps, where nvec1 and nvec2 are the normal vectors of the incident facets. """ from __fut...
the-stack_0_13907
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # 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/LICEN...
the-stack_0_13909
import praw import os import sys from datetime import date import shutil import requests import mimetypes import logging import pprint from redvid import Downloader logger = logging.getLogger(__name__) class SubredditScraper(): def __init__(self, subreddit, output, batch_size=10): mimetypes.init() ...
the-stack_0_13915
#----------------------------------------WEATHER APPLICATION---------------------------------------- import tkinter as tk import requests from tkinter import font #--------------------------------------FUNCTION FOR DISPLAYING THE WEATHER CONDITIONS------------------------ def get_result(weather): try:...
the-stack_0_13916
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # 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 Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) an...
the-stack_0_13917
# -*- coding: utf-8 -*- import copy import logging import warnings from ruamel.yaml import YAML from great_expectations.data_context.util import ( instantiate_class_from_config, load_class, verify_dynamic_loading_support, ) from great_expectations.exceptions import ClassInstantiationError from great_expe...
the-stack_0_13918
# Advent of Code 2020 # # From https://adventofcode.com/2020/day/10 # from collections import Counter from math import prod import networkx as nx import numpy as np adapters = np.sort(np.array(list(map(int, [row.strip() for row in open('../inputs/Advent2020_10.txt', 'r')])))) adapters = np.insert(adapters, 0, 0., axi...
the-stack_0_13920
# Copyright (c) 2014 Vlad Temian <vladtemian@gmail.com> # Copyright (c) 2015-2020 Claudiu Popa <pcmanticore@gmail.com> # Copyright (c) 2015 Ionel Cristian Maries <contact@ionelmc.ro> # Copyright (c) 2017 guillaume2 <guillaume.peillex@gmail.col> # Copyright (c) 2019-2021 Pierre Sassoulas <pierre.sassoulas@gmail.com> # C...
the-stack_0_13921
#!/usr/bin/env python # coding=utf-8 # # Copyright (c) 2013-2015 First Flamingo Enterprise B.V. # # 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...
the-stack_0_13922
# 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...
the-stack_0_13923
def create_lr_scheduler(optimizer, config, max_epochs, num_training_instances): if 'lr-scheduler' not in config: return MyNoneScheduler(optimizer) elif config['lr-scheduler']['type'] == 'linear-decay': return MyLinearDecayScheduler(optimizer, config['lr-scheduler'], max_epochs, num_training_inst...
the-stack_0_13924
from .base_dataset import Dataset import numpy as np import pandas as pd import os.path class CSVDataset(Dataset): """ CSVDataset class. Provide access to the Boston Housing Prices dataset. """ def __init__(self, target_column, transform=None, mode="train", input_data=None, *args, **kwargs): ...
the-stack_0_13927
# coding: utf-8 from __future__ import unicode_literals import re import random from .common import InfoExtractor from ..utils import ( int_or_none, float_or_none, unified_strdate, ) class PornoVoisinesIE(InfoExtractor): _VALID_URL = r'http://(?:www\.)?pornovoisines\.com/showvideo/(?P<id>\d+)/(?P<di...
the-stack_0_13930
# coding: utf-8 import sys sys.path.append('..') from Natural_Language_Processing.common.util import preprocess, create_co_matrix, most_similar text = 'You say goodbye and I say hello.' corpus, word_to_id, id_to_word = preprocess(text) vocab_size = len(word_to_id) C = create_co_matrix(corpus, vocab_size) most_similar...
the-stack_0_13931
#!/usr/bin/env python import rospy from std_msgs.msg import Int32 from geometry_msgs.msg import PoseStamped, Pose from styx_msgs.msg import TrafficLightArray, TrafficLight from styx_msgs.msg import Lane from sensor_msgs.msg import Image from cv_bridge import CvBridge from light_classification.tl_classifier import TLCla...
the-stack_0_13935
# -*- coding: utf-8 -*- # Copyright 2019 Cohesity Inc. import cohesity_management_sdk.models.run_job_snapshot_target import cohesity_management_sdk.models.run_now_parameters class RunProtectionJobParam(object): """Implementation of the 'RunProtectionJobParam' model. Specify the parameters to run a protectio...
the-stack_0_13936
#!/usr/bin/python # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
the-stack_0_13937
import pandas as pd import numpy as np # Define functions for model def confirmed_to_onset(confirmed, p_delay, col_name='num_cases', min_onset_date=None): min_onset_date = pd.to_datetime(min_onset_date) # Reverse cases so that we convolve into the past convolved = np.convolve(np.squeeze(confirmed.iloc[::-1...
the-stack_0_13939
#!/usr/bin/env python ############################################################################## # Copyright (c) 2015 Huawei Technologies Co.,Ltd and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompan...
the-stack_0_13941
"""empty message Revision ID: 5e78cc772642 Revises: ec21bd75ea92 Create Date: 2020-07-22 22:44:45.754328 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '5e78cc772642' down_revision = 'ec21bd75ea92' branch_labels = None depends_on = None def upgrade(): # ...
the-stack_0_13942
import numpy as np def validate_points(points: np.array) -> np.array: # If the user is tracking only a single point, reformat it slightly. if points.shape == (2,): points = points[np.newaxis, ...] elif len(points.shape) == 1: raise_detection_error(points) else: if points.shape[...
the-stack_0_13943
"""Visualize learned representation.""" import os import argparse import importlib import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.pylab as pylab params = {'legend.fontsize': 'large', 'axes.labelsize': 'x-large', 'axes.titlesize':'x-large',...
the-stack_0_13946
import bblfsh_sonar_checks.utils as utils import bblfsh def check(uast): findings = [] methods = utils.get_methods(uast) for m in methods: # Should look at the roles to filter by Boolean but there is a bug in the # Java driver https://github.com/bblf../../java-driver/issues/83 so we chec...
the-stack_0_13948
""" Tests for DatetimeIndex methods behaving like their Timestamp counterparts """ from datetime import datetime import numpy as np import pytest from pandas._libs.tslibs import OutOfBoundsDatetime, to_offset from pandas._libs.tslibs.offsets import INVALID_FREQ_ERR_MSG import pandas as pd from pandas imp...
the-stack_0_13949
# This file is part of QuTiP: Quantum Toolbox in Python. # # Copyright (c) 2011 and later, 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...
the-stack_0_13950
import requests import json import os from github import Github BASE = """--- id: default_repositories title: Default repositories description: "Default repositories in HACS" --- <!-- The content of this file is autogenerated during build with script/generate_default_repositories.py --> """ github = Github(os.environ...
the-stack_0_13952
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: sum = 0 def sumRootToLeaf(self, root: TreeNode) -> int: def dfs(root, path_sum): ...
the-stack_0_13956
exp = str(input('Digite uma expressão: ')) pilha = [] for simb in exp: if simb == '(': pilha.append('(') elif simb == ')': if len(pilha) > 0: pilha.pop() else: pilha.append(')') break if len(pilha) == 0: print('Sua expressão está válida!') else: ...
the-stack_0_13957
# -*- coding: utf-8 -*- """ Class definition of YOLO_v3 style detection model on image and video """ import colorsys import os from timeit import default_timer as timer import numpy as np import tensorflow.compat.v1.keras.backend as K from tensorflow.compat.v1.keras.backend import get_session from tensorflow.keras.mo...
the-stack_0_13959
# to run this script you need a DL1 debug files of hipeRTA and a DL1 file from lstchain from the same run import tables import numpy as np import matplotlib.pyplot as plt from ctapipe.visualization import CameraDisplay from ctapipe.instrument import CameraGeometry from ctapipe.image import tailcuts_clean from lstchai...