content stringlengths 5 1.05M |
|---|
import arcpy, os
class ToolValidator(object):
"""Class for validating a tool's parameter values and controlling
the behavior of the tool's dialog."""
def __init__(self):
"""Setup arcpy and the list of tool parameters."""
self.params = arcpy.GetParameterInfo()
def initializeParameters(s... |
"""Provides Type structures.
"""
# Author: Pearu Peterson
# Created: February 2019
import re
import ctypes
import _ctypes
import inspect
from llvmlite import ir
import warnings
from .targetinfo import TargetInfo
from .utils import check_returns_none
import numba as nb
import numpy as np
from numba.core import typing... |
from builtins import print
import argparse
from f0cal.farm.client import entities
import f0cal.core
from progress.bar import IncrementalBar
from progress.spinner import MoonSpinner
import re
import json
from time import sleep
import os
from f0cal.farm.client.api_client import DeviceFarmApi, ConnectionError, ClientError... |
import CoreMedia
def CMTIMERANGE_IS_VALID(range):
return (
CMTIME_IS_VALID(range.start)
and CMTIME_IS_VALID(range.duration)
and range.duration.epoch == 0
and range.duration.value >= 0
)
def CMTIMERANGE_IS_INVALID(range):
return not CMTIMERANGE_IS_VALID(range)
def CMTIME... |
#!/bin/python3
import sys
E = 100
i = 0
n,k = input().strip().split(' ')
n,k = [int(n),int(k)]
c = [int(c_temp) for c_temp in input().strip().split(' ')]
while E > 0:
i = (i + k) % n
E -= 1
if c[i] == 1:
E -= 2
if i == 0:
break
print(E) |
from django.db import models
class Person(models.Model):
class Meta:
verbose_name_plural = "People"
nick = models.CharField(max_length=56)
name = models.CharField(max_length=128)
email = models.EmailField()
phone = models.CharField(max_length=24, null=True, blank=True)
about = models.... |
import pandas as pd
import glob
import random
import os
import cv2
import numpy as np
import tables
xmltile_path = '/path/to/xml_tiles/'
hdf5_path = 'path/to/save/xml2hdf.hdf5'
csv = 'path/to/xml2tile.csv'
df = pd.read_csv(csv)
df_xml['ids']=df_xml['tile_name'].str[:23]
df=df.rename(columns={'tile_name':'filename'})
... |
from spacy.tokens import Token
class QuestionWord:
FORM = 'FORM'
CHOICE = 'CHOICE'
OBJECT = 'OBJECT'
REASON = 'REASON'
TIME = 'TIME'
PERSON = 'PERSON'
PLACE = 'PLACE'
question_pos = 'QUESTION'
question_words = {
'where': PLACE,
'who': PERSON,
'when': TIME,
... |
# Copyright 2020 University of New South Wales, University of Sydney, Ingham Institute
# 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
# Unle... |
import sys
import os
import shutil
import sys
GLOBAL_PATH='/Users/heitorsampaio/Google_Drive/Projetos/Protein_DeepLearning/DeepPM'
sys.path.insert(0, GLOBAL_PATH+'/lib')
if len(sys.argv) != 7:
print('please input the right parameters: interval')
sys.exit(1)
test_file = sys.arg... |
# Game of X/O
# data structure: list, tupel, dictionary
# tuple are not changabe / immutable
# dictionary uses key words
# thus list is best suited, they allow to access elements via number
board = [" " for i in range(9)]
def print_board():
row1 = "| {} | {} | {} |".format(board[0], board[1], board[2])
row2... |
from oeqa.runtime.case import OERuntimeTestCase
class MpiTest(OERuntimeTestCase):
def test_mpi(self):
processors = [1, 2, 4, 8]
# mpirun binary is in the form "aarch64-poky-linux-mpirun"
prefix = self.tc.td["TARGET_PREFIX"]
for p in processors:
cmd = (prefix + 'mpirun -... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import functools
import tensorflow as tf
from absl import flags
import graph.graph_utils
from graph.block_ops import DepthwiseConv2D, Conv2D, MixConv, MyNetComponents
f... |
#!/usr/bin/env python3
"""Generate badges for repos under an user/org - here we're going to do it for python/ pypi
but this can be easily adapted
"""
from __future__ import annotations
import argparse
import re
from typing import Any
import requests
from lib import github_graph
from lib.utils import getUsername, pri... |
from datetime import date
def is_payday_leap_year(year, payday, frequency='biweekly'):
"""Determine if a given year is a payday leap year.
Determine if a given year is a payday leap year, based on the
given payday on a weekly or biweekly pay calendar (specified by
`frequency`). Assumes paychecks are a... |
import datetime
from unittest.mock import ANY
from contextlib import contextmanager
import pytest
from dateutil.tz import tzutc
from rhub.lab import model
from rhub.api.vault import Vault
from rhub.auth.keycloak import KeycloakClient
API_BASE = '/v0'
def _db_add_row_side_effect(data_added):
def side_effect(ro... |
import config
import pandas as pd
from sklearn.preprocessing import LabelEncoder
def preprocessing(df):
df['adults'].fillna(0, inplace = True)
df['children'].fillna(0, inplace = True)
df['babies'].fillna(0, inplace = True)
df['children'] = df['children'].astype(int)
df['total_guest... |
#!/cygdrive/c/Python25/python
########################################################################
### at-spi.py -- load TIText program onto ATMega128[L] via SPI
###
__doc__ = """
usage: at-spi.py titext_file
"""
import sys
sys.path.insert(0, "build/lib.win32-2.5")
from d2xx import *
from spi import *
from time i... |
from .core import AdvancedBrowser
# Advanced Browser modules
from . import custom_fields
from . import note_fields
from . import config
|
from common.MessageInterface import MessageInterface
from django.conf import settings
import logging,sys,multiprocessing,time,os
logger = logging.getLogger(__name__)
QUEUE_NAME = None
ROUTING_KEY = None
class MessageReceiver(multiprocessing.Process):
''' subscribes to a queue and executes the given callback'''
... |
# coding: utf-8
from operator import attrgetter
from requests_futures.sessions import FuturesSession
from .data import Band
def get_top_bands(pages_to_fetch, lastfm_username, lastfm_api_key):
result = []
futures = []
future_session = FuturesSession(max_workers=10)
for page_idx in range(pages_to_fetch... |
#!/usr/bin/env python
#
# This example shows two easy ways to create a dasboard: using a view as a
# templeate, and copying another dashboard.
# In both cases, a filter is used to define what entities the new dashboard
# will monitor.
#
import getopt
import sys
from sdcclient import SdMonitorClient
#
# Parse argume... |
############################################################
## 01/22/2018 by Lord.Doubi. Revised from OpenCV tutorial ##
############################################################
import cv2
import os
import numpy as np
import Cameracontrol as cc
class Bug():
def __init__(self,name):
self.name... |
"""
API operations for samples in the Galaxy sample tracking system.
"""
import logging
from galaxy import util
from galaxy.util.bunch import Bunch
from galaxy.web import url_for
from galaxy.web.base.controller import BaseAPIController, web
log = logging.getLogger(__name__)
class SamplesAPIController(BaseAPIControl... |
import datetime
import uuid
from django.conf import settings
from django.db import models
from django_countries.fields import CountryField
from django.utils.translation import gettext_lazy as _
from django.utils import timezone
from django_freeradius.models import RadiusCheck
IDENTITY_TOKEN_EXPIRATION_DAYS = getattr... |
"""Test the old numpy pickler, compatibility version."""
import shutil
import os
import random
import nose
from tempfile import mkdtemp
# numpy_pickle is not a drop-in replacement of pickle, as it takes
# filenames instead of open files as arguments.
from joblib import numpy_pickle_compat
#########################... |
import config
from subprocess import Popen, PIPE
from util import gform
import math
import os
import shutil
import numpy as num
import scipy
import tempfile
import sys
from pyrocko import io, util
pjoin = os.path.join
class Gfdb:
def __init__(self, gfdbpath):
self.path = gfdbpath
self.extracto... |
# Copyright 2010-2019 Dan Elliott, Russell Valentine
#
# 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 appl... |
# Generated by Django 2.0.4 on 2018-10-13 18:17
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0055_auto_20181014_0310'),
]
operations = [
migrations.RenameField(
model_name='user',
old_name='school_yearZ',
... |
from typing import Any, Iterator
import psycopg2.errors
from patabase import Postgres
from qucom.exceptions import *
def _error_handler(func):
def wrapper(*args, **kwargs):
assert isinstance(args[0], Qucom)
if 'table' in kwargs:
table = kwargs['table']
else:
tabl... |
import torch
import torch.distributed as dist
def get_world_size():
if not dist.is_available():
return 1
if not dist.is_initialized():
return 1
return dist.get_world_size()
def get_rank():
if not dist.is_available():
return 0
if not dist.is_initialized():
return 0... |
"""
Copyright 2014 Rackspace
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
dist... |
import importlib
import logging
import sys
logger = logging.getLogger('root')
logger.setLevel(logging.INFO)
logFormatter = logging.Formatter('%(asctime)s %(process)d [%(funcName)s] %(levelname)s: %(message)s')
console_handler = logging.StreamHandler()
console_handler.setFormatter(logFormatter)
logger.addHandler(consol... |
class ProgressBar:
def __init__(self, max_value, modulo_threshold):
"""
This is a progress bar that can be printed during iterative processes of fixed length.
:param max_value: int the last value of the iteration, usually an index.
:param modulo_threshold: int modulo that determines ... |
import os
import numpy as np
import pandas as pd
import subprocess
import optparse
from sklearn.svm import SVC
from sklearn import cross_validation
from sklearn import grid_search
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
from sklearn impor... |
"""
Created by catzoo
Description: Discord.py role checks
"""
import os
import asqlite
import env_config
class NoDatabase(Exception):
"""Used for Checks.connection being None"""
pass
# noinspection PyRedundantParentheses
class Checks:
"""
This is used for discord.py checks
Use:
- develop... |
"""Rollease Acmeda Automate Pulse asyncio protocol implementation."""
import logging
from aiopulse.hub import Hub
from aiopulse.elements import Roller, Room, Scene
from aiopulse.errors import (
CannotConnectException,
NotConnectedException,
NotRunningException,
InvalidResponseException,
)
from aiopulse... |
"""
API for the cards project
"""
from dataclasses import asdict
from dataclasses import dataclass
from dataclasses import field
from typing import List
from .db import DB
__all__ = [
"Card",
"CardsDB",
"CardsException",
"MissingSummary",
"InvalidCardId"
]
@dataclass
class Card:
summary: str... |
# Generated by Django 2.2.3 on 2019-07-24 06:50
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('tweet', '0002_tweet'),
]
operations = [
migrations.AddField(
model_name='tweet',
name='... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
from parlai.core.params import ParlaiParser
from parlai.mturk.core.mturk_manager import MTurkManager
from worl... |
from pathlib import Path
from .timestamp import timestamp
RESULTS_DIR_PREFIX = 'results_'
def make_results_dir(results_root, prefix=RESULTS_DIR_PREFIX):
"""make a directory to contain results from an experiment
within a specified "root" results directory
Parameters
----------
results_root : str... |
import asyncio
import logging
from xml.etree import ElementTree
from typing import List, Union
from yarl import URL
from feedsearch_crawler.feed_spider import FeedsearchSpider, FeedInfo
logging.getLogger(__name__).addHandler(logging.NullHandler())
name = "Feedsearch Crawler"
def search(
url: Union[URL, str, L... |
import unittest
import tableauserverclient.server.request_factory as factory
class BugFix257(unittest.TestCase):
def test_empty_request_works(self):
result = factory.EmptyRequest().empty_req()
self.assertEqual(b'<tsRequest />', result)
|
# from abc import ABCMeta
# import requests
# import json
# from requests.sessions import session
# def login(email,password):
# passw = requests.Session()
# payload = {
# 'email':email,
# 'password':password
# }
# response = passw.post('http://127.0.0.1:8000/auth/login/',json=payload)... |
n = int(input())
k = int(input())
total = n
for i in range(k):
total += int(str(n) + ('0' * (i+1)))
print(total) |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A module for the shell command."""
import os
import tempfile
import cr
class ShellCommand(cr.Command):
"""The implementation of the shell command.
... |
from setuptools import setup, find_packages
setup(
name="crysterm",
version="0.1.0",
author="mofuru",
author_email="me@mofuru.is-a.dev",
url="https://github.com/mofuru/crysterm",
license="MIT",
packages=find_packages(exclude=("tests", "docs"))
)
|
#
# Copyright 2011 Twitter, 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, s... |
# coding:utf-8
'''
Created on 2017/12/19
@author: sunyihuan
'''
import math
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from sklearn.model_selection import train_test_split
import scipy.io as scio
def data_check(data):
res = list(np.argmax(data, 1))
num = le... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import tri
from compostela.tree_op import Tree_op
class Auxiliar_func:
@staticmethod
def plot_latent_tree(z_test, y_test, cand, x_s, disc,
y_s, d_d_p, tree, path):
"""
Plot in matplotlib the tree in th... |
MAJOR = 0
MINOR = 4
PATCH = 1
PRE_RELEASE = ''
# Use the following formatting: (major, minor, patch, pre-release)
VERSION = (MAJOR, MINOR, PATCH, PRE_RELEASE)
__short_version__ = '.'.join(map(str, VERSION[:3]))
__version__ = '.'.join(map(str, VERSION[:3])) + ''.join(VERSION[3:])
__package_name__ = 'warprnnt_numba'
_... |
from defines import *
from model import *
from data import *
if __name__ == '__main__':
# step0: enable GPU version
# os.environ["CUDA_VISIBLE_DEVICES"] = "0"
if PARAM_ACTION == 1:
# step1: create training set
myGene = trainGenerator(PARAM_BATCHES,
PARAM_PATH_TRAIN,
PARAM_IMG_FOLDER,
PARAM... |
import time
import logging
import argparse
from pathlib import Path
import cProfile, pstats
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import plotly.express as px
import joblib
import mlflow
import graphviz
from skopt import BayesSearchCV
from skopt.plots import plot_objective
from sklearn.p... |
from __future__ import absolute_import, division, print_function
from abc import ABCMeta, abstractproperty, abstractmethod
import numpy as np
from glue.external import six
from glue.core.exceptions import IncompatibleAttribute
from glue.core.layer_artist import MatplotlibLayerArtist, ChangedTrigger
__all__ = ['Hist... |
import os
def transferRepos(matchList, WorkingDir, fromRepoProtocol = 'https', toRepoProtocol = 'https'):
# print(matchList)
# 切换路径
targetPath = os.path.abspath(WorkingDir)
os.chdir(targetPath)
if(os.path.abspath(os.getcwd()) != targetPath): # 展开为绝对路径,然后进行比较
print("[error] 切换路径失败")
... |
# -*- coding: utf-8 -*-
name = u'pytz'
version = '2018.5'
description = \
"""
pytz library
"""
requires = []
variants = []
def commands():
import os
pytz_libs_path = os.path.join(getenv("PYTHON_LIBS_PATH"), "pytz", "%s" % version)
# env.PATH.append(os.path.join(pytz_libs_path, 'lib'))
... |
from setuptools import setup
import sys, pathlib
# read the contents of your README file
from pathlib import Path
this_directory = Path(__file__).parent
long_description = (this_directory / "README.md").read_text()
version = '0.0.2'
setup(
name='UltraSystray-noicons',
version=version,
description='Ultra... |
from libs.effects.effect import Effect # pylint: disable=E0611, E0401
import numpy as np
class EffectBars(Effect):
def run(self):
effect_config = self._device.device_config["effects"]["effect_bars"]
led_count = self._device.device_config["LED_Count"]
led_mid = self._device.device_config[... |
import os
from django.conf import settings
from django.test import TestCase, Client
class Exercise3Test(TestCase):
def test_view_and_template(self):
"""Test that the view, URLs and template are set up properly by checking the contents of the response."""
c = Client()
resp = c.get('/react-... |
# Generated by Django 3.2.8 on 2021-10-12 14:35
import cloudinary.models
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('authentication', '0003_rename_profilepic_profile_profile_pic'),
]
operations = [
migrations.AlterField(
model_n... |
from scrapy import Spider, Request
from olx.spiders.items import Property
from olx.spiders.loaders import PropertyLoader
class SellPropertiesSpider(Spider):
name = "sell_properties"
def __init__(self, state=None, **kwargs):
super().__init__(**kwargs)
if state is None:
raise Value... |
from saturnv.api.databases.postgresql.presets import Shortcut, Override, Preset, Version, Setting
from saturnv.api.databases.postgresql.shelves import Shelf, ShelfLink
from .core import Session
|
#! /usr/bin/env python
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open('README.md') as readme_file:
readme = readme_file.read()
setup(
name=... |
import boto3
import os
import time
try: # Python3
from urllib.parse import urlparse, urlencode
except ImportError: # Python2
from urlparse import urlparse
from urllib import urlencode
class TransferMonitor(object):
def __init__(self, total_bytes, logger):
self._total_bytes = total_bytes
... |
"""Espresso-Caller: automated and reproducible tool for identifying genomic variations at scale"""
# TODO: is it really necessary for packaging?
name = 'espresso-caller'
|
#!/usr/bin/env python
"""
Kevin Angstadt
University of Virginia
Convert VASim Statevectors into Traces of RAPID line numbers
"""
import argparse, csv, json, copy
def parse_tsv(filename):
mapping = dict()
with open(filename, "rb") as f:
reader = csv.reader(f, delimiter="\t")
for r... |
# Copyright 2017 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.11.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# %% [ma... |
from vergeml.img import ImageType
from vergeml.operation import OperationPlugin, operation
from vergeml.option import option
from PIL import Image
from vergeml.utils import VergeMLError
@operation('random-crop', topic="image", descr="Crop random regions of an image.")
@option('width', type=int, descr="Width of the rec... |
"""
Given an array arr of size N, swap the Kth element from beginning
with Kth element from end.
Algorithm : - After user enters the values we will take 2 variables
pos1 and pos2. Pos1 will have index value of kth position. Pos2 will have index value of kth position
from end. We then use pop function to remove the e... |
"""
PyPI tool
"""
import sys
from subprocess import Popen
import distutils.core # pylint: disable=no-name-in-module, import-error
import os
import importlib.machinery
import requests
PYPI_URL = os.environ.get('PYPI_URL', 'https://pypi.python.org/pypi/')
while PYPI_URL.endswith('/'):
PYPI_URL = PYPI_URL[:-1]
# pyl... |
import plotly.graph_objects as go
import sys
import common
import table_single_provers
import figure_createall
def main_helper(prover_dict):
systems= ["D/const","D/cumul","D/vary","T/const","T/cumul","T/vary"] + ["S4/const","S4/cumul","S4/vary","S5/const","S5/cumul","S5/vary"]
data_mleanTotal = [25,35,45,55... |
# -*- coding: utf-8 -*-
from rest_framework import serializers
from tandlr.payments.models import TeacherPaymentInformation
class TeacherPaymentInformationV2Serializer(serializers.ModelSerializer):
tutor = serializers.SerializerMethodField()
class Meta:
model = TeacherPaymentInformation
fie... |
'''
Module utils
'''
import re
def nyaa_categories(b):
c = b.replace('/?c=', '')
cats = c.split('_')
cat = cats[0]
subcat = cats[1]
categories = {
"1": {
"name": "Anime",
"subcats": {
"1": "Anime Music Video",
"2": "English-tran... |
#!/usr/bin/env python
import glob
import subprocess
import textwrap
import re
import sys
import os
import yaml
import textwrap
from pprint import pprint
s = {}
def compile_papers():
papers = sorted(glob.glob('../hid-sp*/project-paper/content.tex'))
for paper in papers:
print (79* "%")
print (... |
from . import actors
from .actors import *
|
import FWCore.ParameterSet.Config as cms
hltL1TkElectronsEllipticMatchHGC = cms.EDProducer("L1TkElectronTrackProducer",
DRmax = cms.double(0.2),
DRmin = cms.double(0.03),
DeltaZ = cms.double(0.6),
ETmin = cms.double(-1.0),
IsoCut = cms.double(-0.1),
L1EGammaInputTag = cms.InputTag("l1EGammaEEPr... |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from typing import Union, Iterable, Tuple
from scipy.spatial.distance import cdist
def get_points_and_targets(data: Union[str, Iterable[np.ndarray]]) -> Tuple[np.ndarray, np.ndarray]:
"""
Depending on the type of the parameter 'data', retu... |
import pygame
import json
import random
from tool.init import *
from . colliderbox import *
class Mario(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = mario_small_right_img[0][6]
self.rect = self.image.get_rect()
self.rect.x = 0
... |
# Copyright 2016 IBM Corp.
#
# 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 a... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 10 14:27:10 2021
@author: Sergio G. Lopez from the Bioimaging Facility of the John Innes Centre.
"""
# Imports the necessary libraries.
from ncempy.io import dm
import numpy as np
import matplotlib.pyplot as plt
from skimage import filters, morphology, segment... |
# coding: utf-8
from __future__ import print_function, absolute_import, division, unicode_literals
from ruamel_yaml.compat import text_type
if False: # MYPY
from typing import Text, Any, Dict, List # NOQA
__all__ = ["ScalarString", "PreservedScalarString", "SingleQuotedScalarString",
"DoubleQuotedS... |
import argparse
import os
from os import system
from os.path import isdir, isfile
from glob import glob
from multiprocessing import Pool
def get_args():
parser = argparse.ArgumentParser(description='TartanAir')
parser.add_argument('--dataset-dir', default='./',
help='root directory fo... |
class Solution:
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
stack = []
maxArea = 0
area = 0
i = 0
while i < len(heights):
if len(stack) == 0 or heights[stack[0]] <= heights[i]:
... |
# pylint: disable=invalid-name
import time
import pytest
import sys
from unittest.mock import MagicMock
from slack_sdk.errors import SlackApiError
sys.path.append('plugins/sdm')
sys.path.append('e2e/')
from test_common import create_config, DummyAccount, DummyRole, get_rate_limited_slack_response_error
from lib impor... |
import torch
from torch import nn
from torch.autograd import Variable
from torch import transpose as t
from torch import inverse as inv
from torch import mm
from torch import gesv
from fewshots import labels_lrd2_multi, labels_lrd2_bin, labels_r2d2
from fewshots.models.adjust import AdjustLayer, LambdaLayer
from fewsho... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
import global_settings as gs
import pylab
import numpy as np
from find_affine import *
from scipy import linalg
from PyQt4.QtCore import pyqtRemoveInputHook
import pdb
def generate_generic_grid(nx,ny, offset=(0,0), spacing=(1.0,1.0)):
# generates an generic position list for
# a grid with nx*ny postions spaced... |
from flask_restful import Resource
class Endpoint(Resource):
def get(self):
return 'Got get', 200
def post(self):
return 'Got post', 201
|
"""Snakemake wrapper for BUSCO assessment"""
__author__ = "Tessa Pierce"
__copyright__ = "Copyright 2018, Tessa Pierce"
__email__ = "ntpierce@gmail.com"
__license__ = "MIT"
from snakemake.shell import shell
from os import path
log = snakemake.log_fmt_shell(stdout=True, stderr=True)
extra = snakemake.params.get("extr... |
from setuptools import setup, find_packages
setup(
name='django-mininews',
version='0.1',
packages=find_packages(exclude=['example_project']),
license='MIT',
description='Boilerplate for creating publishable lists of objects',
long_description=open('README.rst').read(),
author='Richard Barr... |
from tensorflow.keras.applications.imagenet_utils import preprocess_input
import tensorflow as tf
from utils.augmentations import *
AUTO = tf.data.experimental.AUTOTUNE
@tf.function
def data_augment(image, boxes, labels):
if tf.random.uniform([]) > 0.5:
image = tf.image.random_saturation(image, l... |
#coding: UTF-8
# 信息冗余:对于某些定量特征,其包含的有效信息为区间划分,例如学习成绩,假若只关心“及格”或不“及格”,那么需要将定量的考分,转换成“1”和“0”表示及格和未及格。二值化可以解决这一问题。
import numpy as np
from sklearn.preprocessing import Binarizer
X = np.array([[ 1., -1., 2.],[ 2., 0., 0.],[ 0., 1., -1.]])
print(X)
binarizer = Binarizer(threshold=0.0).fit(X) # fit does nothing
print(bi... |
import json
from unittest.mock import patch
import pytest
from airflow import AirflowException
from dbt.contracts.results import RunStatus
from airflow_dbt_python.operators.dbt import DbtSeedOperator
def test_dbt_seed_mocked_all_args():
op = DbtSeedOperator(
task_id="dbt_task",
project_dir="/pat... |
#!/usr/bin/env python3
import depthai as dai
import json
# Connect device
with dai.Device(dai.OpenVINO.VERSION_2021_4, dai.UsbSpeed.HIGH) as device:
print(f'Is EEPROM available: {device.isEepromAvailable()}')
# User calibration
try:
print(f'User calibration: {json.dumps(device.readCalibration2()... |
import cp1_1_05_swarl_matrix_a
def solution(n):
return cp1_1_05_swarl_matrix_a.solution(n)
if __name__ == "__main__":
input = 2
print("input=", input, "result=", solution(input));
input = 3
print("input=", input, "result=", solution(input));
input = 4
print("input=", input, "result=", solu... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: luzhongyang@huoxian.cn
# datetime: 2021/11/03 下午2:26
# project: DongTai-engine
from dongtai.models.project import IastProject
import time
from dongtai.models.vulnerablity import IastVulnerabilityModel
from collections import namedtuple
from django.db.models import ... |
import re
from itertools import permutations
def calculate(expression, perm):
for op in perm:
pattern = re.compile(r"(\d+|\(-?\d+\))+[%s](\d+|\(-?\d+\))" % op)
while True:
formula = pattern.search(expression)
if formula is None: break
result = "(" + str(eval(form... |
import os
import sys
import shutil
from core import TextStyle
__all__ = [
'link_command',
'unlink_command',
'remove_command',
'list_command',
'root_command'
]
def container_exist(**kwargs):
app_args, logger, manbrew_root = kwargs['app_args'], kwargs['logger'], kwargs['manbrew_root']
conta... |
from RamachanDraw.fetch import fetch
from RamachanDraw.phi_psi import phi_psi
from RamachanDraw.plot import plot
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.