content stringlengths 5 1.05M |
|---|
from ...hek.defs.eqip import *
#import and use the open saucified obje attrs
from .obje import *
# replace the object_type enum one that uses
# the correct default value for this object
obje_attrs = dict(obje_attrs)
obje_attrs[0] = dict(obje_attrs[0], DEFAULT=3)
eqip_attrs = dict(eqip_attrs)
eqip_attrs[1]... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from mephisto.abstractions.blueprint import (
Blueprint,
OnboardingRequired,
BlueprintArgs,
SharedTaskSt... |
import os
from typing import Any, Dict
name: str
env: Dict[Any, Any] = dict(os.environ)
def set_name(new_name: str) -> None:
global name
name = new_name
def set_env(env_to_set: dict) -> None:
global env
env.update(env_to_set)
def unset_env(env_to_unset: dict) -> None:
for k in env_to_unset:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
import sys
from pathlib import Path
DIR = Path(__file__).resolve().parent
ROOT_DIR = DIR.parent
sys.path.append(str(ROOT_DIR))
sys.path.append(str(ROOT_DIR.parent))
from html_parsing.ru_wiktionary_org__wiki__Список_частотных_слов_русского_язык... |
"""
Pyredditchatbot exception classes
"""
class QuotesNotFoundError(Exception):
"""
Raised when Quotes are not be discovered correctly.
"""
pass
class BotCredentialError(Exception):
"""
Raised for any authorisation/authentication error raised by PRAW.
"""
pass
|
# Generated by Django 2.2.18 on 2021-04-04 19:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('permission', '0002_auto_20210404_0258'),
]
operations = [
migrations.AlterField(
model_name='permission',
name='rol... |
def todos_params(*args, **kwargs):
print(f'args: {args}')
print(f'kwargs: {kwargs}')
if __name__ == '__main__':
todos_params('a', 'b', 'c')
todos_params(1, 2, 3, legal=True, valor=12.99)
todos_params('Ana', False, [1, 2, 3], tamanho='M', fragil=False) |
basePath = '/Raid1/Illustris/TNG/'
import numpy as np
from illustris_python.snapshot import loadSubhalo
from illustris_python.groupcat import loadSubhalos
def specific_angular_momentum(x, v, m):
"""
specific angular momentum of a group of particles
Parameters
----------
x : array_li... |
import os
import configparser
def load_config(config_file_path=None):
"""Load a ComptoxAI configuration file from the location specified.
If the user does not provide a value for `config_file_path`, we will try to
load a config file from the default location:
Unix-like: ~/.comptoxai.cfg
Wind... |
from django.contrib import admin
from .models import *
class user_actionAdmin(admin.ModelAdmin):
list_display = ["user","last_seen","action"]
list_filter = ["user","action","last_seen"]
search_fields = ["user","action","last_seen"]
class Meta:
model = user_action
class user_recordAdmin(admin.M... |
"""
"""
import gdsfactory as gf
from gdsfactory.add_pins import add_pins_triangle
from gdsfactory.component import Component
def test_pins_custom() -> Component:
"""You can define the `pins_function` that we use to add markers to each port"""
c = gf.components.straight(length=11.1)
add_pins_triangle(comp... |
# Copyright (c) 2021. Slonos Labs. All rights Reserved.
|
noun_suffix = ['াই', 'াটা', 'াটাই', 'াটাও', 'াটাকে', 'াটাকেও', 'াটি', 'ামি', 'িক', 'িকা', 'ের', 'েরই', 'েরও', 'েরা',
'েরাও', 'েরে', 'ও', 'আবলি', 'আলা', 'এরা', 'এরে', 'কারী', 'কুলের', 'কে', 'কেই', 'কেও', 'খানা', 'খানি',
'গণ', 'গণে', 'গন', 'গাছা', 'গাছি', 'গিরি', 'গুচ্ছ', 'গুলা', 'গুলি', 'গু... |
# Generated by Django 3.1 on 2020-08-31 14:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('NesaraTours', '0002_auto_20200831_0946'),
]
operations = [
migrations.AddField(
model_name='tour',
name=... |
from django.shortcuts import render, redirect
from .forms import Register, ProfileInfo
from django.contrib.auth import authenticate, login
from .models import Profile
from book_listing.models import Book_List
from forum.models import Post
# from django.contrib.auth.models import User
def register(request):... |
import maya.cmds as cmds
import sys
from PySide2 import QtWidgets, QtCore, QtGui
import shiboken2
import maya.OpenMayaUI as apiUI
################################################################################
#Base Attribute Widget
################################################################################
c... |
print('Задачи на циклы и оператор условия')
print()
print('Задача 1')
print('Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована.')
print ('Решение:')
for i in range(1,6):
print ('Строка №', i, '- 0')
continue
print()
print('Задача 2')
print('Пользователь в цикле вводит ... |
from multiprocessing.sharedctypes import Value
import unittest
class RomanNumeralConverter:
def __init__(self, roman_numeral) -> None:
self.roman_numeral = roman_numeral
self.digit_map = {
"M": 1000,
"D": 500,
"C": 100,
"L": 50,
"X": 10,
... |
"""
Kubernetes operator example: all the features at once (for debugging & testing).
"""
import pprint
import time
import kopf
import pykube
import yaml
# Marks for the e2e tests (see tests/e2e/test_examples.py):
E2E_CREATE_TIME = 5
E2E_DELETE_TIME = 1
E2E_TRACEBACKS = True
try:
cfg = pykube.KubeConfig.from_serv... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from astropy.nddata import FlagCollection
def test_init():
FlagCollection(shape=(1, 2, 3))
def test_init_noshape():
with pytest.raises(Exception) as exc:
FlagCollection()
assert exc.value.args[0] ... |
# _*_ coding: utf-8 _*_
#@Time : 2020/8/18 下午 01:39
#@Author : cherish_peng
#@Email : 1058386071@qq.com
#@File : hsms.py
#@Software : PyCharm
from .core.secsgem import SecsGem
from .core.hsms_if import Hsms_If
from .core.secsmessage import SecsMessage
from .core.connectionstate import ConnectionState
... |
def moveAllZerosToRight(arr):
count = 0
for i in range(len(arr)):
if arr[i] != 0:
arr[count] = arr[i]
count += 1
while count < len(arr):
arr[count] = 0
count += 1
return arr
print(moveAllZerosToRight([1,0,0,2,3,0,6,7])) |
# Copyright 2021 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import numpy as np
import time
import chirpz
import chirpz.cychirpz
import pandas as pd
import cPickle as pickle
from ruffus import *
ITERS = 20
@files(None, "benchmark.pickle")
def run(infile, outfile):
rows = []
for FFT_N in [512, 1024, 2048, 4096]:
for N in [64, 128, 256, 512]:
for ... |
"""
The module with CLI code that handles the `hopla support-development` command.
"""
import logging
import click
import requests
from hopla.hoplalib.common import GlobalConstants
from hopla.hoplalib.http import UrlBuilder, RequestHeaders
from hopla.hoplalib.requests_helper import get_data_or_exit
log = logging.get... |
import mimetypes
from abc import abstractmethod
from posixpath import basename, dirname, join, realpath
from datetime import date, datetime
from typing import Union
from requests import RequestException
from transip_stack.exceptions import StackException
class StackNode:
"""
Base class of a STACK node
A... |
from flask_login import LoginManager
from . import app
from .database import session, User
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login_get'
login_manager.login_message_category = 'danger'
@login_manager.user_loader
def load_user(id):
return session.query(User).get(i... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2019-01-17 22:51
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import src.apps.uploads.models
import easy_thumbnails.fields
class Migration(migrations.Migration... |
"""
Decision tree classifiers are attractive models if we care about it interpretability, As the
name decision tree suggests, we can think of this model as breaking down our data by making
decision based on asking a series of questions.
""" |
def add_time(start, duration, day = None):
# can remove later on, this is for testing. This parameter will be given in the function
start_hm = start.split(":")
start_hr = int(start_hm[0])
start_hm = start_hm[1].split(" ")
start_min = int(start_hm[0])
start_ampm = start_hm[1]
# c... |
str_n = input("please enter a number: ")
n = int(str_n)
summation = int(n* (n+1) / 2)
print("summation of 1..",n, "is equal to", summation) |
# This file is part of the Indico plugins.
# Copyright (C) 2017 - 2022 Max Fischer, Martin Claus, CERN
#
# The Indico plugins are free software; you can redistribute
# them and/or modify them under the terms of the MIT License;
# see the LICENSE file for more details.
import json
import time
from urllib.parse import u... |
if __name__ == "__main__":
import time
import os
import sys
sys.path.append("../../")
import pypipegraph as ppg
ppg.new_pipegraph()
def run_long():
time.sleep(20)
raise ValueError()
def run_short():
time.sleep(5)
with open("short.dat", "wb") as op:
... |
# action - PROBE
def action_probe():
"""Формирует и возвращает сообщение PROBE"""
msg = {"action": "probe", "time": "<unix timestamp>"}
return msg
# action - MSG
def action_msg(message, to="#all"):
"""Функция формирует сообщение MSG"""
msg = {"action": "msg", "time": "<unix timestamp>", "to": to, ... |
from dbnd import Config, parameter
class PostgresConfig(Config):
_conf__task_family = "postgres"
auto_log_pg_histograms = parameter(
description="Automatically log all postgres table histograms", default=True
)[bool]
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from math import log10
from torch.optim import lr_scheduler
import pdb
def get_nonlinearity(name):
"""Helper function to get non linearity module, choose from relu/softplus/swish/lrelu"""
if name == 'relu':
return nn... |
import bpy
from bpy.props import *
from bpy.types import Node, NodeSocket
from arm.logicnode.arm_nodes import *
class GetWorldNode(Node, ArmLogicTreeNode):
'''Get world node'''
bl_idname = 'LNGetWorldNode'
bl_label = 'Get World'
bl_icon = 'NONE'
property0: EnumProperty(
items = [('right', ... |
# -*- coding:utf8 -*-
from phoenixdb import connect
from .function import debug
import pymysql
from tool_yy.config import dbconfig as pymysql_config_origin, phoenix_db_config as dbconfig
# noinspection PyPep8Naming,PyMethodMayBeStatic,PyBroadException,PyStatementEffect
class DBConfig(object):
"""
PS: If you ... |
# -*- coding: utf-8 -*-
'''
Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk − Pj| is minimised; what is the value of D?
'''
import timeit
import itertools
start = timeit.default_timer()
def euler_44():
pent = {i * ((3 * i) - 1) / 2 for i in xrange(... |
from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='The Beer Type Prediction project uses a custom neural network to predict the type of beer based on a user's rating criteria',
author='Sean Williams',
license='',
)
|
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'circle_test',
'USER': 'ubuntu',
'PASSWORD': ''
}
}
SAM_API_KEY = ''
# SECURITY WARNING: keep the secret key used in production secret!
# change this before deploying to your own server!
SECR... |
#!/usr/bin/env python
import sys
sys.path.append(
'dist/carla-0.9.0-py%d.%d-linux-x86_64.egg' % (sys.version_info.major,
sys.version_info.minor))
import carla
import os
import random
import time
# This function is here because this functionality haven't been p... |
import pytest
from nbformat.v4 import new_notebook
from ...preprocessors import SaveCells, OverwriteCells
from ...api import Gradebook
from ...utils import compute_checksum
from .base import BaseTestPreprocessor
from .. import (
create_grade_cell, create_solution_cell, create_grade_and_solution_cell,
create_l... |
#!-*- conding: utf8 -*-
#coding: utf-8
"""
Aluno: Gabriel Ribeiro Camelo
Matricula: 401091
"""
import math # Matemática
import re # expressões regulares
# Funções acessórias
#calcula a distancia entre os pontos
dist = lambda x1, y1, z1, w1 , x2, y2, z2, w2: math.sqrt((x2-x1)**2 + (y2-y1)**2 + (z2-z1)**2 + ... |
# coding: utf-8
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2019-Present Datadog, Inc.
from __future__ import absolute_import
import sys
import unittest
im... |
import requests
import logging
import os
from scraper import Scraper
class Pumper():
def __init__(self):
self.access_token = os.getenv("PARTICLE_ACCESS_TOKEN")
self.device_id = os.getenv("PARTICLE_DEVICE_ID")
self.pump_rate = float(os.getenv("PUMP_RATE"))
self.consumption_rate = flo... |
"""
helper functions for the module reader_rpg
"""
import datetime as dt
import numpy as np
from mwr_raw2l1.errors import UnknownFlagValue, WrongInputFormat
def interpret_time(time_in):
"""translate the time format of RPG files to datetime object"""
# offset between RPG and POSIX time in seconds. Care: date... |
"""Kata url: https://www.codewars.com/kata/5bb904724c47249b10000131."""
from typing import List
def points(games: List[str]) -> int:
point: int = 0
for match in games:
y, x = match.split(':')
if x == y:
point += 1
continue
if x < y:
point += 3
... |
import re
from django.test.testcases import TestCase
from sugar.templatetags.pygment_tags import pygmentize
class PygmentTagsTestCase(TestCase):
def _html_stripper(self, input):
"""Quick and dirty HTML tag stripper & whitespace cleaner not intended
for serious use"""
return re.sub('\s+', ... |
import tempfile
import unittest
import numpy
from keras.callbacks import TensorBoard, CSVLogger, ModelCheckpoint
from keras.backend.tensorflow_backend import get_session
from sourced.ml.algorithms.id_splitter.nn_model import prepare_devices
from sourced.ml.algorithms.id_splitter.pipeline import build_schedule, prepar... |
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from tableschema import Field
from goodtables.checks.missing_value import missing_value
import goodtables.cells
# Check
def test_check_missing_... |
import keras
from keras.applications import InceptionResNetV2
from keras.layers import Dense, Dropout, GlobalAveragePooling2D
from model_cx.load_data import load_data
from keras.callbacks import CSVLogger, ModelCheckpoint, ReduceLROnPlateau, LearningRateScheduler, EarlyStopping
import numpy as np
from keras imp... |
"""GCP simple pipeline
This package contains the modules for deploying a simple pipeline on GCP.
It is part of the educational repositories (https://github.com/pandle/materials)
to learn how to write stardard code and common uses of the CI/CD.
Package contents ..
>>> import gcp_simple_pipeline
>>> help(gcp_... |
import inspect
import math
from math import exp, log
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import exponential, lognormal, normal, uniform
from scipy.stats import loguniform
class LC(object):
"""
A class to generate gamma-ray burst light curves (GRB LCs) using a pulse avalance mo... |
# parameters from preprocessing
# Set the method to True if
opt_abbreviation_replacement = True
opt_emphaszie_punctuation = False
opt_clean_hastag = True
opt_emoji_translation = False
opt_remvoe_number = True
opt_emphasize_pos_and_neg_words = False
opt_spelling_correction = True
opt_remove_stopwords = False
opt_stemm... |
from base import auth
import threading
from base import settings, logger
from base.constants import DEFAULT_MIN_TIMEOUT, DEFAULT_MAX_TIMEOUT
from base.mqtt_connector import MqttConnector
from base.skeleton import Webhook, Router
from base.solid import implementer
import asyncio
import multiprocessing as mp
from queue i... |
from rhba_utils import BotUtils, WindowCapture, Vision, HsvFilter
import os
import cv2
import time
import numpy as np
os.chdir(os.path.dirname(os.path.abspath(__file__)))
class EnemyDetect():
def __init__(self) -> None:
pass
def find_enemy(self, gamename, all=False):
othr_plyr_vision = Vision... |
#!/usr/bin/python3
from setuptools import setup, find_packages
setup(name='jkonet',
version='1.0',
description='Proximal Optimal Transport Modeling of Population Dynamics',
url='https://github.com/bunnech/jkonet',
author='Charlotte Bunne',
author_email='bunnec@ethz.ch',
license='M... |
from os import system, name
system('cls' if name == 'nt' else 'clear')
dsc = ('''DESAFIO 112:
Dentro do pacote utilidades_cev que criamos no desafio 111,
temos um módulo dado. Crie uma função chamada
leia_dinheiro() que seja capaz de funcionar como a função input(),
mas com uma validação de dados para aceitar apena... |
from arm.logicnode.arm_nodes import *
class RandomColorNode(ArmLogicTreeNode):
"""Generates a random color."""
bl_idname = 'LNRandomColorNode'
bl_label = 'Random Color'
arm_version = 1
def init(self, context):
super(RandomColorNode, self).init(context)
self.add_output('NodeSocketC... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
QSWATBatch
Run QSWATPlus in batch mode using a project file to provide inputs and parameters
-------------------
begin : 2015-10-20
copyright ... |
"""
Problem:
Given the head to a singly linked list, where each node also has a 'random' pointer
that points to anywhere in the linked list, deep clone the list.
"""
from DataStructures.LinkedList import LinkedList, Node
def rand_join(ll: LinkedList, pos1: int, pos2: int) -> None:
pos_source = ll.head
pos_d... |
from abc import ABC, abstractclassmethod
from ghubunix.models.config import Config
class Authenticator(ABC):
"""Abstract class for Authenticators"""
@abstractclassmethod
def authenticate(self):
"""Perform authentication"""
pass
@abstractclassmethod
def store_token(self):
... |
#!/usr/bin/env python
# coding: utf-8
get_ipython().run_line_magic('matplotlib', 'auto')
import pandas as pd
import numpy as np
import imageio
from datetime import datetime, time, timedelta
import random
from matplotlib import pyplot as plt
from io import BytesIO
from PIL import Image
N_INTERVALS = 10 # specifies ho... |
# -*- coding: utf-8 -*-
"""
vb_nmf.py
Variational Bayes NMF
"""
import scipy as sp
from ..bayes import *
def vb_nmf(X, a_w, b_w, a_h, b_h, n_iter=100):
"""
Variational Bayes NMF
変分ベイズ法によるNMF
"""
# initialize
Winit = gamma(x, a_w, b_w/a_w)
Hinit = gamma(x, a_h, b_h/a_h)
Lw = Winit
... |
from django.contrib.auth import get_user_model
from rest_framework import status, permissions
from rest_framework import viewsets
from rest_framework.decorators import action, permission_classes
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, UpdateModelMixin
from rest_framework.response import Re... |
"""
Fast Johnson-Lindenstrauss Transform (FJLT)
http://people.inf.ethz.ch/kgabriel/software.html
"""
from __future__ import division, print_function
from fjlt.random_projection_fast import fast_unitary_transform_fast, fast_unitary_transform_fast_1d, \
inverse_fast_unitary_transform_fast_1d, import_wisdom, export... |
from src import view
from model.structure import earthquake
from model.utils import plot
import cherrypy
class Earthquake:
def index(self):
pass
def response_spectrum(self, **var):
# Prepare view & model object
template = view.lookup.get_template('structure/earthquake_respon... |
# Generated by Django 2.2.1 on 2019-05-15 03:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('IoT_DataMgmt', '0069_auto_20190514_1740'),
('IoT_MaintOps', '0101_remove_equipmentproblemtype_last_updated'),
]
operations = [
migra... |
import dash
import sys
import dash_html_components as html
from dash.dependencies import Input, Output
def layout():
return html.Div(className = "btn-group", role = "group", children =
[
html.Button(id = "refreshRateButton", className = "btn btn-default dropdown-toggle btn-sm", **{"data-toggle": "dropd... |
#!/usr/bin/env python
from setuptools import setup, find_packages
import os
# Utility function to read README file
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-s3-folder-storage',
version='0.5',
description="Quick extension of django-storages... |
import parser_logger
# path_to_file = "Example_data/F00368"
path_to_file = "/media/hydroubuntu/78AE-4639/F00377"
path_output = "/home/hydroubuntu/Desktop/Current/TestsParser/tests"
verbose = 0
data_parser = parser_logger.Parser_logger()
data_parser.load_file(path_to_file, verbose=verbose)
data_parser.parse_current_d... |
"""
Ginga is a toolkit designed for building viewers for scientific image
data in Python, visualizing 2D pixel data in numpy arrays.
The Ginga toolkit centers around an image display class which supports
zooming and panning, color and intensity mapping, a choice of several
automatic cut levels algorithms and canvases f... |
import clip
from functools import reduce
app = clip.App()
@app.main()
@clip.arg('numbers', nargs=-1, type=int, inherit_only=True)
@clip.flag('-s', '--silent', inherit_only=True)
def calculator():
pass
@calculator.subcommand(inherits=['numbers', '-s'])
def add(numbers, silent):
if not silent:
clip.echo('Add these... |
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.timezone import now
# Create your models here.
class Taxation(models.Model):
intitule: str = models.CharField(max_length=200)
prix: int = models.IntegerField()
description: str = models.CharField(max_lengt... |
from django.utils.text import slugify
from django.db import models
from django.contrib.postgres.fields import JSONField, ArrayField
from django.contrib.contenttypes.fields import GenericRelation, GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from markdownx.models import MarkdownxField
fro... |
"""
__M5ThenClausePart2Complete_MDL.py_____________________________________________________
Automatically generated AToM3 Model File (Do not modify directly)
Author: gehan
Modified: Thu Oct 24 14:34:45 2013
_______________________________________________________________________________________
"""
from stickylink impo... |
import timeit
import io
import os
import json
import pyarrow.parquet
def _bench_read_single(
log2_size: int,
column: str,
use_dictionary: bool,
multiple_pages: bool,
compression: bool,
) -> float:
base_path = f"fixtures/pyarrow/v1"
if use_dictionary:
base_path = f"{base_path}/dic... |
import asyncio
@asyncio.coroutine
def countdown(name, n):
while n > 0:
print(f'Countdown[{name}]:{n}')
yield from asyncio.sleep(1)
n -=1
def main():
loop = asyncio.get_event_loop()
tasks = [
countdown("A", 10), countdown("B", 6)
]
loop.run_until_complete(asyncio.wa... |
""" Custom serializer for pytorch tensors
"""
import json
import torch
import numpy as np
def tensor_to_dict(t):
if isinstance(t, torch.Tensor):
return {"type": "torch.Tensor",
"dtype": str(t.dtype),
"device": t.device.type,
"requires_grad": t.requires_gr... |
__all__ = ['generate_constants_stub']
import textwrap
def generate_constants_stub():
names = [
'e', 'epsilon', 'euler', 'four_over_pi', 'golden_ratio', 'half_pi',
'ln_ln_two', 'ln_ten', 'ln_two', 'one', 'one_over_pi',
'one_over_root_two', 'pi', 'quater_pi', 'root_five', 'root_half_pi',
... |
# -*- coding: utf-8 -*-
"""
PyTest file for SAM/reV econ Wind Balance of System cost model.
Created on Thu Nov 29 09:54:51 2018
@author: gbuster
"""
import json
import os
import pytest
import numpy as np
import pandas as pd
import tempfile
from reV.generation.generation import Gen
from reV.econ.econ import Econ
from... |
from enum import Enum, unique
from lark import Lark, Tree
from .finite_automaton import FiniteAutomaton, State, Symbol
parser = Lark('''?e: e "|" a -> union
| a
?a: a "." b -> concatenation
| b
?b: b "*" -> kleenestar
| c
... |
import os
import torch
import torch.utils.data as data
import torch
import torch.nn.functional as F
import torchvision.transforms as transforms
import random
from PIL import Image, ImageOps
from . import readpfm as rp
import numpy as np
IMG_EXTENSIONS = [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm... |
"""Add checksum column
Revision ID: f26d6a79159d
Revises: 20190202
Create Date: 2020-03-17 11:28:26.163498
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "f26d6a79159d"
down_revision = "20190202"
branch_labels = None
depends_on = None
def upgrade():
with ... |
from musicbox.theory import Tone, Note, Interval, Scale, Chord
def test_tone_init():
tone1 = Tone(0)
tone2 = Tone('C')
assert tone1 == tone2
assert len(list(Tone.all())) == 12
assert len(list(Tone.all('A'))) == 12
assert eval(repr(tone1)) == tone1
assert Tone('C#') == Tone('Db')
def test... |
import numpy as np
np.random.seed(0)
import torch
torch.manual_seed(0)
from torch.utils.data import Dataset, DataLoader, ConcatDataset, RandomSampler
import torchvision
import imageio
import importlib
import random
import glob
import os
import transforms_3d
class patch_DS(Dataset):
"""Implementation of torch... |
from myqlanet.network.predict import predict
import sys
import os
import numpy as np
import cv2
import pandas as pd
import csv
import time
import threading
try:
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
except ImportError:
print("Please Use PyQt5!")
from libs.... |
import docker
import json
import os
import shutil
import base64
import hashlib
import time
from pathlib import Path
from typing import Dict
from vantage6.common.globals import APPNAME
from vantage6.common import debug, info, error
from vantage6.common.docker.addons import remove_container_if_exists
from vantage6.comm... |
"""
A helper script for the development of the ConfigEditor popup window
"""
import sys
from msl.qt import application, excepthook
sys.excepthook = excepthook
gui = application()
#Version 1:
from mass_circular_weighing.gui.widgets.config_editor import ConfigEditor
widgey = ConfigEditor()
widgey.show()
gui.exec()
... |
import unittest
import coc_package
class TestStringMethods(unittest.TestCase):
def test_add(self):
self.assertEqual(coc_package.add(3, 5), 3 + 5)
with self.assertRaises(AttributeError):
coc_package.add(3, "5")
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class BusinessRelationShopInfo(object):
def __init__(self):
self._real_shop_id = None
self._real_shop_no = None
self._shop_category = None
self._shop_name = None
@p... |
import textwrap
class Item():
ATTR_LINE = "Line"
ATTR_RAW = "Raw"
ATTR_ORIGIN = "Origin"
CLASSIFIER = "Item"
ATTR_SUB = "SubItem"
def __init__(self, origin, line, infileline, rawtext):
self.Line = line
self.Raw = rawtext
self.Links = []
self.Origin = origin
... |
#===============================================================================
# Copyright (c) 2015, Max Zwiessele
# 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... |
from typing import *
from strictly import *
@strictly
def find_max(nums : List[int]) -> int:
return max(nums)
# will work, strictly check that the input is a list
find_max([7, 2, 5, 9, 3])
# however, it will not check the the objects in the list
find_max([7, 2, 5, 9, '9000'])
|
# -*- coding: utf-8 -*-
from scrapy.item import Item, Field
class ReportsItem(Item):
url = Field()
link_text = Field()
company = Field()
content = Field()
keywords = Field()
|
# Generated by Django 3.2.5 on 2021-07-05 18:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('devices', '0005_auto_20210705_1511'),
]
operations = [
migrations.CreateModel(
name='AssetTag',
fields=[
... |
import sys
import config
import os
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import matplotlib as mpl
def main():
if 1 < len(sys.argv) :
diagram_path = sys.argv[1]
else:
diagram_path = ""
curDir = os.path.dirname(os.path.realpath(__file__))
data_path = ... |
# -*- coding: utf-8 -*-
import logging
from flask.templating import render_template
from google.appengine.api import memcache
from flask import redirect, helpers, request
from models import Client
from helpers import OAuthDanceHelper
from settings import get_setting
from flask import current_app as app, abort
from dec... |
from typing import List
from collections import Counter
import numpy as np
import networkx as nx
import itertools
def flatten_lists(l):
"""
https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists
"""
return [item for sublist in l for item in sublist]
def are_counters_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.