content stringlengths 5 1.05M |
|---|
from pathlib import Path
import unittest
from pxr import Sdf,Usd, UsdShade
from vox2usd import Vox2UsdConverter
DATA_PATH = Path(__file__).parent.joinpath("data")
class TestUsdPrim(unittest.TestCase):
def test_default_prim(self):
filename = "test_geomsubsets"
vox2usd = Vox2UsdConve... |
# hgweb/wsgicgi.py - CGI->WSGI translator
#
# Copyright 2006 Eric Hopper <hopper@omnifarious.org>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
#
# This was originally copied from the public domain code at
# http://www.python.org... |
import glob
with open('merge.sh', 'w') as newfile:
#glob.glob('/home/jegan/bccgc4/GLIDE_Docking/'+method+'_Docking/cluster_dock_input_'+method+'__testing_TICA_pdb_*__dock_pv.maegz')
#print(paths)
paths = glob.glob('./all_poses/*.maegz')
print(paths)
newfile.write('module load schrodinger\n')
... |
from django.utils.translation import gettext as _
ERROR_UNRECOGNIZED = 10
ERROR_INCOMPLETE_DATA = 11
ERROR_INVALID_HANDLER = 12
ERROR_INVALID_DATA_TYPE = 13
WS_CONNECTED = 20
WS_DISCONNECTED = 21
WS_DENIED = 22
LEVEL_TYPE_NEUTRAL = 30
LEVEL_TYPE_SUCCESS = 31
LEVEL_TYPE_WARNING = 32
LEVEL_TYPE_ERROR = 33
FRAME_NO_AC... |
# Solution: two-pointers
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
result = nums[0] + nums[1] + nums[2]
for i in range(len(nums)-2):
if i >0 and nums[i] == nums[i-1]:
continue
... |
"""
Copyright 2018-2020 Jakub Kuczys (https://github.com/jack1142)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# stemdl_classification.py
# Stemdl Classification benchmark
# SciML-Bench
# Copyright © 2022 Scientific Machine Learning Research Group
# Scientific Computing Department, Rutherford Appleton Laboratory
# Science and Technology Facilities Council, UK.
# All rights rese... |
dado = input('Digite algo: ')
tipo = type(dado)
print('vc digitou um dado tipo: \033[35m{}'.format(tipo))
if dado.isalpha():
print('\033[36mAlpha')
if dado.isalnum():
print('\033[36mAlphaNum')
if dado.isnumeric():
print('\033[36mNumerico')
if dado.isprintable():
print('\033[36mPrintavel')
if dado.isuppe... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
import os
import sys
import re
import traceback
import argparse
from ruamel.yaml import YAML
yaml = YAML()
reload(sys)
sys.setdefaultencoding('utf-8')
content_regex = re.compile(r'---([\s\S]*?)---([\s\S]*)')
replace_regex... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import json
import argparse
import re
import numpy as np
import csv
import sys
from get_target_stat import load_stat
##print all class with its counts##
if __name__ == '__main__':
"""
(F)python get_prune_topic.py --mode... |
# -*- coding: utf-8 -*-
"""Contains functions for generating and reading expression counts."""
# pylint: disable=wildcard-import,redefined-builtin,unused-wildcard-import
from __future__ import absolute_import, division, print_function
from builtins import *
# pylint: enable=wildcard-import,redefined-builtin,unused-wil... |
from django.db import models
from django.conf import settings
from django.utils import timezone
from django.core.validators import MaxValueValidator, MinValueValidator
from datetime import datetime
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post... |
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
import os
import torch
class Flatten(nn.Module):
def __init__(self):
super(Flatten, self).__init__()
def forward(self, x):
return x.view(x.size(0), -1)
class InceptionV3(nn.Module):
"""Pretrained Incepti... |
"""
Command for getting helptext for another command
"""
from ..command import BaseCommand
class HelpCommand(BaseCommand):
"""
Displays help for a command
Required arguments:
If left empty will list all available commands on system
Otherwise pass in a command,
... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
import re
import numpy as np
from ..fitter import initial_period
class TestFitter(object):
"""Test rv.fitter.
"""
def setup(self):
pass
def teardown(self):
pass
def test_initial_period(self):... |
# Copyright 2017 Google 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 ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
# This file is only used if you use `make publish` or
# explicitly specify it as your config file.
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
# If your site is available via HTTPS, make sure SITEURL... |
import unittest
#import Changeling
from mongodec.changeling import Changeling, replace_arg, convert_arg_soup
class TestChangeling(unittest.TestCase):
def test_Changeling(self):
""" Simple changeling test """
# Test that we can make a simple dummy class
return
class Foo(object):
... |
from fastapi import Depends, APIRouter, Request
from starlette.responses import RedirectResponse
from loguru import logger
from app.internal.utils import get_current_user
from app.dependencies import get_db
from app.internal.google_connect import get_credentials, fetch_save_events
from app.routers.profile import route... |
"""Sample code for training models"""
from typing import Any, Mapping, Optional, Sequence, Tuple, Type
import numpy as np
import torch
from opacus import PrivacyEngine
from opacus.utils.batch_memory_manager import BatchMemoryManager
from opacus.validators import ModuleValidator
from tqdm import tqdm
from .data impor... |
# ==================option.test_options.py=====================
# This module adds some test options for the total project.
# Version: 1.0.0
# Date: 2019.08.07
# =============================================================
import os
from option import BaseOptions
###################################################... |
"""import special form
Exmaples:
(import std.io.petr)
"""
from types import ModuleType
from typing import List
import os
import importlib
import importlib.util
import inspect
from mplisp import evaluator
from mplisp.structures import env
def import_module(args: List, node):
"""
Import all functions from a mo... |
import data
import datetime
import pytest
def test_fetching_activity():
activity_data = data.fetch_issue_activity("equinor/gathering-leto")
assert len(activity_data) > 0
assert "closed" in tuple(activity_data.columns)
assert "date" in tuple(activity_data.columns)
assert "open" in tuple(activity_dat... |
#Faça um Programa que verifique se uma letra digitada é "F" ou "M". Conforme a letra escrever:
# F - Feminino, M - Masculino, Sexo Inválido.
sex = str(input('Digite F ou M:\n').upper().strip())
if sex == 'F' or sex == 'M':
if sex == 'F':
print('F = Feminino')
else:
print('M = Masculino')
else:
... |
# -*- coding: utf8 -*-
__title__ = "FreeCAD Autodesk 3DS Max importer"
__author__ = "Jens M. Plonka"
__url__ = "https://www.github.com/jmplonka/Importer3D"
import FreeCAD, triangulate, numpy, zlib, sys, traceback
from importUtils import missingDependency, canImport, newObject, getValidName, getByte, getSho... |
from kivy.config import Config
# Config.set('kivy', 'exit_on_escape', '0')
# Config.set('graphics', 'resizable', '0')
Config.set('graphics', 'width', '640')
Config.set('graphics', 'height', '480')
import os
import cv2
from detection import Face_Detector, Landmark_Detector
from faceswap_cam import face_swap
from kivy.... |
"""External tests associated with doctest_private_tests.py.
>>> my_function(['A', 'B', 'C'], 2)
['A', 'B', 'C', 'A', 'B', 'C']
"""
|
# Copyright 2014 Google 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 or ag... |
from __future__ import unicode_literals
import keyword
import re
from optparse import make_option
import fnmatch
import json
import pyodbc
from django.db import connections
#from django.conf import settings
#from django.utils import six
from django.core.management.commands.inspectdb import Command as InspectDBComma... |
# -*- coding: utf-8 -*-
# Copyright 2019 Spanish National Research Council (CSIC)
#
# 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
#
# Unle... |
from fact.io import read_h5py
from fact.analysis.statistics import li_ma_significance
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from functools import lru_cache, partial
from scipy.optimize import minimize
from numdifftools import Hessian
INVALID = np.finfo(np.float32).max
EPS = 1e-10
# m... |
from chainer_chemistry.dataset.preprocessors.atomic_number_preprocessor import AtomicNumberPreprocessor # NOQA
from chainer_chemistry.dataset.preprocessors.base_preprocessor import BasePreprocessor # NOQA
from chainer_chemistry.dataset.preprocessors.common import construct_adj_matrix # NOQA
from chainer_chemistry.da... |
"""
Django settings for trywq project.
Based on the Django 1.9 template, with wq-specific modifications noted as such.
Generated by 'wq start' 1.0.0-dev.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djan... |
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/7/11 0:14
# @Author : ganliang
# @File : setup.py.py
# @Desc : 安装包
from setuptools import setup, find_packages
"""
编译 python setup.py build
安装 python setup.py install
打包(源代码发布) python setup.py sdist
将项目上传到pypi python setup.py sdist upload
打包成可执行(... |
#!/usr/bin/env python3
# _*_coding:utf-8_*_
# Created by "LiuXin"
# Time 2016/5/25
# 基类
import tornado.web
from setting import client
class BaseHandler(tornado.web.RequestHandler):
def __init__(self, application, request, **kwargs):
super(BaseHandler, self).__init__(application, request, **kwargs)
... |
from django.contrib import admin
from .models import Project, Tag, Skill, Type, Profile, AppForProject
class SkillInline(admin.TabularInline):
model = Project.skill.through
extra = 0
class TagsInline(admin.TabularInline):
model = Project.tag.through
extra = 0
class ProjectAdmin(admin.ModelAdmin):
... |
class NodeOp:
OPERATORS = {
"Data Source": ["Data Source"],
"Filter": ["Filter"],
"Map": ["Map", "FlatMap", "CoMap", "CoFlatMap", "MapPartition"],
"Reduce": ["Reduce"],
"Group by": ["GroupReduce", "CoGroup", "GroupCombine"],
"Join": ["Join", "Outer Join"],
"Bu... |
"""
Tests for mobile API utilities.
"""
import ddt
from django.test import TestCase
from ..decorators import mobile_course_access, mobile_view
@ddt.ddt
class TestMobileAPIDecorators(TestCase):
"""
Basic tests for mobile api decorators to ensure they retain the docstrings.
"""
@ddt.data(mobile_view... |
from base64_decode_popup.EncodingAnalyzer import EncodingAnalyzer
from base64_decode_popup.EncodingAnalysis import EncodingAnalysis
class FilteredBaseEncodingAnalyzer(EncodingAnalyzer):
"""
Analyzer which considers only results passing the
supplied string filter.
"""
def __init__(self, delegate,... |
import time
t= time.time()
limit = 5000000
collatz = {1:1,0:0}
tmp = []
num = 1
cnt = 0
while 2*num <= limit:
collatz[2*num] = collatz[num] + 1
num *= 2
for i in range(3,limit+1):
if i & 1 and i not in collatz:
tmp.clear()
num = i
while num != 1 and num not in collatz:
... |
'''
Based on the paper: Xoodoo cookbook
found at: https://eprint.iacr.org/2018/767.pdf
C X.Y is reference to the paper at chapter X, subchapter Y
'''
# C 2 (Table 1), I randomly removed the bottom four constants so the lenth of the key would be the same as Sparkle
HASH_CONST = 0x00000058000000D000000060000000F00000... |
##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. law. Dissemination
# to ... |
import copy
import json
import logging
import math
import csv
from mrtarget.Settings import Config, file_or_resource
from mrtarget.constants import Const
from mrtarget.common.DataStructure import JSONSerializable, PipelineEncoder
from mrtarget.common.IO import check_to_open, URLZSource
from mrtarget.modules import Ge... |
from fidget.backend.QtWidgets import QLineEdit, QHBoxLayout
from fidget.core.__util__ import first_valid
from fidget.widgets.rawstring import FidgetRawString
class FidgetLine(FidgetRawString):
"""
A string Fidget, in the form of a QLineEdit
"""
MAKE_INDICATOR = MAKE_TITLE = MAKE_PLAINTEXT = False
... |
# ██╗ ██╗██████╗ ███╗ ███╗███████╗ █████╗ ██╗
# ██║ ██║██╔══██╗████╗ ████║██╔════╝██╔══██╗██║
# ███████║██║ ██║██╔████╔██║█████╗ ███████║██║
# ██╔══██║██║ ██║██║╚██╔╝██║██╔══╝ ██╔══██║██║
# ██║ ██║██████╔╝██║ ╚═╝ ██║███████╗██║ ██║███████╗
# ╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝
# Copyright 2019... |
# SPDX-FileCopyrightText: 2021 Luke Granger-Brown <git@lukegb.com>
#
# SPDX-License-Identifier: MIT
from typing import Optional, TextIO
from . import der_x509
from . import enums
from . import types
class CertStoreOutput:
def __init__(self, fp: TextIO):
self.fp = fp
def output(self, cert: Optional[... |
# Generated by Django 3.2.5 on 2021-10-22 08:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("bookwyrm", "0111_merge_0107_auto_20211016_0639_0110_auto_20211015_1734"),
]
operations = [
migrations.RemoveConstraint(
model_na... |
def solution(prices):
answer, stack = [0] * len(prices), []
for i in range(len(prices)):
while stack and prices[i] < prices[stack[-1]]:
answer[stack[-1]] = i - stack[-1]
stack.pop()
stack.append(i)
for i in range(len(stack)):
answer[stack[i]] = len(prices) - ... |
# Copyright (c) OpenMMLab. All rights reserved.
from typing import Dict, List, Optional
import numpy as np
import torch
from mmcv.runner import auto_fp16
from mmcv.utils import ConfigDict
from mmdet.core import bbox2roi
from mmdet.models.builder import DETECTORS
from torch import Tensor
from .query_support_detector i... |
import torch
from trains.benchmark_trains.mhkd_training import train_mhkd_grid
from models.resnet_cifar import resnet8_cifar, resnet110_cifar,resnet20_cifar
from models.Middle_Logit_Gen import Model_Wrapper
from general_utils import test_data_evaluation
from dataloader import get_test_loader_cifar
from models.middle_he... |
from django.contrib import admin
from solo.admin import SingletonModelAdmin
from .models import Settings
@admin.register(Settings)
class SettingsAdmin(SingletonModelAdmin):
...
|
# Copyright 2007-2014 University Of Southern California
#
# 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 ... |
from taskio.model import TaskioTask
class FirstLevelTask(TaskioTask):
def run(self, namespace):
print("buuuu")
class GenerateUuidTask(TaskioTask):
def add_arguments(self, parser):
"""
:param parser:
:return:
"""
parser.add_argument("-a", "--addresses", req... |
def nrvocale(text):
"""Scrieti o functie care calculeaza cate vocale sunt intr-un string"""
count = 0
for c in text:
if c in ['a', 'e', 'i', 'o', 'u']:
count = count + 1
return count
if __name__ == "__main__":
print (nrvocale("Marian"))
|
from django.urls import path
from . import views
urlpatterns = [
path('', views.TestListView.as_view(), name='list'),
path('add/', views.TestCreateView.as_view(), name='create'),
path('<int:pk>/', views.TestDetailView.as_view(), name='detail'),
path('<int:pk>/edit/', views.TestUpdateView.as_view(), na... |
from seaice import *
from firedrake import *
from pathlib import Path
from netCDF4 import Dataset
import numpy as np
import matplotlib.pyplot as plt
path = "./output/mk/figure5"
Path(path).mkdir(parents=True, exist_ok=True)
"""
TEST 2 : EVP
File reproducing figure 5 from Mehlmann and Korn (2021)
Fig 5 a) Energy vs.... |
# MenuTitle: Add UGI anchors
# -*- coding: utf-8 -*-
from AppKit import NSEvent
from UGI import LayerPositions
__doc__ = """
Adds Anchors using the UGI.
"""
from UGI.UGI_importer import import_scripts
unified_infos = import_scripts(Glyphs.font)
Glyphs.clearLog()
# Glyphs.showMacroWindow()
# --- From mekkablue ---
ke... |
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
import matplotlib.pyplot as plt
import seaborn as sns
from flow import *
z = np.load('data/latent_space.npy',mmap_mode = 'c')
z_2 = np.load('data/latent_space_2.npy',mmap_mode = 'c')
z = np.concatenate((z,z_2), axis = 0)
hidden_dim = [... |
def menu_action(menu, name):
for action in menu.actions():
if action.text() == name:
return action
|
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 20 09:44:59 2019
@author: Elkoumy
"""
import pandas as pd
#data1= pd.read_csv(r"C:\Gamal Elkoumy\PhD\OneDrive - Tartu Ülikool\Secure MPC\Business Process Mining SourceCode\Datasets\Road_Traffic_Fine_Management_Process.csv")
#
#output=pd.DataFrame()
#output['case']=data1... |
from .bidirected_graph import BidirectedGraph
from .edge import Edge
from .graph import Graph
from .tnode import TNode
|
import logging
import json
# create logger
logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG)
def printThingAsJSON(thing):
print(json.dumps(thing))
if __name__ == "__main__":
output = {"Hi": "Mom"}
printThingAsJSON(output)
logging.debug("Completed.")
|
import pandas as pd
from os import walk
filedir = './Final_Data/'
flx = next(walk(filedir))[1]
csvs = []
for f in flx:
try:
filenames = ['hdb','hroster']
inner_filenames = next(walk(filedir+f+'/pdb/'), (None, None, []))[2]
# print(filenames,":",inner_filenames)
datax... |
import cv2
from matplotlib import pyplot as plt
import numpy as np
def norm(val,tmin,tmax,nmin,nmax):
downrange = ((val-nmin))/(nmax-nmin)
if(downrange<0):
downrange = 0.0
elif(downrange>1):
downrange = 1.0
uprange = downrange*(tmax-tmin)
return uprange+tmin
#for mono, just take ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------------
__author__ = 'Patrice Carbonneau'
__contact__ = 'patrice.carbonneau@durham.ac.uk'
__copyright__ = '(c) Patrice Carbonneau'
__license__ = 'MIT'
''' This routine compiles sentinel data (preferabl... |
from django.shortcuts import render
from django.http import HttpResponse
from cryptography.fernet import Fernet
# Create your views here.
def homepage(request):
return render(request, 'homepage.html')
def get_secret_link(request):
print ("here")
Entered_Text = request.POST.get('Entered_Text')
#genera... |
#!/usr/bin/env python3
"""Split reports into separate files per appid"""
# pylint: disable=invalid-name
import json
import os
import sys
from datetime import datetime
def load_reports():
all_reports = {}
last_timestamp = 0
with open('reports_piiremoved.json') as reports_file:
reports = json.loa... |
import sys
from lib.utils import Size
class Screen(object):
pos:list = None # i, j position of cursor
size:Size = None
def __init__(self, width:int, height:int):
self._set_size(width, height)
self._init_screen()
def _set_size(self, width, height):
assert width > 0, 'Negative... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import pytest # type: ignore
from sensibility import Language
from sensibility.language.java import java
from sensibility import Position
from location_factory import LocationFactory
test_file_good = r"""package ca.ualberta.cs.emplab.example;
cl\u0061ss Example // ... |
import read
import pandas as pd
from sklearn.svm import LinearSVC, SVC
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score, f1_score
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import classification_re... |
n=1
v = 0
v2 = 20000
for c in range(1,6,1):
peso = float(input('Peso da {}ª pessoa em kg: '.format(n)))
n += 1
if v < peso:
v = peso
elif v2 > peso:
v2 = peso
print('O maior peso é {} kg'.format(v))
print('O menor peso é {} kg'.format(v2)) |
#vars.py
X0=0
X1=0
X2=0
X3=0
#M=1
|
import logging
import tornado.web
class BaseHandler(tornado.web.RequestHandler):
def client_for(self, database):
return self.application.db.client(self.selected_server(), database)
def selected_server(self):
server = self.get_cookie("selected-server") or self.application.db.server_names()[0]
... |
import sys
lines = []
for line in sys.stdin:
lines.append(line.rstrip('\n'))
res = []
divisible = [2, 3, 5, 7, 11]
for color in lines[1:]:
for div in divisible:
if (int(color) % div == 0):
if div not in res:
res.append(div)
print(" ".join([str(i) for i in sorted(res)])) |
from datetime import date
from django.db import models
from django.db.models import Q, F
from django.utils.translation import get_language
from reverse_unique import ReverseUnique
class Article(models.Model):
pub_date = models.DateField()
active_translation = ReverseUnique(
"ArticleTranslation", filt... |
#
# PySNMP MIB module Dell-BRIDGE-SECURITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Dell-BRIDGE-SECURITY
# Produced by pysmi-0.3.4 at Mon Apr 29 18:40:37 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
# Copyright (c) 2016 IBM
# 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... |
#!/usr/bin/python3
import sys,os
import cozir
import time
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
import matplotlib.dates as mdates
import matplotlib.units as munits
import numpy as np
import datetime
import timeit
# ... |
import argparse
import binascii
import iroha
import os
import test_kv
IROHA_HOST_ADDR = os.getenv('IROHA_HOST_ADDR', '127.0.0.1')
IROHA_PORT = os.getenv('IROHA_PORT', '50051')
ADMIN_ACCOUNT_ID = os.getenv('ADMIN_ACCOUNT_ID', 'admin@test')
ADMIN_PRIVATE_KEY = os.getenv(
'ADMIN_PRIVATE_KEY',
'f101537e319568c765b... |
import matplotlib.pyplot as plt
import numpy as np
import scipy.io.wavfile as wav
wav_fname = 'textbookcode/Ch_03/sw440hz.wav'
fs, data = wav.read(wav_fname)
length = data.shape[0] / fs
print(f"length = {length}s")
# Divide audio signal by max int value for signed 16 bit number
data = data/np.iinfo(np.int16).max... |
#!/usr/bin/env python
from os.path import dirname, join
from setuptools import find_packages, setup
import MangAdventure
try:
from isort.settings import default
default['known_django'] = 'django'
except ImportError:
pass
def read(fname):
with open(join(dirname(__file__), fname)) as f:
retu... |
from pybulletgym.envs.roboschool.robots.robot_bases import MJCFBasedRobot
import numpy as np
class Reacher(MJCFBasedRobot):
TARG_LIMIT = 0.27
def __init__(self):
MJCFBasedRobot.__init__(self, 'reacher.xml', 'body0', action_dim=2, obs_dim=9)
def robot_specific_reset(self, bullet_client):
... |
# comment.py
"""
Author: Kyeongyul Kim
Date: 2018-03-14
This example shows how to make multi-line comment
"""
print("This example shows how to make multi-line comment")
|
'''
Some relevant metrics
'''
import numpy as np
import pandas as pd
def partial_log_likelihood_ph(log_partial_hazards, durations, events, mean=True):
"""Partial log-likelihood for PH models.
Arguments:
log_partial_hazards {np.array} -- Log partial hazards (e.g. x^T beta).
durations {np.ar... |
# Copyright 2020 David Matthews
#
# 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 writin... |
'''
Write a Python program to remove the ANSI escape sequences from a string.
'''
import re
text = "PHP Exercises\tMySQL Exercises\nAlgo Exercises\r"
print("Original Text: ", text)
new_text1 = re.sub(r'[\n|\t|\r]+', r'. ', text)
print("New Text: ", new_text1)
|
import asyncio
import itertools
import functools
import math
import re
from attr import __description__
import discord
import os
from discord.ext import tasks, commands
from discord.ext.commands.errors import MissingPermissions
from discord.user import Profile
from discord.utils import get
from dns.message ... |
import asyncio
from dataclasses import dataclass, field
import json
import time
import torch
import numpy as np
import ray
import ray.util
from ray import serve
import os
from datasets import load_dataset, load_metric
import requests
from tqdm import tqdm
from torch.utils.data import DataLoader, Subset
from transform... |
import cv2
import numpy as np
from data_toolbox.data.data_mixer import Buffer
from data_toolbox.data.data_operator import DataOperator
class DilateOperator(DataOperator):
def apply(self, source: Buffer) -> Buffer:
kernel = np.ones((5, 5), np.uint8)
return cv2.dilate(source, kernel, iterations=1)
|
# Copyright 2017 The Forseti Security 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 ap... |
import json
import gzip
import sys
import tqdm
import os
import argparse
from typing import List, Set, Any, Dict
seen: Set[str] = set()
def aspect_link_examples(json_file: str) -> Dict[str, Any]:
"""
Reads the JSON-L file in gzip format.
Generates an AspectLinkExample in a lazy way (using yield).
:pa... |
# Generated by Django 3.2.4 on 2021-06-15 00:13
from django.db import migrations
class Migration(migrations.Migration):
def create_default_paper_template(apps, schema_editor):
Template = apps.get_model('voucher', 'PrintTemplate')
Template.objects.create(
name="Default paper template"... |
import os
import pytest
from unittest import TestCase
from unittest.mock import patch, mock_open
from hm_pyhelper.exceptions import UnknownVariantException, \
UnknownVariantAttributeException
from hm_pyhelper.hardware_definitions import is_rockpi, variant_definitions, \
get_variant_attribute, is_raspberry_pi
... |
from django.conf.urls import url
from surfcar.questions import views
urlpatterns = [
url(r'^$', views.questions, name='questions'),
url(r'^answered/$', views.answered, name='answered'),
url(r'^unanswered/$', views.unanswered, name='unanswered'),
url(r'^all/$', views.all, name='all'),
url(r'^ask/$'... |
#!/usr/bin/python
#! -*- encoding: utf-8 -*-
# Copyright (c) 2015 Pierre MOULON.
# Modified by Ivan Eichhardt in 2019
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#... |
import sys
from io import BytesIO
from PIL import Image
from django.contrib.auth.base_user import BaseUserManager, AbstractBaseUser
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.db import models
class MyUserManager(BaseUserManager):
def create_user(self, email, password=None):
... |
from unittest import TestCase
import os
from tempfile import mktemp
import gzip
from blaze.utils import filetext, filetexts, tmpfile
from blaze.data.utils import tuplify
from blaze.data import *
from blaze.data.usability import *
from blaze.compatibility import xfail
class TestResource(TestCase):
def setUp(self)... |
import logging
import os
import subprocess
from ulauncher.api.client.EventListener import EventListener
from ulauncher.api.shared.action.HideWindowAction import HideWindowAction
logger = logging.getLogger(__name__)
class ItemEnterEventListener(EventListener):
def on_event(self, event, extension):
data = ... |
"""
Tests related specifically to integration with Morango.
"""
import os
import unittest
import uuid
from django.test import TestCase
from django.utils import timezone
from morango.models import InstanceIDModel
from morango.models import Store
from morango.models import syncable_models
from morango.sync.controller im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.