filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_19807 | """
Copyright 2020 The OneFlow 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 law or agr... |
the-stack_106_19808 | # encoding: utf-8
import logging
import re
from six.moves.urllib.parse import urlencode
import six
from six import string_types
import ckan.lib.base as base
import ckan.lib.helpers as h
import ckan.lib.navl.dictization_functions as dict_fns
import ckan.logic as logic
import ckan.lib.search as search
import ckan.mod... |
the-stack_106_19813 | # 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 module contains all the elements that are required to create an
architecture object. These include, the target pr... |
the-stack_106_19814 | #!/usr/bin/env python
import numpy
from pyscf import scf
from pyscf import gto
from pyscf import mcscf
'''
Scan HF molecule triplet state dissociation curve
'''
ehf = []
emc = []
def run(b, dm, mo):
mol = gto.Mole()
mol.verbose = 5
mol.output = 'out_hf-%2.1f' % b
mol.atom = [
["F", (0., 0., 0... |
the-stack_106_19815 | import sys
import requests
webhook_host = 'https://webhook.link/'
consume_filename = 'consume.py'
def new_route():
""" Create a new route, get webhook URL """
r = requests.get(webhook_host + 'api/new')
if r.status_code != 200:
raise RuntimeError(
'Failed to create webhook. Error %d.... |
the-stack_106_19816 | import unittest
from src.school_algorithms._if_not_valid_raise import (_if_not_int_or_float_raise,
_if_not_positive_raise)
from src.school_algorithms import (circle_area,
power_calc,
energy_cal... |
the-stack_106_19819 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import today, random_string
from erpnext.crm.doctype.lead.lead import make_customer
from erpnext.crm.doctype.opportunity.opportunity import mak... |
the-stack_106_19822 | import numpy as np
from scipy.integrate import solve_ivp
from scipy.interpolate import interp1d
phi0 = 0.0001
r0 = 7
delta = 5
q = 2.
def genSim(tag,phi0,r0,delta,q):
def phi(r,phi0,r0,delta,q):
phi = phi0*r**3*np.exp(-((r-r0)/delta)**q)
return phi
def dphidr(r,phi0,r0,delta,q):
a = 3*phi0*np.exp(-((r-r0... |
the-stack_106_19826 | r"""HTTP/1.1 client library
<intro stuff goes here>
<other stuff, too>
HTTPConnection goes through a number of "states", which define when a client
may legally make another request or fetch the response for a particular
request. This diagram details these state transitions:
(null)
|
| HTTPConnection(... |
the-stack_106_19827 | # encoding: utf-8
"""
@author: zeming li
@contact: zengarden2009@gmail.com
"""
import os
import torch
from momentum_teacher.models.m2_teacher import M2Teacher
import torch.distributed as dist
from momentum_teacher.exps.arxiv import base_exp
class Exp(base_exp.BaseExp):
def __init__(self):
super(Exp, sel... |
the-stack_106_19828 | from PyQt5 import QtWidgets, QtGui, uic, QtCore
from PyQt5.QtWidgets import QFileDialog
import os
import csv
#from mainUI import Ui_MainWindow
# Path from main
UI_NAME = "mainUI.ui"
UI_PATH = "./GUI_Design/" + UI_NAME
path = os.getcwd()
qtCreatorFile = path + os.sep + UI_PATH
Ui_MainWindow, QtBaseClass = uic.loadUiT... |
the-stack_106_19830 | # Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
"""
packit.utils.extensions
=======================
Keeps functions that extend Python collections (list to dict, get on nested dict)
and force strict evaluation (`assert_existence`).
"""
from typing import Any
from packit.exceptions imp... |
the-stack_106_19831 | import numpy as np
from sklearn.externals import joblib
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets
from torch.autograd import Variable
from sklearn.model_selection import train_test_split
from tensorboardX import SummaryWriter
import t... |
the-stack_106_19833 | import pandas as pd
import math
from math import sqrt
from math import atan2
from numpy.linalg import norm, det
from numpy import cross, dot
from numpy import radians
from numpy import array, zeros
from numpy import cos, sin, arcsin, rad2deg, deg2rad
from similaritymeasures import curve_length_measure, frechet_dist
fro... |
the-stack_106_19834 | import pytest
from django.test import TestCase
from django.utils.timezone import now
from ..models import *
pytestmark = pytest.mark.django_db
class TipTestCase(TestCase):
def setUp(self):
"""Set up test data for testing Tip model"""
self.tip = Tip.objects.create(timestamp=now(),
... |
the-stack_106_19836 | from __future__ import print_function
import os
from setuptools import setup, find_packages
from distutils import log
from setupbase import (
create_cmdclass, install_npm, combine_commands,
ensure_targets, skip_npm
)
here = os.path.dirname(os.path.abspath(__file__))
node_root = os.path.join(here, 'js')
lo... |
the-stack_106_19837 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Babycoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test mempool limiting together/eviction with the wallet."""
from test_framework.test_framework import... |
the-stack_106_19838 | # -*- coding: utf-8 -*-
"""
Unit tests for the CCSV write module.
Author: Gertjan van den Burg
"""
import tempfile
import unittest
import clevercsv
from clevercsv.dialect import SimpleDialect
class WriterTestCase(unittest.TestCase):
def writerAssertEqual(self, input, expected_result):
with tempfile... |
the-stack_106_19840 | from unittest import mock, TestCase
from ff_espn_api import League
import requests_mock
import json
class LeagueTest(TestCase):
def setUp(self):
self.league_id = 123
self.season = 2018
self.espn_endpoint = "https://fantasy.espn.com/apis/v3/games/FFL/seasons/" + str(self.season) + "... |
the-stack_106_19841 | # 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_19843 | from pymongo import MongoClient
import matplotlib
matplotlib.use("TkAgg")
from matplotlib import pyplot
mongo_uri = "mongodb://admin:admin@ds021182.mlab.com:21182/c4e"
client = MongoClient(mongo_uri)
db = client.get_default_database()
customers = db["customers"]
wom = customers.find({"ref":"wom"}).count()
ads = custo... |
the-stack_106_19844 | __all__ = ["Monitor", "ResultsWriter", "get_monitor_files", "load_results"]
import csv
import json
import os
import time
from glob import glob
from typing import Dict, List, Optional, Tuple, Union
import gym
import numpy as np
import pandas
from stable_baselines3.common.type_aliases import GymObs, GymStepReturn
cl... |
the-stack_106_19845 | import datetime
import random
import time
import pytest
import prefect
from prefect.core import Edge, Flow, Parameter, Task
from prefect.engine.flow_runner import FlowRunner
from prefect.engine.result import NoResult, Result
from prefect.engine.state import Mapped, Pending, Retrying, Success
from prefect.utilities.de... |
the-stack_106_19847 | # -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Common data processing utilities that are used in a
typical object detection data pipeline.
"""
import logging
import numpy as np
import pycocotools.mask as mask_util
import torch
from fvcore.common.file_io import PathMa... |
the-stack_106_19848 | from __future__ import print_function
from compas.utilities import await_callback
from roslibpy import Message
from roslibpy import Ros
from roslibpy.actionlib import ActionClient
from roslibpy.actionlib import Goal
from compas_fab.backends.ros.exceptions import RosError
from compas_fab.backends.ros.messages import E... |
the-stack_106_19849 | from setuptools import setup, find_packages
import sys, os
version = '0.3'
setup(name='penstock',
version=version,
description="",
long_description="""\
""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author='Quintagroup, ... |
the-stack_106_19850 | import activations
import torch
import torch.nn as nn
import torch.distributions as D
from torch.nn import functional as F
import numpy as np
from M_Flow_NICE import FlowModel
class Encoder(nn.Module):
# only for square pics with width or height is n^(2x)
def __init__(self, image_size, nf, hidden_size=None, n... |
the-stack_106_19851 | # import libraries
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
import numpy as np
import pandas as pd
import pickle
from pprint import pprint
import re
import sys
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction.tex... |
the-stack_106_19852 | import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
channel.basic_consume(callback,
queue='hello',
... |
the-stack_106_19855 | from ethronsoft.gcspypi.utilities.queries import get_package_type
from ethronsoft.gcspypi.package.package import Package
from ethronsoft.gcspypi.exceptions import InvalidState
import json
import os
import shutil
import tarfile
import tempfile
import zipfile
class PackageBuilder(object):
def __init__(self, raw_... |
the-stack_106_19858 | import os
import numpy as np
from imblearn.over_sampling import SMOTE
from imblearn.under_sampling import NearMiss
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from PySIC.Data import Plotting
import matplotlib.pyplot as plt
import pandas as pd
class Preprocessing:
def __init__(self,X_Train, Y_Tra... |
the-stack_106_19859 | ## Copyright [2017-2018] UMR MISTEA INRA, UMR LEPSE INRA, ##
## UMR AGAP CIRAD, EPI Virtual Plants Inria ##
## Copyright [2015-2016] UMR AGAP CIRAD, EPI Virtual Plants Inria ##
## ##
## This file is ... |
the-stack_106_19860 | import matplotlib.pyplot as plt
import numpy as np
import mpld3
fig, ax = plt.subplots(subplot_kw=dict(facecolor='#EEEEEE'))
N = 100
scatter = ax.scatter(np.random.normal(size=N),
np.random.normal(size=N),
c=np.random.random(size=N),
s=1000 * np.random.ra... |
the-stack_106_19862 | # -*- coding: utf-8 -*-
"""Boardroom Voter object."""
import datetime
from warnings import warn
from .functions import *
from .errors import UpdateError
from .proposal import Proposal
from .protocol import Protocol
from .params import *
class Voter():
def __init__(self, address):
"""
Voter init m... |
the-stack_106_19863 | import dash
import dash_bootstrap_components as dbc
"""
https://github.com/facultyai/dash-bootstrap-components
dash-bootstrap-components provides Bootstrap components.
Plotly Dash is great! However, creating the initial layout can require a lot
of boilerplate. dash-bootstrap-components reduces this boilerplate by p... |
the-stack_106_19864 | # Copyright (c) 2010 testtools developers. See LICENSE for details.
"""Individual test case execution for tests that return Deferreds.
This module is highly experimental and is liable to change in ways that cause
subtle failures in tests. Use at your own peril.
"""
__all__ = [
'assert_fails_with',
'Asynchro... |
the-stack_106_19865 | #!/usr/bin/env python
#
# Copyright (C) 2019 Matt Struble
# Licensed under the MIT License - https://opensource.org/licenses/MIT
import time
import base64
import io
import os
import cv2
import gym
import numpy as np
from PIL import Image
from gym import spaces
from gym import utils
from gym_chrome_dino.game.chrome_di... |
the-stack_106_19870 | #!/usr/bin/env python3
# Copyright (c) 2014-2017 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the dir... |
the-stack_106_19871 | """
Tests for CaseResource api.
"""
from tests.case.api.crud import ApiCrudCases
from tests import case
import logging
mozlogger = logging.getLogger('moztrap.test')
class CaseResourceTest(ApiCrudCases):
@property
def factory(self):
"""The model factory for this object."""
return self.F.Ca... |
the-stack_106_19872 | import re
def n_gram(arr, n):
return zip(*(arr[_:] for _ in range(n)))
d = dict()
with open("Extra Material 2 - keyword list_with substring.csv") as f:
f.readline()
for line in f:
line = line.split(',')
grp, words = int(line[0]), line[1:]
for w in words:
w =... |
the-stack_106_19873 | import argparse
import kungfu
import tensorflow as tf
from kungfu.tensorflow.ops import egress_rates, monitored_all_reduce
from tensorflow.python.util import deprecation
deprecation._PRINT_DEPRECATION_WARNINGS = False
def parse_args():
p = argparse.ArgumentParser(description='Test')
p.add_argument('--max-st... |
the-stack_106_19875 | _base_ = [
'../_base_/models/resnet18.py',
'../_base_/datasets/imagenet_bs32.py',
'../_base_/schedules/imagenet_bs2048.py',
'../_base_/default_runtime.py'
]
actnn = True
data = dict(
samples_per_gpu=512, # 512*4 = 2048
workers_per_gpu=8,
)
log_config = dict(
interval=100,
hooks=[
... |
the-stack_106_19876 | from problems import VideoGenProblem
from netmodels import TorricelliNet, SliceNet
from losses import TVLoss
from plotting import movie, diffplot
# color space
cspace = "RGB"
# data directory
if cspace == "BW":
prefix = "data/bw/"
elif cspace == "GRAY":
prefix = "data/gray/"
elif cspace == "FLOW":
prefix ... |
the-stack_106_19877 | import BAC0
import logging
logger = logging.getLogger('BAC0')
logger.setLevel('DEBUG')
handler = logging.FileHandler('BAC0Log.txt', mode='a')
handler.setLevel('DEBUG')
logger.addHandler(handler)
bacnet = BAC0.connect('127.0.0.1', bokeh_server=False)
bacnet.whois()
print(bacnet.devices) |
the-stack_106_19878 | from pandac.PandaModules import NodePath
from direct.gui.DirectButton import DirectButton
from toontown.catalog import CatalogGlobals
class CatalogTabButton(NodePath):
def __init__(self, catalogGui, nodeName, clickEvent):
NodePath.__init__(self, catalogGui.attachNewNode(nodeName))
self.active = F... |
the-stack_106_19880 | import numpy as np
import torch, math
import torch.nn as nn
from onmt.modules.Transformer.Layers import EncoderLayer, DecoderLayer, PositionalEncoding, variational_dropout, PrePostProcessing
from onmt.modules.BaseModel import NMTModel, Reconstructor, DecoderState
import onmt
from onmt.modules.WordDrop import embedded_d... |
the-stack_106_19881 | import time
import streamlit as st
from openleveldb.database import LevelDB
@st.cache(hash_funcs={LevelDB: id}, allow_output_mutation=False)
def get_db() -> LevelDB:
return LevelDB("/tmp/testdb/")
db = get_db()
db["key"] = "value"
st.checkbox("make it not crash :)")
num = 20
p = st.progress(0)
for x in ra... |
the-stack_106_19882 | #!/usr/bin/python
#
# Copyright 2018-2020 Polyaxon, 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 ... |
the-stack_106_19883 | """A script which executes an drug repurposing model on input files.
Expects:
/model/: should have feature_means.csv, features_stds.csv,
estimator_coef.csv, most_variant_genes.csv.
/input/: should have all the input files.
Creates:
/output/predictions.csv: a CSV with columns ['lab_id', 'survival']... |
the-stack_106_19885 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... |
the-stack_106_19886 | from distutils.util import strtobool
import os
import logging
from typing import Any, List, Set, NamedTuple
from distutils.version import LooseVersion
try:
import onnx
from tf2onnx.tfonnx import process_tf_graph, tf_optimize
from tf2onnx import optimizer
ONNX_EXPORT_ENABLED = True
except ImportError:
... |
the-stack_106_19887 | # -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from data import coco as cfg
from ..box_utils import match, log_sum_exp
class MultiBoxLoss(nn.Module):
"""SSD Weighted Loss Function
Compute Targets:
1) Produce Confidence Tar... |
the-stack_106_19888 | # -*- coding: utf-8 -*-
# @Author : llc
# @Time : 2021/6/6 14:05
from typing import Optional
from pydantic import BaseModel, Field
from flask_openapi3 import APIBlueprint, OpenAPI
from flask_openapi3 import HTTPBearer
from flask_openapi3 import Tag, Info
info = Info(title='book API', version='1.0.0')
securitySc... |
the-stack_106_19889 | """Support for Xiaomi Mi Air Purifier and Xiaomi Mi Air Humidifier."""
from abc import abstractmethod
import asyncio
from enum import Enum
import logging
import math
from miio.airfresh import OperationMode as AirfreshOperationMode
from miio.airpurifier import OperationMode as AirpurifierOperationMode
from miio.airpuri... |
the-stack_106_19890 | #!/usr/bin/env python3
# Copyright (c) 2015-2016 The Sikacoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Utilities for manipulating blocks and transactions."""
from .mininode import *
from .script import CS... |
the-stack_106_19893 | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
the-stack_106_19894 | # -*- coding: utf-8 -*-
# Copyright (c) 2015 Fredrik Eriksson <git@wb9.se>
# This file is covered by the BSD-3-Clause license, read LICENSE for details.
import xbmc
import xbmcaddon
import xbmcgui
__addon__ = xbmcaddon.Addon()
def display_error_message(
message_id,
append="",
title=__addon__.... |
the-stack_106_19895 | # imports
import os
import time
import mlflow
import argparse
import pandas as pd
import lightgbm as lgb
import matplotlib.pyplot as plt
from sklearn.metrics import log_loss, accuracy_score
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
# define functions
def prep... |
the-stack_106_19899 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2019 all rights reserved
#
"""
Verify processing of a correct pfg input file
"""
def test():
# package access
import pyre.config
from pyre.config.events import Assignment
# get the codec manager
m = p... |
the-stack_106_19900 | import ast
import os.path
import warnings
from datetime import timedelta
import dj_database_url
import dj_email_url
import django_cache_url
import jaeger_client
import jaeger_client.config
import pkg_resources
import sentry_sdk
import sentry_sdk.utils
from django.core.exceptions import ImproperlyConfigured
from django... |
the-stack_106_19901 | import numpy as np
import lenstronomy.Util.util as util
from lenstronomy.ImSim.Numerics.convolution import PixelKernelConvolution
from lenstronomy.Data.pixel_grid import PixelGrid
from lenstronomy.Data.image_noise import ImageNoise
__all__ = ['ImageData']
class ImageData(PixelGrid, ImageNoise):
"""
class to... |
the-stack_106_19902 | pkgname = "rest"
pkgver = "0.9.0"
pkgrel = 0
build_style = "meson"
configure_args = [
"-Dca_certificates=true", "-Dsoup2=false", "-Dgtk_doc=false",
"-Dca_certificates_path=/etc/ssl/certs/ca-certificates.crt"
]
hostmakedepends = [
"meson", "pkgconf", "gobject-introspection", "glib-devel", "vala",
]
makedepen... |
the-stack_106_19903 | import math
import argparse
import numpy as np
from utils import arg_sort, intersect_sizes
def get_args():
parser = argparse.ArgumentParser(description="HyperParameters for String Embedding")
parser.add_argument("--dataset", type=str, default="gen50ks.txt", help="dataset")
parser.add_argument("--nt", typ... |
the-stack_106_19904 | import socket
from _thread import *
import sys
from hardwareControl import responseToTheRequest
## Web Socket
HOST = '' # all available interfaces
PORT = 12345 # Non-privileged port
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print("Socket Created")
try:
s.bind((HOST,PORT))
except socket.error as msg... |
the-stack_106_19907 | import Test
######################################## ANSWER AREA ########################################
def brain_luck(code, input):
Q = [0] * 1000000
output = ''
dp = 0
pc = 0
# > increment the data pointer (to point to the next cell to the right).
# < decrement the data pointer (to point to the next cell to... |
the-stack_106_19908 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Runs CIFAR10 training with differential privacy.
"""
import argparse
import logging
import os
import shutil
import sys
from datetime import datetime, timedelta
from opacus import PrivacyEngine
from opacus.layers import ... |
the-stack_106_19910 | import subprocess
import os
from typing import List, Optional
from core.util import check_gdb
class Args:
'''The arguments processed by parse_args() that need to be passed to run_gdb()'''
def __init__(self, wldbg_args: List[str], gdb_args: List[str]) -> None:
self.wldbg = wldbg_args
self.gdb =... |
the-stack_106_19912 | from django.conf.urls import url
from .tasks.documents import DocumentsTask
from .tasks.mails import MailDocumentsTask
from .views.download import DownloadDocument
urlpatterns = [
url(
"(?P<document_id>.+)/download",
DownloadDocument.as_view(),
name="download-document",
),
url(
... |
the-stack_106_19913 | #!/usr/bin/env python3
"""
Author : wliu <wliu@localhost>
Date : 2021-09-18
Purpose: Solfege
"""
import argparse
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Solfege',
formatter_class=ar... |
the-stack_106_19915 | import sys
m = int(sys.argv[1])
n = int(sys.argv[2])
fn = sys.argv[3]
os = 'UBUNTU12-64-STD'
c_hw = 'pc3000'
s_hw = 'd710'
header = """set ns [new Simulator]
source tb_compat.tcl\n"""
set_node = """set node%d [$ns node]
tb-set-node-os $node%d %s
tb-set-hardware $node%d %s\n"""
set_server = """set server%d [$ns nod... |
the-stack_106_19916 | from JumpScale import j
class TextCharEditor:
"""
represents a piece of text but broken appart in blocks
this one works on a char basis
"""
def __init__(self, text, textfileeditor):
text = text.replace("\t", " ")
text = text.replace("\r", "")
self.chars = [[char, "", 0]... |
the-stack_106_19918 | __all__ = ['atoms_to_graph','get_paths','remove_non_rings','paths_to_atoms',
'remove_dups','remove_labeled_dups','dict_to_atoms','get_vertices',
'shortest_valid_path','is_valid','all_paths','remove_geometric_dups']
'''
This module contains utilities to be used by the rings.py module.
'''
import ... |
the-stack_106_19919 | # -*- coding: utf-8 -*-
"""
:synopsis: Base class for HAL objects
.. moduleauthor:: John Morris <john@dovetail-automata.com>
"""
import hal
import rospy
class HalObjBase(object):
"""Base class for HAL component objects
Takes care of caching objects related to HAL components, like the
component ... |
the-stack_106_19920 | # -*- coding: utf-8 -*-
# Copyright (c) 2012 Fabian Barkhau <fabian.barkhau@gmail.com>
# License: MIT (see LICENSE.TXT file)
from django.conf.urls import patterns, include, url
from apps.common.urls import arg_id, arg_slug
T = arg_slug("team_link")
P = arg_slug("page_link")
L = arg_id("link_id")
... |
the-stack_106_19921 | # Copyright 2021 The Kubeflow 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_19923 | """
These tests are designed to test execution time for
various chat bot configurations to help prevent
performance based regressions when changes are made.
"""
from unittest import skip
from warnings import warn
from random import choice
from tests.base_case import ChatBotSQLTestCase, ChatBotMongoTestCase
f... |
the-stack_106_19925 | # -*- coding: utf-8 -*-
#Figure 7.1
def getRatios(vect1, vect2):
"""Assumes: vect1 and vect2 are equal length lists of numbers
Returns: a list containing the meaningful values of
vect1[i]/vect2[i]"""
ratios = []
for index in range(len(vect1)):
try:
ratios.append(vec... |
the-stack_106_19927 | import igraph
def tet_collision(t1, t2, vx, vy, vz):
sym1 = t1.get_symmetry(vx, vy, vz)
sym2 = t2.get_symmetry(vx, vy, vz)
for s1 in sym1:
for s2 in sym2:
if s1.collision(s2):
return True
return False
def packing_graph(tets, vx, vy, vz, independent = 0):
N = len... |
the-stack_106_19929 | import asyncio
import dataclasses
import logging
import multiprocessing
from concurrent.futures.process import ProcessPoolExecutor
from enum import Enum
from typing import Dict, List, Optional, Set, Tuple, Union
from clvm.casts import int_from_bytes
from chia.consensus.block_body_validation import validate_block_body... |
the-stack_106_19930 | r"""
Littelmann paths
AUTHORS:
- Mark Shimozono, Anne Schilling (2012): Initial version
- Anne Schilling (2013): Implemented
:class:`~sage.combinat.crystals.littelmann_path.CrystalOfProjectedLevelZeroLSPaths`
- Travis Scrimshaw (2016): Implemented
:class:`~sage.combinat.crystals.littelmann_path.InfinityCrystalOfL... |
the-stack_106_19932 | from __future__ import annotations
import typing
import warnings
if typing.TYPE_CHECKING:
import pydantic
from . import spec
def validate_config(
config: typing.MutableMapping[str, typing.Any],
config_spec: typing.Type,
validate: spec.ValidationOption,
):
if not validate:
return None... |
the-stack_106_19933 | #!/usr/bin/env python3
import sys
import pysam
from collections import Counter
from umierrorcorrect.src.get_regions_from_bed import read_bed, sort_regions, merge_regions
def get_chromosome_list_from_bam(f):
contiglist = []
for chrx in f.get_index_statistics():
if chrx.total > 0:
contiglist... |
the-stack_106_19934 | n = int(input())
ps = []
for _ in range(n):
s = input()
ps.append((int(s[:-1]), int(s[-1])))
sum = 0
for p in ps:
sum += p[0] ** p[1]
print(sum)
|
the-stack_106_19936 | import tensorflow as tf
import numpy as np
import sonnet as snt
from dps import cfg
from dps.datasets import EmnistObjectDetectionDataset
"""
The main takeaway from this is that AffineGridWarper layers an axis (-1, 1) x (-1, 1) over the input
image, with y increasing downward and x increasing rightward.
"""
n_examp... |
the-stack_106_19938 | import os
import torch
from torchtext import data, datasets
from argparse import ArgumentParser
def get_args():
EPOCHS = 6
USE_GPU = torch.cuda.is_available()
EMBEDDING_DIM = 300
HIDDEN_DIM = 128
BATCH_SIZE = 50
config = {
"retrain": False,
"epochs": EPOCHS,
"batch_size... |
the-stack_106_19940 | import dgl
import time
import tqdm
import ipdb
import argparse
import pandas as pd
import seaborn as sns
import numpy as np
from sklearn.neighbors import NearestNeighbors
from scipy.stats import pearsonr
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
import torch
import torch.nn.func... |
the-stack_106_19943 | """Support for binary sensor using Beaglebone Black GPIO."""
import voluptuous as vol
from homeassistant.components import bbb_gpio
from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity
from homeassistant.const import CONF_NAME, DEVICE_DEFAULT_NAME
import homeassistant.helpers.config_v... |
the-stack_106_19944 | """
pysd.py
Contains all the code that will be directly accessed by the user in
normal operation.
"""
import sys
if sys.version_info[:2] < (3, 7): # pragma: no cover
raise RuntimeError(
"\n\n"
+ "Your Python version is not longer supported by PySD.\n"
+ "The current version needs to run ... |
the-stack_106_19948 | import os
import cv2
import numpy as np
import logging, sys
from bfio import BioReader, BioWriter
from pathlib import Path
from aicsimageio import AICSImage
from scipy.ndimage.morphology import binary_fill_holes
from aicssegmentation.core.seg_dot import dot_2d_slice_by_slice_wrapper
from aicssegmentation.core.pre_proce... |
the-stack_106_19950 | # Dependencies
import numpy as np
import pandas as pd
from bs4 import BeautifulSoup as bs
import requests
from splinter import Browser
# Initialize browser
def init_browser():
executable_path = {"executable_path": "/usr/local/bin/chromedriver"}
#executable_path = {'executable_path': 'chromedriver.exe'}
r... |
the-stack_106_19951 | # --------------------------------------------------------
# Tensorflow Faster R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by Xinlei Chen
# --------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from __future__ impor... |
the-stack_106_19954 | """
Conditional random field
"""
from typing import List, Tuple, Dict
import torch
from allennlp.common.checks import ConfigurationError
import allennlp.nn.util as util
def allowed_transitions(constraint_type: str, labels: Dict[int, str]) -> List[Tuple[int, int]]:
"""
Given labels and a constraint type, ret... |
the-stack_106_19960 | from argparse import ArgumentParser
import sys
import subprocess
from select import select
import time
# Wait for the given line to be output by the process.
def wait_for_line(process, needle, max_timeout=1000):
start = time.clock()
while(time.clock() - start < max_timeout):
process.poll()
if(process.returncode ... |
the-stack_106_19961 | """Helpers for workings with sequences and (numpy) arrays."""
from itertools import chain
import numpy as np
from scipy.sparse import issparse, csr_matrix
from tqdm import tqdm
def flatten_list(lst):
return list(chain(*lst))
def apply_along_rows(func, X):
"""
Apply function row-wise to input matrix X.
... |
the-stack_106_19963 | import scrapy
from zufang.items import ZufangItem
class GanjiSpider(scrapy.Spider):
name = "zufang"
start_urls = ['http://bj.ganji.com/fang1/chaoyang/']
def parse(self, response):
zf = ZufangItem()
title_list = response.xpath(".//div[@class='f-list-item ']/dl/dd[1]/a/text()").extr... |
the-stack_106_19968 | """Example 02
Section: Rectangular 230 x 450
Compression steel: 1-16# at 35, Tension steel: 3-16# at -35
Output: xu and report of the section.
"""
from rcdesign.is456.stressblock import LSMStressBlock
from rcdesign.is456.concrete import Concrete
from rcdesign.is456.rebar import (
RebarHYSD,
RebarLayer,
Reb... |
the-stack_106_19969 | from base_filter import BaseFilter
class TableScanFilter(BaseFilter):
""" accepts only if the line contains a nscanned:[0-9] nreturned:[0-9] where the ratio of nscanned:nreturned is > 100 and nscanned > 10000
"""
filterArgs = [
('--scan', {
'action':'store_true',
'help':
... |
the-stack_106_19971 | """
The purpose of this script is to find all binaries in the demos src folder and
copy them into the bin folder.
"""
import os
import glob
import shutil
PATH_HERE = os.path.abspath(os.path.dirname(__file__))
def cleanFolder():
for path in glob.glob(f"{PATH_HERE}/bin/*.dll"):
print(f"deleting {os.path.b... |
the-stack_106_19976 | # Copyright 2017 Bloomberg Finance 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
#
# Unless required by applicable law or agr... |
the-stack_106_19977 | # Copyright 2019-2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.