content stringlengths 5 1.05M |
|---|
from data_structures_and_algorithms.data_structures.stacks_and_queues.stacks_and_queues import Stack,Queue
def test_Stack_is_empty():
stack = Stack()
actual= stack.is_empty()
expexted=True
assert actual==expexted
def test_Queue_is_empty():
queue = Queue()
actual= queue.is_empty()
expexted... |
# Copyright 2018-2020 Xanadu Quantum Technologies 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 applicabl... |
import numpy as np
from sklearn.tree import DecisionTreeRegressor
class GradientBoostingRegressor_MarsMan13:
# params_keys : ['learning_rate', 'n_estimators', 'max_depth', 'max_features']
# params_keys : ['learning_rate', 'n_estimators', 'max_leaf_nodes', 'max_features', 'random_state', 'verbose']
... |
import numpy as np
def dijkstra(matrix, source=0):
vertices = len(matrix)
not_visited = np.arange(0, vertices) # list of nodes from (0, 1, 2, 3 ..., N)
previous_node_list = [np.nan] * vertices # list of previous nodes for each node (how we get there)
shortest_distance_from_source_list = [np.inf] * v... |
"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W... |
from typing import List, Dict, Tuple
from scipy.stats import gmean
import numpy as np
import pandas as pd
from py_muvr.data_structures import (
SelectedFeatures,
ScoreCurve,
FeatureEliminationResults,
InnerLoopResults,
FeatureSelectionRawResults,
FeatureSelectionResults,
)
from py_muvr.utils imp... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: test_api.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 google.protobuf import message as _message
from google.protobuf im... |
import sys
import logging
from django.conf import settings
from django.apps import AppConfig
logger = logging.getLogger(__name__)
class ApiMainConfig(AppConfig):
name = "api_main"
def ready(self):
import api_main.signals
if "runserver" in sys.argv or "gunicorn" in sys.argv[0]:
... |
#!/usr/bin/env python
from math import log2
ref_file = open('../../../result/mirage_output_miR-124_vs_RefSeq_NM_2015-07-20_miR-124_overexpression.result','r')
input_file = open('../../../result/gene_exp_miR-124_overexpression_RefSeq_Rep_isoforms.diff','r')
output_file = open('../../../result/gene_exp_miR-124_ov... |
import asyncio
import time
import httpx
from pydantic import BaseModel
from koala.typing import *
ResultType = TypeVar("ResultType", bound='PDResponse')
__PD_ADDRESS = "http://127.0.0.1:2379"
PD_VERSION_URL = f"{__PD_ADDRESS}/pd/api/v1/version"
PD_ID_NEW_SERVER_URL = f"{__PD_ADDRESS}/pd/api/v1/id/new_server_id"
PD_I... |
#25) 1000-digit Fibonacci number
#The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
#The 12th term, F12, is the first term to contain three digits.
#What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
# Solution
def d_fibonacci(n)... |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
#%matplotlib inline
#check dependencies
from utils import pyreq
pyreq.require("matplotlib,pandas")
#gather command line arguments
import argparse
parser = argparse.ArgumentParser()
#data file specification parameters (change which files are loaded)
parser.add_argu... |
import platform
import sys
import pytest
try:
# py3
from urllib.request import urlopen
except ImportError:
# py2
from urllib import urlopen
try:
# py2
from httplib import HTTPSConnection
except ImportError:
# py3
from http.client import HTTPSConnection
from sentry_sdk import capture_... |
import unittest
from datetime import date, datetime, time, timedelta, timezone
from enum import Enum
from uuid import UUID
from sqlalchemy_model_builder.random_builder import RandomBuilder
class TestDateTimeBuilders(unittest.TestCase):
def test_next_date_valid_type(self):
random_date = RandomBuilder.next... |
import os
import sys
import traceback
from django.utils import autoreload
_mtimes = autoreload._mtimes
_win = autoreload._win
_code_changed = autoreload.code_changed
_error_files = []
def my_code_changed():
global _mtimes, _win
for filename in filter(lambda v: v, map(lambda m: getattr(m, "__file__", None), sy... |
#!/usr/bin/python
#coding:utf-8
#
# PROGRAM/MODULE: firebird-base
# FILE: test/test_collections.py
# DESCRIPTION: Unit tests for firebird.base.collections
# CREATED: 20.9.2019
#
# The contents of this file are subject to the MIT License
#
# Permission is hereby granted, free of charge, to any person... |
import os
import time
import requests
import json
from authlib.jose import JsonWebSignature
SWC_SCOPE = "create delete read update"
JWT_TOKEN_HEADER = {"alg": "HS256"}
TOKEN_DURATION = 120
class CommunityToken:
def __init__(
self,
community_domain=os.getenv("SWC_AUDIENCE"),
app_id=os.gete... |
"""ws-pserve script.
DEPRECATED: Wrapper around Pyramid pserve script.
"""
# Standard Library
import sys
import typing as t
# Websauna
from websauna.system.devop.scripts import proxy_to_pyramid_script
try:
import gevent.monkey
gevent.monkey.patch_all()
except ImportError:
pass
def main(argv: t.List[st... |
import unittest
from unicrypto import get_cipher_by_name
from unicrypto import symmetric
# https://github.com/weidai11/cryptopp/blob/master/TestVectors/aes.txt
aes_128_ecb = [
#plaintext, key, ciphertext
('6bc1bee22e409f96e93d7e117393172a', '2b7e151628aed2a6abf7158809cf4f3c', '3ad77bb40d7a3660a89ecaf32466ef97'),
... |
#!/usr/bin/env python
# This example demonstrates how to use the vtkPointWidget to probe a
# dataset and then color the probed point (represented as a cone) as
# per the probed value and orient it as per the vector.
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Start by loadi... |
# -*- coding: utf-8 -*-
import os
from sys import stderr
from eduid_scimapi.app import init_api
__author__ = 'lundberg'
DEBUG = os.environ.get('EDUID_APP_DEBUG', False)
if DEBUG:
stderr.writelines('----- WARNING! EDUID_APP_DEBUG is enabled -----\n')
api = init_api()
|
import numpy as np
N = 100
R = 10000
R_range = range(R)
size = (N, 3)
C = np.zeros((N, 3))
k = 1
print ("100")
print ("STEP: ", k)
for i in range(N):
print ("He ", C[i, 0], " ", C[i, 1], " ", C[i, 2])
k += 1
for j in range(R):
A = np.random.uniform(-1, 1, size)
B = np.sum(np.multiply(A, A), axis=1)
B = np.sqrt(B)... |
__version__ = "0.1"
__author__ = "Lennart Breede"
ERROR_MSG = "ERROR"
def evaluateExpression(expression):
try:
result = str(eval(expression, {}, {}))
except Exception:
result = ERROR_MSG
return result |
import numpy as np
import scipy
import scipy.sparse
import scipy.sparse.linalg
import scipy.stats
def diff(x):
return x[1:] - x[:-1]
def emission_times_loglik(t, b, r, N_max=None, truncate=False):
"""
t = vector of observed emission times
b = bleaching rate
r = emission rate
N_max = max number... |
from typing import List, Optional, Sequence, Union, cast
from jinja2 import Environment, Template
from rivr.http import Request, Response
class JinjaResponse(Response):
def __init__(
self,
request: Request,
template_names: Sequence[str],
context,
environment: Environment =... |
from cassandra.physics.kinematics import Force, EulerAngles, MassiveBody, CompositeBody, Loggable
from cassandra.utils import constrain
import numpy as np
import quaternion as q
class RocketComponent(MassiveBody, CompositeBody, Loggable):
"""
A base class for all rocket components.
Parameters
----------
na... |
# @component {
# "kind" : "predictor",
# "language" : "py",
# "description" : "Performs prediction using previous trained model",
# "permissions": "public",
# "properties": [
# { "name": "Pixel width" , "field": "width", "kind": "integer", "min": 8, "max": 1000, "required": true, "default": 28 },
# { "name":... |
from django.shortcuts import render
# Create your views here.
from lib.http import render_json
from vip.models import Vip
def vip_info(request):
vip_info = []
for vip in Vip.objects.all().exclude(level=0).order_by('level'):
v_info = vip.to_dict()
v_info['perms'] = []
for perm in vip.... |
from django.contrib.auth.models import AbstractUser
#from django.db.models import CharField
from django.db import models
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
class User(AbstractUser):
GENDER_CHOICE = (
('male', 'Male'),
('female', 'Female'),
... |
import frappe
def get_context(context):
inventory = {
inv["name"]: inv["quantity"]
for inv in frappe.get_list("Inventory", fields=["name", "quantity"])
}
context.company = frappe.get_list("Company", ["company_name", "currency"])[0]
items = frappe.get_list(
"Item",
fiel... |
"""
Draw game interface
Use Tkinter and Canvas to draw interface
Provide a way to draw pieces
"""
from core.algorithm import transpose
from error import GameSettingError
from settings import ViewSettings
import tkinter
from tkinter import ttk
import tkinter.messagebox as msgbox
from collections import OrderedDict as ... |
import pandas as pd
from techminer.core.map import map_
from techminer.core.thesaurus import read_textfile
def apply_keywords_thesaurus(
input_file="corpus.csv",
thesaurus_file="TH_keywords.txt",
output_file="corpus.csv",
):
df = pd.read_csv(input_file)
##
## Loads the thesaurus
##
... |
import os
import pickle
import torch
from allennlp.common.params import Params
class KG:
def __init__(
self,
nodes: list,
features: torch.Tensor,
edges: list,
relations: list = None,
params: Params = None,
):
"""Generic KG class.
Args:
... |
from __future__ import print_function
import argparse
import sys
from .factory import from_csv, from_md
from ._compact import StringIO
def main():
parser = argparse.ArgumentParser(description='A simple Python library designed to make it quick and easy to '
'represent tabular ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 29 15:47:36 2018
@author: akurnizk
"""
import utm
import math
import flopy
import sys,os
import numpy as np
import pandas as pd
import moviepy.editor as mpy
import matplotlib.pyplot as plt
import flopy.utils.binaryfile as bf
cgw_code_dir = 'E:\Python KM... |
from permission import Permission
from movie_knight.rules import IsAuthenticated, UserRule, AdminRule
class Template(Permission):
"""Template"""
def rule(self):
pass
class AuthenticatedPermission(Permission):
"""Check if a user is authenticated without checking a role."""
def rule(self):
... |
import socket
import os
from time import strftime
class TcpTimeServer:
def __init__(self, host='', port=12345):
self.addr = (host, port)
self.serv = socket.socket()
self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.serv.bind(self.addr)
self.serv.listen(1)
... |
from django.apps import AppConfig
class EtlConfig(AppConfig):
name = "etl"
|
# To generate client code for static images, run:
# $ pip install absl-py
# $ python client_image.py --input=assets/client/error.gif
from absl import app
from absl import flags
from ntpath import basename
from numpy import array
from numpy import packbits
from numpy import uint8
from numpy import where
from os import ... |
import numpy as np
from dival import TaskTable
from dival.measure import PSNR, SSIM
from dliplib.utils import Params
from dliplib.utils.helper import select_hyper_best_parameters
from dliplib.utils.helper import load_standard_dataset
from dliplib.reconstructors import TVAdamReconstructor
from dliplib.utils.reports im... |
# https://www.hackerrank.com/challenges/icecream-parlor/problem?isFullScreen=true
def icecreamParlor(m, arr):
# Write your code here
index = []
for counter,item in enumerate(arr):
diff = m - item
if diff in arr:
index_of_diff = arr.index(diff)
if diff =... |
"""
Representations of Panels and their templates.
.. moduleauthor:: Scott Petersen <scott@nutech.com>
"""
ADEMCO = 0
DSC = 1
PANEL_TYPES = {
'A': ADEMCO,
'D': DSC,
}
VISTA20 = 0
TEMPLATES = {
VISTA20: {
'name': 'Vista 20',
# number of expanders, starting_address, number of channels
... |
import random, sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QSizePolicy
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from qtWinPltUI import Ui_MainWindow
# plt 차트와 qt를 함께 사용하는 예제
class Main(QMainWindow, Ui_MainWindow):
def __ini... |
PLATFORM_COMPILER_FLAGS = [
'-std=c++14',
'-Wall',
'-Wextra',
# For TestCommon.h
'-Wno-pragmas',
]
|
###############################################################################
# __ _ ___ ____ #
# / _| ___ _ __ _ __ ___ (_) ___|_ _| _ \ #
# | |_ / _ \| '__| '_ ` _ \| |/ __|| || | | | #
... |
from typing import Callable
import numpy as np
def proj_to_self() -> Callable[[np.ndarray], np.ndarray]:
"""return the function of projection that maps to self.
Returns
-------
Callable[[np.ndarray], np.ndarray]
the function of projection that maps to self.
"""
def _proj_to_self(var... |
""" Optimization problem to be solved."""
import yaml
import numpy as np
from scipy.optimize import LinearConstraint, Bounds
from PyMEX.utilits import ParallelPyMex
class Simulation:
""" Reservoir parameters for simulation."""
def __init__(self):
""" Reservoir parameters."""
self.res_param =... |
from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .iq_groups import GroupsIqProtocolEntity
class InfoGroupsIqProtocolEntity(GroupsIqProtocolEntity):
'''
<iq id="{{id}}"" type="get" to="g.us" xmlns="w:g">
<query></query>
</iq>
'''
def __init__(self):
super(InfoGroups... |
#!/usr/bin/env python3
import cmd
import socket
import sys
import select
import threading
import tempfile
import subprocess
import struct
def make_srec(addr, code):
header = 'S00600004844521B'
terminate = 'S9030000FC'
addr = '%.8x' % addr
code = code.encode('hex').upper()
length = '%.2x' % (len(c... |
import numpy as np
import matplotlib.pyplot as plt
def fun(x):
# return 11 * np.sin(x) + 7 * np.cos(5 * x)
return -np.square(x)
# 1.参数初始化
narvs = 1 # 变量个数1212
T0 = 100 # 初始温度
T = T0 # 迭代过程中温度会发生变化,第一次迭代的温度即为T0
maxgen = 200 # 最大迭代次数
Lk = 100 # 每个温度下的迭代次数
alpha = 0.95 # 温度的衰减系数
x_lb = -3... |
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean CLI v1.0. Copyright 2021 QuantConnect Corporation.
#
# 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... |
# Copyright (c) 2019, NVIDIA CORPORATION.
import os
import random
from glob import glob
from io import BytesIO
from string import ascii_letters
import numpy as np
import pandas as pd
import pyarrow as pa
import pytest
import cudf
from cudf.tests.utils import assert_eq
@pytest.fixture(scope="module")
def datadir(da... |
import json
import csv
import os
for f in ['train.txt', 'dev.txt', 'test.txt', 'graph.txt']:
with open(dir+f, encoding='UTF-8') as raw_file:
csv_file = csv.reader(raw_file, delimiter='\t')
for line in csv_file:
e1,r,e2, tim = line
if e1 not in entity_vocab:
en... |
# -*- encoding: utf-8 -*-
'''
@File : config.py
@Contact : guzhouweihu@163.com
@Modify Time @Author @Version @Desciption
------------ ----------- -------- -----------
2020/7/13 14:14 guzhouweihu 1.0 None
'''
import argparse
def create_parser():
parser = argpar... |
# pylint: disable = redefined-outer-name
import os
import pytest
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
config = """
from universum.configuration_support import Configuration
success_step = Configuration([dict(name="Success step", command=["echo", "success"])])
failed... |
##########################################################################
#
# Copyright 2011 LunarG, Inc.
# All Rights Reserved.
#
# 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 res... |
import math
import os
import random
import sys
from torch.utils.data import DataLoader,Dataset
from os import path
import torch
# from scipy.misc import toimage
import torchvision
sys.path.append(path.abspath('../CIFAR_modified/code'))
import CIFAR_modified
from matplotlib import pyplot as plt
import numpy as np
from ... |
"""
12. Min Stack
https://www.lintcode.com/problem/min-stack/description
"""
class MinStack:
def __init__(self):
# do intialization if necessary
self.stack = []
self.min_stack = []
"""
@param: number: An integer
@return: nothing
"""
def push(self, number):
# writ... |
from setuptools import setup
setup(
name="rew",
version="0.1.0",
description="Keep your Brewfile up-to-date",
author="Alex Plate",
author_email="AlexPl292@gmail.com",
url="https://github.com/AlexPl292/rew",
py_modules=['rew'],
entry_points={
'console_scripts': ['rew=rew:main'],
... |
# terrascript/nomad/__init__.py
import terrascript
class nomad(terrascript.Provider):
pass
|
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from click.testing import CliRunner
from rq import get_failed_queue, Queue
from rq.compat import is_python_version
from rq.job import Job
from rq.cli import main
from rq.cli.helpers impo... |
import os
import json
import argparse
from setup import setup_and_run
import rlkit.torch.pytorch_util as ptu
from configs.default import default_pearl_config
from misc_utils import deep_update_dict
def main(args):
variant = default_pearl_config
with open(os.path.join(args.config)) as f:
exp_params... |
import requests, csv, re
from lxml import html
def get_response():
headers = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding':'gzip, deflate',
'Accept-Language':'en-US,en;q=0.8,pt;q=0.6',
... |
class UtilsXDiscordException(Exception):
"""The base exception for the UtilsX discord section!"""
pass
class MissingFormatArguments(UtilsXDiscordException):
"""Exception that gets thrown when a `.format` raises an error due to missing keys."""
pass
|
import requests
import pytest
from lxml.html import fromstring
class TestRouting:
''' Handles the routing tests and assertion
as well as the global pass/fail state
the methods with test_ in their names will be run automatically.
'''
def root(self):
'''Hack to get the root url init... |
"""
'Layers' introduces a number of auxiliary lasagne layers that are used throughout AgentNet and examples
"""
from .broadcast import BroadcastLayer,UnbroadcastLayer,UpcastLayer
from .dict import DictLayer,DictElementLayer
from .helpers import *
from .reapply import ReapplyLayer,reapply
|
from django.test import TestCase
from mock import patch
from robber import expect
from data.constants import AttachmentSourceType
from data.factories import AttachmentFileFactory, AllegationFactory
from document_cloud.factories import DocumentCloudSearchQueryFactory
from document_cloud.search import search_all
from sh... |
# -*- coding: utf-8 -*-
import logging
import json
from data_models.influencers_models import FundingRelationship
from data_models.influencers_models import InterestCategory
from data_models.influencers_models import RegisteredInterest
from data_models.influencers_models import InterestDetail
from utils import mongo
fr... |
#!/usr/bin/env python
# coding=utf-8
from CosmAna import fft
from mpi4py import MPI
import mpiunittest as unittest
import numpy as np
import sys
import logging
logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO)
@unittest.skipIf(MPI.COMM_WORLD.Get_size() > 4, 'mpi-world-size>4')
class TestFFT... |
import itertools
from datetime import date
from decimal import Decimal
import pytest
from applications.api.v1.serializers import ApplicantApplicationSerializer
from applications.enums import BenefitType
from applications.models import Application
from applications.tests.conftest import * # noqa
from applications.test... |
import torch
import string
trans = str.maketrans('(),_-/', ' ','\\"')
def parse_text(text, stopwords=[]):
tokens = text.translate(trans).split()
tokens = [token for token in tokens if token != '']
return list(dict.fromkeys(tokens))
def encode_seq(seq, word2idx, tolerate_miss=True):
res = [... |
for _ in range(int(input())):
v,e=input().split()
v=float(v)
if e=="kg":print("%.4f"%(v*2.2046),"lb")
if e=="lb":print("%.4f"%(v*0.4536),"kg")
if e=="l":print("%.4f"%(v*0.2642),"g")
if e=="g":print("%.4f"%(v*3.7854),"l") |
# https://pytest.org/latest/example/simple.html#control-skipping-of-tests-according-to-command-line-option
import pytest
def pytest_addoption(parser):
parser.addoption("--runslow", action="store_true", help="run slow tests")
|
import requests
from typing import Optional, Dict
from .exception import raise_error
class APIBase:
def __init__(self, config, prefix):
self.baseurl = f'{config.apiserver.address}/api/v1/{prefix}'
self.headers = {'session': config.session}
self.raise_error = raise_error
def _get(se... |
"""
Tests module image
# Author: Vladan Lucic
# $Id$
"""
from __future__ import unicode_literals
__version__ = "$Revision$"
from copy import copy, deepcopy
import os.path
import unittest
#from numpy.testing import *
import numpy
import numpy.testing as np_test
import scipy
from pyto.core.image import Image
from ... |
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis <nichael.aivazis@para-sim.com>
# (c) 1998-2022 all rights reserved
# support
import merlin
# superclass
from .Asset import Asset
# class declaration
class RealAsset(Asset):
"""
Encapsulation of an asset with a physical presence on the filesystem
"""
... |
from ..utils import Object
class DownloadFile(Object):
"""
Downloads a file from the cloud. Download progress and completion of the download will be notified through updateFile updates
Attributes:
ID (:obj:`str`): ``DownloadFile``
Args:
file_id (:obj:`int`):
Identifier ... |
from nltk.sentiment.vader import SentimentIntensityAnalyzer
sia = SentimentIntensityAnalyzer()
sentiment_scores = sia.polarity_scores("Today is a beautiful day :)")
print(sentiment_scores)
print("\n~x~\n")
from nltk import ClassifierI
from nltk.sentiment.vader import SentimentIntensityAnalyzer
class SentimentInten... |
import json
import tkinter
import os
import comm
import index
# flag: true = bot
# flag: false = user
def update(flag, text):
if(flag):
return
else:
return
|
import tasks
from . import base
class CurrencyExchangeCredentialsProvider(base.CredentialsProvider[tasks.FetchBaseCurrencyExchangeReportTask]):
@property
def credentials_path(self) -> str:
return f'{self.task.api_credentials_key}/{self.task.api_credentials_key}_fixer{self.credentials_file_suffix}'
|
# Shamir Secret Sharing Library
# Techruption: Multi-Party All Night
import sympy as sp
import gmpy2
import secrets
class ShamirSecretSharingScheme(object):
def __init__(self,P,n,t):
self.P = P
self.n = n
self.t = t
# Vandermonde matrix for evaluation of polynomials at points [1,.... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 11 18:18:09 2020
@author: Ruben
"""
import pandas as pd
import numpy as np
from pathlib import Path
import pytest
import pvlib
from cpvlib import cpvsystem
mod_params_cpv = {
"gamma_ref": 5.524,
"mu_gamma": 0.003,
"I_L_ref": 0.96,
"I_o_ref": 0.0000000001... |
s = open("generated.h").read()
s = s.split("{")[1].split("}")[0]
s = s.split(",")
s = [int(c, 16) for c in s]
# DECRYPT
key = [0x4b, 0xa9, 0xdc, 0x18][::-1]
for i in range(0x38, 0xa0):
s[i] ^= key[i%4]
key = [0x17, 0xdb, 0x41, 0xdc][::-1]
for i in range(0xf4, 0x13c):
s[i] ^= key[i%4]
key = [0x73, 0xd4, 0x0... |
from pyhop_anytime import *
global state, goals
state = State('state')
state.calibration_target = Oset([('instrument0','star0'),('instrument1','star2'),('instrument2','star2')])
state.on_board = Oset([('instrument0','satellite0'),('instrument1','satellite1'),('instrument2','satellite1')])
state.pointing = Oset([('satel... |
"""
@author: LowinLi
预训练
"""
import os
from transformers import (
BigBirdConfig,
BigBirdForMaskedLM,
LineByLineTextDataset,
DataCollatorForLanguageModeling,
Trainer,
TrainingArguments,
)
import torch
from torch.utils.data.dataset import Dataset, Iterable
from jieba_tokenizer.jieba_t import get_... |
# -*- coding: utf-8 -*-
# Copyright 2018-2022 the orix developers
#
# This file is part of orix.
#
# orix 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 of the License, or
# (at your option) ... |
from akame import Monitor, init
def main() -> None:
"""Function that runs the example"""
monitor = Monitor(
task_name="Does Time Flow in Taipei?",
target_url=(r"http://worldtimeapi.org/api/timezone/Asia/Taipei"),
loop_seconds=60, # every 1 minute
loop_max_rounds=43200, # for... |
#!/usr/bin/python3
from PIL import Image
import numpy as np
import os, sys, argparse
def main():
parser = argparse.ArgumentParser(description='Convert 16B tiff to 8B tiff.')
parser.add_argument(dest="filenames", metavar="F", type=str, nargs='+', help="16B tiff filename to convert")
args = parser.parse_ar... |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/00_outlier_detection.ipynb (unless otherwise specified).
__all__ = ['__load_df', '__scipy_zscore__', 'zscore', '__median', '__left_median', '__right_median', '__first_quartile',
'__third_quartile', '__iqr', 'iqr', 'dbscan', 'ZSCORE', 'IQR']
# Cell
import nump... |
import mysql.connector as mysqlConnector
import os
import json
import time
from pyapacheatlas.auth import ServicePrincipalAuthentication
from pyapacheatlas.core import PurviewClient, AtlasEntity, AtlasProcess
MYSQL_SERVER_HOSTNAME = os.environ.get('MYSQL_SERVER_HOSTNAME','')
MYSQL_INSTANCE_PORT = os.environ.get('MYSQ... |
# coding=utf-8
"""Day 013 - Jedi ways to create Dicts.
This example covers the creation of an important Python data type: Dict.
As a plus, there is an example of Dict creation with Dict Comprehensions.
"""
def run():
### Creating dicts
framework = dict(name='Flask', language='Python', cool=True)
... |
"""
# test_utils for project bmi_calculator
# Created by @Sanjeet Shukla at 11:09 AM 1/16/2022 using PyCharm
"""
from pyspark.sql import SparkSession
def create_spark_session(app_name):
spark = SparkSession.builder \
.appName(app_name) \
.enableHiveSupport() \
.getOrCreate()
return spa... |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\delivery\scheduled_delivery_loot_op.py
# Compiled at: 2019-01-29 22:39:15
# Size of source mod 2**32... |
from pymongo.errors import ServerSelectionTimeoutError
from utils import make_error_response
def add_hooks(app):
@app.errorhandler(Exception)
def catchall_exception_handler(ex):
return make_error_response('Unexpected server error', 500, exception=ex)
@app.errorhandler(ServerSelectionTimeoutError)... |
"""Create models
Revision ID: a0a279efb970
Revises:
Create Date: 2019-01-05 15:44:17.613673
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a0a279efb970'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... |
"""Logging utilities."""
import logging
from . import __title__
# The logging system will call this automagically if its module-level logging
# functions are used. We call it explicitly to make sure something handles
# messages sent to our non-root logger. If the root logger already has handlers
# this is a noop, an... |
from priorityqueue import *
def testPriorityQueue_basico():
pq = crearPriorityQueue()
pushPriorityQueue(pq, 0, 'A')
assert popPriorityQueue(pq) == 'A'
def testPriorityQueue_varios():
pq = crearPriorityQueue()
pushPriorityQueue(pq, 0, 'A')
pushPriorityQueue(pq, 3, 'D')
pushPriorityQueue(... |
# -*- coding: utf-8 -*-
import os
import platform
import pytest
from PySide2 import QtCore
from PySide2.QtWidgets import QApplication
import numpy as np
import vtk
from sksurgeryvtk.widgets.vtk_overlay_window import VTKOverlayWindow
from sksurgeryvtk.widgets.vtk_interlaced_stereo_window import VTKStereoInterlacedWindo... |
from multiprocessing import Process
import typer
import uvicorn
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from ._utils import singleton
@singleton
class Bali:
def __init__(self, base_settings=None, **kwargs):
self.base_settings = base_settings or {}
self.kw... |
"""Generates signals and noises considering real noises"""
import numpy as np
import pandas as pd
from utils import file_helper, pulse_helper
def _save_jitter_file(file_name, folder_name, data):
jitter_file_fmt = '%d', '%.7f', '%.7f', '%.7f', '%.7f', '%.7f', '%.7f', '%.7f'
np.savetxt(
f'{folder_name}... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.