text stringlengths 2 999k |
|---|
import json
from io import StringIO
class ListResponse(object):
def __init__(self):
self.swaggerTypes = {
'ResponseStatus': 'ResponseStatus',
'Response': 'ResourceList',
'Notifications': 'list<Str>'
}
def _convertToObjectList(self):
'''
Con... |
import pyaml, yaml
from .util import PY3
from textwrap import wrap
from pyaml import UnsafePrettyYAMLDumper
def represent_stringish(dumper, data):
data = unicode(data) # read the comment above
style = dumper.pyaml_string_val_style
if not style:
style = 'plain'
multiline = wrap(data, wi... |
from typing import List, Dict, Tuple, Union, Optional, Any, Callable
from unittest import TestCase
from rtc import staticclass
class TestStaticClass(TestCase):
def test_simple_ok(self):
@staticclass(strict=False)
class A:
a: int
b: float
self.assertTrue(bool(A()... |
##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
def encoded_from_base10(number, base, digit_map):
'''
This function returns a string encoding in the "base" for the the "number" using the "digit_map"
Conditions that this function must satisfy:
- 2 <= base <= 36 else raise ValueError
- invalid base ValueError must have relevant information
- di... |
import logging
logging.basicConfig(format=u'%(filename)s [LINE:%(lineno)d] #%(levelname)-8s [%(asctime)s] %(message)s',
level=logging.INFO,
# level=logging.DEBUG,
)
|
__author__ = "anwenhu"
__date__ = "2022/5/2 9:00"
__version__ = "1.1.4"
from zhixuewang.account import (login, login_id, rewrite_str, login_student, login_teacher,
login_student_id, login_teacher_id, load_account)
from zhixuewang.session import get_session, get_session_id
VERSION = t... |
def recommend_user(recommendations, user_id):
recommendations_user = recommendations[recommendations['user_id'] == user_id]
return recommendations_user
def get_popular_songs(processed_data, year):
processed_data_year = processed_data[processed_data['Release Year'] == year]
popular_songs_year = ... |
import fitz
import io
import matplotlib
import pandas as pd
from multiprocessing import cpu_count, Pool
from natsort import os_sorted
from parameters import BASELINE
from path import DATA, INDIVIDUALS, PRINTOUTS
from spectrogram.axes import SpectrogramAxes
from spectrogram.plot import (
create_luscinia_spectrogram... |
#!/usr/bin/env python
#
# Copyright (c) 2019, Colorado School of Mines
# All rights reserved.
#
# Author(s): Neil T. Dantam <ndantam@mines.edu>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistribu... |
import sys
from operator import getitem
from functools import reduce
# ABCs for containers were moved to their own module
try:
from collections.abc import Mapping, Set, Sequence
except ImportError:
from collections import Mapping, Set, Sequence
# Python 3 has no basestring, lets test it.
try:
basestring ... |
"""Mail forms"""
from django import forms
from mitol.mail.api import get_message_classes
def _get_message_class_choices():
"""Get message class choices"""
return [
(message_cls.template_name, message_cls.name)
for message_cls in get_message_classes()
]
class EmailDebuggerForm(forms.Form... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import json
import pprint
import requests
from argh.decorators import arg
import humanfriendly
from lain_cli.auth import SSOAccess, authorize_and_check, get_auth_header
from lain_cli.utils import (check_phase, get_apptype, get_domain, lain_yaml,
... |
import time
import numpy as np
import pytest
import nengo.utils.numpy as npext
from nengo.dists import (
PDF,
Choice,
CosineSimilarity,
DistOrArrayParam,
Exponential,
Gaussian,
QuasirandomSequence,
Samples,
ScatteredHypersphere,
SqrtBeta,
Uniform,
UniformHypersphere,
... |
#!/usr/bin/env python3
import argparse
import csv
import json
import gzip
from functools import partial
from pathlib import Path
from multiprocessing.pool import Pool
import traceback
from typing import List, Tuple, Set
import cv2
import numpy as np
import utils_rssrai
from train_rssrai import Model, HyperParams, Ima... |
import interactions
import src.const
class Message(interactions.Extension):
"""An extension dedicated to message context menus."""
def __init__(self, bot: interactions.Client):
self.bot = bot
self.targets: dict = {}
@interactions.extension_message_command(
name="Create help threa... |
# -*- coding: utf-8 -*-
import collections
import itertools
import json
import os
import posixpath
import re
import time
from datetime import datetime, timedelta
from django.conf import settings
from django.core.cache import cache
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db im... |
"""
Create a column to allow TokenOperation reference to UserPending entry.
Revision ID: 35e98bdc8aed
Revises: 00c617174e54
Create Date: 2021-04-27 18:58:34.606126
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "35e98bdc8aed"
down_revision = "00c617174e54"
bran... |
import datetime
from django.core.management import call_command
from dashboard.testing import BuilderTestCase
from apps.fruits.builder import direct_wholesale_06
from apps.dailytrans.models import DailyTran
from apps.fruits.models import Fruit
from apps.configs.models import Source
from django.db.models import Q
clas... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pickle
import tensorflow as tf
import pandas as pd
import numpy as np
import os
from tensorflow.python.framework import ops
from tensorflow.python.ops import gen_nn_ops
indices =[[0,0,7,22,189]]
mx =... |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Vendor: Huawei
# OS: UMG8900 media gateway
# ---------------------------------------------------------------------
# Copyright (C) 2007-2009 The NOC Project
# See LICENSE for details
# ---------------------------------... |
import sys
# to do list:
# what if multiple students have the same first or last name?
# add validations to inputs
# if first_name match: addGrade() loops through 4 times FIX
students_list = []
def enterStudent():
first_name = str(input("Enter the student's first name : "))
last_name = str(inp... |
import sys, asyncio, aiohttp, async_timeout, collections, csv
from lxml import html, etree
from tld import get_tld
from urllib.parse import urlparse
USER_AGENT = 'Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1'
'''
analizar doctype html5... |
##*****************************************************************************
## Copyright (c) 2014 IBM Corporation and other Contributors.
##
## All rights reserved. This program and the accompanying materials
## are made available under the terms of the Eclipse Public License v1.0
## which accompanies this distribu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""""""
import tkinter as tk
from tkinter import ttk
from tkinter.colorchooser import *
# link
__title__ = "ColourPickerButton"
__version__ = "1.3.5"
__author__ = "DeflatedPickle"
class ColourPickerButton(ttk.Button):
"""
-----DESCRIPTION-----
A TTK ... |
"""Preprocessor for merging consecutive stream outputs for easier handling."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import re
from IPython.utils.log import get_logger
def cell_preprocessor(function):
"""
Wrap a function to be executed on all cel... |
from __future__ import print_function, division
from typing import Optional, List
import numpy as np
import json
import random
import torch
import torch.utils.data
from . import VolumeDataset
from ..augmentation import Compose
from ..utils import crop_volume, relabel,seg_widen_border, tileToVolume
TARGET_OPT_TYPE =... |
import decimal
from waldur_core.logging.loggers import EventLogger, event_logger
class InvoiceLogger(EventLogger):
month = int
year = int
customer = 'structure.Customer'
class Meta:
event_types = (
'invoice_created',
'invoice_paid',
'invoice_canceled',
... |
from __future__ import print_function
from setuptools import setup
from setuptools.command.test import test as TestCommand
import io
import sys
import bitcoingraph
def read(*filenames, **kwargs):
encoding = kwargs.get('encoding', 'utf-8')
sep = kwargs.get('sep', '\n')
buf = []
for filename in filenam... |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Slemanium Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test node disconnect and ban behavior"""
import time
from test_framework.mininode import wait_until
... |
# coding: utf-8
from os import path
from setuptools import setup, find_packages
NAME = "huaweicloudsdkimagesearch"
VERSION = "3.0.67"
AUTHOR = "HuaweiCloud SDK"
AUTHOR_EMAIL = "hwcloudsdk@huawei.com"
URL = "https://github.com/huaweicloud/huaweicloud-sdk-python-v3"
DESCRIPTION = "ImageSearch"
this_directory = path.ab... |
#!/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.
from typing import Any, Dict, Tuple
import torch.optim
from . import ClassyOptimizer, register_optimizer
@register_... |
#!/usr/bin/python
"""
tracks_to_table.py
Author: Ilya Putilin
https://github.com/fantopop/post-production-scripts
Special thanks to Philippe Lagadec for HTML.py module for generating HTML tables.
http://www.decalage.info/python/html
This scripts converts .txt file, that could be exported from Pro Tools
using "Export... |
""" Pricing Controller Module """
__docformat__ = "numpy"
import argparse
from typing import List
import pandas as pd
from tabulate import tabulate
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal.rich_config import console
from gamestonk_terminal import feature_flags as gtff
from gameston... |
import datetime
from docxtpl import DocxTemplate
from docxtpl import InlineImage
from docxtpl import DocxTemplate, InlineImage
# source = []
with open('source.txt') as s:
source = s.read()
source = source.split('\n')
print(type(source),source)
def get_context(producer, model, fuel, price): # возвращает ... |
# -*- 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 task import *
from my_numpy import np, my_list
import copy
# push tests here
def get_standart_der(f1):
def der(u):
der = []
eps = 0.0000001
for i in range(0, len(u)):
u1 = copy.copy(u)
u1[i] = u1[i]+eps
der.append((f1(u1)-f1(u))/eps)
u1[i... |
import pickle
from functools import partial
import pandas as pd
import pytest
from pandas import testing as pdt
from kartothek.io.dask.dataframe import read_dataset_as_ddf
from kartothek.io.eager import store_dataframes_as_dataset
from kartothek.io.testing.read import * # noqa
from kartothek.io_components.metapartit... |
def add(x,y):
#add 2 numbers
return x + y
def subtract(x, y):
#subtract 2 numbers
return y - x
|
# based on code from https://stackabuse.com/minimax-and-alpha-beta-pruning-in-python
import time
import numpy as np
from contextlib import redirect_stdout
from random import randint
class Game:
MINIMAX = 0
ALPHABETA = 1
HUMAN = 2
AI = 3
def __init__(self, recommend=True):
n, s, t = self.ask_conditions()
sel... |
# -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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 os
from unittest import TestCase
from unittest.mock import patch, Mock
from shub_workflow.crawl import CrawlManager, PeriodicCrawlManager, GeneratorCrawlManager
from .utils.contexts import script_args
class TestManager(CrawlManager):
name = "test"
class PeriodicTestManager(PeriodicCrawlManager):
... |
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets 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 appl... |
# -*- coding: utf-8 -*-
"""
Utilities (taken from Spyder source code)
"""
import locale
import sys
PY2 = sys.version_info[0] == 2
PREFERRED_ENCODING = locale.getpreferredencoding()
#==============================================================================
# Python 3 compatibility functions
#===================... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from inspect import isfunction
from operator import mul
from functools import partial, reduce, wraps
from local_attention import LocalAttention
from axial_positional_embedding import AxialPositionalEmbedding
from product_key_memory import P... |
"""
Django settings for agenda project.
Generated by 'django-admin startproject' using Django 3.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# ... |
# Copyright (c) 2020 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 app... |
"""Internal utilities."""
import functools
import numbers
import numpy as np
import scipy.sparse
import torch
from pymde.average_distortion import _project_gradient
_DEVICE = torch.device("cpu")
class SolverError(Exception):
pass
def get_default_device():
return str(_DEVICE)
def _canonical_device(devi... |
#!/usr/bin/env python
import time
from pytest import fixture
from aci_tasks.cloud.aci_container import AciContainer
from aci_tasks.cloud.aci_container_group import AciContainerGroup
from aci_tasks.cloud.aci_resource_group import AciResourceGroup
from aci_tasks.logger import Logger
from aci_tasks.config import Co... |
from __future__ import absolute_import, division, print_function
import datetime
import pandas as pd
from pandas.core.window import Rolling as pd_Rolling
from numbers import Integral
from ..base import tokenize
from ..utils import M, funcname, derived_from
from ..highlevelgraph import HighLevelGraph
from .core impor... |
"""
The flask application package.
"""
from flask import Flask
from flask_jsonrpc import JSONRPC
app = Flask(__name__)
jsonrpc = JSONRPC(app, '/api',enable_web_browsable_api=True)
import ModStorage.views
import ModStorage.api
import ModStorage.ModVizX2Api |
import os
import re
from setuptools import find_packages
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
try:
# obtain version string from __init__.py
init_py = open(os.path.join(here, 'lasagne', '__init__.py')).read()
version = re.search('__version__ = "(.*)"', init_py).grou... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2015 Eugene Frolov <eugene@frolov.net.ru>
#
# 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
#
# ... |
"""ip URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based view... |
from django.db import models
from django.utils import timezone
class Node(models.Model):
node_id = models.CharField(max_length=42, unique=True)
wallet = models.CharField(max_length=42, null=True, blank=True)
earnings_total = models.FloatField(null=True, blank=True)
data = models.JSONField(null=True)
... |
try:
from django.urls import re_path
except ImportError:
from django.conf.urls import url as re_path
from . import views
app_name = "perimeter"
urlpatterns = [re_path(r"^gateway/", views.gateway, name="gateway")]
|
"""Company views."""
# Django REST Framework
from rest_framework import mixins, status, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
# Serializers
from paranuara.companies.serializers import CompanyModelSerializer
from paranuara.companies.serializers import Compan... |
import os
import logging
from datetime import datetime
#
# Setup of logging
#
# path for databases or config files
if not os.path.exists('Logs/'):
os.mkdir('Logs/')
# set logging format
formatter = logging.Formatter("[{asctime}] [{levelname}] [{name}] {message}", style="{")
# create log file
date = datetime.tod... |
import math
from random import random
from copy import deepcopy
import time_estimator
"""
Probably should make these more clear or move them.
"""
eps = .000001
dT = .00001
maxSteps = 15
def mag(x):
"""
Method that returns the magnitude of the vector x
Keyword arguments:
x -- The vector.
Return... |
# 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 may ... |
# 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 appli... |
import json
import yaml
import click
from clickclick import AliasedGroup, Action, ok
from zmon_cli.cmds.command import cli, get_client, yaml_output_option, output_option, pretty_json
from zmon_cli.output import dump_yaml, Output, render_alerts
from zmon_cli.client import ZmonArgumentError
@cli.group('alert-defini... |
_base_ = '../_base_/default_runtime.py'
# model settings
model = dict(
type='RetinaNet',
pretrained='open-mmlab://detectron2/resnet101_caffe',
backbone=dict(
type='ResNet',
depth=101,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_c... |
# 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\routing\portals\portal_data_ocean_ladders.py
# Compiled at: 2020-02-11 20:30:00
# Size of source mod... |
import unittest
import mock
from pygresql import pgdb
from gppylib import gparray
from .gp_unittest import GpTestCase
from gppylib.programs.clsSystemState import *
from gppylib.commands.unix import CommandNotFoundException
#
# Creation helpers for gparray.Segment.
#
def create_segment(**kwargs):
"""
Takes t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# pyhydro documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47:02 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# aut... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# See the full API here:
# https://poloniex.com/support/api/
__author__ = 'maxim'
from six import string_types
import pandas as pd
from util import *
AVAILABLE_PERIODS = [300, 900, 1800, 7200, 14400, 86400]
def get_chart_data(pair, start_time, end_time, period):
... |
#!/usr/bin/env python3
# basic function
def write_message(message):
''' This prints out a simple message within the console window '''
print(message)
write_message('Hello Python!')
|
from telethon import TelegramClient, events, functions
import argparse
# ARGUMENTS
parser = argparse.ArgumentParser(description='Infinity online for Telegram')
parser.add_argument('--appID', type=str,
help='App api_id from your application')
parser.add_argument('--appHASH', type=str,
... |
#/*=============================================================================
#Copyright (c) 2016 Paul W. Bible
#
#Distributed under the Boost Software License, Version 1.0. (See accompanying
#file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#=====================================================... |
import pytest
from transaction.models import TransactionType
class TestTransactionType:
'''The TransactionType model test class.
'''
@pytest.mark.django_db(transaction=True)
@pytest.mark.parametrize(
'type', [
(TransactionType.Type.INCOME, ),
(TransactionType.Type.OUTC... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import getdate, nowdate
no_cache = 1
no_sitemap = 1
def get_context(context):
result = []
for acc in frappe.db.sql("select... |
import os
import numpy as np
import torch
import torch.utils.data as data
import torch.nn.functional as F
from PIL import Image
import matplotlib.pyplot as plt
from lib.datasets.utils import angle2class
from lib.datasets.utils import gaussian_radius
from lib.datasets.utils import draw_umich_gaussian
from lib.datasets.... |
#!/usr/bin/env python
import asyncio
import sys
import stream
async def process_in_term():
process = await asyncio.create_subprocess_exec(*["xterm", "-e", "./example.sh"])
print("Create called")
return await process.wait()
async def interact():
read = await stream.ainput(prompt="Koi", loop=loop),
... |
from collections import defaultdict
from time import ctime
from datetime import datetime
from typing import Any, Dict, List, Tuple, Union, Optional
import emoji
import urwid
from urwid_readline import ReadlineEdit
from bs4 import BeautifulSoup
from bs4.element import NavigableString, Tag
from zulipterminal.config.key... |
#!/usr/bin/python3
import unittest
from base import TestBase
# TODO: tests for invalid amount
# TODO: tests for model edit permission
class OfferTest(TestBase):
def createOffer(self, ownerId, item, amount, price, targetId=None):
params = {
"ownerId" : ownerId,
"item" :... |
## @file
# This file is used to define common static strings used by INF/DEC/DSC files
#
# Copyright (c) 2007 - 2016, 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 th... |
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
RANGE SLIDER
Slider bar between one/two numeric ranges.
License:
-------------------------------------------------------------------------------
The MIT License (MIT)
Copyright 2017-2021 Pablo Pizarro R. @ppizarror
Permission is hereby granted, free of charge,... |
"""
1556. Thousand Separator
Given an integer n, add a dot (".") as the thousands separator and return it in string format.
Example 1:
Input: n = 987
Output: "987"
Example 2:
Input: n = 1234
Output: "1.234"
Example 3:
Input: n = 123456789
Output: "123.456.789"
Example 4:
Input: n = 0
Output: "0"
Constraints:
0 <... |
from unittest.mock import patch, MagicMock
import pytest
from requests import HTTPError, Response
from operatorcert import iib
def test_get_session() -> None:
session = iib.get_session()
assert isinstance(session.auth, iib.HTTPKerberosAuth)
@patch("operatorcert.iib.get_session")
def test_add_builds(mock_s... |
from typing import List, Optional, Tuple, Union, NamedTuple, Callable, Any
import torch
import collections.abc
from torch.utils.data import Dataset, DataLoader
class MetadataCropperDataset(NamedTuple):
f_name: Union[str, int]
loc_x: Union[int, float]
loc_y: Union[int, float]
moran: Union[float, None]
... |
import tables
from phd.satellite.single_processing import convert_data_to_mean_points, save_interpolators
def main():
path = "proton.hdf5"
with tables.open_file(path) as h5file:
data = h5file.get_node("/", "deposit").read()
mean_items, points = convert_data_to_mean_points(data)
file = "proton... |
import service
from service import ccnet_rpc, monitor_rpc, seafserv_rpc, \
seafserv_threaded_rpc, ccnet_threaded_rpc
from service import send_command, check_quota, web_get_access_token, \
unset_repo_passwd, get_user_quota_usage, get_user_share_usage, \
get_user_quota
from service import get_emailusers, cou... |
class BaseHelper:
def __init__(self, device):
self.device = device
def params(self, locals_: dict):
params = locals_.copy()
params.pop('self')
return params
|
# Note: File is called ptext because
# https://github.com/pyinstaller/pyinstaller/issues/4626
from PyInstaller.compat import is_win
from PyInstaller.utils.hooks import collect_dynamic_libs
if is_win:
skip_libs = (
"libffi-7.dll",
"libcrypto-1_1.dll"
"libssl-1_1.dll",
"libjpeg-9.dll... |
import vcs,numpy
assert numpy.allclose(vcs.mkscale(0,1.e35,16) , [0.0, 9.9999999999999995e+33, 1.9999999999999999e+34, 2.9999999999999997e+34, 3.9999999999999998e+34, 4.9999999999999998e+34, 5.9999999999999994e+34, 7e+34, 7.9999999999999996e+34, 9.0000000000000001e+34, 9.9999999999999997e+34])
|
import numpy as np
import math
import logging as log
import sys
from tqdm import tqdm
from scipy.spatial.distance import cosine
from common.feature_distance import calc_features_similarity
from common.common_objects import DetectedObject, validate_detected_object, Bbox
from common.common_objects import get_bbox_center,... |
import itertools
from torchaudio.backend import sox_io_backend
from parameterized import parameterized
from torchaudio_unittest.common_utils import (
TempDirMixin,
PytorchTestCase,
skipIfNoExec,
skipIfNoExtension,
get_wav_data,
load_wav,
save_wav,
sox_utils,
)
from .common import (
... |
#! /usr/bin/env python3
import sys
import datetime
import pytz
import socket
import openpyxl
from influxdb_client import InfluxDBClient, Point, WriteOptions
from influxdb_client.client.write_api import SYNCHRONOUS
def parse_and_import_file(config):
workbook = openpyxl.load_workbook(config['data_file'])
work... |
# This is a Python framework to compliment "Peek-a-Boo, I Still See You: Why Efficient Traffic Analysis Countermeasures Fail".
# Copyright (C) 2012 Kevin P. Dyer (kpdyer.com)
# See LICENSE for more details.
import arffWriter
import wekaAPI
from glove import Glove
import numpy as np
class GloveClassifier:
@stati... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/20_why_hat.ipynb (unless otherwise specified).
__all__ = ['md5hash', 'ModelInput', 'InputEmb', 'InputOneHot', 'InputConti', 'YEncoder', 'YOneHot', 'YConti',
'RichColumn', 'RichDF', 'TabularModel', 'TabularNN']
# Cell
import pandas as pd
import numpy as np
fro... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from common import sort_items
if len(sys.argv) < 2:
print("Sort the dictionary")
print(("Usage: ", sys.argv[0], "[input] ([output])"))
exit(1)
input = sys.argv[1]
if len(sys.argv) < 3:
output = input
else:
output = sys.argv[2]
sort_items(... |
import copy
import os
import sys
import argparse
import traceback
import gc
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-i", "--ip", help="Set IP address for sending tracking data", default="127.0.0.1")
parser.add_argument("-p", "--port", type=int, help... |
# shortest path for graphs with negative cycles
from collections import OrderedDict
from spvertex import SPVertex
def shortestpath(G, W, s):
"""shortest path from start vertex s to all reachable vertices or False if found neg cycle"""
# initialize
for v in G.keys():
v.reset()
s.dist = 0
# ... |
def PageUse():
msg.showinfo("사용방법", "띄워진 창 안에서\n노트를 작성하세요 ✍️")
def PageLicens():
msg.showinfo("라이센스", "MIT License\n\nⓒ 2021 차한음 😎")
def PageVersion():
msg.showinfo("버전", "현재 버전 v2.1.1 ✋")
def MenuHelp(root):
menu = Menu(root)
help = Menu(menu, tearoff=0)
help.add_command(label="사용방법", command=... |
import _plotly_utils.basevalidators
class ThetasrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(self, plotly_name="thetasrc", parent_name="scatterpolargl", **kwargs):
super(ThetasrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
import config
import sys, os
from resnet_heterofl import resnet18
from customized_fllibs import split_model
sys.path.insert(1, os.path.join(sys.path[0], '../../fedscale/core'))
from client import Client
from fllibs import Variable, os, math, torch, logging, np
class Customized_Client(Client):
def __init__(self, c... |
#!/usr/bin/env python
import sys
import numpy as np
import pychemia
from pychemia.visual.searcher import *
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
from pychemia.crystal import CrystalSymmetry
import matplotlib.lines as mlines
import matplotlib.patches as mpatches
from matpl... |
from __future__ import annotations
from typing import TYPE_CHECKING
from openhab_creator import _
from openhab_creator.models.common import MapTransformation
from openhab_creator.models.configuration.equipment.types.gasstation import (
FuelType, GasStation)
from openhab_creator.models.items import (Contact, Group... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.