content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import numpy as np
## Wan-Ting borrow this function from io from stmpy folder.
def _make_attr(self, attr, names, data):
'''
Trys to give object an attribute from self.data by looking through
each key in names. It will add only the fist match, so the order of
names dictates the preferences.
Input... | python |
#!/usr/bin/env python3
# Author: Ali Assaf <ali.assaf.mail@gmail.com>
# Copyright: (C) 2010 Ali Assaf
# License: GNU General Public License <http://www.gnu.org/licenses/>
from itertools import product
def solve_sudoku(size, grid):
""" An efficient Sudoku solver using Algorithm X.
>>> grid = [
... [5... | python |
import unittest
from game_classes import Card
class TestCard(unittest.TestCase):
def test_init(self):
test_card = Card()
self.assertEqual(test_card.counter, 0)
self.assertEqual(len(test_card.selected_numbers), 15)
self.assertEqual(len(test_card.card), 3)
def test_print_card(se... | python |
# An empty class has a dictionary that ...
# holds the attributes of the object.
class A(object):
pass
A = A()
A.__dict__ = {
'key11': 1,
'key2': 2,
}
A.__dict__['key2'] = 3
print(A.__dict__['key2']) # 3 | python |
qtde = int(input('Qual a Qtde: '))
valor = float(input('Qual valor unitário desse produto: '))
preco_total = qtde * valor
print('O preço total é: {}'.format(preco_total)) | python |
"""Application settings."""
import os
import pydantic
class Settings(pydantic.BaseSettings):
"""Main application config.
It takes settings from environment variables.
"""
sqlalchemy_uri: str = os.environ['SQLALCHEMY_URI']
import_token: str = os.environ['AUTH_IMPORT_TOKEN']
| python |
import math
import requests
from typing import Tuple, List
AUTH_KEY = 'GOOGLE API KEY'
PI = math.pi
LatLng = Tuple[float, float]
Polygon = List[LatLng]
"""
Various mathematical formulas for use in Google's isLocationOnEdge and containsLocation algorithms.
Unless otherwise specified all math utilities have be... | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: streamlit/proto/DeckGlJsonChart.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symb... | python |
import os
def skip_if_environ(name):
if name in os.environ:
def skip_inner(func):
return lambda x: None
return skip_inner
def inner(func):
return func
return inner
| python |
from selenium import webdriver
import pandas as pd
import time
import os
# load product file
product = pd.read_csv('../dataset/glowpick_products.csv')
# urls
product_urls = product.product_url.unique()
url = 'https://www.glowpick.com'
# driver
driver = webdriver.Chrome()
# information dataframe
in... | python |
import os
import sys
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(PROJECT_DIR)
sys.path.append(os.path.dirname(BASE_DIR))
SECRET_KEY = '@$n=(b+ih211@e02_kup2i26e)o4ovt6ureh@xbkfz!&@b(hh*'
DEBUG = True
ALLOWED_HOSTS = []
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
INSTA... | python |
from django import forms
from .models import AddressEntry
class AddressEntryForm(forms.ModelForm):
class Meta:
model = AddressEntry
fields = [
'address',
]
| python |
"""
Lines 5 and 6 were adapted from SO code:
http://stackoverflow.com/questions/4383571/importing-files-from-different-folder-in-python
"""
import sys
sys.path.insert(0, '..')
""" END """
import main as program
import pytest
def test_int_0():
assert '0' == program._get_binary(0,1)
def test_int_5():
assert '... | python |
from enum import Enum, auto
class DatabaseActionType(Enum):
WRITE_DATA_STORAGE = auto() # Writes do not require a response on the request
WRITE_STORAGE_INDEX = auto()
READ_CONNECTED_DEVICES = auto() # Reads need response to get requested data
READ_DEVICE = auto() # RPC CALL
DELETE_OLD_DATA = auto() | python |
import os
import imp
import setuptools
version = imp.load_source("ssh2.version", os.path.join("ssh2", "version.py")).version
setuptools.setup(
name="python-ssh",
version=version,
packages=setuptools.find_packages(include=["ssh2", "ssh2.*"]),
package_dir={"ssh2": "ssh2"},
license="MIT",
autho... | python |
#!/usr/bin/env python3
"""Demo on how to run the simulation using the Gym environment
This demo creates a SimRearrangeDiceEnv environment and runs one episode using
a dummy policy.
"""
from rrc_example_package import rearrange_dice_env
from rrc_example_package.example import PointAtDieGoalPositionsPolicy
def main():... | python |
#!/usr/bin/python3
#
# Copyright (c) 2019-2021 Ruben Perez Hidalgo (rubenperez038 at gmail dot com)
#
# 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 requests
from bs4 import BeautifulSoup
import os
from os ... | python |
"""
Copyright 2016 Stephen Boyd, Enzo Busseti, Steven Diamond, BlackRock 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 appl... | python |
# Generated by Django 3.2.1 on 2021-05-09 13:39
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Customer',
fields=[
('id', models.BigAutoFi... | python |
from .BaseNeuralBatch import BaseNeuralBatch
from ..nu import v1
from .. import Ports
import numpy as np
class CubicBatch(BaseNeuralBatch):
def __init__(
self,
name,
parent,
cell_pos,
shape,
unit_distance,
nu_type=v1,
... | python |
from datetime import datetime
import discord
from discord.ext import commands
class cat_debug(commands.Cog, name="Debug commands"):
"""Documentation"""
def __init__(self, bot):
self.bot = bot
@commands.command()
async def tell_me_about_yourself(self, ctx):
print(
f"[{dat... | python |
'''This module computes '''
import argparse
import csv
import io
import os.path
from datetime import datetime
from urllib.request import urlopen
from stockjournal.operator import gmean
csv_header = "Date,Open,High,Low,Close,Volume,Adj Close"
parser = argparse.ArgumentParser(description='Stock stats tool using data \... | python |
# Author: Smit Patel
# Date: 25/07/2018
# File: chatbot_trainer.py
# Licence: MIT
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
import os
bot = ChatBot('Bot')
bot.set_trainer(ListTrainer)
while True:
message = input('You:')
if message.strip() !=... | python |
#!/usr/bin/python3
#
'''
### Desafio de request de url ###
Extrair o nono e o quarto campos do arquivo CSV
sobre região de influencia das Cidades
Ignorar a primeira linha que é o cabechalho do arquivo
dados = entrada.read().decode('latin1')
Arquivo IBGE esta no formato ISO-8859-1 (aka latin1)
Essa linha baixa o arqui... | python |
class TennisGame():
def __init__(self, first_player_name="player1", second_player_name="player2"):
self.first_player_name = first_player_name
self.second_player_name = second_player_name
self.first_player_score = 0
self.second_player_score = 0
@property
def first_player_sco... | python |
# @Time : 2020/11/14
# @Author : Gaole He
# @Email : hegaole@ruc.edu.cn
# UPDATE:
# @Time : 2020/12/3
# @Author : Tianyi Tang
# @Email : steventang@ruc.edu.cn
# UPDATE
# @Time : 2021/4/12
# @Author : Lai Xu
# @Email : tsui_lai@163.com
"""
textbox.evaluator.bleu_evaluator
####################################... | python |
import torch
import numpy as np
import pandas as pd
from os.path import join
from pathlib import Path
from torch.utils.data import Dataset
from torch.nn.utils.rnn import pad_sequence
class DSet(Dataset):
''' This is the WSJ parser '''
def __init__(self, path, split):
# Setup
self.path = path
... | python |
#!/usr/bin/env python
import astropy.units as u
__all__ = ['toltec_info', ]
toltec_info = {
'instru': 'toltec',
'name': 'TolTEC',
'name_long': 'TolTEC Camera',
'array_physical_diameter': 127.049101 << u.mm,
'fov_diameter': 4. << u.arcmin,
'fg_names': ['fg0', 'fg1', 'fg2', 'fg3'],
'fg0'... | python |
"""\
Examples
For the development.ini you must supply the paster app name:
%(prog)s development.ini --app-name app --init --clear
"""
from pyramid.paster import get_app
import atexit
import logging
import os.path
import select
import shutil
import sys
EPILOG = __doc__
logger = logging.getLogger(__name__)
def... | python |
import logging
import os.path
DEFAULT_LOG_PATH = None
DEFAULT_LOG_DIR = os.path.join(os.path.dirname(__file__), "logs")
if not os.path.exists(DEFAULT_LOG_DIR):
try:
os.mkdir(DEFAULT_LOG_DIR)
except OSError:
DEFAULT_LOG_DIR = None
if DEFAULT_LOG_DIR:
DEFAULT_LOG_PATH = os.path.join(DEFAULT_L... | python |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# Hea... | python |
# coding: utf-8
from mhw_armor_edit.ftypes import StructFile, Struct
class WpDatEntry(Struct):
STRUCT_SIZE = 65
id: "<I"
unk1: "<H"
base_model_id: "<H"
part1_id: "<H"
part2_id: "<H"
color: "<B"
tree_id: "<B"
is_fixed_upgrade: "<B"
crafting_cost: "<I"
rarity: "<B"
kire_... | python |
# Generated by Django 3.2.4 on 2021-06-20 12:31
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('auth... | python |
from setuptools import setup
from os import path
with open('README.md') as f:
long_description = f.read()
setup(
name='itrcnt',
module='itrcnt.py',
version='0.1.2',
license='BSD',
author='mao2009',
url='https://github.com/mao2009/Python_Counter',
description='Alternative for Range ... | python |
"""
testing for agent's config
"""
import os
import pytest
import yaml
from eha.agent.config import load
@pytest.mark.parametrize('content, envs, result', (
(
"""
foo: 123
bar: 234
""",
{},
{
'foo': 123,
'bar': 234,
}
),
(
"""
foo: 1... | python |
default_app_config = 'kolibri.content.apps.KolibriContentConfig'
| python |
import os
import pandas as pd
def read_parquet(data_path, num_partitions=None, random=False, verbose=True, columns=None):
files = os.listdir(data_path)
if random:
import random
random.shuffle(files)
if num_partitions is None:
num_partitions = len(files)
data = []
n... | python |
#!/usr/bin/env python
import os
import sys
fn_read_keys = None
dn_sstable_keys = None
read_keys = []
key_sstgen = {}
def LoadReadKeys():
global read_keys
print "loading read keys from %s ..." % fn_read_keys
with open(fn_read_keys) as fo:
for line in fo.readlines():
read_keys.append(line.strip().lower())
... | python |
#
# Copyright (c) Sinergise, 2019 -- 2021.
#
# This file belongs to subproject "field-delineation" of project NIVA (www.niva4cap.eu).
# All rights reserved.
#
# file in the root directory of this source tree.
# This source code is licensed under the MIT license found in the LICENSE
#
from typing import Callable, List,... | python |
# Copyright 2016
# Drewan Tech, LLC
# ALL RIGHTS RESERVED
db_user = 'web_service_admin'
db_password = 'web_service_admin'
db_host = 'postgres'
db_port = '5432'
users_to_manage = {'random_matrix':
{'authorized_databases':
['matrix_database'],
'password':
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (C) 2014 Arulalan.T <arulalant@gmail.com>
#
# This file is part of 'open-tamil/txt2ipa' package examples
#
import sys
sys.path.append("../..")
from tamil.txt2ipa.ipaconvert import ipa, broad
from tamil.txt2ipa.transliteration import tam2lat
text = "வணக்கம் தமிழகம் "
... | python |
import tkinter as tk
import tkinter.messagebox as msg
import socket
import configparser
import threading
import time
import os
def warning(message):
msg.showwarning("Предупреждение", message)
def error(message, error=None):
msg.showerror("Ошибка", message)
print(error)
class Server(socket.socket):
d... | python |
import pytest
from text_normalizer.tokenization import replace_bigrams
@pytest.mark.benchmark(group='ivr_convert')
def test_benchmark_replace_synonyms(benchmark, tokenize, benchmark_text):
tokens = list(tokenize(benchmark_text))
benchmark(lambda: list(replace_bigrams(tokens)))
| python |
from product import product
from company import company
from pathlib import Path
# Loading products info
products = []
products_list_file = open(str(Path(__file__).resolve().parent) + "/products_list.txt", "r")
for p in products_list_file:
p = p.replace("\n", "")
p = p.split(",")
products.append(product(... | python |
# Title: Trapping Rain Water
# Link: https://leetcode.com/problems/trapping-rain-water/
import sys
from heapq import heappop, heappush
sys.setrecursionlimit(10 ** 6)
class Solution():
def trap(self, heights: list) -> int:
water = 0
walls = []
for i, height in enumerate(heights):
... | python |
from __future__ import unicode_literals
from django.contrib import admin
from authtools.admin import NamedUserAdmin
from .models import Profile, TokenFirebase
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from import_export.admin import ImportExportModelAdmin
from import_... | python |
from decimal import Decimal
from django.apps import apps
from rest_framework import serializers
from rest_flex_fields import FlexFieldsModelSerializer
from ....checkout.utils import get_taxes_for_checkout
from ....glovo.utils import glovo_get_lowest_price
from ....runningbox.utils import runningbox_order_estimate
from... | python |
import requests
import json
import re
class RestApi(object):
# base_url example http://aaa.co.com/webhdfs
def __init__(self, base_url, username, password):
self.name = "nhso core api" + base_url
self.base_url = base_url
self.username = username
self.password = password
... | python |
import threading
import time
import socket
import sys
import copy
import pprint
pp = pprint.PrettyPrinter(indent=2)
# global variables
turn = 1
convergence = 0
round = 1
update_occured = 0
nodes = {
"0" : {"name": "A", "index": 0, "port": 10000, "update": 1},
"1" : {"name": "B", "index": 1, "port": 10001, "up... | python |
#!/usr/bin/env python
"""Setup script for the package."""
import os
import sys
import setuptools
PACKAGE_NAME = 'api'
MINIMUM_PYTHON_VERSION = 3, 6
def check_python_version():
"""Exit when the Python version is too low."""
if sys.version_info < MINIMUM_PYTHON_VERSION:
sys.exit("Python {}.{}+ is r... | python |
# Back compatibility -- use broad subdirectory for new code
from bcbio.broad.metrics import *
| python |
import copy
import torch
import numpy as np
from PIL import Image
from torchvision import transforms
class BlackBoxAttack(object):
MEAN = np.array([0.485, 0.456, 0.406])
STD = np.array([0.229, 0.224, 0.225])
def __init__(self, model, input_size=224, epsilon=16, num_iters=10000,
early_s... | python |
import RPi.GPIO
import sys
import random
sys.path.append("../../")
from gfxlcd.driver.nju6450.gpio import GPIO
from gfxlcd.driver.nju6450.nju6450 import NJU6450
RPi.GPIO.setmode(RPi.GPIO.BCM)
def hole(o, x, y):
o.draw_pixel(x+1, y)
o.draw_pixel(x+2, y)
o.draw_pixel(x+3, y)
o.draw_pixel(x+1, y + 4)
... | python |
from utils.functions import get_env
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'HOST': get_env("POSTGRES_HOST", "db"),
'PORT': get_env("POSTGRES_PORT", "5432"),
'NAME': get_env("POSTGRES_DB"),
'USER': get_env("POSTGRES_USER"),
'PASS... | python |
# Copyright 2022 The HuggingFace Team. 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 applicabl... | python |
# Copyright 2014 Hewlett-Packard Development Company, L.P.
# 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... | python |
import tensorflow as tf
class Model:
def __init__(self, image_size = 224, n_classes = 16, fc_size = 1024):
self.n_classes = n_classes
tf.compat.v1.disable_eager_execution()
self.dropout = tf.compat.v1.placeholder(tf.float32, name="dropout_rate")
self.input_images = tf.compat.v1.... | python |
'''
based on the noise model of https://github.com/paninski-lab/yass
'''
import numpy as np
from scipy.spatial.distance import pdist, squareform
import os
import torch
def make_noise(n, spatial_SIG, temporal_SIG):
"""Make noise
Parameters
----------
n: int
Number of noise events to generate
... | python |
import matplotlib.pyplot as plt
import numpy as np
p_guess = [0.5,0.55,0.6,0.7]
repeat_experiment = 30
n = 32
k = 5
plt.title('n = 32, k = 5')
plt.xlabel("Number of CRPs", fontsize=12)
plt.ylabel("Accuracy (x100%)", fontsize=12)
crps = np.load('./xorpuf'+str(k)+'_n'+str(n)+'_reps'+str(repeat_experiment... | python |
# Copyright 2013 NEC Corporation
# 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 ... | python |
# -*- coding: UTF-8 -*-
# @yasinkuyu
import sys
import time
import config
from BinanceAPI import *
# trader.py --quantity -- symbol --profit --wait_time
# ex: trader.py 1 IOTABTC 1.3 1
#int(sys.argv[0]) #quantity
#sys.argv[1] #symbol
#sys.argv[2] #percentage of profit
#sys.argv[3] #wait_time
TEST_MODE = False
PRO... | python |
from typing import List, Dict, Optional, Set, Any, Tuple, Type
from Dataset import GraphDataset
from Models.EmbeddingLayers import EmbeddingLayer
from Models.GnnLayers import GCNLayer, GATLayer, HGCNLayer, IHGNNLayer
from Models.PredictionLayers import HemPredictionLayer
from Helpers.Torches import *
from Helpers.Glob... | python |
import matplotlib.pyplot as plt
import numpy as np
# Define a main() function that prints a data statistics.
def main():
data = np.loadtxt('data/populations.txt')
year, hares, lynxes, carrots = data.T # trick: columns to variables
plt.axes([0.1, 0.1, 0.5, 0.8])
plt.plot(year, hares, year, lynxes, ye... | python |
from ..datapack import DataPack
from ..logging import logging
from .data_utils import make_coord_array
import numpy as np
import os
import astropy.time as at
def make_example_datapack(Nd,Nf,Nt,pols=None, time_corr=50.,dir_corr=0.5*np.pi/180.,tec_scale=0.02,tec_noise=1e-3,name='test.hdf5',clobber=False):
logging.in... | python |
#! /usr/bin/env python
# If you ever need to modify example JSON data that is shown in the sampleData.js file, you can use this script to generate it.
import sys
import os
from pathlib import Path
sys.path.append(str(Path(os.path.dirname(__file__)).parent))
import json
from cloudsplaining.shared.validation import check... | python |
#!/usr/bin/env python3
#
# id3v1.py
# From the stagger project: http://code.google.com/p/stagger/
#
# Copyright (c) 2009-2011 Karoly Lorentey <karoly@lorentey.hu>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following con... | python |
a = np.arange(30).reshape((2,3,5))
a[a>5] | python |
import os
import sys
from cseg import cut_file
msr_test = 'corpus/msr_test.utf8'
msr_test_gold = 'corpus/msr_test_gold.utf8'
msr_out = ['output/msr_test_2_add1', 'output/msr_test_2_ad', 'output/msr_test_2_kn', 'output/msr_test_1',
'output/msr_test_2_add1_hmm', 'output/msr_test_2_ad_hmm',
'output/... | python |
"""
created by ldolin
"""
"""
正则表达式
动机:
1.经常性文本处理
2.文本内容的快速搜索,定位,提取比较复杂
3.产生正则表达式
定义:
正则即是文本的高级匹配模式,提供搜索,替代,查找等功能,
本质是由一系列特殊符号和字符组成的字符串
特点:
1.方便检索和修改文本内容的操作
2.支持多种编程语言
3.灵活多样
目标:
1.能够看懂并编写基本简单的正则表达式
2.能够使用python操作正则表达式
设... | python |
from datetime import timezone, timedelta, datetime, date, time
import databases
import pytest
import sqlalchemy
import ormar
from tests.settings import DATABASE_URL
database = databases.Database(DATABASE_URL, force_rollback=True)
metadata = sqlalchemy.MetaData()
class DateFieldsModel(ormar.Model):
class Meta:... | python |
import json
import os
from pathlib import Path
import shutil
from appdirs import user_data_dir
from elpis.engines.common.objects.fsobject import FSObject
from elpis.engines.common.utilities import hasher
from elpis.engines.common.utilities.logger import Logger
from elpis.engines.common.errors import InterfaceError
fro... | python |
import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader, sampler
import h5py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from itertools import cycle
import seaborn as sns
from matplotlib.colors import ListedColormap
import matplotlib as mpl
from matplotlib.font_man... | python |
from django import forms
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Ore
class CreateNewOreupdate(forms.ModelForm):
class Meta:
model = Ore
fields = ('oret','... | python |
import pytest
import pandas as pd
from hypper.data import (
read_banking,
read_breast_cancer_data,
read_churn,
read_congressional_voting_records,
read_german_data,
read_hr,
read_phishing,
read_spect_heart,
)
@pytest.mark.parametrize(
"read_fun",
[
read_banking,
... | python |
"""Base camera module
This file contains the class definition for the Camera class on which
all subsequent cameras should be based on.
"""
from __future__ import print_function, division
import numpy.random as npr
from .log import logger
# from .ringbuffer import RingBuffer
from .camprops import CameraProperties
# f... | python |
from .copy import files_copy
from .delete import files_delete
from .download import files_download
from .history import files_history
from .import_files import files_import
from .list import files_list
from .mkdir import files_mkdir
from .move import files_move
from .pems_delete import files_pems_delete
from .pems_list... | python |
import turtle
def draw_piece(row, col, color):
x = offset_x + 25 + col * 2 * (radius + gap)
y = offset_y - 25 - row * 2 * (radius + gap)
t.up()
t.home()
t.goto(x,y)
t.down()
t.color(color)
t.begin_fill()
t.circle(radius)
t.end_fill()
def draw(x, y):
global board, rb, winner
col = int((x - ... | python |
from machine.tokenization import ZwspWordDetokenizer
def test_detokenize_empty() -> None:
detokenizer = ZwspWordDetokenizer()
assert detokenizer.detokenize([]) == ""
def test_detokenize_space() -> None:
detokenizer = ZwspWordDetokenizer()
assert (
detokenizer.detokenize(["គែស", "មាង់", " ", ... | python |
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
# Copyright (C) 2017-2020 German Aerospace Center (DLR) and others.
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 2.0 which is available at
# https://www.eclipse.org/legal/epl-2.... | python |
#!/bin/python3
# name: vignette_testing.py
# author: nbehrnd@yahoo.com
# license: 2019, MIT
# date: 2019-12-02 (YYYY-MM-DD)
# edit: 2019-12-03 (YYYY-MM-DD)
#
""" Probe for gnuplot palettes' differences
Script 'palette_decomposition.py' provides rapid access to visualize
the channels of R, G, B of RG... | python |
from learnml.metrics import mean_squared_error
import numpy as np
import unittest
class Test(unittest.TestCase):
def test_mean_squared_error(self):
expected_results = [0, 1]
for i, y_pred in enumerate(np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]])):
self.assertEqual(expected_results[i],... | python |
# -*- coding: utf-8 -*-
import json
from TM1py.Objects.User import User
from TM1py.Services.ObjectService import ObjectService
class SecurityService(ObjectService):
""" Service to handle Security stuff
"""
def __init__(self, rest):
super().__init__(rest)
def create_user(self, user):
... | python |
from abc import abstractmethod
from typing import Callable, Tuple
import numpy as np
from ._func import Func
class OriFunc(Func):
@abstractmethod
def __call__(self, t: float) -> float:
"""
:param t: Time.
:return: Orientation in degrees.
"""
pass
class Tangential(Or... | python |
a = ["1", 1, "1", 2]
# ex-14: Remove duplicates from list a
a = list(set(a))
print(a)
# ex-15: Create a dictionary that contains the keys a and b and their respec
# tive values 1 and 2 .
my_dict = {"a":1, "b":2}
print(my_dict)
print(type(my_dict))
# Add "c":3 to dictionary
my_dict["c"] = 3
print(my_dict)
my_dict2... | python |
from task_grounding.task_grounding import TaskGrounding, TaskGroundingReturn, TaskErrorType
from database_handler.database_handler import DatabaseHandler
import unittest
from unittest.mock import Mock
from ner_lib.ner import EntityType
from ner_lib.command_builder import Task, TaskType, ObjectEntity, SpatialType, Spati... | python |
# Generated by Django 3.2.5 on 2022-01-24 05:22
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('metrics', '0002_initial'... | python |
from itertools import count
CARD_PUBLIC_KEY = 14205034
DOOR_PUBLIC_KEY = 18047856
def transform_one_step(value, subject_number):
return (value * subject_number) % 20201227
def transform(loop_size, subject_number=7):
value = 1
for _ in range(loop_size):
value = transform_one_step(value, subject_... | python |
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from __future__ import unicode_literals
import swapper
from factory import (
Sequence,
SubFactory,
post_generation,
)
from accelerator.tests.factories.core_profile_factory import CoreProfileFactory
from accelerator.tests.factories.expert_category_fac... | python |
from typing import Callable, Dict, Tuple, Text
from recommenders.datasets import Dataset
import numpy as np
import tensorflow as tf
import tensorflow_recommenders as tfrs
from pathlib import Path
SAVE_PATH = Path(__file__).resolve().parents[1] / "weights"
class RankingModel(tfrs.models.Model):
def __init__(
... | python |
"""Convert Noorlib library html to OpenITI mARkdown.
This script subclasses the generic MarkdownConverter class
from the html2md module (based on python-markdownify,
https://github.com/matthewwithanm/python-markdownify),
which uses BeautifulSoup to create a flexible converter.
The subclass in this module, NoorlibHtml... | python |
import pytest
from bot.haiku.models import HaikuMetadata
@pytest.fixture()
def haiku_metadata(data_connection):
"""Create a haiku metadata."""
HaikuMetadata.client = data_connection
return HaikuMetadata
| python |
#!/usr/bin/env python3
import argparse
import os
import re
import sys
from itertools import product
import h5py
import numpy as np
if __name__ == "__main__":
ORIG_WIDTH = 512
ORIG_NUM_PARAMS = 4
parser = argparse.ArgumentParser()
parser.add_argument("hdf5_files", nargs="*",
h... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author : EINDEX Li
@File : __init__.py.py
@Created : 26/12/2017
"""
from aiospider.tools.singleton import OnlySingleton
class AIOSpider(metaclass=OnlySingleton):
def __init__(self, loop=None):
self.config = dict()
self.loop ... | python |
# @author: Michael Vorotyntsev
# @email: linkofwise@gmail.com
# @github: unaxfromsibiria
import logging
import string
from enum import Enum
from hashlib import sha256, md5
from random import SystemRandom
_cr_methods = {
'sha256': sha256,
'md5': md5,
}
class ServiceGroup(Enum):
service = 1
server = 2... | python |
from decimal import *
N = int(input())
print(int(int((N-1)*N)/2))
| python |
# -*- coding: utf-8 eval: (yapf-mode 1) -*-
#
# January 13 2019, Christian E. Hopps <chopps@labn.net>
#
# Copyright (c) 2019, LabN Consulting, L.L.C.
# 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 ob... | python |
from pyrete.settings import settings
from . import (
get_attr_name,
ParserLiterals,
)
class DataLayer(object):
"""
The DataLayer is responsible for fetching data from the database.
It parses the provided rules and fetches only the data required for running the rules.
Example:
.. code-bl... | python |
#!/usr/bin/env python
"""
Raven-django
============
Raven-Django is a Raven extension that provides full out-of-the-box support
for `Django <https://www.djangoproject.com>`_ framework.
Raven itself is a Python client for `Sentry <http://www.getsentry.com/>`_.
"""
# Hack to prevent stupid "TypeError: 'NoneType' object... | python |
from typing import List
import allure
from markupsafe import Markup
from overhave.entities import OverhaveDescriptionManagerSettings
class DescriptionManager:
""" Class for test-suit custom description management and setting to Allure report. """
def __init__(self, settings: OverhaveDescriptionManagerSetti... | python |
# Copyright 2021 The Pigweed 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.