text stringlengths 1 927k |
|---|
# Copyright (c) 2019 Gurjit Singh
# This source code is licensed under the MIT license that can be found in
# the accompanying LICENSE file or at https://opensource.org/licenses/MIT.
import sys
import datetime
import pathlib
import argparse
from tinytag import TinyTag
def parseArgs():
def dirPath(pth):
... |
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.EGL import _types as _cs
# End users want this...
from OpenGL.raw.EGL._types import *
from OpenGL.raw.EGL import _errors
from OpenGL.constant import Constant as _C
import ctype... |
#!/usr/bin/python
"""
abodecl by Wil Schrader - An Abode alarm Python library command line interface.
https://github.com/MisterWil/abodepy
Published under the MIT license - See LICENSE file for more details.
"Abode" is a trademark owned by Abode Systems Inc., see www.goabode.com for
more information. I am in no way ... |
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# Copyright 2016 Google Inc. 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 ag... |
#run using python fibonacci_search.py -v
'''
@params
arr: input array
val: the value to be searched
output: the index of element in the array or -1 if not found
return 0 if input array is empty
'''
def fibonacci_search(arr, val):
"""
>>> fibonacci_search([1,6,7,0,0,0], 6)
1
>>> fibonacci_search([1,-1,... |
# 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... |
# coding: utf-8
import pandas as pd
import numpy as np
def main():
nezha_result = pd.read_csv('./result_nezha.csv', header=None)
nezha_result.columns = ['report_ID', 'label']
dl_result = pd.read_csv('./result_dl.csv', header=None)
dl_result.columns = ['report_ID', 'label']
new_label_nezha = [i.s... |
#!/bin/env python
"""
Simple VTK example in Python to load an STL mesh and display with a manipulator.
Chris Hodapp, 2014-01-28, (c) 2014
"""
import vtk
def render():
# Create a rendering window and renderer
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
# Create a... |
import sys
sys.path.append('.')
import lxmls.sequences.crf_online as crfo
import lxmls.sequences.structured_perceptron as spc
import lxmls.readers.pos_corpus as pcc
import lxmls.sequences.id_feature as idfc
import lxmls.sequences.extended_feature as exfc
print "CRF Exercise"
corpus = pcc.PostagCorpus()
train_seq = ... |
from .imports import *
from .lroptimize.sgdr import *
from .lroptimize.triangular import *
from .lroptimize.lrfinder import *
from .lroptimize.optimization import AdamWeightDecay
from . import utils as U
from .vision.preprocessor import ImagePreprocessor
from .vision.predictor import ImagePredictor
from .text.preproc... |
import asyncio
import json
import logging
import queue
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta
from typing import Dict, Tuple, List
from cincanregistry.models.tool_info import ToolInfo
from cincanregistry.models.version_info import VersionInfo, VersionType
from .check... |
from __future__ import print_function
import helpers_test
from cparser import *
from cparser.interpreter import *
from helpers_test import *
import ctypes
def test_interpret_c_cast():
state = parse("int f()\n { int v = (int) 42; return v; } \n")
interpreter = Interpreter()
interpreter.register(state)
... |
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def test(self):
self.build()
lldbutil.run_to_source_breakpoint(self,"// break here", lldb.SBFileSpec... |
"""
===========================
FiveThirtyEight style sheet
===========================
This shows an example of the "fivethirtyeight" styling, which
tries to replicate the styles from FiveThirtyEight.com.
"""
from matplotlib import pyplot as plt
import numpy as np
plt.style.use('fivethirtyeight')
x = np.linspace(... |
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class RetinaLoss(nn.Module):
def __init__(self,
image_w,
image_h,
alpha=0.25,
gamma=2,
beta=1.0 / 9.0,
epsilon=1e... |
from django.conf.urls import include, url
from rest_framework import routers
from restapi.views import (UserViewSet, ProjectViewSet, ImageViewSet,
ApplicationViewSet, PortViewSet, ResourceLimitViewSet, VolumeViewSet,
is_authenticated, create_image, upload_volume, list_hosts,
AutoScalerViewSet, EnvironmentVi... |
# -*- coding: utf-8 -*-
"""共有リンク関連APIの実装."""
# community module
from flask import abort, request
# project module
from circle_core.models import MetaDataSession, ReplicationLink
from .api import api
from .utils import respond_failure, respond_success
from ..utils import (oauth_require_read_schema_scope, oauth_requir... |
'''helpers module for astro_reduce -- UI constants and handy functions.'''
from hashlib import md5
from json import dump
from os.path import basename
from re import sub
import click
import matplotlib.colors as colors
import numpy as np
from astropy.io import fits
from astropy.visualization import ImageNormalize, ZSca... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 15 11:01:01 2020
In this notebook I give a very simple (and rather uncommented) example of
how to use scikit-learn to perform an Empirical Orthogonal Function
decomposition (EOF analysis, often referred to as well as Principal
Component Analysi... |
from flask import Flask
from flask import Response
from flask import render_template
app = Flask(__name__)
@app.route('/')
def index():
#return render_template("index.html")
return "<h2>This works, which is surprising sometimes. Now with 140% more DevOps!</h2>"
@app.route("/healthz")
def healthz():
re... |
import re
import os
def load_inria_annotations(index):
filename = os.path.join('Annotations', index + '.txt')
with open(filename) as f:
data = f.read()
objs = re.findall('\(\d+, \d+\)[\s\-]+\(\d+, \d+\)', data)
num_objs = len(objs)
return objs
if __name__ == '__main__':
files = ['1', '... |
import contextlib
import glob
import io
import os.path
import re
import sys
__file__ = os.path.abspath(__file__)
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
INTERNAL = os.path.join(ROOT, 'Include', 'internal')
STRING_LITERALS = {
'empty': '',
'dot': '.',
}
IGNORED = {
'ACTION', #... |
import pickle
import string
import numpy as np
import multiprocessing
# system setup
ProcessNum=np.min((10, multiprocessing.cpu_count()))
# Used for generating the random filename
FileNameChars = list(string.letters + string.digits)
FileNameLen = 30
'''
Process the binary file
'''
def read_bin(path):
with open(path... |
# Generated by Django 2.2.10 on 2020-07-21 13:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('obras_sociales', '0005_auto_20200426_1155'),
]
operations = [
migrations.AddField(
model_name='obrasocialpaciente',
... |
# Copyright 2017 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... |
import aoc.d14
from tests.aoc.test_base import BaseTestCase
class TestAll(BaseTestCase):
def test_part_one(self):
self.run_aoc_part(14, 5902420735773, aoc.d14.p_1)
def test_part_two(self):
self.run_aoc_part(14, 3801988250775, aoc.d14.p_2) |
import json, subprocess
from ... pyaz_utils import get_cli_name, get_params
def list_operation():
params = get_params(locals())
command = "az maps map list-operation " + params
print(command)
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = ... |
from datetime import datetime
from django.contrib import messages
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_laz... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 16 21:26:27 2017
@author: Xin
"""
# -*- coding: utf-8 -*-
"""Main module."""
import pandas as pd
import csv
import time
import itertools
import math
import json
#initialization class
class Init:
def __init__(self, filename):
self.file... |
import Tkinter as tk
import ttk
import tkFileDialog
import tkMessageBox
import tkSimpleDialog
import cv2
import cv2.cv as cv
import os
import multiprocessing
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.backend_bases import key_press_handler
f... |
# @Time : 2019/4/24 22:34
# @Author : xufqing
from rest_framework import serializers
from ..models import Label
from ..models import DeviceInfo
class LabelSerializer(serializers.ModelSerializer):
'''
标签序列化
'''
hosts = serializers.PrimaryKeyRelatedField(many=True, required=False, queryset=DeviceInf... |
from numpy.testing import *
from numpy.lib import *
from numpy.core import *
from numpy.compat import asbytes
def assert_all(x):
assert(all(x)), x
class TestCommonType(TestCase):
def test_basic(self):
ai32 = array([[1,2],[3,4]], dtype=int32)
af32 = array([[1,2],[3,4]], dtype=float32)
... |
from determined_common.schemas.expconf._validate import validation_errors |
# november 2021
# Internship project: Confidence bounds
# RANDOM DOT MOTION TASK (variant with 6 confidence options)
# (Does the majority of dots move left or right? How confident are you about your choice?)
# Participants complete multiple blocks of consecutive dot motion trials
# 3 training blocks with increasing co... |
import ui
class StackOverflowManagementView (object):
def __init__(self, download_action, refresh_main_view, delete_action, refresh_stackoverflow_action, theme_manager):
self.data = []
self.delete_action = delete_action
self.download_action = download_action
self.refresh_main_view = refresh_main_view
self.r... |
import pathlib
import logging
from ruamel import yaml
from qhub.deploy import deploy_configuration
from qhub.schema import verify
from qhub.render import render_template
logger = logging.getLogger(__name__)
def create_deploy_subcommand(subparser):
subparser = subparser.add_parser("deploy")
subparser.add_ar... |
#!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Copyright (c) 2017 The Raven Core developers
# Copyright (c) 2018 The Colombo Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test Hierarc... |
import math
from collections import Counter
# Collect BLEU-relevant statistics for a single hypothesis/reference pair.
# Return value is a generator yielding:
# (c, r, numerator1, denominator1, ... numerator4, denominator4)
# Summing the columns across calls to this function on an entire corpus will
# produce a vector... |
# Copyright 2018-2019 Jetperch LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
point_cloud_range = [-54.0, -54.0, -5.0, 54.0, 54.0, 3.0]
class_names = [
'car', 'truck', 'construction_vehicle', 'bus', 'trailer', 'barrier',
'motorcycle', 'bicycle', 'pedestrian', 'traffic_cone'
]
voxel_size = [0.075, 0.075, 0.2]
out_size_factor = 8
evaluation = dict(interval=1)
dataset_type = 'NuScenesDatase... |
import numpy as np
import properties
import z_order_utils
class BaseMetadata(properties.HasProperties):
name = properties.String("Name of the block model", default="")
description = properties.String("Description of the block model", default="")
# Other named metadata?
class BaseOrientation(properties.H... |
##### DEPENDENCIES ####
from dronekit import connect, VehicleMode, LocationGlobalRelative,APIException
import time
import socket
import exceptions
import math
import argparse
##### FUNCTIONS #####
def connectMyCopter():
"""
:return: Vehicle object connected to IP adress specified in terminal
"""
pars... |
# -*- coding:utf-8 -*-
# This file is adapted from the torchvision library at
# https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
# 2020.6.29-Changed for Modular-NAS search space.
# Huawei Technologies Co., Ltd. <linyunfeng5@huawei.com>
# Copyright 2020 Huawei Technologies Co., Ltd.
... |
# Code in this file is copied and adapted from
# https://github.com/openai/evolution-strategies-starter.
from collections import namedtuple
import logging
import numpy as np
import random
import time
from typing import Optional
import ray
from ray.rllib.agents import Trainer, TrainerConfig
from ray.rllib.agents.es im... |
import yagmail
receiver = "ikiguma%73628@gmail.com"
body = "Thank you for registering with Bookshelf!"
subject = "Successful Registration!"
html = '<a href="https://bookshelfaacdl.herokuapp.com/"><br />Bookshelf</a>'
def sending_email(receiver, subj, body, html):
yag = yagmail.SMTP("bookshelfaacdl", "&UD0$r?zir... |
from __future__ import unicode_literals
import frappe, sys
import erpnext
import frappe.utils
from erpnext.demo.user import hr, sales, purchase, manufacturing, stock, accounts, projects, fixed_asset, education
from erpnext.demo.setup import education, manufacture, setup_data, healthcare
"""
Make a demo
1. Start with ... |
"""The module which houses the Parametrized Quantum Circuit trainer class.
It generates the TensorFlow Quantum model, and allows Keras like API to
train and evaluate a model.
"""
import typing
import cirq
import tqdm.auto as tqdm
import warnings
warnings.filterwarnings("ignore")
import tensorflow as tf
import tens... |
from RPQ import loadgraph, runquery, bfs
from parse import NFA, State
import re
def get_outgoing_nodes(filename):
g = loadgraph(filename)
domain_name = list(g.keys())[0].split(":")[0]
nodes_out = set()
node_in = domain_name.lower()
for key in g.keys():
if key.split(":")[0].lower() != node_... |
"""
Downloads and creates data manifest files for IEMOCAP
(https://paperswithcode.com/dataset/iemocap).
Authors:
* Mirco Ravanelli, 2021
* Modified by Pierre-Yves Yanni, 2021
* Abdel Heba, 2021
"""
import os
import sys
import re
import json
import random
import logging
import glob
from scipy.io import wavfile
from... |
import gcodesender as gc
import os
import operator
def ensure_directory(file_path):
"""Checks the given file path for a directory, and creates one if not already present.
Args:
file_path: a string representing a valid URL
"""
directory = os.path.dirname(file_path)
if not os.path.exists(di... |
from discord.ext import commands
import sqlite3
import os, sys
from colorama import Fore, Back, Style
import threading
from time import sleep
import asyncio
import start
from settings import repeatedTimer, fancyStats, guildStats, databaseMigrator, serverChatLog, chatLeaderboard, configFunctions, welcomeMessages, extr... |
#!/usr/bin/env python
name1 = "Kirk Byers"
name2 = "George Washington"
name3 = "Thomas Jefferson"
name4 = input("Enter fourth name: ")
print()
print("{:>30}".format(name1))
print("{:>30}".format(name2))
print("{:>30}".format(name3))
print("{:>30}".format(name4))
print() |
"""
Extract the words from a tree and reverse the tokenization
"""
def get_words(tree):
# Assume well formed
if len(tree) == 2:
return [tree[1]]
else:
return get_words(tree[1]) + get_words(tree[2])
LEFT = {
'``': '"',
'-LRB-': '(',
'$': '$',
}
RIGHT = {
"''": '"',
"-RR... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the kaprekarNumbers function below.
def kaprekarNumbers(p, q):
found = False
for n in range(p,q+1):
d = len(str(n))
s = n*n
ds = len(str(s))
l=str(s)[:ds-d]
r=str(s)[ds-d:]
if l ... |
# -*- coding: utf-8
from __future__ import absolute_import, unicode_literals
import os
import sys
DEBUG = True
USE_TZ = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "33333333333333333333333333333333333333333333333333"
# Build paths inside the project like this: os.path.join(B... |
'''
test access_groups
'''
import uuid
import pytest
from tenable.errors import UnexpectedValueError, APIError
from tests.checker import check
@pytest.fixture(name='rules')
def fixture_rules():
'''
Fixture to return access_group rules structure
'''
return [('ipv4', 'eq', ['192.168.0.0/24'])]
@pytest.f... |
#-------------------------------------------------------------#
# MobileNetV2的网络部分
#-------------------------------------------------------------#
import math
import numpy as np
import tensorflow as tf
from tensorflow.keras import backend
from tensorflow.keras.layers import (Activation, Add, BatchNormalization,
... |
from rest_framework.decorators import api_view
from rest_framework import status, views
from rest_framework.response import Response
from .serializers import EntitySerializer, UserEntitySerializer
from .services import create_entity, deduct_user_entity, update_or_create_user_entity, claim_income
from .selectors import ... |
#!/usr/bin/python3
#
# Sets up a simple db to hold tuning parameters and log file names
# Maintains parameters for tuning runs
# Runs halcmds
# Starts and stops sampler runs
#
# Copyright 2021 Robert Bond
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in com... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: awsenergylabelercliexceptions.py
#
# Copyright 2021 Theodoor Scholte, Costas Tyfoxylos, Jenda Brands
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal ... |
import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow.keras.layers import Conv2D, MaxPooling2D, \
UpSampling2D, Cropping2D, concatenate, ZeroPadding2D, SpatialDropout2D
import functools
def create(input_shape, num_class=1, activation=tf.nn.relu):
opts = locals().copy()
# model = De... |
#!/usr/bin/python
def main():
nums = [5000, 10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000]
# nums = [1, 10]
for num in nums:
f = open("mt_xor_" + str(num) + ".v", "w+")
f.write("module mt_xor_" + str(num) + "(\n")
for i in range(num):
f.write(" input a" + str(i)+ ",\n... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Centralized catalog of paths."""
import os
class DatasetCatalog(object):
DATA_DIR = "datasets"
DATASETS = {
"coco_2017_train": {
"img_dir": "coco/train2017",
"ann_file": "coco/annotations/instances_trai... |
#!/usr/bin/python
# multitonePygameSampler.py
# this enables you to press the buttoins on PiPiano like a piano, and will play the sounds out of the Pi's audio output like a proper keyboard
# Author : Zachary Igielman
# to run:
# sudo python multitonePygameSampler.py
# to change volume:
# amixer cset numid=1 -- 80%
#... |
from schema import Schema, And, Optional
import re
def tags_validator(tags):
if tags:
tags = tags.replace(', ', ',').split(',')
tag_pattern = re.compile('^[A-Za-z0-9\-\_]+$')
for tag in tags:
if not tag_pattern.match(tag):
return False
return True
ret... |
from hyperlink_preview.hyperlink_preview import HyperLinkPreview
import json
import sys
import timeit
try:
import gevent
except ImportError:
gevent = None
class Node(object):
def __init__(self, name, id_):
self.name = name
self.id_ = id_
self.children = {}
self.hitCount =... |
"""Web client."""
import asyncio
import socket
import aiohttp
import async_timeout
import backoff
from integrationhelper.const import GOOD_HTTP_CODES
class WebClient:
"""Web client."""
def __init__(self, session=None, logger=None):
"""
Initialize.
Sample Usage:
from integra... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2012, Red Hat, Inc
# Written by Seth Vidal <skvidal at fedoraproject.org>
# Copyright: (c) 2014, Epic Games, Inc.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, p... |
# -*- coding: utf-8 -*-
""" mca module
"""
# Author: Olivier Garcia <o.garcia.dev@gmail.com>
# License: BSD 3 clause
import numpy as np
from sklearn.preprocessing import LabelBinarizer
from fanalysis.base import Base
class MCA(Base):
""" Multiple Correspondence Analysis (MCA)
This class inherits from... |
from django.shortcuts import render
from django.conf import settings
from django.http import JsonResponse
from pymongo import MongoClient
from dashboard_nosql import urls
from rest_framework import (response, schemas, filters, generics, viewsets,
views)
from rest_framework.parsers import J... |
"""Code for handling downloading of ensembl files used by scout from CLI"""
import logging
import pathlib
import click
from scout.utils.scout_requests import (
fetch_ensembl_exons,
fetch_ensembl_genes,
fetch_ensembl_transcripts,
)
LOG = logging.getLogger(__name__)
def print_ensembl(out_dir, resource_ty... |
from .coco_eval import do_coco_evaluation
def coco_evaluation(
dataset,
predictions,
output_folder,
box_only,
iou_types,
expected_results,
expected_results_sigma_tol,
ignore_uncertain=False,
use_iod_for_ignore=False,
eval_standard='coco',
gt_file=None,
use_ignore_attr=T... |
#!/usr/bin/env python3
"""
This module defines a KakSender class to communicate with Kakoune sessions
over Unix sockets. It implements smooth scrolling when executed as a script.
"""
import sys
import os
import time
import socket
SEND_INTERVAL = 2e-3 # min time interval (in s) between two sent scroll events
class ... |
import logging
LOG = logging.getLogger(__name__)
def default_fallback(ex, route_name, payload, ctx):
LOG.error(
"Error %s occur while handling route %s with payload %s and ctx %s" %
(ex, route_name, payload, ctx))
LOG.exception(ex)
raise ex
class SingleBotFlowFactory:
_botflow = Non... |
import argparse
import os
print("In extract.py")
print("As a data scientist, this is where I use my extract code.")
parser = argparse.ArgumentParser("extract")
parser.add_argument("--input_extract", type=str, help="input_extract data")
parser.add_argument("--output_extract", type=str, help="output_extract directory")... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pylint: disable=C0103,C0111
"""Definition of enum Direc."""
# 定义方向类型的枚举
from enum import Enum, unique
# 导入枚举类Enum和装饰器unique
# unique装饰器检查不会枚举有相同值的元素
@unique
class Direc(Enum):
"""Directions on the game plane."""
# 定义各个方向在游戏中的值
NONE = 0
LEFT = 1
UP ... |
# Copyright 2020, Charles Powell
import websockets
import json
import logging
import asyncio
import dpath.util
from socket import gaierror
from asyncio_mqtt import Client, MqttError
from contextlib import AsyncExitStack
from typing import Dict
# Independently set WS logger
wslogger = logging.getLogger('websockets')
w... |
from . import e3d
from . import e41
from . import c3d
from . import c2d
from . import sta
from . import visuals |
"""A module as test dummy for flake8-assertAlmostEqual."""
import unittest
class TestSelfAssertEqualDetection(unittest.TestCase):
"""Dummy for flake8-assertAlmostEqual."""
def setUp(self):
"""Set up."""
self.my_result = 5.0473
def test_detection(self):
"""Detect flake8-assertAlm... |
import numpy as np
from chesscog.core.coordinates import from_homogenous_coordinates, to_homogenous_coordinates
def test_from_homogenous_coordinates():
coords = np.array([2., 4., 2.])
expected = np.array([1., 2.])
assert np.allclose(from_homogenous_coordinates(coords), expected)
def test_to_homogenous_... |
from pubnub.pubnub import PubNub
from pubnub.pnconfiguration import PNConfiguration
from pubnub.endpoints.users.get_users import GetUsers
SUB_KEY = 'sub'
AUTH = 'auth'
def test_get_users():
config = PNConfiguration()
config.subscribe_key = SUB_KEY
config.auth_key = AUTH
users = PubNub(config).get_us... |
import os
from setuptools import setup, find_packages
from pagebits import VERSION
f = open(os.path.join(os.path.dirname(__file__), 'README.rst'))
readme = f.read()
f.close()
setup(
name='django-pagebits',
version=".".join(map(str, VERSION)),
description='django-pagebits is better more end user friendly... |
"""
This file offers the methods to automatically retrieve the graph Bacillus sp. FJAT-27251.
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--protei... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
from agate import Table
from agate.data_types import Number, Text
from agate.testcase import AgateTestCase
class TestJoin(AgateTestCase):
def setUp(self):
self.left_rows = (
(1, 4, 'a'),
(2, 3, 'b'),
(None, 2, 'c')
)... |
"""Module for generating an ensemble model from a given config file.
Exports a single class, Ensemble, which provides methods for training the ensemble,
saving the individual model files to disk and making predictions.
"""
import os
import sys
import numpy as np
import tensorflow as tf
import tensorflow.keras as k
fr... |
import numpy as np
import gym
import gym_flock
import glob
import sys
import rl_comm.gnn_fwd as gnn_fwd
from rl_comm.ppo2 import PPO2
from stable_baselines.common.vec_env import SubprocVecEnv
from stable_baselines.common.base_class import BaseRLModel
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'serif... |
from setuptools import setup
import re
with open('flask_blogtheme.py', 'r') as f:
version = re.search(r'__version__\s*=\s*[\'"](.+)[\'"]', f.read()).group(1)
setup(
name='Flask-BlogTheme',
version=version,
description='Flask extension to read switch theme easily',
author='Frost Ming',
author_e... |
#!/usr/bin/env python2
# Copyright (c) 2014 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test resurrection of mined transactions when
# the blockchain is re-organized.
#
from test_framework impo... |
import json
import copy
import requests
import datetime
from logUtils import *
# Log file location
_logFilePath = r"D:/Temp/Logging/createViews_[date].log"
# ArcGIS Online
_sourceFLUrl = "[YOUR-FEATURE-LAYER-URL]"
_uniqueValueField = "PROVINCIE"
_username = "[YOUR-USERNAME]"
_password = "[YOUR-PASSWORD]"
# Sript pa... |
#
# PySNMP MIB module CADANT-TIME-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CADANT-TIME-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:28:52 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
from . import plugin_pb2 as plugin__pb2
from . import provider_pb2 as provider__pb2
class ResourceProviderStub(object):
"""ResourceProvider is a service that... |
# Copyright 2016-2020 Swiss National Supercomputing Centre (CSCS/ETH Zurich)
# ReFrame Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
import os
import reframe as rfm
import reframe.utility.sanity as sn
#
# The following tests implement the dependency graph be... |
"""Runs the environments located in flow/benchmarks.
The environment file can be modified in the imports to change the environment
this runner script is executed on. This file runs the ARS algorithm in rllib
and utilizes the hyper-parameters specified in:
Simple random search provides a competitive approach to reinfor... |
from sys import stdout
from os import getpid
from BARTender import *
from ctypes import *
def show(ptr):
for i in range(32):
if ((i%4) == 0):
stdout.write('\n')
stdout.write("%s"%ptr[i])
stdout.write(' ')
stdout.write('\n')
x = BARTender()
print ("Test 3: Allocate 2 pages of memory and swap their PTEs")
... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
from torch import nn
from torch.nn import functional as F
from detectron2.layers import ShapeSpec
from detectron2.modeling.roi_heads import (
build_box_head,
build_mask_head,
select_foreground_proposals,
ROI_HEADS_REGIS... |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Simple echo server that echoes back client input.
You can run this .tac file directly with:
twistd -ny telnet_echo.tac
This demo sets up a listening port on 6023 which accepts telnet connections.
No login for the telnet server is require... |
# 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, software
# distributed under the... |
"""Interactive mode tests."""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import range
from builtins import next
from future import standard_library
standard_library.install_aliases()
import os
import re
import pytest
import six
import req... |
"""
Interfaces for serializing Django objects.
Usage::
from google.appengine._internal.django.core import serializers
json = serializers.serialize("json", some_query_set)
objects = list(serializers.deserialize("json", json))
To add your own serializers, use the SERIALIZATION_MODULES setting::
SERIAL... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.