text stringlengths 1 927k |
|---|
"""
SAI testing test bed setup.
Notes:
This test is used to setup the SAI testing environment, and start the SAI test cases
from the PTF.
For running this tests, please specify the sai test case folder via the parameters --sai_test_folder.
"""
import pytest, socket, sys, itertools, lo... |
#This is to get the factorial of a particular number]
num = int(input("Enter the number to calculate the factorial: "))
'''while i<5:
num = int(input("Enter the number to calculate the factorial: "))
def fact(num):
if num == 0:
return 1
return num * fact(num-1)
print(fact... |
# Copyright 2021 NREL
# 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
# distri... |
#helps to create env file
#2021 - Angelo Poggi : angelo.poggi@webair.com
import click
@click.command()
@click.option('--createenv', '-c', help="""Helps you to create the .env file required to use this script.\n
mikrotikhtml --createenv <username> <password>""", required=True)
@click.argument(... |
# mock.py
# Test tools for mocking and patching.
# Copyright (C) 2007-2011 Michael Foord & the mock team
# E-mail: fuzzyman AT voidspace DOT org DOT uk
# mock 0.8.0
# http://www.voidspace.org.uk/python/mock/
# Released subject to the BSD License
# Please see http://www.voidspace.org.uk/python/license.shtml
# Scripts... |
# Copyright (c) 2011 Jeff Garzik
#
# Previous copyright, from python-jsonrpc/jsonrpc/proxy.py:
#
# Copyright (c) 2007 Jan-Klaas Kollhof
#
# This file is part of jsonrpc.
#
# jsonrpc is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# th... |
from bokeh.plotting import figure, output_file, show
if __name__ == '__main__':
output_file('graficado_simple.html')
fig = figure()
total_vals = int(input('Cuantos valores quieres graficar? '))
x_vals = list(range(total_vals))
y_vals = []
for x in x_vals:
val = int(input(f'Valor y para {x}'))
y_vals.appen... |
import gc
import glob
import json
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy as sp
import lightgbm as lgb
from collections import Counter
from functools import partial
from math import sqrt
from joblib import Parallel, delayed
from tqdm import tqdm
from PIL import Image
from s... |
# Copyright (c) 2018,2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Cartopy specific mapping utilities."""
try:
from cartopy.feature import Feature, Scaler
from ..cbook import get_test_data
class MetPyMapFeature(Feature):
... |
from cvxpy import Maximize, Problem, Variable, hstack, vstack
import numpy as np
import time
# Create two scalar optimization variables.
ANSWERS = []
TIME = 0
A = np.array([ [1, 2, 0, 1], \
[0, 0, 3, 1], \
[0, 3, 1, 1], \
[2, 1, 2, 5], \
[1, 0, 3, 2] ])
A_star = hstack(A,A)
c_max = np.array([100] * 5)
p = np.arr... |
# Reference to Flask: http://flask.pocoo.org/
from flask import Flask, current_app
from flask_restful import Api, Resource
import spotify.Spotify as Spotify
from flask_cors import CORS
# Reference to MySQL connector: https://dev.mysql.com/doc/connector-python/en/
import mysql.connector
from mysql.connector import erro... |
from pathlib import Path
import json
import random
import os
import numpy as np
import torch
from torch.nn import CrossEntropyLoss
from torch.optim import SGD, lr_scheduler
import torch.multiprocessing as mp
import torch.distributed as dist
from torch.backends import cudnn
import torchvision
from opts import parse_op... |
"""VOC Dataset Classes
Original author: Francisco Massa
https://github.com/fmassa/vision/blob/voc_dataset/torchvision/datasets/voc.py
Updated by: Ellis Brown, Max deGroot
"""
'''
Adapted from https://github.com/amdegroot/ssd.pytorch
'''
from .config import HOME
import os.path as osp
import sys
import torch
import tor... |
import torch
from torch import optim
from torch.nn import Parameter
import torch.nn.functional as F
class Encoder(torch.nn.Module):
def __init__(self, input_size, hidden_size, num_layers, dropout):
super(Encoder, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers =... |
# -*- coding: utf-8 -*-
class ML(dict):
def __init__(self, classifier=None, name=''):
"""Init ML object
Keyword arguments:
classifier (object) -- sklearn-like classifier
"""
self.clf = classifier
self.meta = {
'name': name
}
def fit(self... |
from urllib.parse import quote_plus
from django import template
register = template.Library()
@register.filter
def multiply_10(value):
return int(float(value) * 10)
@register.filter
def color(value):
if value >= 8:
return 'success'
if value >= 6:
return 'info'
if value >= 4:
... |
from pyssrs import SSRSReport
from parse_xlsx_xml import ParseXlsx
from xlsx_rc_convertor import convert_rc_formula |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"module_name": "Testapp",
"color": "grey",
"icon": "octicon octicon-file-directory",
"type": "module",
"label": _("Testapp")
}
] |
def leia_int(n):
while True:
try:
nu = int(input(n))
except(ValueError, TypeError):
print('\033[31mERRO: por favor, digite um número inteiro válido.\033[m')
continue
else:
return nu
def leia_float(n):
while True:
try:
nu... |
# Coding:utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2018 yutiansut/QUANTAXIS
#
# 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 th... |
from ftplib import FTP
import popen2, time, sys
directory = sys.argv[1]
filename = sys.argv[2]
download_dir = sys.argv[3]
host = sys.argv[4]
size_ftp = sys.argv[5]
path_to_cvs = sys.argv[6]
'''this commands needs to be redirected to /dev/null or it won't work, also can't read out from this for debugging b/c process wi... |
#! /usr/bin/env python
# Copyright Red Hat, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... |
from uuid import uuid4
from changes.constants import Result, Status
from changes.testutils import APITestCase, SAMPLE_DIFF
class BuildFlakyTests(APITestCase):
def setUp(self):
super(BuildFlakyTests, self).setUp()
self.project = self.create_project()
self.create_plan(self.project)
... |
import os
from lizard_ui.settingshelper import setup_logging
from lizard_ui.settingshelper import STATICFILES_FINDERS
DEBUG = True
TEMPLATE_DEBUG = True
# SETTINGS_DIR allows media paths and so to be relative to this settings file
# instead of hardcoded to c:\only\on\my\computer.
SETTINGS_DIR = os.path.dirname(os.pa... |
#!/usr/bin/env python
#
# Copyright 2017 Google Inc.
# Copyright 2018 Open GEE Contributors
#
# 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... |
# Copyright (c) 2019 Red Hat, Inc.
#
# 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, ... |
from rest_framework import serializers
from authentication.serializers import AccountSerializer
from posts.models import Post
class PostSerializer(serializers.ModelSerializer):
author = AccountSerializer(read_only=True, required=False)
class Meta:
model = Post
fields = ('id', 'author', 'con... |
"""Test wlan configuration API.
pytest --cov-report term-missing --cov=aiounifi.wlan tests/test_wlans.py
"""
from asynctest import Mock
from aiounifi.wlan import Wlans
def test_ports():
"""Test that different types of ports work."""
wlans = Wlans(fixture_wlans, Mock())
assert len(wlans.values()) == 2
... |
import pytest
from hamcrest import assert_that, contains_exactly, equal_to, has_properties, is_ # type: ignore
import gilded_rose
class TestGildedRose:
def test_combined_case(self):
items = [
gilded_rose.Item(name='+5 Dexterity Vest', sell_in=10, quality=20),
gilded_rose.Item(nam... |
from rpython.rlib import jit
from . import pretty
class ImmutableEnv(object):
_immutable_fields_ = ['_w_slots[*]', '_prev']
def __init__(self, w_values, prev):
self._w_slots = w_values
self._prev = prev
@jit.unroll_safe
def at_depth(self, depth):
#depth = jit.promote(depth)
... |
# -*- coding:utf-8 -*-
# author: Hong Fangzhou
# @file: model_zoo.py
# @time: 2020/09/26 17:05
from .modules import BEV_Unet
from .modules import PointNet
from .modules import spconv_unet
from .modules import pytorch_meanshift
from .loss import instance_losses
from .loss import lovasz_losses
from utils.evaluate_panopt... |
#!/usr/bin/env python2
"""
Logging part of a multicast group scanner.
Needs to be run with capabilities allowing it to read
raw data from the network interface. (usually root)
Author: Lasse Karstensen <lasse.karstensen@gmail.com>, April 2013.
"""
import sys
import socket
import pcapy
import impacket
import datetime
f... |
# coding: utf-8
#
# Copyright 2014 The Oppia 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 requi... |
#!/usr/bin/env python3
import smtplib # make the smtplib module avail
import getpass # secret acceptance of password
def send_my_message(subj, txt):
mypass = getpass.getpass("Enter your Password:")
myaddress = input("Enter your mail.com address (ex. pythonstudent01@mail.com):")
content = f"""From:{myaddre... |
# @Author : Xavier Faure
# @Email : xavierf@kth.se
import os
import sys
#add the required path
path2addgeom = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())),'geomeppy')
sys.path.append(path2addgeom)
#add scripts from the project as well
sys.path.append("..")
from subprocess import check_call
from geomep... |
# coding: utf-8
from __future__ import absolute_import
from google.appengine.ext import ndb
import flask_restful
import flask
from api import helpers
import auth
import model
import util
from main import api_v1
@api_v1.resource('/repo/', endpoint='api.repo.list')
class RepoListAPI(flask_restful.Resource):
def g... |
###############################################################################
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
###############################################################################
imp... |
#Contains all the functions required for assessing flood risk
#Exercise 2B - assessing flood risk by level:
def stations_level_over_threshold(stations, tol):
"""returns a list of tuples of stations with relative water level over tol."""
stations_over_threshold = []
for station in stations:
try: ... |
# -*- coding: utf-8 -*-
__author__ = 'ffuentes'
import argparse
import os
import sys
import csv
import logging
from apps.noclook.models import ServiceType, ServiceClass
from django.core.management.base import BaseCommand, CommandError
logger = logging.getLogger('noclook_service_types_import')
def insert_service_ty... |
from flask import Blueprint, render_template, g, request, flash
import flask_sijax
from main.models.borrower import Borrower
from flask_login import LoginManager, login_user, login_required, logout_user, current_user
from main.maintenance.borrower.forms import BorrowerMaintenanceForm
from main.spa_handler.sijax_handler... |
#! /usr/bin/python
from RPi import GPIO
import signal
import rospy
from geometry_msgs.msg import Twist
clk1 = 13 #left wheel
dt1 = 6
clk2 = 19 #right Wheel
dt2 = 26
def keyboardInterruptHandler(signal, frame):
print("this is velocity publisher signing off ...")
exit(0)
GPIO.setmode(GPIO.BCM)
GPIO.setup(clk1... |
# -*- coding: utf-8 -*-
# Natural Language Toolkit: A Chart Parser
#
# Copyright (C) 2001-2018 NLTK Project
# Author: Edward Loper <edloper@gmail.com>
# Steven Bird <stevenbird1@gmail.com>
# Jean Mark Gawron <gawron@mail.sdsu.edu>
# Peter Ljunglöf <peter.ljunglof@heatherleaf.se>
# URL: <http://n... |
# Copyright (c) 2013-2016 CORE Security Technologies
#
# This software is provided under under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# Config utilities
#
# Author:
# Ronnie Flathers / @ropnop
#
# Description:
# Helpful enum methods... |
"""
'spyplugins' makes uses of namespace packages to keep different plugins
organized in the sitepackages directory and in the user directory.
Spyder plugins can be of 'io' type or 'ui' type. Each type also makes use
of namespace packages.
For more information on namespace packages visit:
- https://www.python.org/dev... |
"""Check if userbot alive. If you change these, you become the gayest gay such that even the gay world will disown you."""
import asyncio
from telethon import events
from telethon.tl.types import ChannelParticipantsAdmins
from platform import uname
from userbot import ALIVE_NAME
from userbot.utils import admin_cmd
ALI... |
# Unindo dicionários e listas
# Crie um programa que leia nome, sexo e idade de várias pessoas, guardando os dados de cada pessoa em um dicionário
# e todos os dicionários em uma lista. No final, mostre:
# A) Quantas pessoas foram cadastradas
# B) A média de idade
# C) Uma lista com as mulheres
# D) Uma lista de pesso... |
"""Manage config entries in Home Assistant."""
from __future__ import annotations
import asyncio
import functools
import logging
from types import MappingProxyType, MethodType
from typing import Any, Callable, Dict, List, Optional, Set, Union, cast
import weakref
import attr
from homeassistant import data_entry_flow... |
#!/usr/bin/env python
import threading
mylock = threading.RLock()
num = 0
class WorkThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.t_name = name
def run(self):
global num
while True:
mylock.acquire()
print('\n%s locked, number: %d' %(self.t_name, num))
if... |
import os
import pytest
import pycondor
from pycondor.utils import (clear_pycondor_environment_variables, checkdir,
assert_command_exists, get_condor_version,
parse_condor_version, split_command_string,
decode_string)
from pycondor.comp... |
#!/usr/bin/env python
#
# Copyright (c) 2016, Nest Labs, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this ... |
# This file is a part of Arjuna
# Copyright 2015-2021 Rahul Verma
# Website: www.RahulVerma.net
# 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... |
def blocks_to_collect(level): |
import argparse
import os
import pdfkit
import re
import validators
from robobrowser import RoboBrowser
def remove_non_ascii_chars(text):
return re.sub(r'[^\x00-\x7F]+', ' ', text)
base_url = 'https://learning.oreilly.com'
parser = argparse.ArgumentParser(
description='A small program to download books fro... |
import unittest, os.path, os
from PIL import ImageGrab
from .removeImg import remove_img
class TestRemove_img(unittest.TestCase):
# Deveria excluir uma imagem
def test_remove_img_remove(self):
img = ImageGrab.grab((0,0,500,500))
path = "tmp.png"
img.save(path)
img.close()
pathExists = os.path.... |
import os
token = os.environ.get('telegram_token')
channel_chat_id = '-1001479800791'
help_text = """Привет!
Это чат-бот "Мудрые слова".
Нажмите на /quote, для того, чтобы получить новую цитату.
Подписывайтесь на наш телеграм канал @amit_thoughts, чтобы получать ежедневно дозу мудрости.
Удачи!
""" |
import linkedList as L
myLL = L.linkedList()
myLL.pushToHead("last item")
myLL.pushToHead("first item")
print(myLL.popFirst())
print(myLL.popFirst())
#output:
#first item
#last item |
#!/usr/bin/python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... |
# Third party imports
from gmprocess.metrics.transform.transform import Transform
from gmprocess.stationstream import StationStream
from gmprocess.stationtrace import StationTrace
class Differentiate(Transform):
"""Class for computing the derivative."""
def __init__(self, transform_data, damping=None, period=... |
"""
Copyright (c) 2011, 2012, Regents of the University of California
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
This is rumdom run node.
subscribe No topcs.
Publish 'cmd_vel' topic.
mainly use for simple sample program
by Takuya Yamaguhi.
'''
import rospy
import random
from geometry_msgs.msg import Twist
class RandomBot():
def __init__(self, bot_name="NoName"):
... |
"""duello URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/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 ... |
'''
Configuration object
====================
The :class:`Config` object is an instance of a modified Python ConfigParser.
See the `ConfigParser documentation
<http://docs.python.org/library/configparser.html>`_ for more information.
Kivy has a configuration file which determines the default settings. In
order to cha... |
from pyjamas_core import Supermodel
from pyjamas_core.util import Input, Output, Property
from datetime import datetime, timedelta
from Models._utils.time import datetime2utc_time, utc_time2datetime
import numpy as np
from pytz import timezone
import json
from scipy.interpolate import griddata
import pandas as pd
impor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
episode, season, episode_count, season_count and episode_details properties
"""
import copy
from collections import defaultdict
from rebulk import Rebulk, RemoveMatch, Rule, AppendMatch, RenameMatch
from rebulk.match import Match
from rebulk.remodule import re
from reb... |
### DiscreteLog.py
###
### Compute x when given h, g prime p, and the range of x [0 <= x <= max], such that g**x = h mod p
###
### This uses meet-in-the-middle-attack, namely, expand x as x = x0 * sqrt(max) + x1, find x0 and x1
### such that h/(g**x1) == (g**sqrt(max) )**x0 in mod p, by exausive attack.
###
### MIT L... |
import torch
import tqdm
from torch.utils.data import DataLoader
import torch.nn.functional as F
from torch import optim, nn
from dataset import Script_dataset
from config import TrainingConfig, CONFIG_PATH
from model import BaseModel
from tools import logging, get_time
from datetime import datetime
import os
from shut... |
# %% [markdown]
# ## Dicision tree
# %%
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.datasets import make_moons
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
import os
import graphviz
from skl... |
from collections import defaultdict, namedtuple
AclPermission = namedtuple('AclPermission', 'app, action')
# Null rule. Only useful in tests really as no access group should have this.
NONE = AclPermission('None', 'None')
# A special wildcard permission to use when checking if someone has access to
# any admin, or... |
'''
test/debug the reporting program w.t.h. of this file :-)
@author: rbudde
'''
from datetime import datetime
import time
from util import *
from store import *
from entry import *
if __name__ == "__main__":
logDir = "D:/data/openroberta-lab/server/master/admin/logging/statistics-2020"
logFile = "01.log.zi... |
# 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... |
import datetime
from platform import uname
from flask import Flask
server = Flask(__name__)
@server.route("/")
def getgreeting():
return uname()[0] + " | " + uname()[1] + " | " + str(datetime.datetime.now())
if __name__ == "__main__":
server.run(host='0.0.0.0') |
"""
Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
import boto3
import configparser
import logging
import os
import pytest
import typing
logger = logging.getLogg... |
# The MIT License (MIT)
# Copyright (c) 2018 by EUMETSAT
#
# 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,... |
import turtle
def draw_square(some_turtle):
for i in range(1,5):
some_turtle.forward(100)
some_turtle.right(90)
def draw_art():
window = turtle.Screen()
window.bgcolor("blue")
img_tt = turtle.Turtle()
img_tt.shape("turtle")
img_tt.color("white")
img_tt.speed(2)
for i in... |
#!/usr/bin/env python
'''
Aoide | Reduction & Analysis of MUSE observations
-------------------------------------------------
Dr. Grant R. Tremblay | Harvard-Smithsonian Center for Astrophysics
grant.tremblay @ cfa.harvard.edu
See the README associated with this repository for documentation & examples.
'''
from __fu... |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import sys... |
"""Helper methods for components within Home Assistant."""
from __future__ import annotations
from collections.abc import Iterable, Sequence
import re
from typing import TYPE_CHECKING
from homeassistant.const import CONF_PLATFORM
if TYPE_CHECKING:
from .typing import ConfigType
def config_per_platform(
con... |
from nose.plugins.attrib import attr
@attr('demo_smoke', 'smoke', 'known_bad')
def test_dummy_known_bad_with_assertion_error():
"""
test_dummy_known_bad_with_assertion_error
I'd like to buy the world a Dr Pepper!
"""
assert False
@attr('demo_smoke', 'smoke', 'known_bad')
def test_dummy_known_bad... |
# Copyright (c) 2021 PPViT 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 applicable l... |
from typing import List
import django_filters
from django.db.models import Q
from django.utils import timezone
from ...discount import DiscountValueType
from ...discount.models import Sale, Voucher, VoucherQueryset
from ..core.filters import ListObjectTypeFilter, ObjectTypeFilter
from ..core.types.common import DateT... |
import datetime
from enum import Enum
from random import randint
from time import sleep
from base.collection_wrapper import ApiCollectionWrapper
from common import common_func as cf
from common import common_type as ct
import constants
from utils.util_log import test_log as log
class Op(Enum):
create = 'create'
... |
import numpy as np
import pytest
from jina.executors.evaluators.rank.recall import RecallEvaluator
@pytest.mark.parametrize(
'eval_at, expected',
[
(0, 0.0),
(1, 0.2),
(2, 0.4),
(3, 0.4),
(5, 0.4),
(100, 0.4)
]
)
def test_recall_evaluator(eval_at, expected)... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import re
from jinja2.exceptions import TemplateSyntaxError
import frappe
from frappe import _
from frappe.utils import get_datetime, now, quoted, strip_html
from frappe.utils.jinja import render_template
from frappe.uti... |
#!/usr/bin/env python
# Copyright 2012 Google Inc. All Rights Reserved.
"""Utils exporting data from AFF4 to the rest of the world."""
import os
import Queue
import stat
import time
import logging
from grr.lib import aff4
from grr.lib import rdfvalue
from grr.lib import serialize
from grr.lib import threadpool
from... |
#!/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.
import argparse
import distutils.version
import enum
import errno
import fnmatch
import glob
import itertools
import js... |
import unittest
from collections import defaultdict
class Solution:
def findTargetSumWays(self, nums: list[int], target: int) -> int:
dps = []
dp = defaultdict(int, {nums[0]: 1})
dp[-nums[0]] += 1
dps.append(dp)
for i in range(1, len(nums)):
dp = defaultdict(i... |
#!/usr/bin/env python
#
# File Name : bleu.py
#
# Description : Wrapper for BLEU scorer.
#
# Creation Date : 06-01-2015
# Last Modified : Thu 19 Mar 2015 09:13:28 PM PDT
# Authors : Hao Fang <hfang@uw.edu> and Tsung-Yi Lin <tl483@cornell.edu>
from bleu_scorer import BleuScorer
class Bleu:
def __init__(self, n=4... |
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
enum = enumerate(seasons)
print(enum)
print(type(enum))
print(list(enum))
my_list = ['apple', 'banana', 'grapes', 'pear']
for c, value in enumerate(my_list, 1):
print(c, value) |
from office365.runtime.client_value import ClientValue
class SPSiteCreationRequest(ClientValue):
def __init__(self, title, url, owner=None):
super(SPSiteCreationRequest, self).__init__()
self.Title = title
self.Url = url
self.WebTemplate = "SITEPAGEPUBLISHING#0"
self.Owner... |
crc32table_le=[[
0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL,
0x076dc419L, 0x706af48fL, 0xe963a535L, 0x9e6495a3L,
0x0edb8832L, 0x79dcb8a4L, 0xe0d5e91eL, 0x97d2d988L,
0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, 0x90bf1d91L,
0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
0x1adad47dL, 0x6ddde4ebL, 0xf4d4... |
import EulerRunner
digits = ('73167176531330624919225119674426574742355349194934'
+ '96983520312774506326239578318016984801869478851843'
+ '85861560789112949495459501737958331952853208805511'
+ '12540698747158523863050715693290963295227443043557'
+ '66896648950445244523161731856403098711121722383113'
+ '62229893423380... |
#!/usr/bin/env python
"""
Spectral features summarized over time using mean and variance. Returns a 22-dimension
feature vector for each audio sample.
Features:
- Spectral Centroid
- Spectral Bandwidth
- Spectral Contrast (7 frequency bands)
- Spectral Flatness
- Spectral Rolloff
"""
import numpy ... |
# -*- coding: utf-8 -*-
"""
Wrapper for Graphics Files
"""
import os
import six
from sage.misc.temporary_file import tmp_filename
from sage.structure.sage_object import SageObject
import sage.doctest
class Mime(object):
TEXT = u'text/plain'
HTML = u'text/html'
LATEX = u'text/latex'
JSON = u'applicat... |
from flask import Blueprint
bp = Blueprint('api.v1', __name__)
# NOTE: Add extra blueprint routes to this import list
from app.api.v1 import errors, planes, tokens, users |
import os
from pathlib import Path
import cv2
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import interp1d
from scipy.signal import resample
from utils.sig_proc_utils import notch_filter, baseline_correction
def window_slice(data, window_size, stride, channel_mode='channel_last'):
a... |
# Generated by Django 2.1.4 on 2019-02-18 14:37
from django.db import migrations, models
import django.db.models.deletion
import provisioning.utils
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('identity', '0001_initial'),
]
operations = [
migr... |
"""
=============================
Tractography Clustering
=============================
Overview
========
**This example gives a tour of clustering related features of dipy.**
First import the necessary modules
----------------------------------
``numpy`` is for numerical computation
"""
import numpy as np
imp... |
# Copyright 2014 - Mirantis, 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 i... |
"""
Copyright 2017 Robin Verschueren
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, softw... |
import torch
import torchio as tio
import numpy as np
def load_tio_image(fn):
"""
ScalarImage(shape: (c, w, h, d))
dtype: torch.DoubleTensor
"""
arr = np.load(fn).swapaxes(0,3)
return tio.ScalarImage(tensor=arr)
def arr_2_tio_image(arr):
"""
ScalarImage(shape: (c, w, h, d))
dtype: ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.