text stringlengths 2 999k |
|---|
# coding: utf-8
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: api-support@onshape.zendesk.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
im... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class VideoTools:
@staticmethod
def flatten_high(image_high, upscale_factor):
"""
Reshapes the high resolution input image with shape
B x C x H*upscale_factor x W*upscale_factor
to a low resolution output imag... |
# Copyright 2012 Grid Dynamics
# 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... |
"""Config flow to configure the SimpliSafe component."""
from simplipy import API
from simplipy.errors import SimplipyError
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_CODE, CONF_PASSWORD, CONF_TOKEN, CONF_USERNAME
from homeassistant.core import callback
from ... |
"""Init for Cockpit."""
from pkg_resources import DistributionNotFound, get_distribution
from cockpit.cockpit import Cockpit
from cockpit.plotter import CockpitPlotter
# Extract the version number, for accessing it via __version__
try:
# Change here if project is renamed and does not equal the package name
di... |
"""
mysql-connector==2.2.9
SQLAlchemy==1.4.22
"""
import os
import sys
import datetime
import configparser
from sqlalchemy import Column, DateTime, ForeignKey, String, create_engine, Index
from sqlalchemy.dialects.mysql import INTEGER, LONGTEXT, SMALLINT, TINYINT
from sqlalchemy.orm import relationship, sessio... |
import setuptools
setuptools.setup(
name="Flask-API-Framework",
version="0.0.3",
keywords="flask api framework",
description="Flask API Framework",
long_description="Please see the project links.",
project_urls={
"Documentation": "https://flask-api-framework.readthedocs.io/",
"... |
import json
import xmltodict
import subprocess
import random
import string
import os
import os.path
import sys
class BlastPlasmid:
def __init__(self, plasmidSeq):
self.plasmidSeq = plasmidSeq
randomFileName = ''.join(random.choice(string.ascii_uppercase+string.digits) for _ in range(10))+".tmp"
... |
from django.forms import ModelForm
from ..models import Project
class ProjectForm(ModelForm):
class Meta:
model = Project
fields = ('title','body','parent',)
def __init__(self, *args, **kwargs):
'''Uses the passed request to choices for parent projects'''
if kwargs['request'... |
import multiprocessing
import operator
import os
from collections import defaultdict
from functools import partial
import cv2
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from PIL import Image
from skimage import feature
from sklearn.metrics.pairwise import euclidean_distances
from .base imp... |
import numpy as np
def macro_search(state, domain, bfs_tree, pattern_database, max_depth, color_neutral=True):
# returns result = (recolor index, actions, rule index, macro, triggering state, new_state)
# or result = False if there is no path to a macro or solved state
patterns = pattern_database.patterns... |
from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers
from nautobot.core.api import ChoiceField, ContentTypeField, WritableNestedSerializer
from nautobot.extras import choices, models
from nautobot.users.api.nested_serializers import NestedUserSerializer
__all__ = [
"Ne... |
import uuid
from app.db.database import Base
from pydantic import EmailStr, HttpUrl
from sqlalchemy import Boolean, Column, DateTime, String, func
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
class Seller(Base): # type: ignore
__tablename__ = "seller"
id = Column(... |
from __future__ import absolute_import
from django.db import transaction
from django.db.models import Q
from rest_framework import serializers
from rest_framework.response import Response
from sentry import roles
from sentry.api.bases.organization import (
OrganizationEndpoint, OrganizationPermission
)
from sentr... |
import logging
from django.db import models
from jsonfield import JSONField
from ...bases.metadata.models import BaseListingItemRelation
logger = logging.getLogger(__name__)
class EmbeddedInfo(models.Model):
path = models.CharField(max_length=500)
query_key = models.CharField(max_length=50)
index = mo... |
"""
Created by Epic at 9/1/20
"""
from asyncio import Event, get_event_loop, Lock
from logging import getLogger
from .exceptions import Unauthorized, ConnectionsExceeded, InvalidToken
from .http import HttpClient, Route
from .dispatcher import OpcodeDispatcher, EventDispatcher
from .gateway import DefaultGatewayHandle... |
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_uploads import UploadSet, configure_uploads
from flask_uploads.extensions import DOCUMENTS, IMAGES
files = UploadSet('files', IMAGES + DOCUMENTS)
db = SQLAlchemy()... |
import numpy as np
import pytest
import optuna
def test_wfg_2d() -> None:
for n in range(2, 30):
r = n * np.ones(2)
s = np.asarray([[n - 1 - i, i] for i in range(n)])
for i in range(n + 1):
s = np.vstack((s, np.asarray([i, n - i])))
np.random.shuffle(s)
v = opt... |
usuario=input("informe o usuário: \n")
senha=usuario
while senha==usuario:
senha = input("informe uma senha diferente do usuário")
if senha==usuario:
print("A senha digitada não é válida")
|
viewset = CognateViewSet.as_view({"get": "list"})
paths = [
"/words?por=deus",
"/",
"/words",
"/words?*=no",
"/words?eng=banana&comparison=equal",
"/words?fra=bataillon&por=entidade",
"/words?fra=ba*&por=entidade",
"/words?zzzzzzz=zzzz&por=entidade",
]
for i in range(300):
for path ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import argparse
import random
import shutil
from common import get_filenames
# Logging
from logging import getLogger, StreamHandler, INFO
logger = getLogger()
logger.setLevel(INFO)
logger.addHandler(StreamHandler())
def parse_argments(argv):
pa... |
from astropy import units as u
from solarviewer.config.base import DialogController, ItemConfig, ViewerType, DataType, DataModel, ViewerController
from solarviewer.ui.rotate import Ui_Rotate
from solarviewer.viewer.map import MapModel
class RotateController(DialogController):
def __init__(self):
DialogCo... |
from __future__ import absolute_import
from datetime import timedelta
import six
from django.core.urlresolvers import reverse
from django.utils import timezone
from exam import patcher
from freezegun import freeze_time
from sentry.incidents.logic import (
create_incident_activity,
subscribe_to_incident,
)
fr... |
import discord
from yrumee.modules import Module
class GradEraserModule(Module):
"""
<대학원 제거기>
[.대학원생] 대학원생 목록 표시
[.대학원갈래요] 대학원제거기 비활성화
[.대학원안가요] 대학원제거기 활성화
[.대학원에 @대상 살아요] 대학원생 목록에 해당 유저 등록 (ex. .대학원에 @이건우 살아요)
[.교수님 @대상 안보여요] 대학원생 목록에 해당 유저 삭제 (ex. .교수님 @이건우 안보여요)
"""
def __ini... |
import os
import sys
import datetime
from retirement_api.models import (AgeChoice,
Question,
Step,
Page,
Tooltip,
Calibration)
import mock
from m... |
"""
Contains the definition of Font.
"""
from .style import Style
class Font(Style):
"""
Represents a font style.
"""
def __init__(self, family, style, size, postscript_name):
"""Initialize this Font."""
super().__init__('font')
self.family = family
self.style = style
... |
# Linear form class.
class LinearForm(object):
"""Class of linear forms."""
pass
|
import goldsberry
class transition(goldsberry.masterclass.NbaDataProviderPlayType):
def __init__(self, season=goldsberry.apiparams.default_season, team=False):
url_modifier = 'Transition'
goldsberry.masterclass.NbaDataProviderPlayType.__init__(self, url_modifier, year=season, team=team)
class is... |
from __future__ import division
import numpy as np
import scipy.optimize as op
from scipy.interpolate import InterpolatedUnivariateSpline
from scipy.interpolate import RectBivariateSpline
from scipy import integrate
import cosmo
class ConcentrationConversion:
def __init__(self, MCrelation, cosmology=None):
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class Functi... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import importlib
# Make subpackages available:
__all__ = ['config']
for pkg in __all__:
if pkg != 'config':
importlib.impor... |
# Generated by Django 3.1.3 on 2020-11-20 20:07
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
# Copyright 2015 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
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... |
from __future__ import absolute_import
import os
import sys
import collections
import torch
from torch.autograd import Variable
import torch.nn as nn
from torch import optim
import torch.nn.functional as F
from program_synthesis.algolisp.dataset import data
from program_synthesis.algolisp.models import prepare_spec... |
# ------------------------------------------------------------------- #
# Copyright (c) 2007-2008 Hanzo Archives Limited. #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file ... |
# Copyright 2020 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... |
#This is just a Python version of the https://www.exploit-db.com/exploits/39909
#Also check out https://github.com/hantwister/FakeDellOM
#You need to have openssl installed
from xml.sax.saxutils import escape
import BaseHTTPServer
import requests
import thread
import ssl
import sys
import re
import os
i... |
from typing import Dict
from typing import NewType
from typing import cast
from logging import Logger
from logging import getLogger
from math import degrees
from pytrek.engine.Computer import Computer
from pytrek.engine.Direction import Direction
from pytrek.engine.DirectionData import DirectionData
from pytrek.eng... |
"""
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... |
import pika
class PikaPublisher(object):
def __init__(self, exchange_name):
self.exchange_name = exchange_name
self.queue_exists = False
def publish(self, message, routing_key):
conn = pika.AsyncoreConnection(pika.ConnectionParameters(
'127.0.0.1',
crede... |
#!/usr/bin/env python3
import re
import unicodedata
from glob import glob
patterns = [
'../../Assets/Nova/Fonts/CharsetChinese.txt',
'../../Assets/Resources/Scenarios/*.txt',
'../../Assets/Resources/LocalizedResources/*/Scenarios/*.txt',
'../../Assets/Resources/LocalizedStrings/*.json',
]
out_filename... |
from kivy.app import App
from kivy.factory import Factory
from kivy.properties import ObjectProperty
from kivy.lang import Builder
from electrum_ltc.util import base_units_list
from electrum_ltc.i18n import languages
from electrum_ltc_gui.kivy.i18n import _
from electrum_ltc.plugins import run_hook
from electrum_ltc i... |
'''
Author: hanyu
Date: 2021-01-06 10:13:41
LastEditTime: 2021-01-09 09:31:12
LastEditors: hanyu
Description: policy network of PPO
FilePath: /test_ppo/examples/PPO_super_mario_bros/policy_graph.py
'''
from ray_helper.miscellaneous import tf_model_ws
def warp_Model():
'''
description: warp the policy model
... |
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def main():
return """<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$(document).ready... |
"""Add Build.family_id
Revision ID: cb99fdfb903
Revises: 1109e724859f
Create Date: 2013-12-23 11:32:17.060863
"""
# revision identifiers, used by Alembic.
revision = 'cb99fdfb903'
down_revision = '1109e724859f'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('build', sa.Column('fam... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
from setuptools import find_packages, setup
MAIN_REQUIREMENTS = ["airbyte-cdk~=0.1.12", "requests_oauthlib~=1.3.0", "pytz~=2021.1", "pendulum~=1.5.1"]
TEST_REQUIREMENTS = [
"pytest~=6.1",
"pytest-mock~=3.6.1",
"jsonschema~=3.2.0",
"respons... |
"""
ASGI config for suorganizer project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_S... |
from sqlalchemy.ext.declarative import declarative_base
from history_meta import VersionedMeta, VersionedListener
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import clear_mappers, compile_mappers, sessionmaker, deferred
from sqlalchemy.test.testing import TestBase, eq_
... |
#!/usr/bin/env python3
# Copyright (c) 2017-2018 The Machinecoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test multiwallet.
Verify that a machinecoind node can load multiple wallet files
"""
import os
imp... |
# 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 ... |
# Copyright 2021 The DDSP 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 wri... |
# -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2018 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... |
from time import time
class Timer:
"""
Simple class for checking time
"""
def __init__(self):
self.start_time: float = -1
self.end_time: float = -1
self.duration: float = -1
def start(self):
self.start_time = time()
def stop(self):
self.end_time = tim... |
# Copyright 2008-2009 ITA Software, 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 ... |
import scrapy
from ..items import DealsItem
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
import time
class DealsSpider(scrapy.Spider):
name = 'deals'
allowed_domains = ['amazon.com', 'amazon.co.uk']
#To enable there to be a limit of how many pages to crawl we need ... |
"""
day 12
"""
import math
from part_1 import read_input, east, north, south, west, rotate, manhatten
def rotate(wayp_y, wayp_x, pos_y, pos_x, degrees):
delta_wayp_y = wayp_y - pos_y
delta_wayp_x = wayp_x - pos_x
if degrees == 90:
wayp_y = pos_y - delta_wayp_x
wayp_x = pos_x + delta_wayp_y... |
from django.apps import AppConfig
class ApiConfig(AppConfig):
name = 'API'
|
""" Test the Cookiecutter template.
A template project is created in a temporary directory, the project is built,
and its tests are run.
"""
from json import loads
from pathlib import Path
from shlex import split
from subprocess import check_call
from tempfile import TemporaryDirectory
from cookiecutter.main import ... |
# The MIT License (MIT)
#
# Copyright (c) 2019 Jonah Yolles-Murphy
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, cop... |
###############
# Repository: https://github.com/lgervasoni/urbansprawl
# MIT License
###############
import osmnx as ox
import pandas as pd
import geopandas as gpd
import numpy as np
from .tags import height_tags
from ..settings import storage_folder
# Format for load/save the geo-data ['geojson','shp']
geo_format... |
# Copyright (c) OpenMMLab. All rights reserved.
import os
import tempfile
from os import path as osp
import mmcv
import numpy as np
import pandas as pd
from lyft_dataset_sdk.lyftdataset import LyftDataset as Lyft
from lyft_dataset_sdk.utils.data_classes import Box as LyftBox
from pyquaternion import Quaternion
from m... |
# Generated by Django 3.2.7 on 2021-09-08 13:54
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='UserProfile'... |
##
##
# File auto-generated against equivalent DynamicSerialize Java class
class StatusResponse(object):
def __init__(self):
self.hostname = None
self.jvmName = None
self.statistics = None
def getHostname(self):
return self.hostname
def setHostname(self, hostname):
... |
# coding: utf-8
"""
IdCheck.IO API
Check identity documents
OpenAPI spec version: 0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You... |
# Copyright (c) 2015 OpenStack Foundation
#
# 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 ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, 2019 Kevin Breit (@kbreit) <kevin.breit@kevinbreit.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA ... |
# ---------------------------------------------
# Calibration of predicted probabilities.
# ---------------------------------------------
import numpy as np
import pandas as pd
import sklearn
from . import utils
class SoftMaxCalibration:
def __init__(self, num_calibration, num_bins):
self._num_calibration... |
from harstorage.tests import *
class TestChartController(TestController):
"""
Test suite for chart export
"""
def test_01_export_svg(self):
"""Export SVG"""
# Expected valid image
with open("harstorage/tests/functional/testdata/validfile.svg") as file:
response ... |
from django.db import models
from cached_fields.fields import CachedIntegerField
from cached_fields.mixins import CachedFieldsMixin
from prefetchapp.handlers import OrderSummaryCacheHandler
class OrderSummary(models.Model):
total = CachedIntegerField(OrderSummaryCacheHandler, null=True)
class Service(models.Model... |
import numpy as np
import pickle
with open('sum_rew_final_policy.pkl','rb') as f:
li = pickle.load(f)
ch = np.array(li)
catastrophes = np.sum(ch<-1000)
opt = np.sum((ch>(max(li)-20))&(ch <= max(li)))
print('first 300 rollouts')
print(li[1:300])
print('min rew', min(li))
print('max rew', max(li))
print('mean rew',np... |
import numpy as np
import shutil
import os
from os.path import join
from tempfile import mkdtemp
from pysph import has_h5py
try:
# This is for Python-2.6.x
from unittest2 import TestCase, main, skipUnless
except ImportError:
from unittest import TestCase, main, skipUnless
from pysph.base.utils import get_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .version import __version__
SEPARATOR = u'$_$'
TEST_REQUEST = u'ping'
VERSION = __version__
DEFAULT_SSH_PORT = u'22'
DEFAULT_SSH_USERNAME = u'root'
DEFAULT_SSH_PASSWORD = u'CleepR00t' |
from django.urls import path
from blog import views
urlpatterns = [
path("", views.index),
path("article/<int:id>/", views.detail),
]
|
import numpy
import structlog
from gost.utils import evaluate, evaluate_themes, evaluate_nulls, FmaskThemes
from gost.data_model import Measurement
_LOG = structlog.get_logger("fmask")
def test_evaluate_themes_identical(
ref_fmask_measurement1: Measurement, test_fmask_measurement1: Measurement
):
"""Test th... |
# Copyright 2008-2018 pydicom authors. See LICENSE file for details.
"""Read a dicom media file"""
import os
from struct import Struct, unpack
from types import TracebackType
from typing import (
Iterator, Tuple, Optional, Union, Type, cast, BinaryIO, Callable
)
from pydicom.misc import size_in_bytes
from pydicom... |
import json
import numpy as np
from sanic import Sanic
from sanic import response
from geojson import Polygon
from shapely import geometry as geo
app = Sanic("PopulationDataInquireServer")
def fetchPopulationFromFile(lon, lat):
global data
x = int((lat + 90) * 5)
y = int((lon + 180) * 5)
return float... |
from pathlib import Path
from fastai.vision.widgets import *
from fastbook import *
def search_images_bing(key, term, max_images: int = 100, **kwargs):
params = {'q':term, 'count':max_images}
headers = {"Ocp-Apim-Subscription-Key":key}
search_url = "https://api.bing.microsoft.com/v7.0/images/search"
... |
# -*- coding: utf-8 -*-
import numpy as np
def signal_to_class(data, n=2, normalize=True):
"""
Converts a list of signals to a n-dimensional list of classes [buy, .., sell].
Arguments
n (int): Number of classes.
normalize (bool): It normalizes to unity. False - the signal changes only the... |
from configuration import *
file_name = 'PdfWithAnnotations.pdf'
uploadFile(file_name)
response = pdf_api.get_document_file_attachment_annotations(
file_name, folder=temp_folder)
pprint(response) |
# searchAgents.py
# ---------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley... |
from os import path
import matplotlib.pyplot as plt
import numpy as np
from compound_poisson import mcmc
from compound_poisson import time_series
from compound_poisson.mcmc import target_time_series
class TimeSeriesMcmc(time_series.TimeSeries):
"""Fit Compound Poisson time series using Rwmh from a Bayesian sett... |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "${prefix}/include".split(';') if "${prefix}/include" != "" else []
PROJECT_CATKIN_DEPENDS = "roscpp;std_msgs;sensor_msgs;geometry_msgs;nav_msgs;tf;turtlebot3_msgs".replace(';', ' ')
PKG_CONFIG_LIBRARIE... |
import os
import pytest
import salt.utils.verify
from tests.support.mock import patch
@pytest.mark.skip_on_windows(reason="Not applicable for Windows.")
@patch("os.chown")
@patch("os.stat")
def test_verify_env_race_condition(mock_stat, mock_chown):
def _stat(path):
"""
Helper function for mock_st... |
"""Generate a 256-bit private key."""
import sys
import secrets
argv = sys.argv
error_msg = "Must confirm by running: python gen_key.py [KEY_FILE_PATH] confirm"
if len(argv) > 2:
if argv[2] == "confirm":
try:
with open(argv[1], "w") as f:
print("A new key is generated at %s" ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
功能实现:检查所提供的函数是否对列表中至少一个元素返回True。
解读:
结合使用any()和map()检查fn是否为列表中的任何元素返回True
"""
def some(lst, fn=lambda x: x):
return any(map(fn, lst))
# Examples
print(some([0, 1, 2, 0], lambda x: x >= 2))
print(some([0, 0, 1, 0]))
# output:
# True
# True
|
#!/usr/bin/env python3
#
# This file is part of Magnum.
#
# Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
# 2020, 2021, 2022 Vladimír Vondruš <mosra@centrum.cz>
# Copyright © 2020 janos <janos.meny@googlemail.com>
#
# Permission is hereby granted, free of charge, to any ... |
# Copyright 2019 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, ... |
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
"""
Creating two dataframes, for the second and third models,
and using then to plot model performance.
"""
def plot_model_pref(folder="plots", name="Model preformance", bf=False):
# the dataframes
df = pd.DataFrame([[0.98, "full", "NN,... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on April 2020
@author: Thomas Bonald <bonald@enst.fr>
"""
from typing import Iterable, Optional
import numpy as np
from sknetwork.hierarchy.postprocess import cut_straight
from sknetwork.visualization.colors import STANDARD_COLORS
def get_index(dendrogram, ... |
import datetime
import hashlib
import bs4
# XXX We may want to suppress soupsieve warning later on
def fill_header(src_filename, dst_filename):
"""Populate HTML <header></header> of file specified by dst_filename."""
filename = src_filename
hashsum = sha256sum(src_filename)
timezone = datetime.timezon... |
import pandas as pd
import numpy as np
import scipy.stats as ss
def cramers_v(confusion_matrix: pd.DataFrame) -> int:
"""
Calculate Cramers V statistic for categorial-categorial association.
uses correction from Bergsma and Wicher,
Journal of the Korean Statistical Society 42 (2013): 323-328
:par... |
import logging
from datetime import datetime
from io import BytesIO
from socket import socket
from time import time
from bunch import Bunch
import user
from pool import manager
from tds import mq
from tds.exceptions import AbortException
from tds.packets import PacketHeader
from tds.request import LoginR... |
from __future__ import unicode_literals
from django.db import models
from authentication.models import Account
class Post(models.Model):
id = models.AutoField(primary_key=True)
author = models.ForeignKey(Account)
barcode = models.TextField()
latitud = models.TextField()
longitud = models.TextFiel... |
# Copyright 2020 John Dorn
#
# 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... |
from .taxonerd import TaxoNERD
from .cli import *
__version__ = "1.3.0"
|
#!/usr/bin/env python
# Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
# Performs benchmark and append data to //website/data.json.
# If //website/data.json doesn't exist, this script tries to import it from
# gh-pages branch.
# To view the results locally run ./tools/http_server.py and visit
#... |
import matplotlib.pyplot as plt
class SignChangeSparseMap:
def __init__(self):
self.x_plus = []
self.x_minus = []
self.y_plus = []
self.y_minus = []
def add_right_change(self, x, y):
self.x_plus.append([x, y])
def add_left_change(self, x, y):
self.x_minus... |
# -*- coding: utf-8 -*-
"""
@Time : 2019/3/3 19:55
@Author : Wang Xin
@Email : wangxin_buaa@163.com
"""
import torch
import torch.nn as nn
from torch.nn import BatchNorm2d
import torchvision.models.resnet
affine_par = True
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.