id
stringlengths
3
8
content
stringlengths
100
981k
404386
from utils import * class MetaDataParser(object): def __init__(self): # sentiment files train_sentiment_files = sorted(glob.glob('../../input/petfinder-adoption-prediction/train_sentiment/*.json')) test_sentiment_files = sorted(glob.glob('../../input/petfinder-adoption-prediction/test_sent...
404405
import random from typing import Dict from framework.data_generator.replay.replay_generator import ReplayDownloaderGenerator from framework.replay.replay_format import GeneratedHit class HitGenerator(ReplayDownloaderGenerator): def __init__(self, **kwargs): super().__init__(**kwargs) ...
404408
import scipy.io import scipy.stats import numpy as np from EasyTL import EasyTL import time if __name__ == "__main__": datadir = r"D:\Datasets\EasyTL\amazon_review" str_domain = ["books", "dvd", "elec", "kitchen"] list_acc = [] for i in range(len(str_domain)): for j in range(len(str_domain)): if i == j: ...
404434
from common_fixtures import * # NOQA def test_create_k8s_container_no_k8s(context): c = context.create_container(labels={ 'io.kubernetes.pod.namespace': 'n', 'io.kubernetes.pod.name': 'p', 'io.kubernetes.container.name': 'POD', }) c = context.client.wait_success(c) assert c.st...
404442
from core.providers.aws.boto3 import prepare_aws_client_with_given_cred import boto3 def get_event_client(aws_auth_cred): """ Returns the client object for AWS Events Args: aws_auth (dict): Dict containing AWS credentials Returns: obj: AWS Cloudwatch Event Client Obj """ retu...
404474
import time import cv2 import numpy as np import glob import os import dlib import argparse imgMustache = cv2.imread("mustache.png", -1) orig_mask = imgMustache[:,:,3] orig_mask_inv = cv2.bitwise_not(orig_mask) imgMustache = imgMustache[:,:,0:3] origMustacheHeight, origMustacheWidth = imgMustache.shape[:2] imgGlass =...
404481
from wingedsheep.carcassonne.objects.coordinate_with_side import CoordinateWithSide class City: def __init__(self, city_positions: [CoordinateWithSide], finished: bool): self.city_positions = city_positions self.finished = finished
404515
from bentoml import env, artifacts, api, BentoService from bentoml.adapters import JsonInput @env(infer_pip_packages=True) class ScoreIdentifier(BentoService): """ A score identifier service that returns a score based on the given data """ @api(input=JsonInput()) def predict(self, parsed_json): ...
404544
from logging import getLogger import numpy from rdkit.Chem import rdMolDescriptors from chainer_chemistry.dataset.preprocessors.common import MolFeatureExtractionError # NOQA from chainer_chemistry.dataset.preprocessors.mol_preprocessor import MolPreprocessor # NOQA class ECFPPreprocessor(MolPreprocessor): d...
404599
import c3d import struct import unittest import numpy as np def genByteWordArr(word, shape): ''' Generate a multi-dimensional byte array from a specific word. ''' arr = np.array(word) for d in shape[::-1]: arr = arr[np.newaxis].repeat(d, 0) return arr, [len(word)] + [d for d in shape] ...
404603
import logging import collections from werkzeug.utils import cached_property # Source realms, to differentiate sources in the site itself ('User') # and sources in the site's theme ('Theme'). REALM_USER = 0 REALM_THEME = 1 REALM_NAMES = { REALM_USER: 'User', REALM_THEME: 'Theme'} # Types of relationships a ...
404609
import copy import json import os from typing import Optional from experiments.src.gin.gin_utils import bind_parameters_from_dict from experiments.src.training.training_train_model import train_model from src.huggingmolecules.featurization.featurization_api import PretrainedFeaturizerMixin from src.huggingmolecules.mo...
404683
import pytest from bvspca.animals.management.commands.sync_petpoint_data import Command from bvspca.animals.models import AnimalCountSettings @pytest.mark.django_db def test_decrement_animal_count(): animal_settings = AnimalCountSettings.objects.get(pk=1) animal_settings.cats_adopted = 22 animal_settings...
404687
from django.db import models class BackupFile(models.Model): backup_file = models.FileField(upload_to="backup_mp3")
404689
from collections import OrderedDict def load_pytorch_pretrain_model(paddle_model, pytorch_state_dict): ''' paddle_model: dygraph layer object pytorch_state_dict: pytorch state_dict, assume in CPU device ''' paddle_weight=paddle_model.state_dict() print("paddle num_params:",len(paddle_weight)) ...
404730
import pytest from busy_beaver.blueprints.tasks.retweeter import start_post_tweets_to_slack_task from busy_beaver.models import PostTweetTask from busy_beaver.tasks.retweeter import fetch_tweets_post_to_slack MODULE_TO_TEST = "busy_beaver.blueprints.tasks.retweeter" @pytest.fixture def patched_retweeter_trigger(moc...
404740
import logging import requests from typing import Dict from confluence.exceptions.generalerror import ConfluenceError logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) class ConfluenceAuthenticationError(ConfluenceError): """This exception corresponds to 401 errors on the REST API.""...
404769
from twilio.twiml.voice_response import VoiceResponse, Start, Stream response = VoiceResponse() start = Start() start.stream( name='Example Audio Stream', url='wss://mystream.ngrok.io/audiostream' ) response.append(start) print(response)
404781
import logging from common.requester import DelayedRequester from common.storage.image import ImageStore from util.loader import provider_details as prov LIMIT = 1000 DELAY = 5.0 RETRIES = 3 PROVIDER = prov.CLEVELAND_DEFAULT_PROVIDER ENDPOINT = 'http://openaccess-api.clevelandart.org/api/artworks/' delay_request = De...
404844
import re from conans import CMake, ConanFile, tools def get_version(): try: content = tools.load("CMakeLists.txt") version = re.search("set\\(ASIOCHAN_VERSION (.*)\\)", content).group(1) return version.strip() except OSError: return None class AsioChan(ConanFile): name ...
404858
import json import re import base64 import pprint from app.services import FormFillerService def test_vr_en_form(app, db_session, client): payload_file = 'app/services/tests/test-vr-en-payload.json' with open(payload_file) as payload_f: payload = json.load(payload_f) ffs = FormFillerService(payload=payloa...
404905
import os from os.path import dirname, join, abspath from unittest.case import TestCase from unittest.suite import TestSuite from subprocess import STDOUT, check_output, CalledProcessError from numba.testing.ddt import ddt, data from numba.testing.notebook import NotebookTest from numba import cuda # setup coverage d...
404931
from django.conf import settings from elasticsearch_dsl import Search, Index, DocType, Date, Text, Nested from elasticsearch_dsl import InnerObjectWrapper from elasticsearch_dsl.connections import connections connections.create_connection( hosts=[settings.ES_URL], **settings.ES_CONNECTION_PARAMS ) def make_se...
404937
import torch import torch.nn as nn import torch.nn.init as nn_init from .components import FlowNetC, FlowNetS, FlowNetSD, FlowNetFusion # (Yuliang) Change directory structure from .components import tofp16, tofp32, save_grad from .components import ChannelNorm, Resample2d class FlowNet2(nn.Module): def __init__...
405012
import logging from telebot import TeleBot, logger from config import Config bot = TeleBot( token=Config.TELEGRAM_BOT_RELEASE_TOKEN, threaded=Config.IS_THREADED_BOT ) logger.setLevel(logging.INFO) from tg_bot import handlers
405027
from __future__ import print_function import sys, os sys.path.insert(1, os.path.join("..","..","..")) import h2o from tests import pyunit_utils from h2o.estimators.extended_isolation_forest import H2OExtendedIsolationForestEstimator def extended_isolation_forest(): print("Extended Isolation Forest Smoke Test") ...
405054
import responses from binance.spot import Spot as Client from tests.util import random_str from tests.util import mock_http_response mock_item = {"key_1": "value_1", "key_2": "value_2"} mock_exception = {"code": -1, "msg": "error message"} key = random_str() secret = random_str() @mock_http_response(responses.POST...
405070
from typing import Any from typing import Callable from typing import List from typing import Union from notion_client import Client from notion_scholar.publication import Publication class Property: @staticmethod def title(value: str) -> dict: return {'title': [{'text': {'content': value}}]} @...
405087
import bridgekeeper import pytest @pytest.yield_fixture(autouse=True) def clean_global_permissions_map(): for k in list(bridgekeeper.perms.keys()): del bridgekeeper.perms[k] yield
405103
from collections import defaultdict from typing import Dict, Any, List, Optional from fluidml.common import Task from fluidml.common.exception import TaskResultKeyAlreadyExists, TaskResultObjectMissing from fluidml.storage import ResultsStore def pack_results(all_tasks: List[Task], results_store: Re...
405163
import pymysql connection = pymysql.connect(host="localhost", user="user", password="<PASSWORD>") cursor = connection.cursor() cursor.execute("some sql", (42,)) # $ getSql="some sql"
405170
from rllab.baselines.linear_feature_baseline import LinearFeatureBaseline from sandbox.ours.envs.normalized_env import normalize from sandbox.ours.envs.base import TfEnv from sandbox.ours.policies.improved_gauss_mlp_policy import GaussianMLPPolicy from rllab.misc.instrument import run_experiment_lite from rllab.misc.in...
405174
import numpy as np from precise.skaters.managers.covmanagerfactory import static_cov_manager_factory_d0 from precise.skaters.portfoliostatic.equalport import equal_long_port from precise.skaters.covariance.identity import identity_scov from precise.skaters.managers.buyandholdfactory import buy_and_hold_manager_factory ...
405185
import json from .common import SearpcError def _fret_int(ret_str): try: dicts = json.loads(ret_str) except: raise SearpcError('Invalid response format') if 'err_code' in dicts: raise SearpcError(dicts['err_msg']) if 'ret' in dicts: return dicts['ret'] else: ...
405214
from dataclasses import dataclass from typing import List import numpy as np from paralleldomain.model.annotation.common import Annotation from paralleldomain.utilities.mask import boolean_mask_by_value, boolean_mask_by_values, encode_int32_as_rgb8 @dataclass class SemanticSegmentation2D(Annotation): """Represe...
405219
import json from pyevt import abi, address, ecc, libevt libevt.init_lib() # Type and Structures class BaseType: def __init__(self, **kwargs): self.kwargs = kwargs def dict(self): return self.kwargs def dumps(self): return json.dumps(self.kwargs) class User: def __init__(...
405250
from datetime import datetime from elasticsearch import ConflictError from ocd_backend import celery_app from ocd_backend import settings from ocd_backend.es import elasticsearch from ocd_backend.exceptions import ConfigurationError from ocd_backend.log import get_source_logger from ocd_backend.mixins import (OCDBack...
405255
from flask import Blueprint from flask_restx import Api from orca.api.apis.v1 import graph as graph_ns from orca.api.apis.v1 import ingestor as ingestor_ns from orca.api.apis.v1 import alerts as alerts_ns def initialize(graph): blueprint = Blueprint('api', __name__, url_prefix='/v1') api = Api(blueprint, titl...
405277
import unittest from tests.utils import TestHarness, tasks, TaskErrorException @tasks.bind() def hello_workflow(first_name='Jane', last_name='Doe'): return f'Hello {first_name} {last_name}' @tasks.bind() def pass_into_multi_arg_workflow(initial_return, *args, **kwargs): return tasks.send(pass_through, *ini...
405287
from pprint import pprint from pynso.client import NSOClient from pynso.datastores import DatastoreType # Setup a client client = NSOClient('10.159.91.14', 'admin', 'admin') # Get information about the API print('Getting API version number') pprint(client.info()['version']) # Get the information about the running d...
405345
import tensorflow as tf import numpy as np import os import pandas as pd import matplotlib.pyplot as plt MODEL_NAME = "" CLIP = True # if your model was trained with np.clip to clip values CLIP_VAL = 10 # if above, what was the value +/- model = tf.keras.models.load_model(MODEL_NAME) VALDIR = 'validation_data' ...
405372
import FWCore.ParameterSet.Config as cms # adapt the L1TMonitor_cff configuration to offline DQM # DQM online L1 Trigger modules from DQM.L1TMonitor.L1TMonitor_cff import * # DTTF to offline configuration l1tDttf.online = False # input tag for BXTimining bxTiming.FedSource = 'rawDataCollector'
405384
from django.conf.urls import url from kitsune.motidings import views # Note: This overrides the tidings tidings.unsubscribe url pattern, so # we need to keep the name exactly as it is. urlpatterns = [ url(r"^unsubscribe/(?P<watch_id>\d+)$", views.unsubscribe, name="tidings.unsubscribe") ]
405395
import websockets import asyncio class WSserver(): async def handle(self,websocket,path): recv_msg = await websocket.recv() print("i received %s" %recv_msg) await websocket.send('server send ok') def run(self): ser = websockets.serve(self.handle,"192.168.43.51","1111") asyncio.ge...
405428
import featuretools as ft import pandas as pd import os from tqdm import tqdm def make_user_sample(orders, order_products, departments, products, user_ids, out_dir): orders_sample = orders[orders["user_id"].isin(user_ids)] orders_keep = orders_sample["order_id"].values order_products_sample = order_produ...
405432
import torch # Creating the graph x = torch.tensor(1.0, requires_grad = True) y = torch.tensor(2.0) z = x * y # Displaying for i, name in zip([x, y, z], "xyz"): print(f"{name}\ndata: {i.data}\nrequires_grad: {i.requires_grad}\n\ grad: {i.grad}\ngrad_fn: {i.grad_fn}\nis_leaf: {i.is_leaf}\n")
405445
import caffe import numpy as np import os import sys import lang_seg_model as segmodel from util.processing_tools import * import train_config def train(config): with open('./lang_seg_model/proto_train.prototxt', 'w') as f: f.write(str(segmodel.generate_model('train', config))) caffe.set_device(conf...
405453
import sys import numpy as np from data.format import Events class VoxelGrid: def __init__(self, num_bins: int=5, width: int=640, height: int=480, upsample_rate: int=1): assert num_bins > 1 assert height > 0 assert width > 0 self.num_bins = num_bins self.width = width ...
405546
import copy from unittest import mock import graphene import pytest from ....plugins.error_codes import PluginErrorCode from ....plugins.manager import get_plugins_manager from ....plugins.models import PluginConfiguration from ....plugins.tests.sample_plugins import ChannelPluginSample, PluginSample from ....plugins...
405614
import logging logger = logging.getLogger(__name__) def discover(): """ Auto-discover any Gutter configuration present in the django INSTALLED_APPS. """ from django.conf import settings from django.utils.importlib import import_module for app in settings.INSTALLED_APPS: module =...
405661
from django.contrib import admin from grandchallenge.publications.forms import PublicationForm from grandchallenge.publications.models import Publication class PublicationAdmin(admin.ModelAdmin): list_display = [ "identifier", "year", "title", "referenced_by_count", "citat...
405675
import snoop @snoop def main(): try: @int def foo(): pass except: pass if __name__ == '__main__': main()
405694
from pub import Pub class RecordthresherPub(Pub): def __init__(self, **kwargs): super().__init__(**kwargs) self._authors = None @property def authors(self): return self._authors @authors.setter def authors(self, authors): self._authors = authors @property ...
405733
import os import fileinput for f in os.listdir('.'): if ".md" in f: # Read in the file with open(f, 'r') as file : filedata = file.read() # Replace the target string filedata = filedata.replace('\n', ' \n') filedata = filedata.replace(' ?', chr(160)+"?") ...
405741
from __future__ import division, print_function import os import shutil import theano import theano.tensor as T from blocks.extensions.saveload import Checkpoint from plat.sampling import grid_from_latents from plat.grid_layout import create_chain_grid from plat.fuel_helper import get_anchor_images class SampleChec...
405744
from __future__ import absolute_import from . import caffe_pb2 as pb import google.protobuf.text_format as text_format import numpy as np from .layer_parameter import LayerParameter class _Net(object): def __init__(self): self.net = pb.NetParameter() self.name_dict = {} self.add_layer_set...
405763
import os import sys import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import seaborn as sns from os.path import join from algorithms.utils import summaries_dir, experiment_dir, experiments_dir, ensure_dir_exists from utils.utils import log sns.set() COLORS = ['blue', 'green', 'red', 'cy...
405769
class Solution(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ First = ['Q','W','E','R','T','Y','U','I','O','P'] SEC = ['A','S','D','F','G','H','J','K','L'] LAST= ['Z','X','C','V','B','N','M'] answer = [] f...
405854
class Solution: def shortestPalindrome(self, s: str) -> str: temp = s + '#' + s[::-1] i = 1 l = 0 lps = [0] * len(temp) while i < len(temp): if temp[i] == temp[l]: lps[i] = l + 1 i += 1 l += 1 elif l != 0...
405865
from bibliopixel.animation.strip import Strip from bibliopixel.colors import COLORS, make, palette from bibliopixel.colors.arithmetic import color_scale, color_blend from numpy import random, concatenate """ Emitter animation By <NAME> 4/1/2019 A strip animation with particle system emitters. Watch a video describi...
405878
from __future__ import unicode_literals from six import text_type from database_sanitizer.session import hash_text_to_int, hash_text_to_ints def sanitize_email(value): if not value: return value (num1, num2, num3) = hash_text_to_ints(value.strip(), [16, 16, 32]) given_name = given_names[num1 % g...
405886
import unittest import torch import numpy as np import os import shutil import neural_network_lyapunov.dynamics_learning as dynamics_learning import neural_network_lyapunov.worlds as worlds import neural_network_lyapunov.encoders as encoders import neural_network_lyapunov.relu_system as relu_system import neural_netwo...
405903
import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDHarvester import DQMEDHarvester rpcDCSSummary = DQMEDHarvester("RPCDCSSummary", NumberOfEndcapDisks = cms.untracked.int32(4), )
405929
from tomviz import utils import numpy as np import tomviz.operators class CenterOfMassAlignmentOperator(tomviz.operators.CancelableOperator): def transform_scalars(self, dataset): """Automatically align tilt images by center of mass method""" self.progress.maximum = 1 tiltSeries = utils....
405939
from aws_cdk import core from aws_cdk.aws_ec2 import Vpc, NatProvider, SubnetConfiguration, SubnetType class NetworkStack(core.Stack): def __init__(self, scope: core.Construct, id: str, props, **kwargs) -> None: super().__init__(scope, id, **kwargs) # Subnet configurations for a public and priva...
405968
from __future__ import print_function import pandas as pd df = pd.read_csv("validation-metadata.csv").fillna(value='') df.loc[df.column_name == 'id', 'column_name'] = 'name' df.loc[df.foreign_column == 'id', 'foreign_column'] = 'name' # Remove "_id" from column names for idx, row in df.iterrows(): col_name = ro...
405971
from typing import Tuple import itertools import re import numpy as np import GPy from emukit.model_wrappers.gpy_model_wrappers import GPyModelWrapper from ..parameters.cfg_parameter import CFGParameter from ..parameters.string_parameter import StringParameter from ..parameters.protein_base_parameter import ProteinBas...
405973
import unittest import os from hamlpy.ext import has_any_extension class ExtTest(unittest.TestCase): """ Tests for methods found in ../ext.py """ def test_has_any_extension(self): extensions = [ 'hamlpy', 'haml', '.txt' ] # no directory ...
405983
import re import logging # Console colors W = '\033[0m' # white (normal) R = '\033[31m' # red G = '\033[32m' # green # regex for timestamp patched masscan grepable output reg1 = re.compile('^Timestamp: (?P<Timestamp>\d+)\tHost: (?P<IP>\d+.\d+.\d+.\d+) \(\)\tPort: (?P<Port>\d+)\tService: title\tBanner: (?P<Info>.*)$'...
405986
import rdtest import renderdoc as rd class GL_Buffer_Truncation(rdtest.Buffer_Truncation): demos_test_name = 'GL_Buffer_Truncation' internal = False
405988
import logging import os from dotenv import load_dotenv from objdict import ObjDict import json import requests from impl.timer import timefunc from impl.parser import Parser load_dotenv() def set_log_level(debug): """ :param debug: Boolean value :return: None """ if bool(debug): logging...
405992
import asyncio import os import subprocess import tempfile from pathlib import Path from .version import VERSION __all__ = [ 'AsyncPydf', 'generate_pdf', 'get_version', 'get_help', 'get_extended_help', ] THIS_DIR = Path(__file__).parent.resolve() WK_PATH = os.getenv('WKHTMLTOPDF_PATH', str(THIS_D...
406007
import urllib import os import time import requests import uuid import json import zipfile import base64 from azure.storage.table import TableService, Entity, TablePermissions STORAGE_ACCOUNT_NAME = os.environ['STORAGE_ACCOUNT_NAME'] STORAGE_ACCOUNT_KEY = os.environ['STORAGE_ACCOUNT_KEY'] DATABRICKS_API_BASE_URL = os...
406008
import unittest from unittest.mock import patch, MagicMock from datetime import timedelta import json import os import threading import signal import subprocess import tempfile import sys from osgar.record import Recorder class Sleeper: def __init__(self, cfg, bus): self.e = threading.Event() def s...
406010
from quick_orm.core import Database from sqlalchemy import Column, String class DefaultModel: name = Column(String(70)) __metaclass__ = Database.MetaBuilder(DefaultModel) class User: pass class Group: pass Database.register() if __name__ == '__main__': db = Database('sqlite://') ...
406013
from dataclasses import dataclass from typing import Dict, Any, Optional from lighttree.interactive import Obj from elasticsearch import Elasticsearch from pandagg import Mappings, MappingsDict from pandagg.interactive.mappings import IMappings from pandagg.search import Search @dataclass class Index: name: str...
406028
import os import numpy as np from string import ascii_uppercase from io_spatial import do_rotation, rotate_check from io_helpers import make_grid, are_you_numpy from collections import OrderedDict import gzip ### Written by <NAME>, AG Klebe Marburg University ### 08/2016 class field (object): """ This is a c...
406034
import pandas as pd import os from typing import Union import numpy as np import matplotlib.pyplot as plt import seaborn as sns import matplotlib as mpl def series_to_colors(s: pd.Series, color_palette_map: str = 'husl', cdict: dict = None): """ Convert a pandas series to a color_map. ---------------------...
406097
import json import sys import os from typing import List import semver ROOT_DIR = os.path.dirname(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir)) APACHE_AIRFLOW_ARCHIVE = os.path.join(ROOT_DIR, "docs-archive") def get_all_versions(directory: str) -> List[str]: return sorted( (...
406107
import os import pytest import yaml from dbt.tests.util import run_dbt from tests.functional.sources.fixtures import ( models__schema_yml, models__view_model_sql, models__ephemeral_model_sql, models__descendant_model_sql, models__multi_source_model_sql, models__nonsource_descendant_sql, see...
406148
import numpy as np def net_2_deeper_net(bias, noise_std=0.01): """ This is a similar idea to net 2 deeper net from http://arxiv.org/pdf/1511.05641.pdf Assumes that this is a linear layer that is being extended and also adds some noise Args: bias (numpy.array): The bias for the layer we are ad...
406170
import os from typing import Union, Tuple, List, NamedTuple import torch from torch import nn, Tensor from torch.nn import functional as F from torch.optim import Optimizer from torch.optim.lr_scheduler import _LRScheduler from backbone.base import Base as BackboneBase from bbox import BBox from nms.nms import NMS fr...
406198
import pytest from configmanager import Config, Item, RequiredValueMissing, Types, NotFound def test_simple_config(): # Initialisation of a config manager config = Config({ 'greeting': 'Hello, world!', 'threads': 1, 'throttling_enabled': False, }) # Attribute-based and key-ba...
406237
from django.http.response import HttpResponse from django.shortcuts import render, get_object_or_404 from .models import * # Create your views here. def index(request): warehouses = Warehouse.objects.all() orders = Order.objects.filter(tracking="Pending") context = { "warehouse": warehouses, ...
406265
deleteObject = True editObject = True getObject = {'id': 1234, 'fingerprint': 'aa:bb:cc:dd', 'label': 'label', 'notes': 'notes', 'key': 'ssh-rsa AAAAB3N...pa67 <EMAIL>'} createObject = getObject getAllObjects = [getObject]
406306
import sys from optparse import OptionParser from qrencode import encode_scaled, QR_ECLEVEL_H from prettyqr.blobgrid import BlobGrid from prettyqr.logos import clear_logo_space, get_svg_logo from prettyqr.svg import svg_start, svg_end def main(): parser = OptionParser( usage="usage: %prog [options] text")...
406327
import medic from maya import OpenMaya class NonUniqueName(medic.PyTester): def __init__(self): super(NonUniqueName, self).__init__() def Name(self): return "NonUniqueName" def Description(self): return "Non unique name(s) exists" def Match(self, node): return node.o...
406365
import os import subprocess import argparse parser = argparse.ArgumentParser() parser.add_argument('--profiling', type=str, default='NO', help='Run with profiler? - (YES/NO)') parser.add_argument('--case_start', type=str, default='0', help='Testing range starting case # - (0-83)') parser.add_argument('--case_end', typ...
406427
import os import datetime import numpy as np import tensorflow as tf from sacred import Experiment from sacred.observers import FileStorageObserver, RunObserver from deep_rlsp.model import LatentSpaceModel, InverseDynamicsMDN from deep_rlsp.run import get_problem_parameters # changes the run _id and thereby the pat...
406445
import os import numpy as np import matplotlib.pyplot as plt x = np.linspace(-1.0, 1.0, 10000, endpoint=True) ws1 = np.zeros_like(x) ws2 = np.zeros_like(x) ws1[np.abs(x) <= 1e-4] = 1 ws2[x > 0.99] = 1 plt.subplot(211) plt.title("ws1") plt.grid() plt.xlim(-1, 1) plt.ylim(-1.2, +1.2) plt.plot(x, ws1) plt.subplot(212...
406463
import pandas as pd import numpy as np ######################################################################################################### ''' Feature Engineering ''' def create_name_feat(train, test): for i in [train, test]: i['Name_Len'] = i['Name'].apply(lambda x: len(x)) i['Name_Title'] =...
406476
from torch import nn class ARCNN(nn.Module): def __init__(self, n_colors=3): super(ARCNN, self).__init__() self.base = nn.Sequential( nn.Conv2d(n_colors, 64, kernel_size=9, padding=4), nn.PReLU(), nn.Conv2d(64, 32, kernel_size=7, padding=3), nn.PReLU(...
406492
import pendulum def test_year(): d = pendulum.Date(1234, 5, 6) assert d.year == 1234 def test_month(): d = pendulum.Date(1234, 5, 6) assert d.month == 5 def test_day(): d = pendulum.Date(1234, 5, 6) assert d.day == 6 def test_day_of_week(): d = pendulum.Date(2012, 5, 7) assert d....
406519
import unittest from programy.extensions.scheduler.scheduler import SchedulerExtension from programytest.client import TestClient class SchedulerExtensionClient(TestClient): def __init__(self, mock_scheduler=None): self._mock_scheduler = mock_scheduler TestClient.__init__(self) def load_con...
406521
import os import sys init = os.path.abspath(__file__) test = os.path.dirname(init) project = os.path.dirname(test) sys.path.insert(0, project)
406536
import copy import torch import torchvision from fcos_core.config import cfg from fcos_core.augmentations.image_level_augs.img_level_augs import Img_augs from fcos_core.augmentations.box_level_augs.box_level_augs import Box_augs from fcos_core.augmentations.box_level_augs.color_augs import color_aug_func from fcos_core...
406554
class Rectangle: def __init__(self, dx, dy): # 初期化関数 self.dx = dx self.dy = dy def cal_area(self): # 面積を計算する関数 self.area = self.dx * self.dy return self.area
406579
import argparse import os import sys import time import numpy as np import torch from torch.autograd import Variable from torch.optim import Adam from torch.utils.data import DataLoader from torchvision import datasets from torchvision import transforms import utils from transformer_net import TransformerNet from vgg...
406588
import json import dash from dash.dependencies import Input, Output, State import dash_core_components as dcc import dash_html_components as html import dash_cytoscape as cyto from demos import dash_reusable_components as drc app = dash.Dash(__name__) server = app.server # ###################### DATA PREPROCESSING...
406594
import py, os, sys from pytest import raises from .support import setup_make, pylong, pyunicode, IS_WINDOWS, ispypy currpath = py.path.local(__file__).dirpath() test_dct = str(currpath.join("datatypesDict")) def setup_module(mod): setup_make("datatypes") class TestLOWLEVEL: def setup_class(cls): imp...