filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_106_26048
""" Copyright (c) 2019, Brian Stafford Copyright (c) 2019-2020, The Decred developers See LICENSE for details Based on dcrd MsgTx. """ from decred import DecredError from decred.crypto.crypto import hashH from decred.dcr import txscript from decred.util.encode import ByteArray from . import wire # TxVersion is the...
the-stack_106_26050
#Pranav Mishra #BioCompute Object Creator Minimum Viable Product import os import json import jsons import sys import hashlib from json import JSONEncoder from pprint import pprint from datetime import datetime try: import cPickle as pickle except ModuleNotFoundError: import pickle class BCO(): ...
the-stack_106_26051
import cx_Freeze import sys import os import PySide2 plugins_path = os.path.join(PySide2.__path__[0], "plugins") base = None if sys.platform == 'win32': base = "Win32GUI" executables = [ cx_Freeze.Executable("emoch.py", base=base) ] cx_Freeze.setup( name = "EmoCh- Speech Emotion Analysis", options = {"build_ex...
the-stack_106_26052
"""2. Train Mask RCNN end-to-end on MS COCO =========================================== This tutorial goes through the steps for training a Mask R-CNN [He17]_ instance segmentation model provided by GluonCV. Mask R-CNN is an extension to the Faster R-CNN [Ren15]_ object detection model. As such, this tutorial is also...
the-stack_106_26055
import os import unittest import tempfile from io import StringIO from pathlib import Path from robot.utils.asserts import assert_equal from robot.parsing import get_tokens, get_init_tokens, get_resource_tokens, Token T = Token def assert_tokens(source, expected, get_tokens=get_tokens, **config): tokens = list...
the-stack_106_26056
''' This script does all the data preprocessing. You'll need to install CMU-Multimodal DataSDK (https://github.com/A2Zadeh/CMU-MultimodalDataSDK) to use this script. There's a packaged (and more up-to-date) version of the utils below at https://github.com/Justin1904/tetheras-utils. Preprocessing multimodal data is rea...
the-stack_106_26057
# Copyright (c) 2016 Universidade Federal Fluminense (UFF) # Copyright (c) 2016 Polytechnic Institute of New York University. # Copyright (c) 2018, 2019, 2020 President and Fellows of Harvard College. # This file is part of ProvBuild. """Lightweight objects for storage during collection""" from __future__ import (abso...
the-stack_106_26061
import json import os import sys import numpy as np import random import math import time from graph import GraphBatch import torch import torch.nn as nn from torch.autograd import Variable from torch import optim import torch.nn.functional as F from env import R2RBatch, R2RBatch_neg from utils import padding_idx, ad...
the-stack_106_26062
class Node: def __init__(self, key): self.data = key self.left = None self.right = None def find_lca(root, n1, n2): path1 = [] path2 = [] # Find paths from root to n1 and root to n2. # if either n1 or n2 not present return -1 if not find_path(root, path1, n1) or not fin...
the-stack_106_26065
import tensorflow as tf mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.D...
the-stack_106_26067
# coding=utf-8 import logging __author__ = 'ThucNC' import os from PIL import Image from tinify import tinify _logger = logging.getLogger(__name__) class ImageOptimizer: """ For best result: 1. use png as source file, 2. make cover and thumbnail and optimize them, 3. convert to jp...
the-stack_106_26068
#!/usr/bin/env python #ckwg +28 # Copyright 2011-2013 by Kitware, 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: # # * Redistributions of source code must retain the above copyright notice,...
the-stack_106_26069
"""This module contains the meta information of ConfigGetEstimateImpact ExternalMethod.""" import sys, os from ..ucscoremeta import MethodMeta, MethodPropertyMeta method_meta = MethodMeta("ConfigGetEstimateImpact", "configGetEstimateImpact", "Version142b") prop_meta = { "cookie": MethodPropertyMeta("Cookie", "co...
the-stack_106_26070
from django.test import TestCase from django.test.client import Client from django.core.urlresolvers import reverse from error.models import Error from issues.models import Issue from notifications.models import Notification from appengine_django.auth.models import User as AppUser from google.appengine.api.users impo...
the-stack_106_26071
# Copyright (C) 2017, Anthony Oteri # All rights reserved. """Control panel for the time clock.""" from __future__ import absolute_import import logging import time import Tkinter as tk import ttk from datetime import datetime from chronos import event from chronos.db import ProjectService, RecordService from chrono...
the-stack_106_26073
from PIL import Image import torch import torch.backends.cudnn as cudnn import torch.utils.data import torch.nn.functional as F import torchvision.transforms as transforms import numpy as np from collections import OrderedDict import importlib from .utils import CTCLabelConverter import math def custom_mean(x): re...
the-stack_106_26076
import sys import collections def input(): return sys.stdin.readline()[:-1] N = int(input()) A = [] for i in range(N): tmp = list(input()) c = collections.Counter(tmp) A.append(c) ans = '' for i in range(N//2): for k in A[i].keys(): if k in A[(i+1)*-1]: ans = ans+k ...
the-stack_106_26077
import os from fifteen_api import FifteenAPI # initialization tts_api = FifteenAPI(show_debug=True) # be aware that there is a serverside max text length. If text is too long, it will be trimmed. print(tts_api.max_text_len) ### valid usage examples # get tts raw bytes (well, assuming that Fluttershy is not currently...
the-stack_106_26078
from configs.config import Config def load_config(dataset_name): cfg = Config() ''' Experiment ''' cfg.experiment_idx = 1 cfg.trial_id = None cfg.train_mode = 'train' ''' Dataset ''' cfg.dataset_name = dataset_name cfg.set_hint_patch_shape((96, 96, 96)) cfg.num_classes = 4 ...
the-stack_106_26079
from plotly.basedatatypes import BaseTraceType import copy class Scattermapbox(BaseTraceType): # connectgaps # ----------- @property def connectgaps(self): """ Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. ...
the-stack_106_26081
from __future__ import print_function import sys import os # This is important to allow access to the CTFd application factory sys.path.append(os.getcwd()) import datetime import hashlib import netaddr from flask_sqlalchemy import SQLAlchemy from passlib.hash import bcrypt_sha256 from sqlalchemy.sql.expression import...
the-stack_106_26082
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import torch class WelfordCovariance(object): """ Implements Welford's online scheme for estimating (co)variance (see :math:`[1]`). Useful for adapting diagonal and dense mass structures for HMC. **References** ...
the-stack_106_26083
from domain.ErrorTypes import ErrorTypes from validity import IncomingEdgeValidityChecker, DataSourceValidityChecker from utils import CodeGenerationUtils import os # Consider adding offset option... def generate_code(args): node = args["node"] requireds_info = args["requireds_info"] edges = args["edges"] ...
the-stack_106_26085
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from scipy import interpolate import hitomipy import pycuba import os class ClassBiSpectrum(): def __init__(self): self.initialize() def initialize(self): self.k_temp = np.zeros(1) self.P_temp = np.zeros(1) self...
the-stack_106_26087
# import json import json from django.db.models import QuerySet, Q from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from apps.ticket.models import TicketCustomField from apps.workflow.models import State from service.account.account_base_service import AccountBaseService from service.base_servi...
the-stack_106_26088
# Copyright 2019 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 or agreed to in writing, so...
the-stack_106_26090
# coding=utf-8 # Copyright 2019 The Tensor2Tensor Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
the-stack_106_26092
# -*- coding: utf-8 -*- """ lantz.drivers.legacy.kentech.hri ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Implements the driver for Kentech High Repetition Rate Image Intensifier revisions 1 and 2. Implementation Notes -------------------- The set of commands is cumbersome and inconsistent. Moreover...
the-stack_106_26094
import unittest from flask import current_app from flask_testing import TestCase from api import app from app.main.config import * class TestDevelopmentConfig(TestCase): def create_app(self): app.config.from_object('app.main.config.DevelopmentConfig') return app def test_app_is_development(...
the-stack_106_26095
# adapted from: https://github.com/lucidrains/vit-pytorch/blob/main/vit_pytorch/vit.py import torch import torch.nn.functional as F from torch import nn from torch.utils import checkpoint from einops import rearrange, repeat import triton import triton.language as tl import time @triton.jit def blub_kernel( q...
the-stack_106_26097
import numpy as np import pandas as pd import streamlit as st import os import src from datetime import datetime from pandas.util import hash_pandas_object import boto3 s3 = boto3.resource( service_name='s3', region_name=st.secrets["region_name"], aws_access_key_id=st.secrets["AWS_ACCESS_KEY_ID"], aws...
the-stack_106_26099
#!/usr/bin/env python3 # Copyright (c) 2021 The Khronos Group Inc. # Copyright (c) 2021 Valve Corporation # Copyright (c) 2021 LunarG, Inc. # Copyright (c) 2021 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 ob...
the-stack_106_26102
# Copyright 2020 The Cirq Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
the-stack_106_26109
""" Basic unit test module for the at module. """ import os import sys import unittest cwd = os.getcwd() if cwd not in sys.path: sys.path.insert(0, os.getcwd()) import at class TestATParsing(unittest.TestCase): """Defines unit tests for verifying parsing functionality.""" TEST_CMDS = [('AT+CEMODE=0', ...
the-stack_106_26110
""" Convert case data into format that can be used to construct model instance """ from nemde.core.casefile.lookup import convert_to_list, get_intervention_status from nemde.core.casefile.algorithms import get_parsed_interconnector_loss_model_segments from nemde.core.casefile.algorithms import get_interconnector_loss_...
the-stack_106_26111
# Natural Language Toolkit: Twitter client # # Copyright (C) 2001-2021 NLTK Project # Author: Ewan Klein <ewan@inf.ed.ac.uk> # Lorenzo Rubio <lrnzcig@gmail.com> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ Utility functions for the :module:`twitterclient` module which do not require...
the-stack_106_26112
"""Determine the status of a nix build as lazily as possible in a bisect-friendly format""" import sys import argparse from pathlib import Path from nix_bisect import nix, exceptions, git_bisect from nix_bisect.derivation import Derivation def drvish_to_drv(drvish, nix_file, nix_options, nix_argstr): """No-op o...
the-stack_106_26113
# Enter an interactive TensorFlow Session. import tensorflow as tf sess = tf.InteractiveSession() x = tf.Variable([1.0, 2.0]) a = tf.constant([3.0, 3.0]) # Initialize 'x' using the run() method of its initializer op. x.initializer.run() # Add an op to subtract 'a' from 'x'. Run it and print the result sub = tf.sub(...
the-stack_106_26114
# Copyright 2021 University College London (UCL) Research Software Development # Group. See the top-level LICENSE file for details. # # SPDX-License-Identifier: Apache-2.0 import os.path as path import sys import reframe as rfm import reframe.utility.sanity as sn # Add top-level directory to `sys.path` so we can eas...
the-stack_106_26116
"""Tests for the storage helper.""" from datetime import timedelta from unittest.mock import patch import pytest from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.helpers import storage from homeassistant.util import dt from tests.common import async_fire_time_changed, mock_coro MOCK_VERS...
the-stack_106_26118
from urllib.parse import urljoin import requests from cypherpunkpay.common import * from cypherpunkpay import disable_unverified_certificate_warnings from cypherpunkpay.bitcoin.ln_invoice import LnInvoice from cypherpunkpay.net.http_client.clear_http_client import ClearHttpClient class LightningException(Exception...
the-stack_106_26119
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
the-stack_106_26120
# # BSD 3-Clause License # # Copyright (c) 2017 xxxx # All rights reserved. # Copyright 2021 Huawei Technologies Co., Ltd # # 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-stack_106_26122
# -*- encoding: utf-8 -*- # # Copyright 2013 Hewlett-Packard Development Company, L.P. # # 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 # # ...
the-stack_106_26128
# (C) Datadog, Inc. 2013-2016 # (C) Justin Slattery <Justin.Slattery@fzysqr.com> 2013 # All rights reserved # Licensed under Simplified BSD License (see LICENSE) # stdlib import re # 3rd party import requests # project from checks import AgentCheck from util import headers # Constants COUCHBASE_STATS_PATH = '/pools...
the-stack_106_26130
import operator from operator import methodcaller import dask.array as da import dask.dataframe as dd import numpy as np import numpy.testing as npt import pandas as pd import pytest from dask.dataframe.utils import tm import ibis import ibis.expr.datatypes as dt from ... import connect, execute pytestmark = pytest...
the-stack_106_26131
# Copyright 2019 kubeflow.org. # # 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,...
the-stack_106_26132
import json HTML_TEMPLATE = """ <h1>Resource</h1> <h2>Attributes</h2> <pre> <code> {attributes} </code> </pre> <h2>Links</h2> <ul> {links} </ul> """ def deserialize_html(resource): def render(accumulator, link): return accumulator + '<li><a href="{0}">{0}</a></li>\n'.format(link) def render_links(...
the-stack_106_26134
# Copyright (C) 2011 Google 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: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
the-stack_106_26135
try: import uerrno try: import uos_vfs as uos open = uos.vfs_open except ImportError: import uos except ImportError: print("SKIP") raise SystemExit try: uos.mkfat except AttributeError: print("SKIP") raise SystemExit class RAMFS: SEC_SIZE = 512 def __...
the-stack_106_26138
import json import time from os import listdir from os.path import isfile, join import requests from lxml import html, cssselect from lxml.html.clean import clean_html import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) def get_gov(tax_code, write_to_file=True): try: start...
the-stack_106_26139
"""CFNgin blueprint representing raw template module.""" import hashlib import json import os import sys from jinja2 import Template from ..exceptions import InvalidConfig, UnresolvedVariable from ..util import parse_cloudformation_template from .base import Blueprint def get_template_path(filename): """Find ra...
the-stack_106_26141
import sys, os, glob, shutil from subprocess import check_call from scrapy import version_info def build(suffix): for ifn in glob.glob("debian/scrapy.*"): s = open(ifn).read() s = s.replace('SUFFIX', suffix) pre, suf = ifn.split('.', 1) ofn = "%s-%s.%s" % (pre, suffix, suf) ...
the-stack_106_26146
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Set axis label """ import numpy as np import matplotlib.pyplot as plt # Build datas ############### x = np.arange(-10, 10, 0.01) y = np.sin(x) # Plot data ################# fig = plt.figure(figsize=(8.0, 8.0)) ax = fig.add_subplot(111) ax.plot(x, y) # Set label...
the-stack_106_26147
""" Preprocess the SNLI dataset and word embeddings to be used by the ESIM model. """ # Aurelien Coet, 2018. import os import pickle import argparse import fnmatch import json from esim.data import Preprocessor def preprocess_SNLI_data(inputdir, embeddings_file, tar...
the-stack_106_26148
import logging from argparse import ArgumentParser, Namespace from typing import Any, List, Optional, Union from transformers import Pipeline from transformers.commands import BaseTransformersCLICommand from transformers.pipelines import SUPPORTED_TASKS, pipeline try: from uvicorn import run from fastapi imp...
the-stack_106_26151
import logging import sastvd.helpers.tokenise as svdt from gensim.models.doc2vec import Doc2Vec, TaggedDocument def train_d2v( train_corpus, vector_size=300, window=2, min_count=5, workers=4, epochs=100, dm_concat=1, dm=1, ): """Train Doc2Vec model. Doc2Vec.load(savedir / "d2...
the-stack_106_26152
import asyncio import time import pandas as pd def extract(file): dtype_dict = {"Nr": "int", "Kommunenavn": "string", "Adm. senter": "string", "Fylke": "category", "Målform": "category", "Domene": "string" }...
the-stack_106_26153
import PIL from PIL import Image, ImageOps, ImageDraw import pandas as pd import shutil import os.path import random from pathlib import Path ############### CONFIGURE ######################## # Table Configure Variables # Image Size Configuration IMAGE_START_NUMBER = 1 IMAGE_END_NUMBER = 200 TABLE_IM_PIXEL = 480...
the-stack_106_26154
from typing import Any, Callable, Dict, List, Optional, Type, TypeVar, Union import attr from ..types import UNSET, Unset from ..util.serialization import is_not_none T = TypeVar("T", bound="EndpointAddresses") @attr.s(auto_attribs=True) class EndpointAddresses: """Addresses at which an endpoint is reachable o...
the-stack_106_26156
from PySide2.QtUiTools import QUiLoader from PySide2.QtCore import QFile from PyQt5 import QtCore, QtGui, uic, QtWidgets import sys import cv2 import threading import queue app = QtWidgets.QApplication(sys.argv) running = False capture_thread = None q = queue.Queue() form_class = uic.loadUiType("test.ui") print(form_...
the-stack_106_26157
"""Tests queue_info.py""" from __future__ import absolute_import import tempfile import unittest import mock from botocore.exceptions import ClientError from kale import queue_info from kale import settings from kale import sqs class QueueInfoTest(unittest.TestCase): """Tests for QueueInfo class.""" _prev...
the-stack_106_26158
import json import stat import datetime import base64 import re import tarfile import io from connexion import request from anchore_engine import utils import anchore_engine.apis from anchore_engine.apis.authorization import get_authorizer, RequestingAccountValue, ActionBoundPermission from anchore_engine.apis.context...
the-stack_106_26160
# -*- coding: utf8 -*- # Imports. {{{1 import sys # Try to load the required modules from Python's standard library. try: import os import traceback import argparse from time import time import hashlib except ImportError as e: msg = "Error: Failed to load one of the required Python modules! (...
the-stack_106_26161
import copy import torch.nn as nn from .layer_config import default_layer_config, LayerConfig, NormType from .flatten import Flatten from typing import Any, Sequence, List, Optional def denses( sizes: Sequence[int], dropout_probability: float = None, activation: Any = nn.ReLU, normali...
the-stack_106_26162
''' Created on 5 nov. 2018 @author: david ''' import logging import time from engine.motor import Motor from sensor.wheel import WheelMotion logging.basicConfig(level=logging.INFO) THROTTLE = 80.0 MAX_STEPS = 20 TIMEOUT = 0.02 done = False def onStep(): if sensor.getTravelSteps() >= MAX_STEPS: ...
the-stack_106_26164
import socket import threading def recv_data(sock): while True: data = sock.recv(1024) print('\r' + data.decode() + '\n' + 'You: ', end='') host = '127.0.0.1' port = int(input('Input port: ')) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.connect((host, port)) if not port: ...
the-stack_106_26166
""" ************************************************************************** Script Name : Expunge_eMails_Utilities.py Author : SS. Kanagal. Description : This file contains all the utilities required by : Expunge_eMail_v1.5.py. Input Parameters: None. Version History...
the-stack_106_26169
# coding=utf-8 # Copyright 2021 The Tensor2Tensor Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
the-stack_106_26172
# Copyright 2017 the pycolab 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
the-stack_106_26173
from hw2skeleton import cluster from hw2skeleton import io import os def test_similarity(): filename_a = os.path.join("data", "276.pdb") filename_b = os.path.join("data", "4629.pdb") activesite_a = io.read_active_site(filename_a) activesite_b = io.read_active_site(filename_b) # update this assert...
the-stack_106_26175
import pytest from OpenSSL.SSL import TLSv1_2_METHOD from OpenSSL.SSL import Error, WantReadError from OpenSSL.SSL import Context, Connection from openssl_psk import patch_context patch_context() def interact_in_memory(client_conn, server_conn): """ Try to read application bytes from each of the two `Con...
the-stack_106_26177
# This is the default command line for PMARS, with the settings we've specified PMARS_CLI = "pmars -k -p 8000 -c 80000 -p 8000 -l 100 -d 100" # This addition to the command line makes PMARS run with just validation PMARS_NO_GRAPHICS = " -r 0 -v 000" class MetadataNotFoundException (Exception): pass def check_fo...
the-stack_106_26178
# -------------------------------------------------------- # Tensorflow Faster R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by Xinlei Chen, based on code from Ross Girshick # -------------------------------------------------------- import tensorflow as tf import numpy as np import os impo...
the-stack_106_26179
# Copyright 2018 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
the-stack_106_26180
#! /usr/bin/env python3 # GPTune Copyright (c) 2019, The Regents of the University of California, # through Lawrence Berkeley National Laboratory (subject to receipt of any # required approvals from the U.S.Dept. of Energy) and the University of # California, Berkeley. All rights reserved. # # If you have questions ab...
the-stack_106_26182
# coding=utf-8 # Copyright 2021 The Google Research 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_106_26183
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmdet.core.bbox.iou_calculators import bbox_overlaps from mmdet.core.bbox.transforms import bbox_cxcywh_to_xyxy, bbox_xyxy_to_cxcywh from .builder import MATCH_COST @MATCH_COST.register_module() class BBoxL1Cost: """BBoxL1Cost. Args: weight (in...
the-stack_106_26184
import unittest import numpy as np from fastestimator.op.numpyop.univariate import WordtoId from fastestimator.test.unittest_util import is_equal class TestWordToId(unittest.TestCase): @classmethod def setUpClass(cls): cls.map_dict = {'a': 0, 'b': 11, 'test': 90, 'op': 25, 'c': 100, 'id': 10, 'word'...
the-stack_106_26185
from django import forms from .models import Snippet from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, ButtonHolder, Field, Div, HTML class SnippetForm(forms.ModelForm): helper = FormHelper() class Meta(): model = Snippet widgets = { 'title...
the-stack_106_26186
# -*- coding: utf-8 -*- from addons.base.models import (BaseOAuthNodeSettings, BaseOAuthUserSettings, BaseStorageAddon) from django.db import models from framework.auth.core import Auth from osf.models.files import File, Folder, BaseFileNode from addons.base import exceptions from addon...
the-stack_106_26191
import abc import sys import time from collections import OrderedDict from functools import reduce import numba import numpy as np from shapely.geometry import Polygon from second.core import box_np_ops from second.core.geometry import (points_in_convex_polygon_3d_jit, ...
the-stack_106_26192
# -*- coding: utf-8 -*- from __future__ import division from __future__ import absolute_import from __future__ import print_function __author__ = 'christoph.statz <at> tu-dresden.de' from tqdm import tqdm from maui import context from maui.field import Field from desolvex.helper import ObjectSwapper class Explici...
the-stack_106_26193
# Copyright (c) Microsoft Corporation and Fairlearn contributors. # Licensed under the MIT License. """ ============================== Metrics with Multiple Features ============================== """ # %% # This notebook demonstrates the new API for metrics, which supports # multiple sensitive and conditional feature...
the-stack_106_26196
from docsvr import DocReqCmd class doFILEVERIFY(DocReqCmdCmd): def processCommand(self): src=self.translatePath(self.path) r=["BAD DIR","NOT EXISTS","EXISTS","BAD CALL"] try: r=r[self.validatePFN(src)] except: r="BAD CALL" self.request.send_ok("OK|%s...
the-stack_106_26198
import os from google.cloud import storage def load_data(): gcsBucket = "continuous-intelligence" key = "store47-2016.csv" if not os.path.exists('data/raw'): os.makedirs('data/raw') if not os.path.exists("data/raw/" + key): client = storage.Client() bucket = client.get_bucket(...
the-stack_106_26199
import abc from collections import OrderedDict import time import gtimer as gt import numpy as np from rlkit.core import logger, eval_util from rlkit.data_management.env_replay_buffer import MultiTaskReplayBuffer from rlkit.data_management.path_builder import PathBuilder from rlkit.samplers.in_place import InPlacePat...
the-stack_106_26202
import sys import cPickle import csv gtf_file = sys.argv[1] out_file = sys.argv[2] ####################################### keep_list = ["gene", "CDS", "start_codon", "stop_codon", "five_prime_utr", "three_prime_utr", "exon"] with open(gtf_file, "r") as gtf, open(out_file, "wb") as table_file: writer = csv.writer(...
the-stack_106_26206
import bblfsh_sonar_checks.utils as utils import bblfsh def check(uast): findings = [] binexpr_nodes = bblfsh.filter(uast, "//InfixExpression[@roleBinary and @roleExpression]") for node in binexpr_nodes: left = None right = None for c in node.children: if bblfsh.rol...
the-stack_106_26211
import torch.nn as nn import torch.nn.functional as F class LeNet5(nn.Module): def __init__(self): super(LeNet5, self).__init__() self.conv1 = nn.Conv2d(1, 6, (5,5), padding=0) self.conv2 = nn.Conv2d(6, 16, (5,5)) self.fc1 = nn.Linear(16*5*5, 120) self.fc2 = nn.Linear(1...
the-stack_106_26212
import sys import click import six from pyfiglet import figlet_format from termcolor import colored import docker from dstools.launcher import launch_tool def log(string, color, font="slant", figlet=False): if colored: if not figlet: six.print_(colored(string, color)) else: ...
the-stack_106_26213
# -*- coding: utf-8 -*- """ Created on Mon Jun 11 13:50:08 2018 @author: Salomon Wollenstein """ import numpy as np import pandas as pd import os 'Parameters' dir_shpfile = 'G:/My Drive/Github/PoA/shp/Jing/journal.shp' dir_data = 'G:/Team Drives/MPO 2015/INRIX_byQuarter/4-6' # Will take all of the csv files containe...
the-stack_106_26216
import komand import time from .schema import GetNewAlertsInput, GetNewAlertsOutput, Input, Output, Component # Custom imports below from datetime import datetime class GetNewAlerts(komand.Trigger): def __init__(self): super(self.__class__, self).__init__( name='get_new_alerts', ...
the-stack_106_26217
import os import re import external.cclib as cclib import logging from subprocess import Popen, PIPE from qmdata import CCLibData from molecule import QMMolecule class Mopac: """ A base class for all QM calculations that use MOPAC. Classes such as :class:`MopacMol` will inherit from this class. "...
the-stack_106_26218
# pylint: disable=g-bad-file-header # Copyright 2020 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/...
the-stack_106_26219
import argparse import os import scipy.io as scio import cv2 as cv import numpy as np import utils import resnet_image import pickle import paddle.optimizer as optim import paddle import datetime import sys from paddle.io import DataLoader,TensorDataset def net_train(net,data_loader,opt,loss_func,cur_e,args): # ...
the-stack_106_26222
import argparse import os import random from glob import glob from pathlib import Path import numpy as np import tifffile from PIL import Image from tqdm import tqdm def img_loader(fp): if Path(fp).suffix.lower() in [".jpg", ".jpeg", ".png"]: arr = np.array(Image.open(fp)) else: arr = tifffil...
the-stack_106_26224
#!/usr/bin/env python # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: from qap.cli import QAProtocolCLI if __name__ == "__main__": obj = QAProtocolCLI() obj.run()
the-stack_106_26226
import random import numpy as np import time import torch as T import os.path from tqdm import tqdm #device = T.device("cpu") # apply to Tensor or Module # ----------------------------------------------------------- class InputDataset(T.utils.data.Dataset): def __init__(self, src_file,n_rows=None): all...
the-stack_106_26227
# Copyright 2020-2021 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 ap...