text stringlengths 1 927k |
|---|
# from Slide 21 "Divide by 0" slide
# The SORN has 10 presence bits set to represent the half-open interval (–1, 2]. Begin by taking the reciprocal, which is lossless and preserves the contiguity of the unums in the result.
from punum import *
a = Alphabet.p2()
x = Pbound((-a.one()).next(),a.one().next().next())
p... |
# copyright 2019 Mojang (Microsoft Corporation), Python translation by EtlamGit
from gridSprite import gridSprite
def painting(path, x, y, w, h):
return gridSprite('assets/minecraft/textures/painting/' + path + ".png", x, y, w, h, 0, 0, 16, 16)
painting_input = 'assets/minecraft/textures/painting/paintings_kri... |
import json as json
import numpy as np
import networkx as nx
from networkx.readwrite import json_graph
# with open('./example_data/toy-ppi-feats.npy') as load_f:
def t1():
with open('./example_data/toy-ppi-G.json') as f:
data = json.load(f)
for i in data:
print(i)
print(data['directed'])
... |
# Copyright 2017 Capital One Services, 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... |
# Lint as: python3
# Copyright 2018, The TensorFlow Federated 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 ... |
from django.apps import AppConfig
class StandardizerConfig(AppConfig):
name = 'ml_api.standardizer' |
# -*- coding: utf-8 -*-
"""
DBL Python API Wrapper
~~~~~~~~~~~~~~~~~~~~~~
A basic wrapper for the top.gg API.
:copyright: (c) 2020 Assanali Mukhanov & top.gg
:license: MIT, see LICENSE for more details.
"""
__title__ = 'dblpy'
__author__ = 'Francis Taylor'
__license__ = 'MIT'
__copyright__ = 'Copyright 2020 Assanali ... |
from rest_framework import serializers
from life.users.models import District, LocalBody, State, Ward
class StateSerializer(serializers.ModelSerializer):
class Meta:
model = State
fields = "__all__"
class DistrictSerializer(serializers.ModelSerializer):
class Meta:
model = District
... |
import time
from datetime import timedelta
from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings
from corehq.form_processor.reprocess import reprocess_unfinished_stub
from corehq.util.celery_utils import no_result_task
from corehq.util.decorators import serial_tas... |
import datetime
from unittest import IsolatedAsyncioTestCase
from unittest.mock import AsyncMock
from dipdup.config import ContractConfig
from dipdup.config import OperationHandlerConfig
from dipdup.config import OperationHandlerTransactionPatternConfig
from dipdup.config import OperationIndexConfig
from dipdup.config... |
from abc import ABC, abstractmethod
class ChebpyBaseException(Exception, ABC):
def __init__(self, *args):
if args:
self.message = args[0]
else:
self.message = self.default_message
def __str__(self):
return self.message
@property
@abstractmethod
def... |
from app.models.base_model import BaseModel, db
from app.validators.cep_validator import is_valid_cep
from app.validators.coordinates_validator import is_valid_latitude, \
is_valid_longitude
from app.validators.none_or_empty_validator import is_none_or_empty
from app.validators.string_format_validator import is_flo... |
#!/usr/bin/env python
# Copyright (c) 2013-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from __future__ import division,print_function,unicode_literals
import biplist
from ds_store import DSStore... |
## @file
# fragments of source file
#
# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#TF enemy position from ralative_pos topic
#Add time losed enemy to color_flag
import rospy
import tf2_ros
import tf_conversions
import tf
import math
from geometry_msgs.msg import PoseStamped
from geometry_msgs.msg import TransformStamped
from geometry_msgs.msg import ... |
#!/usr/bin/env python3
# If not stated otherwise in this file or this component's license file the
# following copyright and licenses apply:
#
# Copyright 2020 Metrological
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may o... |
from setuptools import setup
import json
with open("metadata.json", encoding="utf-8") as fp:
metadata = json.load(fp)
setup(
name="lexibank_castroyi",
description=metadata["title"],
license=metadata.get("license", ""),
url=metadata.get("url", ""),
py_modules=["lexibank_castroyi"],
includ... |
"""Demonstrates how an application might use the barcode_wheel library"""
import sys
import barcode_wheel
import svgwrite
import pathlib
import logging
import tempfile
import csv
from time import sleep
demo_contents = (
"""
22001,Money Order (Principal),
22101,Money Order (Fee),
10502,Club Card Savings,
12345678901,T... |
"""Whitebox MLPipeline."""
import warnings
from typing import Union, Tuple, cast
from .base import MLPipeline
from ..features.wb_pipeline import WBFeatures
from ..selection.base import EmptySelector
from ...dataset.np_pd_dataset import NumpyDataset, PandasDataset
from ...ml_algo.tuning.base import ParamsTuner
from ..... |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, List, Optional, Set
import logging
from pajbot.managers.handler import HandlerManager
from pajbot.models.emote import Emote, EmoteInstance, EmoteInstanceCountMap
from pajbot.modules import BaseModule
from pajbot.modules.base import ModuleSetti... |
import os
from py2neo import Graph
import ast
from json import dumps
from flask import Flask, render_template, g, Response, request
from neo4j import GraphDatabase, basic_auth
app = Flask(__name__)
app.debug = True
# The password must be changed to your NEO4J password.
driver = GraphDatabase.driver('bolt://localhost'... |
import os
from typing import Dict, Iterable, List, Sequence, Set, Tuple
try:
import looker_sdk
from looker_sdk.sdk.api31.methods import Looker31SDK
from looker_sdk.sdk.api31.models import DashboardElement
except ImportError:
print("Please install metaphor[looker] extra\n")
raise
from metaphor.mode... |
#!/usr/bin/env python3
import sys
import json
import urllib.request
def find_subnet_rules(env, product, subnets):
all_subnets = get_all_subnets(env, product, subnets)
rule_names = [x['rule_name'] for x in all_subnets]
subnet_ids = [x['subnet_id'] for x in all_subnets]
result = {}
result['subnet... |
"""
Implement pow(x, n), which calculates x raised to the power n (x^n).
Example 1:
Input: 2.00000, 10, Output: 1024.00000
Example 2:
Input: 2.10000, 3, Output: 9.26100
Example 3:
Input: 2.00000, -2, Output: 0.25000, Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:
-100.0 < x < 100.0, n is a 32-bit signed integer, wi... |
# 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
# d... |
#!/usr/bin/env python
import os
import stat
PROJECT_DIRECTORY = os.path.realpath(os.path.curdir)
def remove_file(filepath):
os.remove(os.path.join(PROJECT_DIRECTORY, filepath))
if __name__ == '__main__':
if 'no' in '{{ cookiecutter.command_line_interface|lower }}':
cli_file = os.path.join('{{ cook... |
#!/usr/bin/env python
'''Check that a workshop's index.html metadata is valid. See the
docstrings on the checking functions for a summary of the checks.
'''
from __future__ import print_function
import sys
import os
import re
from datetime import date
from util import Reporter, split_metadata, load_yaml, check_unwan... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import asyncio
import os
import warnings
import time
import random
import threading
from itertools import chain
from urllib.parse import (parse_qs,
unquote,
urlparse)
from aredis.connection import (RedisSSLContext,
... |
class CodeConstant():
SYSTEM_ERROR = "系统错误,请与管理员联系"
REQUEST_FAILUE = "请求失败"
FILE_UPLOAD_FAILUE = "文件上传失败"
FILE_DELETE_FAILUE = "文件删除失败"
CODE_000 = "000" # 接口提交成功
CODE_001 = "001" # 接口非法请求错误
CODE_002 = "002" # 接口传递参数错误
CODE_003 = "003" # 接口异常
# 接口返回码信息 ** /
REQUEST_SUCCESS = "... |
#!/usr/bin/python
#
# Copyright (c) 2016 Matt Davis, <mdavis@ansible.com>
# Chris Houseknecht, <house@redhat.com>
#
# 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
ANS... |
print("Propriedades e Descritores")
input()
print("Propriedades - Permitem gerenciar a criação")
print("e manipulação de atributos de uma da classe")
print("Semelhante aos métodos __getattr__, __setattr")
print("e __getattribute__ porem menos genéricos")
input()
print("Exemplo")
class Pessoa(object):
def __init_... |
# -*- coding: utf-8 -*-
import logging
import os
import re
import sys
import time
from concurrent.futures import as_completed
from contextlib import contextmanager
from shutil import make_archive, rmtree
from typing import Callable, Dict, List, Optional, Union
from packaging.version import parse
from pebble import Pro... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("TEST")
process.load("FWCore.Framework.test.cmsExceptionsFatal_cff")
process.load("SimGeneral.HepPDTESSource.pythiapdt_cfi")
#process.load("SimGeneral.HepPDTESSource.pdt_cfi")
process.load("GeneratorInterface.TauolaInterface.TauSpinner_cfi")
process.Rando... |
"""
WSGI config for LoginAndRegistration project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault... |
# -----------------------------------------------------------------------------
# Copyright (c) 2009-2016 Nicolas P. Rougier. All rights reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
import numpy as np
from glumpy import app, gl, glo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""NiBabies runner."""
from .. import config
def main():
"""Entry point."""
from os import EX_SOFTWARE
from pathlib import Path
import sys
import gc
from multiprocessing import Process, Manager
from .parser import parse_args
from ..utils.bi... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
import astropy.units as u
__all__ = ['ApertureMask']
class ApertureMask:
"""
Class for an aperture mask.
Parameters
----------
data : array_like
A 2D array representing the fractional overlap of an apert... |
# Software License Agreement (BSD License)
#
# Copyright (c) 2019, Zerong Zheng (zzr18@mails.tsinghua.edu.cn)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code mus... |
#!/usr/bin/env python
import numpy
import unittest
from lib.abstract_recommender import AbstractRecommender
from lib.collaborative_filtering import CollaborativeFiltering
from lib.evaluator import Evaluator
from util.data_parser import DataParser
from util.model_initializer import ModelInitializer
class TestcaseBase(... |
# Write a procedure, count_words, which takes as input a string
# and returns the number of words in the string. You may consider words
# as strings of characters separated by spaces.
def count_words():
passage =("The number of orderings of the 52 cards in a deck of cards "
"is so great that if every one of the almo... |
"""
Need something to ingest the CTRE provided bridge data
RSAI4
RLRI4
Run from RUN_1MIN
"""
from __future__ import print_function
import datetime
import sys
from io import BytesIO
import ftplib
import subprocess
import pytz
import pyiem.util as util
from pyiem.observation import Observation
def main():
""... |
# Copyright (c) 2020 by Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
import os
import pandapipes
import pytest
from pandapower.test.toolbox import tempdir... |
from distutils.core import setup
setup(name='formdown',
version='1.0',
py_modules=['formdown'],
) |
import requests
def put_data():
headers = {
'Accept': '*/*',
'User-Agent': 'request',
}
data = {
"id":1,
"title":"A test title",
"body":"A test description",
"userId":1,
}
post_id = 1
url = "https://jsonplaceholder.typicode.com/posts/"
respo... |
#!/usr/bin/env python3
"""
A collection of utilities for the epitome pipeline. Mostly for getting
subject numbers/names, checking paths, gathering information, etc.
"""
import os
import sys
import copy
import datetime
import subprocess
import tempfile
import shutil
import logging
import math
import yaml
import ciftif... |
"""
holland.mysql.xtrabackup
~~~~~~~~~~~~~~~~~~~~~~~
Xtrabackup backup strategy plugin
"""
import sys
import logging
from os.path import join
from holland.core.backup import BackupError
from holland.core.util.path import directory_size
from holland.lib.compression import open_stream
from holland.backup.xtrabackup.mys... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Windows firewall log parser."""
from __future__ import unicode_literals
import unittest
from plaso.parsers import winfirewall
from tests.parsers import test_lib
class WinFirewallParserTest(test_lib.ParserTestCase):
"""Tests for the Windows firewall... |
from datetime import datetime
from thenewboston_node.business_logic.blockchain.memory_blockchain import MemoryBlockchain
from thenewboston_node.business_logic.models import (
BlockchainStateMessage, CoinTransferSignedChangeRequest, PrimaryValidatorSchedule
)
from thenewboston_node.business_logic.models.account_sta... |
# Generated by Django 2.1.5 on 2019-08-29 21:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('courses', '0025_courseuser_section'),
]
operations = [
migrations.AddField(
model_name='course',
name='last_taught',... |
from django.contrib.sitemaps.views import x_robots_tag
from django.contrib.sites.shortcuts import get_current_site
from django.template.response import TemplateResponse
from .video_sitemap import VideoElement
@x_robots_tag
def video_sitemap(request, sitemaps,
template_name='djangocms_youtube/sitema... |
# !/usr/bin/python3
# -*- coding: utf-8 -*-
from PIL import Image
import os
import sys
import json
from datetime import datetime
from ImageProcess import Graphics
# 定义压缩比,数值越大,压缩越小
SIZE_normal = 1.0
SIZE_small = 1.5
SIZE_more_small = 2.0
SIZE_more_small_small = 3.0
def make_directory(directory):
"""创建目录"""
o... |
import threading
from typing import NamedTuple
import zmq
from database import BLOCKCHAIN, DATATYPE, Database
from ethereum_blockchain_iterator import (
ParseEthereumBlockBodies,
ParseEthereumBlockHeaders,
)
from parser import DataExtractor
from pathlib import Path
ERC20_TRANSFER_METHOD_ID = bytes.fromhex("a9... |
import numpy as np
import time
import tempfile
import os
import importlib.util
import argparse
from typing import Sequence
import subprocess
import re
import oneflow as flow
import oneflow._oneflow_internal as oneflow_internal
DEFAULT_TIMES = 20
gpu_memory_used_by_oneflow = 0
def import_file(path):
spec = im... |
from abc import ABC, abstractproperty
class Base(ABC):
@abstract
@property
def some_method(self):
pass
class <weak_warning descr="Class Sub must implement all abstract methods">S<caret>ub</weak_warning>(Base):
pass |
from __future__ import print_function
import numpy as np
class BaseModel(object):
"""
base dictionary learning model for classification
"""
# def __init__(self)
def predict(self, data):
raise NotImplementedError
def evaluate(self, data, label):
pred = self.predict(data)
... |
from django.core.management.base import BaseCommand
from user.models import User
from mailing_list.models import EmailRecipient
class Command(BaseCommand):
def handle(self, *args, **options):
for user in User.objects.filter(emailrecipient__isnull=True, email__isnull=False):
EmailRecipient.obj... |
import json
import os
import shutil
import tempfile
from time import time
from .compat import is_win32
try:
import xbmc
import xbmcvfs
is_kodi = True
except ImportError:
is_kodi = False
if is_win32 and not is_kodi:
xdg_cache = os.environ.get("APPDATA",
os.path.expan... |
from django.urls import path
from simpleticket import views
urlpatterns = [
path('', views.view_all),
path('view/<int:ticket_id>/', views.view),
path('new/', views.create),
path('submit_ticket/', views.submit_ticket),
path('update/<int:ticket_id>/', views.update),
path('update_ticket/<int:tick... |
#
# Copyright (c) 2017 nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/vulnerablecode/
# The VulnerableCode software is licensed under the Apache License version 2.0.
# Data generated with VulnerableCode require an acknowledgment.
#
# You may not use this software except in comp... |
# -*- coding: utf-8 -*-
# @Time: 2020/4/20 12:38
# @Author: GraceKoo
# @File: 401_binary-watch.py
# @Desc:https://leetcode-cn.com/problems/binary-watch/
from typing import List
class Solution:
def readBinaryWatch(self, num: int) -> List[str]:
def count_binary_1(i):
return bin(i).count("1")
... |
"""
MIT License
Copyright (c) 2020-2021 phenom4n4n
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, copy, modify, merge, publis... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 CERN.
#
# invenio-app-ils is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Loan custom serializer functions."""
from invenio_circulation.proxies import current_circulation
from invenio_... |
import pytest
from helpers.cluster import ClickHouseCluster
import random
import string
import os
import time
from multiprocessing.dummy import Pool
cluster = ClickHouseCluster(__file__)
node = cluster.add_instance('node', main_configs=['configs/enable_keeper.xml'], with_zookeeper=True, use_keeper=False)
from kazoo.cl... |
from os.path import join
import numpy as np
from functools import reduce
from operator import add
class Cell:
def __init__(self, xy=None, chromosomes=None, lineage=''):
# set generation
self.lineage = lineage
# set chromosomes
if chromosomes is None:
chromosomes = np... |
#Дано натуральное число N. Выведите слово YES, если число N является точной степенью двойки, или слово NO в противном случае.
#Операцией возведения в степень пользоваться нельзя!
# Оформите в виде обычной и хвостовой рекурсии
# Вариант с хвостовой рекурсией преобразуйте в цикл while
def is_power_of_two(N):
return ... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads_v2/proto/services/shopping_performance_view_service.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from go... |
#!/usr/bin/env python
#
# File Name : rouge.py
#
# Description : Computes ROUGE-L metric as described by Lin and Hovey (2004)
#
# Creation Date : 2015-01-07 06:03
# Author : Ramakrishna Vedantam <vrama91@vt.edu>
import numpy as np
import pdb
def my_lcs(string, sub):
"""
Calculates longest common subsequence ... |
# For more settings, see: https://docs.gunicorn.org/en/stable/settings.html
import multiprocessing
wsgi_app = "main:run()"
workers = 1
worker_connections = 100
bind = ":8050"
timeout = 30
# Worker is changed to prevent worker timeouts
# See: https://github.com/benoitc/gunicorn/issues/1801#issuecomment-585886471
worke... |
import simplejson as S
def test_encoding1():
encoder = S.JSONEncoder(encoding='utf-8')
u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
s = u.encode('utf-8')
ju = encoder.encode(u)
js = encoder.encode(s)
assert ju == js
def test_encoding2():
u = u'\N{GREEK SMALL LETTER... |
"""The Emporia Vue integration."""
import asyncio
from datetime import datetime, timedelta
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
import logging
from pyemvue import PyEmVue
from pyemvue.device import VueDeviceChannel
from pyemvue.enums import Scale
import voluptuous a... |
import os
from ....utils import catkin_success
from ....utils import in_temporary_directory
from ....utils import redirected_stdio
from ....workspace_assertions import assert_no_warnings
from ....workspace_assertions import assert_warning_message
from ....workspace_assertions import assert_workspace_initialized
@in_... |
# --------------------------------------------------------------------------------------------
# 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
# flake8: noqa
# pylint: skip-file
# type: ignore
import time
import cereal.messaging as messaging
from selfdrive.car.honda.interface import CarInterface
from selfdrive.controls.lib.events import ET, EVENTS, Events
from selfdrive.controls.lib.alertmanager import AlertManager
def cycle_alerts(... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import logging
from typing import Dict
import torch
from detectron2.layers import ShapeSpec
from ..box_regression import Box2BoxTransformRotated
from .build import PROPOSAL_GENERATOR_REGISTRY
from .rpn import RPN
from .rrpn_outputs import RRPNOutp... |
from abc import abstractmethod
import PIL
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from torch.hub import load_state_dict_from_url
from torchvision.models import DenseNet as _DenseNet
from torchvision.models import ResNet as _ResNet
from torchvision.m... |
import base64
import datetime
import json
import logging
import time
import requests
from .. import exception, ssl
from . import base
logger = logging.getLogger(__name__)
class IncapsulaSite(base.Server):
BASE_URL = "https://my.incapsula.com:443"
def __init__(self, api_key, api_id, site_id, crt_name, **k... |
# Collection of supporting functions for wrapper functions
__author__ = 'AndrewAnnex'
from ctypes import c_char_p, c_bool, c_int, c_double, c_char, c_void_p, sizeof, \
POINTER, pointer, Array, create_string_buffer, create_unicode_buffer, cast, Structure, \
CFUNCTYPE, string_at
import numpy
from numpy import ct... |
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, BaggingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.neural_network import MLPClassifier
f... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.base.exchange import Exchange
# -----------------------------------------------------------------------------
try... |
from django.contrib import admin
class JobPostAdmin(admin.ModelAdmin):
list_display = (
'id',
'user',
'title',
'slug',
'employment_option',
'wage_salary',
'start_date',
'bookmarked',
'bookmarked',
... |
# -*- coding: utf-8 -*-
# Copyright 2018 Novo Nordisk Foundation Center for Biosustainability,
# Technical University of Denmark.
#
# 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... |
import os
import sys
from platon_keys import keys
from platon_utils.curried import keccak, text_if_str, to_bytes
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
def gen_node_keypair(extra_entropy=''):
extra_key_bytes = text_if_str(to_bytes, extra_entropy)
key_bytes = keccak(os.urandom(32) + extra_key_... |
import os
import nltk
import wget
def download_data():
try:
nltk.data.find("tokenizers/punkt")
except LookupError:
nltk.download("punkt")
try:
nltk.data.find("corpora/stopwords")
except LookupError:
nltk.download("stopwords")
if "data" not in os.listdir(os.getcwd()... |
# coding: utf-8
"""
Copyright 2016 SmartBear Software
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 -*-
# Copyright (c) 2013 Artem Glebov
import sys
import transmissionrpc
__settings__ = sys.modules[ "__main__" ].__settings__
def get_settings():
params = {
'address': __settings__.getSetting('rpc_host'),
'port': __settings__.getSetting('rpc_port'),
'user': __settings_... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright 2016 Twitter. 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... |
"""
NCams Toolbox
Copyright 2019-2020 Charles M Greenspon, Anton Sobinov
https://github.com/CMGreenspon/NCams
"""
import os
import time
import math
import pylab
import ncams
BASE_DIR = os.path.join('C:\\', 'FLIR_cameras', 'PublicExample')
def main():
cdatetime = '2019.12.19_10.38.38';
camera_config_dir = o... |
from unittest import TestCase
from tests import get_data
from pytezos.michelson.converter import build_schema, decode_micheline, encode_micheline, micheline_to_michelson
class StorageTestKT1DkY42MwUA1eC9jHNU2MVHqcLqhLvvbxaW(TestCase):
@classmethod
def setUpClass(cls):
cls.maxDiff = None
cls.... |
class User():
def __init__(self, id, username, password):
self.id = id
self.username = username
self.password = password
self.rooms = [] |
import importlib
import xarray as xr
import numpy as np
import pandas as pd
import sys
from CASutils import filter_utils as filt
from CASutils import readdata_utils as read
from CASutils import calendar_utils as cal
importlib.reload(filt)
importlib.reload(read)
importlib.reload(cal)
expname=['SASK_CLM5_CLM5F_01.001... |
import click
from parsec.cli import pass_context, json_loads
from parsec.decorators import custom_exception, dict_output, _arg_split
@click.command('delete_dataset_collection')
@click.argument("history_id", type=str)
@click.argument("dataset_collection_id", type=str)
@pass_context
@custom_exception
@dict_output
def ... |
import xlwt
# 创建excel工作表
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet('sheet1')
# 设置表头
worksheet.write(0, 0, label='产品名称') # product_name
worksheet.write(0, 1, label='产品规模(万)') # volume
worksheet.write(0, 2, label='基金成立日期') # setup_date
worksheet.write(0, 3, label='所投资管计划/信托计划名称') # ... |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
import numpy as np
def main():
# input
H, W = map(int, input().split())
Ass = [[*map(int, input().split())] for _ in range(H)]
# compute
Ass = np.array(Ass)
# output
print(np.sum(Ass - np.min(Ass)))
if __name__ == '__main__':
main() |
# Copyright 2016 Red Hat, 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 ... |
import gpipsfs
def test_coron():
gpi = gpipsfs.GPI()
gpi.obsmode='H_coron'
psf = gpi.calc_psf(monochromatic=1.6e-6)
assert psf[0].data.sum() < 5e-4
def test_direct():
gpi = gpipsfs.GPI()
gpi.obsmode='H_direct'
psf = gpi.calc_psf(monochromatic=1.6e-6)
assert psf[0].data.sum() > 0.99
... |
import graphene
from graphene_django.types import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField
from graphql_relay.node.node import from_global_id
from . import models
class TransactionNode(DjangoObjectType):
class Meta:
model = models.Transaction
filter_fields = ... |
# coding=utf-8
# *** WARNING: this file was generated by the Kulado Kubernetes codegen tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
# Make subpackages available:
__all__ = [
"v1beta1",
] |
'''
================================================
DOWNLOAD_AUDIOSET REPOSITORY
================================================
Original:
repository name: download_audioset
repository version: 1.0
repository link: https://github.com/jim-schwoebel/download_audioset
author: Jim Schwoebel
... |
from __future__ import absolute_import
# Copyright (c) 2010-2016 openpyxl
import pytest
from openpyxl.xml.constants import CHART_DRAWING_NS
from openpyxl.xml.functions import Element, fromstring, tostring
from openpyxl.tests.helper import compare_xml
class DummyDrawing(object):
"""Shapes need charts which need... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.