filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_28145 | import torch, os
import numpy as np
from torch import optim
from torch.autograd import Variable
from MiniImagenet import MiniImagenet
from naive5 import Naive5
import scipy.stats
from torch.utils.data import DataLoader
from torch.optim import lr_scheduler
import random, sys, pickle
import argparse
from torch import nn
... |
the-stack_106_28147 | # qubit number=3
# total number=12
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
import networkx as nx
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collectio... |
the-stack_106_28148 | # SVM Regression
#----------------------------------
#
# This function shows how to use TensorFlow to
# solve support vector regression. We are going
# to find the line that has the maximum margin
# which INCLUDES as many points as possible
#
# We will use the iris data, specifically:
# y = Sepal Length
# x = Pedal W... |
the-stack_106_28149 | import collections as _collections
import os as _os
import uuid as _uuid
import six as _six
from flytekit.common import sdk_bases as _sdk_bases
from flytekit.common import utils as _utils
from flytekit.common.exceptions import scopes as _exception_scopes
from flytekit.common.exceptions import user as _user_exceptions... |
the-stack_106_28150 | # coding: utf-8
# /*##########################################################################
# Copyright (C) 2004-2016 V.A. Sole, European Synchrotron Radiation Facility
#
# This file is part of the PyMca X-ray Fluorescence Toolkit developed at
# the ESRF by the Software group.
#
# Permission is hereby granted, free ... |
the-stack_106_28151 | import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib
import time
import ot
from scipy import linalg
from scipy import sparse
import gromovWassersteinAveraging as gwa
import spectralGW as sgw
from geodesicVisualization import *
import json
# Load the S-GWL code
import DataIO as Dat... |
the-stack_106_28152 | """
Fine-tune Faster R-CNN on HICO-DET
Fred Zhang <frederic.zhang@anu.edu.au>
The Australian National University
Australian Centre for Robotic Vision
"""
import os
import math
import json
import copy
import time
import torch
import bisect
import argparse
import torchvision
import numpy as np
from tqdm import tqdm
f... |
the-stack_106_28153 | __all__ = ['call_echo', 'call_mkdir', 'call_rmdir', 'call_ls']
from pathlib import Path
import shutil
from ..namedregistry import export
from .baseops import subprocess_run
@export(name='echo')
def call_echo(value, verbose=False):
result = subprocess_run(['echo', 'hello', value])
if verbose:
print(re... |
the-stack_106_28154 | # coding=utf-8
from __future__ import division
import logging
from itertools import permutations
from os.path import join
from typing import List
from typing import Optional
from typing import Tuple
from typing import Union
import numpy as np
import pandas as pd
from joblib import Memory
from koino.plot.base import h... |
the-stack_106_28155 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import sys
if not (sys.version_info.major == 3 and sys.version_info.minor > 5):
print("Python version %s.%s not supported version 3.6 or above required - exiting" % (sys.version_info.major,sys.version_info.minor))
sys.exit(1)
import os
import io
for path in [os.ge... |
the-stack_106_28160 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyTqdm(PythonPackage):
"""A Fast, Extensible Progress Meter"""
homepage = "https://gi... |
the-stack_106_28162 | # -*- coding: utf-8 -*-
import logging
import math
import os
import time
import datetime
import traceback
from typing import Dict, Optional, List, Tuple, Union, Iterable, Any
import torch
import torch.optim.lr_scheduler
from allennlp.common import Params
from allennlp.common.checks import ConfigurationError, parse_c... |
the-stack_106_28163 | import pendulum
from dagster.core.definitions.run_request import InstigatorType
from dagster.core.scheduler.instigation import InstigatorState, InstigatorStatus
from dagster.core.test_utils import create_test_daemon_workspace
from dagster.daemon import get_default_daemon_logger
from dagster.daemon.sensor import execute... |
the-stack_106_28165 | import scrapy
from datetime import datetime, timedelta
def clean_time(input):
time = input.lower().replace(',','').replace('alle ','').replace('il ',' ').strip()
to_english={}
to_english['gennaio']='january'
to_english['febbraio']='february'
to_english['marzo']='march'
to_english['aprile']='apr... |
the-stack_106_28166 | EMPTY_STRING = '<DYNAMODB_EMPTY_STRING>'
def SimpleToField(simple):
if isinstance(simple, list):
return {'L': [SimpleToField(nested_simple) for nested_simple in simple]}
elif isinstance(simple, dict):
return {'M': {nested_key: SimpleToField(nested_simple) for nested_key, nested_simple in simple.items()}}
... |
the-stack_106_28168 | # System libs
import os
import argparse
from distutils.version import LooseVersion
import json
# Numerical libs
import numpy as np
import torch
import torch.nn as nn
import csv
import logging
# Our libs
from dataset import TestDataset
from models import ModelBuilder, SegmentationModule
from utils import colorEncode, fi... |
the-stack_106_28170 | # coding=utf-8
# Copyright 2022 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_28172 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
"""
This test verifies that the Spack directory layout works properly.
"""
import os
import os.path
import pytest
import ... |
the-stack_106_28173 | # Copyright 2016 Autodesk 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... |
the-stack_106_28175 | import torch
from mmdet.core import bbox2result, bbox2roi, build_assigner, build_sampler
from ..builder import HEADS, build_head, build_roi_extractor
from .base_roi_head import BaseRoIHead
from .test_mixins import BBoxTestMixin, MaskTestMixin
@HEADS.register_module()
class StandardRoIHead(BaseRoIHead, BBoxTestMixin,... |
the-stack_106_28176 | #######################################################################
# Implementation of FM partition
# You need to implement initialize() and partition_one_pass()
# All codes should be inside FM_Partition class
# Name: Dennis Liu
# UT EID: dl34437
####################################################################... |
the-stack_106_28177 | from sklearn import cluster
from distance import calc_ars, get_gmm_clusters, principal_angle_distance
import click
from plot_utils import get_nx_graph
from utils import get_as_numpy_array, map_embeddings_to_consecutive
@click.command()
@click.option("-e1", "--embeddings_1", type=str, required=True)
@click.option(... |
the-stack_106_28179 | from .authenticator import Authenticator
from .websocket_client import WebSocketClient
from .constants import (
API_URL,
WEB_BASE_URL,
WS_BASE_URL,
START_SPLASH_TEXT,
END_SPLASH_TEXT,
codes,
)
from .tester import Tester
from .web_server import WebServer
from .logger import logger
class LocalSe... |
the-stack_106_28181 | from __future__ import absolute_import, division, print_function, unicode_literals
import json
import os
import shlex
import stat
import time
import unittest
from typing import IO, Optional, Union
import common_tests
import hierarchy_tests
from hh_paths import hh_client
from saved_state_test_driver import (
Saved... |
the-stack_106_28183 |
from sqlalchemy.orm import sessionmaker
import requests
import os
import json
import models
import wingo_fiber
def save_appendix(model, item):
idx = model.id
# Init
directory = "results/{:}".format(idx)
if not os.path.exists(directory):
os.mkdir(directory)
# Download images
for i... |
the-stack_106_28184 | import json
from django.test import override_settings
from allauth.account.models import EmailAddress
from allauth.socialaccount.models import SocialAccount
from allauth.socialaccount.providers.amazon_cognito.provider import (
AmazonCognitoProvider,
)
from allauth.socialaccount.providers.amazon_cognito.views impo... |
the-stack_106_28186 | # 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 ap... |
the-stack_106_28187 | import torch
import torch.nn as nn
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_... |
the-stack_106_28190 | """Moderate Ray Tune run (32 trials, 4 actors).
This training run will start 32 Ray Tune trials, each starting 4 actors.
The cluster comprises 32 nodes.
Test owner: krfricke
Acceptance criteria: Should run through and report final results, as well
as the Ray Tune results table. No trials should error. All trials sho... |
the-stack_106_28191 | import argparse
import os
import pickle as pkl
from pathlib import Path
import cv2
import numpy as np
import pandas as pd
import skimage
import skimage.io
from skimage import feature
from sklearn import svm, metrics
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.utils import Bunch
de... |
the-stack_106_28192 | # import random module
import random
# compliment list
compliments = ['Amazing!', 'Great Work!', 'Fantastic!',
"Incredible!", "Nice Job!", "Excellent!", "Stupendous!"]
# global score var
# this will be useful when we use it in functions.
score = 0
# main function
def quizQuestion(guess, answer):
... |
the-stack_106_28193 | import collections
import re
from functools import partial
from itertools import chain
from django.core.exceptions import EmptyResultSet, FieldError
from django.db import DatabaseError, NotSupportedError
from django.db.models.constants import LOOKUP_SEP
from django.db.models.expressions import F, OrderBy, RawSQL, Ref,... |
the-stack_106_28195 | # -*- coding: utf-8 -*-
from pip_services3_commons.errors.UnauthorizedException import UnauthorizedException
from pip_services3_rpc.services.HttpResponseSender import HttpResponseSender
class BasicAuthorizer:
def anybody(self):
return lambda req, res, next: next()
def signed(self):
def inne... |
the-stack_106_28196 | #!/usr/bin/env python3
# cabal_wrapper.py <FILE.JSON>
#
# This wrapper calls Cabal's configure/build/install steps one big
# action so that we don't have to track all inputs explicitly between
# steps. It receives the path to a json file with the following schema:
#
# { "component": string # Cabal component ... |
the-stack_106_28197 | import logging
import json
from libs import baseview, util, rollback
from rest_framework.response import Response
from django.http import HttpResponse
from core.models import SqlOrder, SqlRecord
from libs.serializers import Record
CUSTOM_ERROR = logging.getLogger('Yearning.core.views')
class record_order(baseview.Sup... |
the-stack_106_28198 | """
Building and world design commands
"""
from builtins import range
import re
from django.conf import settings
from django.db.models import Q
from evennia.objects.models import ObjectDB
from evennia.locks.lockhandler import LockException
from evennia.commands.cmdhandler import get_and_merge_cmdsets
from evennia.util... |
the-stack_106_28199 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 9 15:09:18 2021
@author: alef
"""
"""
For: aceita sequencias estáticas e iteradores.
Iteradores acessam elementos de forma sequencial
Com o for a referência aponta para cada elemento a cada iteração.
o break pode ser usado para interromper o laç... |
the-stack_106_28201 | import networks
class VrtNu(networks.ClosedTVNetwork):
def __init__(self, apikey, *args, **kwargs):
self.apikey = apikey
super(VrtNu, self).__init__(*args, **kwargs)
def login(self):
payload = {"loginID": self.username, "password": self.password,
"ApiKey": self.api... |
the-stack_106_28203 | #!/usr/bin/env python3.7
import os
import subprocess
import re
import argparse
import sys
import glob
from Bio import SeqIO
def virus_pred(assembly_file, output_dir, virome_dataset, prok_mode):
"""Creates fasta file with viral contigs and putative prophages predicted with VirFinder_Euk_Mod and Virsorter"""
#VirFind... |
the-stack_106_28204 | import os
import sys
import torch
sys.path.append(os.path.dirname(os.path.dirname(os.getcwd())))
sys.path.append(os.path.join(os.getcwd(), 'generative_inpainting'))
import argparse
from exp.loaddata_utils import ImageNetLoadClass
from exp.general_utils import Timer
import numpy as np
import os
from arch.sensitivity.B... |
the-stack_106_28206 | import csv
from photo_radar import models
from photo_radar.fetchers import canada
def save_as_csv():
with open("photo_radar.csv", "w") as f:
writer = csv.writer(f)
writer.writerow(
[
"id",
"street",
"city",
"provience",
... |
the-stack_106_28209 | import abc
from logging import getLogger
from os import path
import pandas as pd
from clinica.utils.inputs import check_caps_folder
logger = getLogger("clinicadl")
class SplitManager:
def __init__(
self,
caps_directory,
tsv_path,
diagnoses,
baseline=False,
multi_c... |
the-stack_106_28210 | """257. Binary Tree Paths
https://leetcode.com/problems/binary-tree-paths/
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
"""
from typing imp... |
the-stack_106_28212 | import time
from constants import *
# All selenium imports
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
# All the common utilities th... |
the-stack_106_28213 | from sqlpuzzle._common import check_type_decorator
from .queryparts import QueryPart
__all__ = ('Limit',)
class Limit(QueryPart):
def __init__(self, limit=None, offset=None):
super().__init__()
self._limit = limit
self._offset = offset
def __str__(self):
res = ''
if s... |
the-stack_106_28214 | # 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_106_28215 | # Copyright 2015-2017 Espressif Systems (Shanghai) PTE 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.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
the-stack_106_28216 | #!/usr/bin/env python
# coding: utf-8
import nose
import itertools
import os
import string
import warnings
from distutils.version import LooseVersion
from datetime import datetime, date
from pandas import (Series, DataFrame, MultiIndex, PeriodIndex, date_range,
bdate_range)
from pandas.compat imp... |
the-stack_106_28218 | from sqlalchemy import *
from migrate import *
from migrate.changeset import schema
pre_meta = MetaData()
post_meta = MetaData()
options = Table('options', post_meta,
Column('id', Integer, primary_key=True, nullable=False),
Column('name', String(length=64)),
Column('properties', String(length=256)),
)
d... |
the-stack_106_28219 | nome = str(input('Nome: '))
idade = int(input('Idade: '))
peso = float(input('Peso: '))
altura = float(input('Altura: '))
n_sus = str(input('Número do SUS:'))
diagnostico = str(input('Diagnostico: '))
print(f'{nome},{idade},{peso},{altura},{n_sus},{diagnostico}')
'''954,7 kb
886,9 kb
https://repl.it/repls/DeliciousHast... |
the-stack_106_28220 | import matplotlib as mpl
import matplotlib.gridspec as gridspec
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
from . import cartopy_borders, cartopy_proj_albers
def map_pretty(ax, title=''):
state_borders, us_border = cartopy_borders()
ax.add_geometries(
state_borders,
... |
the-stack_106_28221 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#!/usr/bin/env python
import glob
import os
import torch
from setuptools import find_packages
from setuptools import setup
from torch.utils.cpp_extension import CUDA_HOME
from torch.utils.cpp_extension import CppExtension
from torch.utils.cpp_ext... |
the-stack_106_28222 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Netius System
# Copyright (c) 2008-2020 Hive Solutions Lda.
#
# This file is part of Hive Netius System.
#
# Hive Netius System is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apache
# Foun... |
the-stack_106_28223 | import re
import requests
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.contrib.admin.sites import site as admin_site
from django.db.models.fields.related import ManyToOneRel
from django.forms import fields, Media, ModelChoiceField
from django.forms.widgets import RadioSelect
from d... |
the-stack_106_28224 | import pytest
from flask import Flask
from flask_discord_interactions import DiscordInteractions, SlashCommand, Response
def test_slash_command(discord, client):
with pytest.deprecated_call():
command = SlashCommand(lambda ctx: "ping", "ping", "No description", [], [])
# make sure the object still w... |
the-stack_106_28231 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import jsonate.fields
import test_app.models
class Migration(migrations.Migration):
dependencies = [
('test_app', '0002_mymodelwithjsonatefield'),
]
operations = [
migrations.CreateMo... |
the-stack_106_28233 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
from os import symlink
class Bridger(MakefilePackage):
"""Bridger : An Efficient De novo Transcr... |
the-stack_106_28235 | # -*- coding: utf-8 -*-
"""
Plot point-spread functions (PSFs) and cross-talk functions (CTFs)
==================================================================
Visualise PSF and CTF at one vertex for sLORETA.
"""
# Authors: Olaf Hauk <olaf.hauk@mrc-cbu.cam.ac.uk>
# Alexandre Gramfort <alexandre.gramfort@inr... |
the-stack_106_28236 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# test_maxsum.py
# algorithms
#
# Created by Haibao Tang on 06/19/21
# Copyright © 2021 Haibao Tang. All rights reserved.
#
import pytest
@pytest.mark.parametrize(
"input,output",
[
([4, 4, 9, -5, -6, -1, 5, -6, -8, 9], (17, 0, 2)),
([8, -10, 10... |
the-stack_106_28237 | """
This file offers the methods to automatically retrieve the graph Paraliobacillus sp. PM-2.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: protein--prote... |
the-stack_106_28238 | import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from numba import jit,double,int64
@jit(double(double,double))
def cos2phi(qc,qt):
e1=3.94
e2=4.84
k1t=-0.105
k2t=0.149
lamda=0.262
Delta = 0.5*(e2+k2t*qt-e1-k1t*qt)
return Delta / np.sqrt( Delta**2. ... |
the-stack_106_28240 | from aws_cdk import (
core,
aws_iam,
)
class KnowledgeAnalyzerIAMStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
self.PREFIX = id
## **************** Create HealthLake Knowledge Analyzer Servic... |
the-stack_106_28242 | from nltk.stem.isri import ISRIStemmer
from nltk.corpus import stopwords
from nltk.tokenize import WordPunctTokenizer
import pickle
import argparse
tokenizer = WordPunctTokenizer()
stemmer = ISRIStemmer()
stopwords = set(stopwords.words('arabic'))
SYMBOLS = set('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~\"')
print(stopwords)
... |
the-stack_106_28249 | # coding=utf-8
# Copyright 2020 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_28251 | import os
import cv2
import numpy as np
from keras.models import load_model
from keras.callbacks import Callback, ModelCheckpoint
import sklearn
from sklearn.model_selection import train_test_split
import csv
samples = []
data = 'data2/driving_log.csv'
print (data)
#load the lines in driving log file
with open(data) ... |
the-stack_106_28253 | import os
import re
from jinja2 import Environment, FileSystemLoader
def extract_version_parts(git_response):
regex = r"v(\d)\.(\d)\.(\d)(?:-(\d+)-([a-z0-9]+)(?:-([a-z0-9]+))?)?"
matches = re.finditer(regex, git_response, re.MULTILINE)
groups = list(matches)[0].groups()
if len(groups) > 3... |
the-stack_106_28254 | import importlib
import os
import sys
import jinja2
from flask import Flask
from flask import send_from_directory
from flask_admin import Admin
from flask_admin.menu import MenuLink
from flask_login import current_user
from shopyo.api.file import trycopy
from shopyo.config import app_config
from shopyo.init import cs... |
the-stack_106_28255 | import socket
import InfoSource
class SocketPinger(InfoSource.InfoSource):
def __init__(self):
super(SocketPinger, self).__init__()
self.IP = ""
self.Port = 0
self.Name = "Server status"
self.StatusStr = ("UP", "DOWN")
def __call__(self):
Sock = socket.socket(s... |
the-stack_106_28256 | from copy import deepcopy
from types import MethodType
class Prototype(object):
"""
Prototype design pattern abstract class.
- External Usage documentation: U{https://github.com/tylerlaberge/PyPattyrn#prototype-pattern}
- External Prototype Pattern documentation: U{https://en.wikipedia.org/wiki/Proto... |
the-stack_106_28257 | """
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
from collections import defaultdict
s = in... |
the-stack_106_28258 | #!D:\PTU\Gardenia\venv\Scripts\python.exe
# Copyright (c) 2005-2012 Stephen John Machin, Lingfo Pty Ltd
# This script is part of the xlrd package, which is released under a
# BSD-style licence.
from __future__ import print_function
cmd_doc = """
Commands:
2rows Print the contents of first and last row in e... |
the-stack_106_28259 | # ----------------------------------------------------------------------------
# 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_106_28262 |
# written by Yang Li for the Leafcutter repo
# forked by mdshw5 and converted to Python3
# https://github.com/mdshw5/leafcutter/blob/master/scripts/leafcutter_cluster_regtools.py
# requires regtools installation
# https://github.com/griffithlab/regtools
# /home/yangili1/tools/regtools/build/regtools junctions extr... |
the-stack_106_28264 | # flake8: noqa
import numpy
import numpy as np
from skimage.data import camera
from skimage.metrics import peak_signal_noise_ratio as psnr
from skimage.metrics import structural_similarity as ssim
from aydin.io.datasets import (
normalise,
add_noise,
dots,
lizard,
pollen,
newyork,
character... |
the-stack_106_28266 | #!/usr/bin/env python3
import rospy
import json
from lg_msg_defs.srv import USCSMessage
from lg_msg_defs.srv import DesiredState
from interactivespaces_msgs.msg import GenericMessage
from std_msgs.msg import String
from appctl_msg_defs.msg import Mode
from lg_common.helpers import run_with_influx_exception_handler
N... |
the-stack_106_28267 | import sys
import h5py
import numpy as np
from pydata.increment import __next_index__
if 'pyslave' in sys.modules :
from pyslave import __slave_disp__ as disp
else:
disp = print
class createh5(h5py.File):
"""Create a new H5 file to save data.
Use the append_dataset to add data to the file."""... |
the-stack_106_28268 | #!/usr/bin/env python
# -*- noplot -*-
import time
from pylab import *
def get_memory():
"Simulate a function that returns system memory"
return 100*(0.5 + 0.5*sin(0.5*pi*time.time()))
def get_cpu():
"Simulate a function that returns cpu usage"
return 100*(0.5 + 0.5*sin(0.2*pi*(time.time() - 0.25)))... |
the-stack_106_28269 | import numpy as np
import logging
from benchmarker import benchmark
logger = logging.getLogger('expNN_BLAS_level_2_to_level_3')
@benchmark
def naive_loop(A, B, C):
for i in range(C.shape[1]):
C[:, i] = A @ B[:, i]
return C
@benchmark
def recommended_loop(A, B, C):
C = A @ B
return C
def e... |
the-stack_106_28272 | # %%
import torch
import math
from UnarySim.kernel.tanh import tanhPN
from UnarySim.stream.gen import RNG, SourceGen, BSGen
from UnarySim.metric.metric import ProgError
import matplotlib.pyplot as plt
import time
import math
import numpy as np
# %%
def tanh_fsm_test(bw=8, mode="bipolar", rng="Sobol", depth=4):
... |
the-stack_106_28273 | import os
import sys
import psutil
from monk.gluon_prototype import prototype
from monk.compare_prototype import compare
from monk.pip_unit_tests.gluon.common import print_start
from monk.pip_unit_tests.gluon.common import print_status
import mxnet as mx
import numpy as np
from monk.gluon.losses.return_loss import l... |
the-stack_106_28274 | import cgi
import json
import re
from django.conf import settings
from django.core.urlresolvers import reverse
from django.shortcuts import render
from django.http import HttpResponse, \
HttpResponseForbidden, HttpResponseNotFound, HttpResponseServerError
from django.template.loader import render_to_string
from dj... |
the-stack_106_28275 | ########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. 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... |
the-stack_106_28276 | # -*- coding: utf-8 -*-
# Save Model Using Pickle
from pandas import read_csv
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
import pickle
url = './data/pima-indians-diabetes.data.csv'
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'cl... |
the-stack_106_28277 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright © 2018 Michael J. Hayford
""" Top level model classes
.. Created on Wed Mar 14 11:08:28 2018
.. codeauthor: Michael J. Hayford
"""
import os.path
import json_tricks
import rayoptics
import rayoptics.elem.elements as ele
import rayoptics.optical.model_consta... |
the-stack_106_28278 | #!/usr/bin/env python3
"""
Scripts to drive a donkey 2 car
Usage:
manage.py (drive)
Options:
-h --help Show this screen.
"""
import os
import time
from docopt import docopt
import donkeycar as dk
#import parts
from donkeycar.parts.controller import LocalWebController, \
JoystickController, We... |
the-stack_106_28279 | # -*- coding: utf-8 -*-
# Copyright 2017 IBM RESEARCH. 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 requ... |
the-stack_106_28284 | import copy
from typing import List
import torch
from sympy import simplify_logic
from entropy_lens.logic.metrics import test_explanation
from entropy_lens.logic.utils import replace_names
from entropy_lens.nn import Conceptizator
from entropy_lens.nn.logic import EntropyLinear
def explain_class(model: torch.nn.Mod... |
the-stack_106_28286 | from django.apps import AppConfig
from django.conf import settings
from django.core import exceptions
from raven.contrib.django.models import initialize
class SenSysConfig(AppConfig):
name = 'sensys.contrib.django'
label = 'sensys_contrib_django'
verbose_name = 'SenSys'
def ready(self):
# s... |
the-stack_106_28288 | """Support for tracking consumption over given periods of time."""
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.const import CONF_NAME
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers import discovery
from homeassistant.helpers.dispatcher imp... |
the-stack_106_28289 | #!/usr/bin/env python3
import typer
from typing import Optional
from rich import print
import os
import tempfile
import subprocess
from rich.markup import escape
from rich.console import Console
import random
c = Console(highlight=False)
def print(s):
c.print(s)
def run(s: Optional[str] = None, race: bool = Tru... |
the-stack_106_28291 | # Copyright 2018 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... |
the-stack_106_28293 | #!/usr/bin/env python
from matplotlib import pyplot as plt
import numpy as np
import torch
import torchvision.transforms as transforms
from torch.utils.data import random_split
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
import time
import pandas as pd
from customDataset im... |
the-stack_106_28294 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2017-18 Richard Hull and contributors
# See LICENSE.rst for details.
"""
Tests for the :py:class:`luma.core.interface.serial.bitbang` class.
"""
from unittest.mock import Mock, call
from luma.core.interface.serial import bitbang
import luma.core.error
imp... |
the-stack_106_28295 | # Copyright The OpenTelemetry 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 or agreed to in ... |
the-stack_106_28299 | import asyncio
import secrets
from jotbox import Jotbox, Payload, JWTDecodeError
from jotbox.whitelist.redis import RedisWhitelist
# Define the payload model
class AccessPayload(Payload):
user_id: int
# Create our Jotbox instance with some settings
jot = Jotbox[AccessPayload](
encode_key=secrets.token_hex()... |
the-stack_106_28300 | #! /usr/bin/env python
import argparse
from string import Template
import settings
def make_igvsession(igv_ed_umcu, igv_ed_hc, bam, vcf_hc, sample_id, vcf_SNV, axis, statistic):
template_file = Template(open(settings.template_xml).read())
new_session = "{0}_{1}_{2}_igv.xml".format(sample_id, statistic, args.ru... |
the-stack_106_28301 | import bs4
import requests
import os
import brotli
limit = 1290
def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix):].replace('/', '')
return text
def get_links(i):
url = f"http://23.95.221.108/page/{i}"
html = requests.get(url).text
soup = bs4.Beautifu... |
the-stack_106_28303 | from tradssat.tmpl.var import CharacterVar, FloatVar
cul_vars_PTSUB = {
CharacterVar('VAR#', 6, spc=0, info='Identification code or number for the specific cultivar.'),
CharacterVar('VAR-NAME', 16, header_fill='.', info='Name of cultivar.'),
CharacterVar('EXPNO', 5, miss='.', info='Number of experiments us... |
the-stack_106_28304 | from setuptools import find_packages
from setuptools import setup
package_name = 'ros2doctor'
setup(
name=package_name,
version='0.18.0',
packages=find_packages(exclude=['test']),
data_files=[
('share/' + package_name, ['package.xml']),
('share/ament_index/resource_index/packages',
... |
the-stack_106_28306 | #!/usr/bin/env python3
import sys
import gzip
filename_fa = sys.argv[1]
f_fa = open(filename_fa, 'r')
if filename_fa.endswith('.gz'):
f_fa = gzip.open(filename_fa, 'rt')
seq_list = dict()
seqlen_list = dict()
for line in f_fa:
if line.startswith('>'):
tmp_tokens = line.strip().lstrip('>').split('|')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.