content stringlengths 5 1.05M |
|---|
from . import credentials
# set the creds dir to HOME
import os
from . import credentials_manager
from .charts import (
youtube,
applemusic,
spotify,
shazam,
soundcloud,
beatport,
itunes,
youtube,
deezer,
cm_score,
amazon,
qq,
)
from . import track
from . import albu... |
from .base import pyjs_bridge, VueDecorator
def map_hook(hook_name):
if hook_name == "component_updated":
return "componentUpdated"
return hook_name
class DirectiveHook(VueDecorator):
def __init__(self, fn, hooks=(), name=None):
name = name if name else fn.__name__
self.__key__ =... |
#!/usr/bin/env python
import os
import sys
import glob
import lxml.etree
import Bcfg2.Options
def main():
opts = dict(repo=Bcfg2.Options.SERVER_REPOSITORY)
setup = Bcfg2.Options.OptionParser(opts)
setup.parse(sys.argv[1:])
files = []
for plugin in ['Bundler', 'Rules', 'Default']:
files.ex... |
"""
This module implements the LRP epsilon-rule for a linear layer, skipping
the activation function.
"""
import numpy as np
def lrp_linear(x: np.ndarray, y: np.ndarray, rel_y: np.ndarray,
w: np.ndarray = None, eps: float = 0.001) -> np.ndarray:
"""
Implements the LRP-epsilon rule for a linear ... |
import os
import sys
import numpy as np
import torch
import torch.nn as nn
from skimage import io
from skimage.transform import resize
sys.path.append('../')
from util.file_utils import mkdirs_if_not_exist
from config.cfg import cfg
from models.vgg import MMNet
def ext_feat(eval_model, img_path):
"""
extrac... |
from django.urls import path
from . import views
urlpatterns = [
path('tour/<int:tour_id>', views.show_tour),
path('tour/registered/<int:tour_id>', views.tours_registered),
path('tour/registered', views.All_Tours_Registered.as_view()),
path('tour/', views.All_Tours.as_view()),
path('reservation_cre... |
#!/usr/bin/env python3
## PYTHON VERSION MUST BE 3.7 OR HIGHER
import json, argparse, inspect, sys, os, io, base64, aiohttp, urllib, asyncio, aiofiles, aioconsole
import logging, re, concurrent.futures, configparser, motor.motor_asyncio, ssl, zipfile
import blitzutils as bu
from blitzutils import WG
from blitzutils im... |
from django.test import TestCase, Client
from django.urls import reverse
from django.contrib.auth.models import User
from users.models import Profile
class TestViews(TestCase):
def setUp(self):
self.client = Client()
self.register_url = reverse('register')
self.profile_url = reverse('profile')
self.client.fo... |
# Copyright 2021 Universität Tübingen, DKFZ and EMBL for the German Human Genome-Phenome Archive (GHGA)
#
# 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... |
"""Decorator class defined for class init."""
class Decoratorfunc(object):
"""Give decorator function precedence.
Allow decorator function to be the first argument to
class constructor, this argument will be passed to the
__call__() method implicitly.
https://docs.python.org/3/reference/datamode... |
"""
AWS and AWS S3 Helper functions.
"""
import boto3
import botocore.exceptions
import json
import logging
import traceback
class aws_helper(object):
"""
Helper class for connecting to AWS.
"""
def __init__(self, aws_profile=None, logger=False):
"""
Initialization function of the aw... |
import abc
from typing import List
from orders.domain.entities.offer_entity import OfferEntity
class OfferRepository(metaclass=abc.ABCMeta):
@abc.abstractmethod
def get_all(self) -> List[OfferEntity]:
raise NotImplementedError
|
from umongo import Document, validate
from umongo.fields import StringField, ListField, ReferenceField
from app import app
from app.permissions.documents import Permission
instance = app.config["LAZY_UMONGO"]
@instance.register
class Microservice(Document):
name = StringField(unique=True, allow_none=False, req... |
from Stack import Stack
# from pythonds.basic.stack import Stack
def divideBy2(num):
remstack = Stack()
while num > 0:
rem = num % 2
remstack.push(rem)
num = num // 2
# binString = ''
# while not remstack.isEmpty():
# binString = binString + str(remstack.pop())
#... |
# HAML_GUI
# stuff for matlib plot
from matplotlib.ticker import NullFormatter # useful for `logit` scale
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.pyplot import figure
import PySimpleGUI... |
import numpy as np
import argparse
import binvox_rw
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Write an example BINVOX file.')
parser.add_argument('output', type=str, help='BINVOX file.')
args = parser.parse_args()
volume = np.zeros((32, 32, 32))
volume[10:22, 10:22,... |
import socket
import sys
import time
import threading
x = socket.socket()
h_name= socket.gethostname()
print("server will start on host: ", h_name)
port= 1234
x.bind((h_name, port))
print( "server done binding to host and port successfully")
print("server is waiting for incoming connections")
x.listen()
connection,ad... |
"""Utilities for I/O and buffering.
Author: Seth Axen
E-mail: seth.axen@gmail.com
"""
import os
import gzip
import bz2
import logging
HDF5_BUFFER_SIZE = 100
class HDF5Buffer(object):
"""Buffer for periodically writing to HDF5 file.
A kill signal can result in an unclosed and therefore unusable
HDF5 fi... |
""" Contains Scene object for representing a .msh file and the function to create one
from a Blender scene. """
from dataclasses import dataclass, field
from typing import List, Dict
from copy import copy
import bpy
from mathutils import Vector
from .msh_model import Model, Animation, ModelType
from .msh_scene im... |
#!/usr/bin/env python3
import os
import re
import json
import time
import socket
import argparse
import statistics
import subprocess
import collections
import multiprocessing
# Make CUDA_VISIBLE_DEVICES order match to nvidia-smi
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = ""
#... |
'''
Copyright 2022 Airbus SAS
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
dis... |
# count occurence of characters in string
import sys
string = sys.argv[1]
charCounts = {}
for ch in string:
if ch in charCounts:
charCounts[ch] += 1
else:
charCounts[ch] = 1
for key, val in charCounts.iteritems():
print key + ':' + str(val)
|
#q2test.py
"""test function for question 2 of the ADS assignment, 2018-19"""
def q2test():
"""tests for the function count_ephemeral"""
correct = True
result = count_ephemeral(1, 10, 2)
if result != 2:
correct = False
print("test failed for n1=1, n2=10, k=2; correct result is 2... |
number1 = 10
number2 = 20
numbers = [[2,3],2,3,4]
def changeNumber(number1, number2):
number1 = 30
number2 = 40
print('in function changeNumber, number1 = ',number1,'number2= ',number2)
def changeNumbers(numbers):
numbers[1] = 222
changeNumber(number1,number2)
print('Outside function changeNumbe... |
"""
# Text-Fabric kernel
Text-Fabric can be used as a service.
The full API of Text-Fabric needs a lot of memory, which makes it unusably for
rapid successions of loading and unloading, like when used in a web server context.
However, you can start TF as a service process,
after which many clients can connect to it,
... |
"""Tests for security module."""
from azure.kusto.data.exceptions import KustoAuthenticationError
from azure.kusto.data.request import KustoConnectionStringBuilder
from azure.kusto.data.security import _AadHelper, AuthenticationMethod
def test_unauthorized_exception():
"""Test the exception thrown when authoriza... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=locally-disabled, invalid-name, wrong-import-position
"""
gfm-cmark-py - A Python wrapper for GitHub's fork of 'cmark', supporting GFM) extensions.
This setuptools script follows the DRY principle and tries to
minimize repetition of project m... |
import xml.etree.ElementTree as ET
parsers = {}
def getParser(langPath):
global parsers
if langPath not in parsers:
parsers[langPath] = Parser(langPath)
return parsers[langPath]
class Parser:
def __init__(self, langPath):
#Initialize variables
self.syllables = set()
sel... |
class label:
def __init__(self, name = "[LABEL]",
shift = 0, mask = 0xFFFFFFFF, comment = "", annotation = "", *args, **kwargs):
self.name = name
self.shift = shift
self.mask = mask
self.comment = comment
self.annotation = annotation
class labelbits... |
# Create a user for Airflow
from airflow import models, settings
from airflow.contrib.auth.backends.password_auth import PasswordUser
# Get configuration from the environment.env file
import os
from os.path import join, dirname
from dotenv import load_dotenv
dotenv_path = join(dirname(__file__), '../environment.env')... |
from aiogram import types
from keyboards.inline import back_callback, blank_callback
from middlewares import _
from models.event import Day
days = {
'monday': _('Понедельник'),
'tuesday': _('Вторник'),
'wednesday': _('Среда'),
'thursday': _('Четверг'),
'friday': _('Пятница'),
'saturd... |
import random
from operator_api.simulation.swap import send_swap, freeze_last_swap, finalize_last_swap, cancel_last_swap, finalize_swap
from ledger.models import Transfer
from swapper.tasks.cancel_finalize_swaps import cancel_finalize_swaps_for_eon
from swapper.tasks.confirm_swaps import confirm_swaps_for_eon
from swa... |
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
from spikewidgets.widgets.basewidget import BaseWidget
def plot_multicomp_graph(multi_sorting_comparison, sorter_names=None, draw_labels=False, node_cmap='viridis',
edge_cmap='hot_r', alpha_edges=0.7, colorbar=False, fi... |
import librosa
import panns_inference
from panns_inference import AudioTagging, SoundEventDetection, labels
import os
import numpy as np
# Use panns_inference model to generate feature vector of audio
def get_audio_embedding(path):
try:
audio, _ = librosa.core.load(path, sr=32000, mono=True)
audio ... |
import pandas as pd
from pandas.io.json import json_normalize
import json
from SPARQLWrapper import SPARQLWrapper , JSON
def getLabels(qid):
query = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX wd: <http://www.wikidata.org/entity/> SELECT ?label WHERE { wd:"+qid+" rdfs:label ?label . FILTER (langMat... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 14 22:15:01 2021
@author: mi19356
"""
from PyLengMorph.fileconstruct import grainboundary |
import datetime
import logging
from functools import reduce
from flask_babel import lazy_gettext
from .filters import Filters
try:
import enum
_has_enum = True
except ImportError:
_has_enum = False
log = logging.getLogger(__name__)
class BaseInterface(object):
"""
Base class for all data mod... |
import requests
import json
from ros.config import INVENTORY_ADDRESS
def fetch_host_from_inventory(insights_id, rh_identity):
host_api_url = f"{INVENTORY_ADDRESS}/api/inventory/v1/hosts?insights_id={insights_id}"
headers = {'x-rh-identity': rh_identity, 'Content-Type': 'application/json'}
res = requests.g... |
# encoding: utf-8
"""The IPython Core Notification Center.
See docs/source/development/notification_blueprint.txt for an overview of the
notification module.
"""
__docformat__ = "restructuredtext en"
#-------------------------------------... |
#!/usr/bin/env python3
"""
Plot the velocity law for a Schlosman and Vitello wind for a CV disk wind.
"""
import alpha_disc_spectrum
import numpy as np
from constants import *
from scipy.optimize import brentq
from matplotlib import pyplot as plt
verbose = False
class SV93wind:
"""
Create a SV93 style win... |
# fireworks
from random import uniform, gauss
import pyglet
from lepton import (
Particle, ParticleGroup, default_system, domain, ParticleSystem,
)
from lepton.domain import Cylinder
from lepton.renderer import BillboardRenderer
from lepton.texturizer import SpriteTexturizer
from lepton.emitter import StaticEmitter... |
#
# Copyright (C) 2010-2017 Samuel Abels
# The MIT License (MIT)
#
# 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,... |
from compas.geometry import Point, Line, Polyline
from compas_occ.geometry import OCCNurbsCurve as NurbsCurve
from compas_view2.app import App
from compas_view2.objects import Collection
line = Line(Point(0, 0, 0), Point(3, 3, 0))
curve = NurbsCurve.from_line(line)
print(curve)
# ===================================... |
import configparser
from fastapi import FastAPI
from os.path import abspath, dirname, join
config_file = join(abspath(dirname(__file__)), '../config.ini')
config = configparser.ConfigParser()
config.read(config_file)
app = FastAPI(
root_path='/api/v1'
)
try:
from src.modules.logging import Logging
logg... |
import numpy as np
import torch
import os
import pickle
from numba import jit
import torch.nn as nn
from .ucb import UCB
from .utils import Model
@jit(nopython=True)
def calc_confidence_multiplier(confidence_scaling_factor, approximator_dim, iteration, bound_features,
reg_factor, delta):... |
from plenum.common.messages.node_messages import ViewChangeDone
def test_future_vcdone_when_propagate_primary_no_quorum(fake_node):
"""
Check, that view_change would not be started without quorum of future_view_change_done messages
if propagate_primary is True
"""
frm = 'Node3'
current_view = ... |
import inspect
import os
from unittest import TestCase
import pytest
from osbot_k8s.utils.Docker_Desktop_Cluster import DEFAULT_DOCKER_DESKTOP_NAME
from osbot_utils.utils.Misc import obj_dict, list_set, obj_list_set, class_functions, class_functions_names, \
list_index_by, list_group_by, obj_data, list_get_field
... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyFunctools32(PythonPackage):
"""Backport of the functools module from Python 3.2.3 for us... |
from unittest import TestCase
from word_break import Solution
class TestWordBreak(TestCase):
def test_separation(self):
self.assertTrue(Solution().wordBreak("leetcode", ["leet", "code"]))
def test_reusing_dictionary_word(self):
self.assertTrue(Solution().wordBreak("applepenapple", ["apple", ... |
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
import Model as M
import numpy as np
from torch.nn.parameter import Parameter
from torch.nn.parallel import replicate, scatter, parallel_apply, gather
import concurrent.futures
class MarginalCosineLayer(M.Model):
def ... |
import numpy as np
import pandas as pd
import seaborn as sns
from pandas import read_csv
import json
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
from transform import Transform
from w2v import W2V
import nltk
# nltk.download('stopwords') # Uncomment to download sto... |
# Time convolutional neural network, adapted from the implementation from Fawaz et. al
# https://github.com/hfawaz/dl-4-tsc/blob/master/classifiers/cnn.py
#
# Network originally proposed by:
#
# @article{zhao2017convolutional,
# title={Convolutional neural networks for time series classification},
# author={Zhao, B... |
import matplotlib
import matplotlib.pylab as plt
import data_utils
from numpy.core.defchararray import asarray
import librosa
import IPython.display as ipd
import os
import sys
import numpy as np
import torch
import IPython
from hparams import create_hparams
from model import Tacotron2
from layers import TacotronSTFT,... |
# coding: utf-8
from sqlalchemy import Column, Date, DateTime, Integer, Numeric
from sqlalchemy.schema import FetchedValue
from application import db
class StatDailySite(db.Model):
__tablename__ = 'stat_daily_site'
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.Date, nullable=False, ind... |
"""Literature Gene Cell Type Score"""
import numpy as np
import pandas as pd
from larval_gonad.validation import GeneValidator
def main():
fbgn2symbol = (
pd.read_feather(snakemake.input["gene_annot"], columns=["FBgn", "gene_symbol"])
.set_index("FBgn")
.squeeze()
)
lit_genes = ge... |
################################################################################
##
## This library is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public
## License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your op... |
# encoding: utf-8
"""
open booking connect
Copyright (c) 2021, binary butterfly GmbH
Use of this source code is governed by an MIT-style license that can be found in the LICENSE file.
"""
from tortoise.models import Model
from tortoise import fields
from ..common.enums import Connection
from .base import B... |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
from enum import Enum
class FormRecognizerApiVersion(str, Enum):
"""Form Recognizer API versions supported by this package"""
#: This is the default version
... |
from .normalizer import AbstractTextNormalizer, TextNormalizer
from .sentence import AbstractSentenceSegmenter, SentenceSegmenter
__name__ = 'naive_text'
__version__ = '0.0.1'
|
import unittest
import os
from atlascli.atlaskey import AtlasKey, AtlasEnv
from atlascli.errors import AtlasEnvironmentError
class TestAtlasKey(unittest.TestCase):
def setUp(self):
self._public = os.environ[AtlasEnv.ATLAS_PUBLIC_KEY.value]
self._private = os.environ[AtlasEnv.ATLAS_PRIVATE_KEY.va... |
"""
Problem link:
Solution By Keshav Mishra
"""
from sys import stdin,stdout
from collections import Counter , deque
from queue import PriorityQueue
import math
helperConstants = True
helperUtilityFunctions = True
def input(): return stdin.readline().strip()
# def print(s): stdout.write(str(s)+'\n')
if helperCon... |
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file acc... |
import os,sys
import torch.utils
import torch
from torch.utils.data.dataloader import DataLoader
from PIL import Image
import numpy as np
class MydataSet(torch.utils.data.Dataset):
def __init__(self,layout, imgpath, transform=None, target_transform=None):
imgs = []
for line in open(layout... |
#!/usr/bin/env python
# This script comes with no warranty use at your own risk
#
# Title: pause_snapshot
# Author: Drew Russell - Rubrik Ranger Team
# Date: 03/29/2018
# Python ver: 3.6.4
#
# Description:
#
# Pause and Resume a policy driven snapshot of a Virtual Machine
##################################... |
# -*- coding: utf-8 -*-
__author__ = 'Adward'
# Python utils imports
import os
import sys
from time import time
import sqlite3
# Standard scientific Python imports
import matplotlib.pyplot as plt
import numpy as np
# Import classifiers and performance metrics
from sklearn.preprocessing import *
from sklearn.metrics.... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from MessageFunction import MessageFunction
from UpdateFunction import UpdateFunction
from ReadoutFunction import ReadoutFunction
import torch
import torch.nn as nn
from torch.autograd import Variable
__author__ = "Pau Riba, Anjan Dutta"
__email__ = "priba@cvc.uab.cat, adutt... |
import pandas as pd
import icd as icd
#from icd import long_to_short_transformation
#from icd import icd_to_comorbidities
# Sample Test passing with nose and pytest
def test_long_to_short_transformation():
d_data = {"id":[1,1,1,2,2,3],"idx_roll":["A","B","C","A","B","A"],"dx_1":["F11","E40","","F32","C77","G10"],"d... |
"""
MIT License
Copyright (c) 2021 TDYQ-Liu
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, publish, dist... |
# -*- coding:utf-8 -*-
# @Time : 2021/6/4 10:43
# @Author : Leo Li
# @Email : 846016122@qq.com
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import time
import math
import cv2
from PIL import Image as IMG
from tqdm import... |
##########################################################################################################
# Argparser#############################################################
import argparse
parser = argparse.ArgumentParser(description='Simple AI APP')
"""
parser.add_argument('-learning_rate','--learning', actio... |
from flask import Flask
app = Flask(__name__)
with app.app_context():
from letterjam import letterjam as letterjam_blueprint
app.register_blueprint(letterjam_blueprint, url_prefix='/api')
|
from _ast import AST
# We recycle the Python AST mostly as a convienance so that we can
# exploit the machinery that exists in the standard library.
class Module(AST):
_fields = ['body']
def __repr__(self):
return "Module(%s)" % (repr(self.body),)
class Const(AST):
_fields = ['value']
def _... |
from flasgger import swag_from
from flask.json import jsonify
from flask_restful import Resource
from flask_restful.reqparse import Argument
from repositories import RechercheRepository
from util import parse_params
class RechercheResource(Resource):
""" Verbs relative to the notes """
@staticmethod
@... |
#import numpy as np
from matplotlib import pyplot
#from matplotlib import transforms
def setup_figure_pars():
# update plotting parameters from a dictionary
fig_width = 8 # width in inches
fig_height = 6 # height in inches
fig_size = [fig_width, fig_height]
params = {'axes.labelsize': 18, #un... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ray import Language
from ray.util.annotations import PublicAPI
from ray._raylet import JavaFunctionDescriptor
from ray._raylet import CppFunctionDescriptor
__all__ = [
"java_function",
"java_actor... |
#!/usr/bin/env python
import os
import time
from PIL import Image
from ConfigParser import NoOptionError
import s3
import server
import settings
import db
import logger
l = logger.setup('hook')
cfg = settings.config()
sender = 0
def generate_key(fileName):
"""
Generate a unique filename based on the current ... |
import numpy as np
from bench_press.run.actions.action import *
from bench_press.run.policy.nn_policy import NNPolicy
class NNOnestepInsertPolicy(NNPolicy):
PRESS_DIST = 1150
UP_DIST = 250
SCRIPT = [
None,
DeltaAction((0, 0, PRESS_DIST)),
None,
DynamixelAngleAction(-49.5),... |
#!/usr/bin/env python3
# Copyright 2018 Mycroft AI 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... |
# -*- coding: utf-8 -*-
"""DogsVsCatsClassifierUsingTransferLearning.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1e4rRisTKwJuUxFHit57_iRf1puuIo66p
"""
import tensorflow as tf
tf.test.gpu_device_name()
# Load the Drive helper and mount
from g... |
import traceback
from functools import partial
import logging
import telegram
from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove
from telegram.ext import CommandHandler, Updater, ConversationHandler, Filters, MessageHandler, RegexHandler
from . import models
from .models import Channel, DisabledChannel
lo... |
"""Functions for clustering sequences before input.
This includes computing a distance matrix using MinHash, and
clustering that matrix.
"""
from collections import defaultdict
from collections import OrderedDict
import logging
import operator
import numpy as np
from scipy.cluster import hierarchy
from adapt.utils ... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.test import TestCase
from ..models import DatabaseResize
from .factory import DatabaseResizeFactory
class DatabaseResizeTestCase(TestCase):
def setUp(self):
self.database_resize = DatabaseResizeFactory()
def... |
#!/usr/bin/env python3
# std
import unittest
# ours
import clusterking.util.metadata as metadata
class TestNestedDict(unittest.TestCase):
def test_nested_dict(self):
nd = metadata.nested_dict()
nd[1][2][3] = None
self.assertEqual(nd, {1: {2: {3: None}}})
def test_turn_into_nested_di... |
from commands.base import ArxCommand
class CmdApplyConsumable(ArxCommand):
"""
Uses/applies a consumable object
Usage:
use <object> on <target>
Use a consumable object on a target. Different
consumable objects have requirements on what they
can be used on. For example, 'incen... |
"""Entrypoint module, in case you use `python -mmopidy_rpi_remote`."""
from mopidy_rpi_remote.cli import main
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
from __future__ import print_function, division
import itertools
import numpy as np
def cross_validate(cv_data, data_splitter, estimator, estimator_params,
lamdas_list, error_fn, error_fn_params, verbose=True,
save_x_hats=False):
"""
Compute e(lam... |
# -*- coding: utf-8 -*-
# @version : Python3.6
# @Time : 2017/4/21 11:40
# @Author : Jianyang-Hu
# @contact : jianyang1993@163.com
# @File : mularange_0421.py
# @Software: PyCharm
import numpy
from numpy import *
a = arange(9).reshape(3,3)
print(a)
#水平分割
print(hsplit(a,3))
print(split(a,3,axis=1))
#垂直分割
pri... |
from rest_framework import serializers
from core.models import User, Profile, FriendRequest, Message
from django.db.models import Q
class FriendFilter(serializers.PrimaryKeyRelatedField):
"""filter for receiver"""
def get_queryset(self):
request = self.context['request']
friends = FriendReques... |
# (C) 2021 Jayant Kageri
from pyrogram import idle, Client, filters
from _pyrogram import app, LOGGER
from _pyrogram.modules import *
import os
print("Pyrogram User Client Started \nPowered By @MwK\n(C) 2021 Shamil Habeeb Nelli")
app.run()
|
import npm
import npm plus
import git
_com_.text.command.npmplus('_com_.py);
args.command.npmplus('npm plus');
from npm plus
onload_commands();
class get.package.npmplus('commands.cpp');
def _com_(self, commandsfile=npm plus);
self.commands= npm plus
|
from bs4 import BeautifulSoup
class User:
def __init__(self, user=None, full_name="", location="", blog="", date_joined=None, id=None, tweets=0,
following=0, followers=0, likes=0, lists=0):
self.user = user
self.full_name = full_name
self.location = location
self.blog = bl... |
import base64
import random
from Crypto.Cipher import AES
from hashlib import sha256
class AESCipher(object):
def __init__(self, key, block_size=32):
self.bs = block_size
if len(key) >= len(str(block_size)):
self.key = key[:block_size]
else:
self.key = self._pad(key)... |
import time
import mss
import numpy as np
import cv2
import math
import keyboard
# Map Size 1.1
# Map Zoom 0.9
def raycast(img, point_a, point_b):
# assume black is void/ boundary
if point_b[0] - point_a[0] == 0:
b_slope = 0.00000001
else:
b_slope = (point_b[0] - point_a[0... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import pandas as pd
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--format', default='forex', choices=['forex', 'stock'], help="c... |
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from __future__ import print_function
import random
import unittest
import numpy as np
from noisemaker import *
class TestNoise(unittest.TestCase):
def test_regular_movement(self):
ax = random.randint(-100, 100)
ay = random.randint(-100, 100)
j = noise((1, 100), (ax, ay))
k = ... |
import os
from platon_env.chain import Chain
from utils.path import join_path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
chain_file = join_path(BASE_DIR, 'file/chain_file.yml')
genesis_file = join_path(BASE_DIR, 'file/genesis.json')
platon = join_path(BASE_DIR, 'file/platon')
def test_chain_factory():
... |
l = [10, 20, 30 ,40, 50, 60]
print(l[:2])
print(l[2:])
# s[a:b:c],对s在a和b之前以c为间隔取值
str = 'bicycle'
print(str[::3])
print(str[::-1])
print(str[::-2])
# 切片操作
l2 = list(range(10))
print(l2)
l2[2:5] = [20, 30]
print(l2)
del l2[5:7]
print(l2)
l2[3::2] = [11, 22]
print(l2)
l2[2:5] = [100]
print(l2)
# 复制序列
l3 = [1, 2, 3]
pr... |
import os.path
import pandas as pd
from evaluation_metrics import pairwise_accuracy
try:
import cPickle as pickle
except Exception as e:
import pickle
from helper_funs import format_creationDate
def timestaps(creationDate1,creationDate2):
y1,mo1,d1,h1,mi1 = format_creationDate(creationDate1)
y2,mo2,d2,h2,mi2 = fo... |
from distutils.core import setup
setup(
name='toy_air_shower',
version='0.0.0',
description='Simulate the Cherenkov-light of gamma-ray induced air-showers',
url='https://github.com/cherenkov-plenoscope/toy_air_shower',
author='Sebastian Achim Mueller',
author_email='sebastian-achim.mueller@mpi-... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.