content
stringlengths
5
1.05M
# Copyright 2011 Nicholas Bray # # 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 json from datetime import date, datetime, timezone from vaccine.models import Answer, Event, Message, StateData, User def test_message_serialisation(): """ Message should be able to be serialised and deserialised with no changes """ message = Message( to_addr="27820001001", fro...
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt import glob from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets from pathlib import Path import matplotlib.ticker as mticker import os import warnings from textwrap import wrap de...
""" A wrapper around nosetests to run JavaScript tests in a CI environment. Example:: python run_jstests.py --with-xunit \ --with-django-serv --django-host hudson.mozilla.org \ --with-jstests \ --jstests-server http://jstestnet.farmd...
from bottle import route, static_file, template, run, post, request import logic @route('/favicon.ico') def server_favicon(): print("Here for FAV") return static_file('/favicon.ico', root='./static/img') @route('/static/<filepath:path>') def server_static(filepath): return static_file(filepath, root='./s...
import pytest from .data import settings as settings_data TEST_SETTING_NAME = 'TAPIS_CLI_LOG_LEVEL' NONEXIST_SETTING_NAME = 'TAPIS_CLI_FLUX_CAPACITOR' def test_settings_find_config(): """Settings module can locate the env file """ from tapis_cli import settings c = settings.find_config() assert c....
from django.apps import apps from django.conf import settings from django.contrib import admin from django.urls import include, path from django.views.decorators.vary import vary_on_headers from django.views.generic import TemplateView from wagtail.admin import urls as wagtailadmin_urls from wagtail.contrib.sitemaps.v...
# Copyright (c) 2018, ZIH, # Technische Universitaet Dresden, # Federal Republic of Germany # # 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 t...
import logging import errno from typing import ( IO, Any, Dict, List, Optional, Union, ) import shutil import os class PathHandler(object): """ Base Path handler class for a URI. It routes I/O for a generic URI which may look like "protocol://path/to/file". """ def get_cach...
while True: matriz = list() coluna1 = list() coluna2 = list() coluna3 = list() matriz.append(coluna1) matriz.append(coluna2) matriz.append(coluna3) maior = list() P = 0 coluna1.append(int(str(input('digite um numero para a posiçao [1:1] da matriz:')).strip())) coluna2.append...
from os import system , name def limpaTela(): if name == 'nt': system('cls') else: system('clear') limpaTela() def maquina(a, b, c, d, e): ''' Máquina responsável por vender Celulares, com capacidade para cinco unidades de cada produto, sem limite de notas, onde o troco é devolvido ao usuário...
import pytest import dns from mailspoof import DMARCScan def test_good(monkeypatch): dmarc_scan = DMARCScan() def mock_fetch(domain): return 'v=DMARC1; p=reject; rua=mailto:mailauth-reports@google.com' monkeypatch.setattr(dmarc_scan, 'fetch', mock_fetch) issues = dmarc_scan('_dmarc.google....
def test_a(): assert True def test_a(): assert True
#!/usr/bin/env python3 import gi gi.require_version('Gst', '1.0') from gi.repository import Gst, GObject from .create_gstreamer_pipe import create_gstreamer_pipe from .convert_YUV import YUV_to_RGB, YUV_to_gray class Camera(): def __init__(self): pipeline, self.sink = create_gstreamer_pipe() ret =...
# -*- coding: utf-8 -*- import opencc import argparse def convert_file(input_file, output_file, config='t2s'): """ 简繁转换 :param input_file: 输入文件路径 :param output_file: 输出文件路径 :param config: 配置文件, config in ['s2t', 't2s', 's2tw', 'tw2s', 's2hk', 'hk2s', 's2twp', 'tw2sp', 't2tw', 't2hk'], 参...
from urllib.request import Request, urlopen import re import whois import socket GOV_LIST = [".gov", "cic", ".ca", "cic", "cra", "canada", ".edu"] def get_txt(url, tags): req = Request(url) req.add_header('User-Agent', 'Mozilla/5.0') file = urlopen(req) res = [] for line in file: ...
#!/usr/bin/env python import re from operator import itemgetter ref_file = open('../../../data/RNA-seq_miR-124_miR-155_transfected_HeLa/gene_exp_miR-155_overexpression_RefSeq_Rep_isoforms.diff','r') input_file = open('../../../result/mirage_output_rev_seed_miR-155_vs_RefSeq_NM_2015-07-30.txt','r') output_file ...
#! /usr/bin/env python # This file is part of the dvbobjects library. # # Copyright (c) 2005-2013 Lorenzo Pallara l.pallara@avalpa.com # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either ...
"""Fetch PATH (NJ/NYC) feed.""" from datetime import datetime import logging from bs4 import BeautifulSoup import requests from FeedSource import FeedSource, TIMECHECK_FMT URL = 'http://trilliumtransit.com/transit_feeds/path-nj-us/' FILE_NAME = 'path.zip' LAST_UPDATED_FMT = '%Y-%m-%d %H:%M' LOG = logging.getLogger...
# -*- coding: utf-8 -*- import sys import re class Node(object): __num__ = -1 def __init__(self): self.transition = {} self.suffixLink = None self.ids = set() self.id = Node.__num__ Node.__num__ += 1 def addTransition(self, node, start, end, ch): self.transi...
from .wavefront_sensor import WavefrontSensorOptics, WavefrontSensorEstimator from ..optics import OpticalSystem, MicroLensArray from ..field import CartesianGrid, Field, SeparatedCoords from ..propagation import FresnelPropagator import numpy as np from scipy import ndimage class ShackHartmannWavefrontSensorOptics(W...
from django.conf.urls import patterns, include, url from django.contrib import admin from birde import views urlpatterns = patterns('', # Examples: # url(r'^$', 'birde.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', views.index, name='index'), url(r'^send/', views.sen...
# Generated by Django 2.2.11 on 2020-09-03 13:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('facility', '0173_auto_20200903_1625'), ] operations = [ migrations.AddField( model_name='historicalpatientregistration', ...
from django.apps import AppConfig class StudentsConfig(AppConfig): default_auto_field = 'django.db.models.AutoField' name = 'students'
from construct import * from construct.lib import * def enum_deep_literals__container1__container2__animal(subcon): return Enum(subcon, canary=4, turtle=7, hare=12, ) enum_deep_literals__container1__container2 = Struct( ) def enum_deep_literals__container1__animal(subcon): return Enum(subcon, dog=4, cat...
from rest_framework.routers import DefaultRouter from django.urls import path, include from . import viewsets app_name = 'api_finance' # Routers for HR's to add payments, OT, or leave. router = DefaultRouter() router.register('balance', viewsets.AllStudentBalanceViewSet, basename='balance') router.register('salary', ...
import os import sys import json import argparse import jinja2 import matplotlib matplotlib.use('Agg') import numpy as np import matplotlib.pyplot as plt def graphData( args ): with open( args.jsonfile, 'r' ) as f: jsonData = json.load( f, encoding='utf-8' ) with open( args.lookupjsonFile, 'r' ) as f: lookup...
from unittest.mock import Mock import pytest from flask import current_app from werkzeug.exceptions import BadRequest from scenario_player.services.rpc.schemas.base import RPCClientID, RPCCreateResourceSchema @pytest.fixture def test_schema(): """Minimal schema to test the :class:`RPCCreateResourceSchema` and :...
class CalibreEbookConvertGenerator(object): """ Calibre 'ebook-convert' Generator """ _DESCRIPTION = "Calibre 'ebook-convert' Generator" format = None use_cache = None verbose = None logger = None def __init__(self, format="mobi", use_cache=False, verbose=False, logger=None): ...
from src.Utils.Fitness import * from src.Utils.Population import * import matplotlib.pyplot as plt import pandas as pd from scipy.spatial import distance from src.Utils.Graphs import * from time import time from src.Utils.HyperParameters import * class MOSAARM: def __init__(self,nbItem,populationSize,nbIteration,n...
#!/usr/bin/python3 # Script to trigger profile change to OpenAPS Autosync # Can be used to trigger automatic profile change after autotune # from datetime import datetime import hashlib import sys import argparse import requests def trigger(site, api_key): # defining the api-endpoint if not site.endswith('...
import datetime, json, os, uuid from time import time from PIL import Image import torch from torchvision import transforms from torchvision.models import resnet50 tmp = '/dev/shm/' SCRIPT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__))) class_idx = json.load(open(os.path.join(SCRIPT_DIR, "imagenet_cla...
import torch from qiqc.registry import register_aggregator @register_aggregator('last') class BiRNNLastStateAggregator(object): def __call__(self, hs, mask): batchsize, maxlen, n_hidden = hs.shape idx = mask.sum(dim=1) - 1 zeros = idx * 0 fw_h = hs[range(batchsize), idx][:, :n_hi...
#=============================================================================== # NAME: TestMainWriter.py # # DESCRIPTION: A writer for generating main.cpp files for test component toDo() test case. # # AUTHOR: Jordan Ishii # EMAIL: jordan.ishii@jpl.nasa.gov # DATE CREATED : July 8, 2019 # # Copyright 2015, Californ...
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2017-03-14 16:32 from __future__ import unicode_literals from django.db import migrations def add_odi_breakdowns(apps, schema_editor): """ All wins going forward will have ODI breakdowns since the code does that and it makes reporting easier, so add them...
import binascii import struct from typing import Union def calc_parity(values: bytes) -> int: parity = 0x00 for value in values: parity ^= value return parity def data_to_bytes(data: Union[bool, int, float, str, bytes, None]) -> bytes: if data is None: result = b'' elif isinstance...
import numpy as np from scipy import stats, linalg ''' TODO: [] Nan-protection [] RSP version [] cross-version [] basic version ''' def fit_covariate(x, cov): coeffX = linalg.lstsq(cov, x)[0] return x - cov.dot(coeffX) # def partial_corr(x, y, covarX, covarY=None): # if covarY is None: # covarY...
"""Collection of layers focusing on transforming tensors while keeping the number of dimensions constant.""" import torch import torch.nn as nn class Conv(nn.Module): """Convolutional layer. Parameters ---------- n_input_channels : int Number of input channels. n_output_channels : int ...
import sublime, sublime_plugin import subprocess, threading import traceback import re, time, copy import os import queue import collections import html from User.output import * class Task: class Sentinel: pass def __init__(self, command, working_dir): env = copy.copy(os.environ) env...
#!/usr/bin/env python # -*- coding: utf-8 -*- from conan.packager import ConanMultiPackager from conans import tools import importlib import os def get_module_location(): repo = os.getenv("CONAN_MODULE_REPO", "https://raw.githubusercontent.com/bincrafters/conan-templates") branch = os.getenv("CONAN_MODULE_BR...
import pytest import tempfile import os import json import boto3 from core import Config # Load Environment variables. Config.load_local_into_env('private.test.env.json', stage=Config.Stages.TEST) # Import the remaining modules after the test ENV variables have been loaded and set. from tests.synapse_test_helper impo...
#!/usr/bin/env python import os import re try: import setuptools except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, Extension, find_packages import setuptools.command.build_py from pip.req import parse_requirements version_file = os.path.join('src', 've...
import sublime import sublime_plugin import unittest class __bespoke_docs_test_replace_cursor_position(sublime_plugin.TextCommand): def run(self, edit): cursor_placeholder = self.view.find('\|', 0) if not cursor_placeholder or cursor_placeholder.empty(): return self.view.sel()...
numbers = [1, 2, -2, -8, 0] stride = 2 result = [] for idx in range(0, len(numbers), stride): result.append(numbers[idx] - 1) print(result)
import unittest import scripts.mdcontentcheck as mdchecker class MDContentCheckTester(unittest.TestCase): def test_extract_links_and_words(self): md_content = \ ''' Hi there this is a link [linked](link.md) and this is not (not a link). Good luck. ''' ...
class Compile: def __init__(self): self.run() def run(self): import os os.system("cd B.O.P.E && gradlew setupDecompWorkspace --stop && gradlew clean build") #os.system("cd B.O.P.E && gradlew runClient --stop && gradlew clean build") import shutil try: shutil.copyfile("B.O.P.E/build/libs/bope-0.4-all...
import sys from opcodetools.disassembler import binary from opcodetools.cpu import cpu_manager # py dasm Z80 1000 "a.bin+b.bin+c.bin" cpuname = sys.argv[1] org = int(sys.argv[2], 16) names = sys.argv[3] bindata = binary.load_binary(names) cpu = cpu_manager.get_cpu_by_name(cpuname) print('; CPU:', cpuname) print('...
from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy from django.core.management.base import BaseCommand from django.conf import settings from onadata.apps.logger.models import Instance, XForm from onadata.libs.utils.model_tools import queryset_iterator class Command(BaseCom...
import logging import threading import time import OPi.GPIO as GPIO import opz_ha.defaults as defaults from opz_ha.utils import check_config, fahrtigrade, get_1wire_path, get_mode, read_sensor logger = logging.getLogger(__name__) class GDORelay(object): def __init__(self, client, modestring, channel, topic, qos, ...
import operator import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable, Function def generic_power_method(affine_fun, input_size, eps=1e-8, max_iter=500, use_cuda=False): """ Return the highest singular value of the linea...
from rest_framework import serializers from uchicagohvz.game.models import * class KillSerializer(serializers.ModelSerializer): class Meta: model = Kill fields = ('id', 'killer', 'victim', 'location', 'date', 'points') killer = serializers.SerializerMethodField(method_name='get_killer') victim = serializers.Se...
import argparse def parse_args(): parser = argparse.ArgumentParser() # hardware config parser.add_argument("--gpu_id", type=str, default="0", help="GPU ids to use (separated by comma e.g. 0,1,2,3)") parser.add_argument("--num_workers", type=int, default=0, help="number of dataloader workers") # tr...
""" !!!!!!!!!!!!!! ! DEPRECATED ! !!!!!!!!!!!!!! Various tools to read WAIS data Author: Cyril Grima <cyril.grima@gmail.com> """ import numpy as np import pandas as pd import os import glob import string from scipy.interpolate import UnivariateSpline from params import * def grep_params(word, season = season): ...
from .ns_util import * from .cut import * from .git import * from .man import * from .wire import * from .yaml_util import * __all__ = [ "ns", "ns_path", "clone", "source_manifest", "remote_push_manifest", "remote_pull_manifest", "stash_transfer_site_manifest", "yaml_manifests", "ge...
#!/usr/bin/env python from __future__ import absolute_import, unicode_literals import os import argparse from . import log from .osm_extract_downloader import OsmExtractDownloader def main(): parser = argparse.ArgumentParser(usage="OSM Extract Download tool.") parser.add_argument('id', help='Extract ID') ...
from ._abstract import AbstractScraper from ._utils import get_minutes, normalize_string, get_yields class Przepisy(AbstractScraper): @classmethod def host(cls): return "przepisy.pl" def title(self): return self.schema.title() def description(self): return self.schema.descrip...
# (c) Copyright [2017] Hewlett Packard Enterprise Development LP # # 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...
# -*- coding: utf-8 -*- # author:lyh # datetime:2020/7/13 23:55 """ 188. 买卖股票的最佳时机 IV 给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。 注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 示例 1: 输入: [2,4,1], k = 2 输出: 2 解释: 在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2 。 示例 2: 输入: [3,2,...
# -*- coding: utf-8 -*- """Implentation of builtin command `/help`. """ from typing import ( Dict, Optional, Sequence, Tuple, Union ) from telecom.command import ( Command ) from telecom.selector import ( ArgumentSelector ) class CommandSelector(ArgumentSelector): """Selects a comman...
import contextlib import logging from typing import Any, Dict, Optional import sentry_sdk from sentry_sdk.integrations.logging import LoggingIntegration from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration log = logging.getLogger(__name__) def setup_sentry( dsn, environment=None, service_name=No...
import re import sys import requests # Last update: 2019-02-16 lang_choice = { "C++14": 88, "Java": 3, "Python 3": 28, "C11": 75, "PyPy3": 73, "C": 0, "C++": 1, "C++11": 49, "C++17": 84, "Java (OpenJDK)": 91, "Java 11": 93, "Python 2": 6, "PyPy2": 32, "Ruby 2.5"...
from typing import Optional from kivy.uix.screenmanager import ScreenManager class WindowManager(ScreenManager): current_filepath: Optional[str] = None
from django.shortcuts import render from products.models import Merchandise from django.contrib.auth.decorators import login_required # Create your views here. @login_required() def search_merch(request): merchandise = Merchandise.objects.filter(name__icontains=request.GET["q"]) return render(request, "produ...
import json import requests from db import articles start = 0 articles_collec = [] request = requests.get("https://api.spaceflightnewsapi.net/v3/articles/count") total_articles = int(request.content.decode('utf-8')) while True: r = requests.get( f"https://api.spaceflightnewsapi.net/v3/articles?_sort=i...
#!/usr/bin/python """ // // Copyright (C) 2009 Institut fuer Telematik, Universitaet Karlsruhe (TH) // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or ...
#! /usr/bin/env python # -*- coding: utf-8 -*- class EventRegister(object): def __init__(self): self.registry = {} self.check_queue = [] def init_register(self, index): self.registry[index] = [0] def clear(self): self.registry = {} def register(self, index, *args): ...
# Copyright (c) 2020 SMHI, Swedish Meteorological and Hydrological Institute. # License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit). """ Created on 2021-05-28 11:04 @author: johannes """ import time from sirena.session import Session if __name__ == '__main__': session_obj = Session( ...
from rl import spaces from rl.agents import BaseAgent from rl.agents.tabular import ActionValuesTable # This is, like Q-Learning, off-policy TD(0) learning. The difference # is that the expected action-value is used in the update rather than # the maximum. It is still off-policy because the behavior that determines # ...
"""Support for the Environment Canada weather service.""" from datetime import datetime, timedelta import logging import re from env_canada import ECData import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( ATTR_ATTRIBUTION, ATTR_LOCATION, ...
import pytest from kool.db.flatfile import Query class TestQuery(object): def test_no_path(self): with pytest.raises(ValueError): Query() == 2 def test_eq(self): query = Query().value == 1 assert query({'value': 1}) assert not query({'value': 2}) assert h...
#Copyright (c) 2020 Jan Kiefer #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES...
"""Migration for a given Submitty course database.""" def up(config, database, semester, course): """ Run up migration. :param config: Object holding configuration details about Submitty :type config: migrator.config.Config :param database: Object for interacting with given database for environme...
# -*- coding: utf-8 -*- """ forms.secure_redirect_back ~~~~~~~~~~~~~~~~~~~~~~~~~~ Secure Back Redirects with WTForms http://flask.pocoo.org/snippets/63/ """ import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) from urlparse import urlparse, urljoin from...
import os import time import numpy as np from numpy import genfromtxt, array class Dataset(dict): def __init__(self, **kw): dict.__init__(self,kw) self.__dict__ = self # Some datasets have string variables. If you want a raw_data attribute you # must create this in the dataset's load function. ...
# encoding: utf-8 from __future__ import print_function import sys template = """ from distutils.core import setup, Extension import sys import pprint from Cython.Distutils import build_ext ext = Extension("%(name)s", sources = %(source_files)s, language="c++", include_dirs = %(include_dirs)r, e...
import os from flask import Flask, flash, session, request, make_response, render_template, abort, redirect, url_for, jsonify, json from markupsafe import escape, Markup from werkzeug.utils import secure_filename from flaskext.mysql import MySQL import pymysql UPLOAD_FOLDER = './static/files/' ALLOWED_EXTENSIONS = {'t...
import pytest from django.apps import apps from django.core.cache import cache from dynamic_models.utils import ModelRegistry from dynamic_models.models import ModelSchema, FieldSchema TEST_APP_LABEL = "dynamic_models" @pytest.fixture(autouse=True) def cleanup_cache(): try: yield finally: ca...
# Generated by Django 2.2.3 on 2019-12-11 19:31 from django.db import migrations, models import ic_marathon_app.validators class Migration(migrations.Migration): dependencies = [ ('ic_marathon_app', '0006_auto_20191210_2017'), ] operations = [ migrations.AlterField( model_na...
def test_main_import(): # Ensure that the main package is importable. import inspector assert inspector is not None
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 20 21:49:40 2020 @author: jose """ import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_...
from django.contrib import admin from JobTrak.admin import JobTrakAdmin # Register your models here.
from django.shortcuts import render, HttpResponse, redirect from .models import Article from django.utils import timezone def home(request): return render(request, 'home.html') def login(request): username = request.POST.get('username') password = request.POST.get('password') if username == 'user1' a...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilitie...
from flask import request, render_template_string, session import pathlib from io import StringIO class PlutoTV_HTML(): endpoints = ["/plutotv", "/plutotv.html"] endpoint_name = "page_plutotv_html" endpoint_category = "pages" pretty_name = "PlutoTV" def __init__(self, fhdhr, plugin_utils): ...
# # Class for one-dimensional thermal submodel for use in the "1+1D" pouch cell model # import pybamm from ..base_thermal import BaseThermal class CurrentCollector1D(BaseThermal): """ Class for one-dimensional thermal submodel for use in the "1+1D" pouch cell model. The thermal model is averaged in the x...
""" @brief test log(time=2s) """ import unittest from pyquickhelper.loghelper import fLOG from pymyinstall.installhelper import get_pypi_version class TestPypiVersion(unittest.TestCase): def test_package_list(self): fLOG( __file__, self._testMethodName, OutputPrin...
#!/usr/bin/python class Cellphone(str): def __init__(self, number): self.value = str(number) def isvalid(self): #a number can contain '+', ' ', '-', '/', '(', ')' _num = self.value.replace('+','') _num = _num.replace(' ','') _num = _num.replace('-','') _num = _nu...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('tasks', '0001_initial'), ] operations = [ migrations.AlterField( model_name='task', name='content', ...
from .draw import (circle, ellipse, set_color, polygon_perimeter, line, line_aa, polygon, ellipse_perimeter, circle_perimeter, circle_perimeter_aa, bezier_curve, rectangle, rectangle_perimeter) from .draw3d import ellipsoid, ellipsoid_stats from ._draw import _be...
import gym from gym import spaces import numpy as np import os from . import locobot_interface from softlearning.environments.helpers import random_point_in_circle from .base_env import LocobotBaseEnv from .utils import * class LocobotGraspingEnv(LocobotBaseEnv): """ Environment contains a single block. ...
from biostar.settings.base import * import os # Add the custom directory # This should be a fully qualified absolute path THEME_PATH = os.path.join(HOME_DIR, "org", "bioconductor", "templates") TEMPLATE_DIRS = [THEME_PATH] + TEMPLATE_DIRS
import os from subprocess import run from pynnotator import settings import shutil shutil.rmtree(settings.vcf_validator_dir) os.makedirs(settings.vcf_validator_dir) os.chdir(settings.vcf_validator_dir) command = 'wget https://github.com/EBIvariation/vcf-validator/releases/download/v0.7/vcf_validator' run(command,shel...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import load_library from tensorflow.python.platform import resource_loader greedy_assignment_ops = load_library.load_op_library( resource_loader.get_path_to_datafile('_gree...
import unittest from imbox.query import build_search_query from datetime import date class TestQuery(unittest.TestCase): def test_all(self): res = build_search_query() self.assertEqual(res, "(ALL)") def test_unread(self): res = build_search_query(unread=True) self.assertEqu...
from typing import Dict, Union import numpy as np COVARIANCE_MATRICES = dict() def get_eigenval_diversity_index(eig_vals: np.ndarray): """Return Simpson diversity index of eigvalue explained variance ratios. Args: eig_vals : eigenvalues in descending order """ tot = sum(eig_vals) var_...
import requests import os import time def main(): os.system("clear") print('''\033[1;31m ______ .d$$$******$$$$c. .d$P" "$$c $$$$$. .$$$*$. .$$ 4$L*$$. .$$Pd$ '$b $F *$. "$$e.e$$" 4$F ^$b d$ $$ z$$$e $$ '$. $P...
from kafka import KafkaConsumer consumer = KafkaConsumer('user-details', bootstrap_servers='127.0.0.1:9092', auto_offset_reset='earliest', group_id='test05') for message in consumer: # print(type(message)) # print(dir(message)) print(message)
from hass_apps.loader import *
import sublime import sublime_plugin import sys import os import logging from unittest import TextTestRunner from .core import TestLoader from .core import DeferringTextTestRunner from .mixin import UnitTestingMixin from .const import DONE_MESSAGE from .utils import ProgressBar import threading version = sublime.versi...
"""The utils for SQL statements generation.""" def find_named_variables(mapping): """Find correspondance between variable and relation and its attribute.""" var_dictionary = dict() for relation_instance in mapping.lhs: for i, variable in enumerate(relation_instance.variables): name = r...