text
stringlengths
2
999k
class NewsSource: ''' News Source class to define News Source Objects ''' def __init__(self,id,name,description,url,category,country): self.id =id self.name = name self.description = description self.url = url self.category = category self.country = count...
import json from dateutil.relativedelta import relativedelta from django.conf import settings as django_settings from django.contrib import messages from django.contrib.auth import logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.paginator im...
# Copyright 2017 The TensorFlow 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 applica...
import json import base64 import time CLOCK_SKEW = 5 def expired(jwt: str) -> bool: """Checks if JWT token has expired Expiration checked by inspecting the "exp" field of the JWT payload. If "exp" key is not found, a ValueError will be raised. Returns True if expired, false otherwise. """ i...
import math def f(l,r): if l == r: return l else: b = int(math.log(r,2)) if p[b] <= l: return f(l-p[b],r-p[b])+p[b] elif p[b+1]-1 <= r: return p[b+1]-1 else: return p[b]-1 p = [1] for i in range(64): p.append(p[-1]*2) n = int(input(...
import os from setuptools import setup, find_packages def readme(): with open('README.rst') as fptr: return fptr.read() PACKAGE_NAME = 'pyhomematic' HERE = os.path.abspath(os.path.dirname(__file__)) VERSION = '0.1.74' PACKAGES = find_packages(exclude=['dist', 'build', 'tests']) REQUIRES = [] setup( ...
""" Defines electronic property calculators. Electronic property calculators calculate the electronic properties of molecules, namely the dipole moment, electron affinity and ionization potential. Each :class:`.ElectronicPropertyCalculator` is initialized with some settings and calculates the electronic properties of ...
''' Training script for ImageNet Copyright (c) Wei YANG, 2017 ''' from __future__ import print_function import argparse import os import shutil import time import random import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as optim import torch.utils.data...
""" Copyright (c) 2017 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import print_function, unicode_literals from atomic_reactor.constants import INSPECT_CONFIG from atomic_reactor.plugin import...
# -*- coding: utf-8 -*- from django.template import Library, loader from django.urls import resolve import six from ..models import BlogCategory as Category from ..models import Tag register = Library() @register.simple_tag() def post_date_url(post, blog_page): post_date = post.date url = blog_page.url + b...
# (C) Datadog, Inc. 2020-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) from contextlib import closing import snowflake.connector as sf from datadog_checks.base import AgentCheck, ConfigurationError from datadog_checks.base.utils.db import QueryManager from . import queries...
import sys import os import subprocess sys.path.append(snakemake.config['paths']['mcc_path']) import scripts.mccutils as mccutils def main(): install_path = snakemake.config['paths']['install']+"/tools/" mccutils.remove(snakemake.params.zipfile) download_success = mccutils.download(snakemake.params.url, sn...
import os from functools import cmp_to_key import numpy from . import cInterface from .extraData import ExtraDataUnpacker class UMFileException(Exception): pass class File: '''A class for a UM data file that gives a view of the file including sets of PP records combined into variables ''' de...
import abc import logging import mimetypes import os import shutil import string import tempfile from inspect import isclass from typing import ( Any, Dict, List, Optional, Tuple, TYPE_CHECKING, ) from markupsafe import escape from galaxy import util from galaxy.datatypes.metadata import ( ...
import time import requests def count_words_at_url(url): """Just an example function that's called async.""" time.sleep(8) resp = requests.get(url) text_length = len(resp.text.split()) print(text_length) return text_length
#! encoding:utf-8 import tensorflow as tf import numpy as np import time import sys from tqdm import tqdm from nlpgnn.datas import TUDataset from nlpgnn.metrics import Losess, Metric from nlpgnn.models import GraphSAGE from nlpgnn.gnn.utils import merge_batch_graph from sklearn.metrics import classification_report dim...
# Generated by Django 2.0.2 on 2018-02-08 11:57 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='DLQueue', fields=[ ('id', models.AutoField(...
import json import os import pytest from detect_secrets.core import baseline from detect_secrets.core import plugins from detect_secrets.core.secrets_collection import SecretsCollection from detect_secrets.core.usage import ParserBuilder from detect_secrets.settings import get_settings from testing.mocks import mock_...
class Solution: def findDuplicates(self, nums): """ :type nums: List[int] :rtype: List[int] """ end = [] dict = {} for item in nums: if item in dict: dict[item] += 1 else: dict[item] = 1 if di...
""" This component is used to create a connection to a Visonic Power Max or PowerMaster Alarm System Currently, there is only support for a single partition The Connection can be made using Ethernet TCP, USB (connection to RS232) or directly by RS232 Initial setup by David Field """ import logging import voluptuou...
# Copyright 2015 Tesora Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
from . import errno from .flags import ( SEQUENCE_LOCKTIME_DISABLE_FLAG, SEQUENCE_LOCKTIME_TYPE_FLAG, VERIFY_DISCOURAGE_UPGRADABLE_NOPS, VERIFY_CHECKLOCKTIMEVERIFY, VERIFY_MINIMALIF, VERIFY_CHECKSEQUENCEVERIFY, ) from pycoin.coins.SolutionChecker import ScriptError def make_bad_opcode(opcode, even_o...
# Copyright (c) 2014 VMware, Inc. # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
# Copyright 2022 Touca, Inc. Subject to Apache-2.0 License. from dataclasses import dataclass from time import sleep from typing import List from datetime import date from random import random import touca @dataclass class Course: name: str grade: float @dataclass class Student: username: str fulln...
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-11-27 20:41 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('reports', '0006_merge_20161127_1541'), ] operations = [ migrations.AlterFie...
#!/usr/bin/python # Author: Zion Orent <zorent@ics.com> # Copyright (c) 2015 Intel Corporation. # # 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 limi...
from flask import Flask, render_template, request, jsonify, redirect, make_response from functools import wraps import hashlib import json import os # create a flask app app = Flask(__name__) # basic paths to use try: with open('./static/json/admin.json', 'r') as admin: admin_json = json.load(admin) ...
import logging from moreorless.click import echo_color_unified_diff from imperfect import parse_string from ..types import BaseSuggestion, Env LOG = logging.getLogger(__name__) class MoveCoverageIni(BaseSuggestion): # https://coverage.readthedocs.io/en/v4.5.x/config.html def check(self, env: Env, autoappl...
# -*- coding: utf-8 -*- u"""NSLS-II BlueSky integration :copyright: Copyright (c) 2018 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function from pykern import pkcollections from pykern import pkconfig from py...
from django.urls import path from . import views urlpatterns = [ path('',views.index), path('music/',views.music), path('music/lukas/',views.lukas), path('music/script/',views.script), path('music/mack/',views.mack), ]
"""save images every 0.5 sec in input movie """ import cv2 INPUT_TITLE = 'movie08' INPUT_MOVIE = 'movie/' + INPUT_TITLE + '.mp4' OUTPUT_TITLE = INPUT_TITLE OUTPUT_SIZE = (224, 224) INTERVAL = 30 # in frame cap = cv2.VideoCapture(INPUT_MOVIE) rep, frame = cap.read() INPUT_WIDTH = cap.get(cv2.CAP_PROP_FRAME_WIDTH) IN...
# coding=utf-8 # 实现主要思路 # 1. 获取网页教程的内容 # 2. 获取主页当中的ul-list # 3. 根据获取的ul-list 当中的a 不断发送请求,获取数据,并写入 import os import logging import requests import pickle from weasyprint import HTML from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.desired_capabilities import Des...
import torch import torch.nn.functional as F import configparser import matplotlib.pyplot as plt import os import numpy as np plt.figure(figsize=(20,5)) import ast import sys #to import parent-level modules os.chdir('Temporal-Based Approach') sys.path.append('..') from model.StackedLSTM import StackedLSTM from util...
import torch import random import numpy as np from torch.nn import functional as F # ============================================== # 设置种子 def set_seed(seed): np.random.seed(seed) random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) # ============================...
""" The actual layout for the renderer. """ from __future__ import unicode_literals from prompt_toolkit.application.current import get_app from prompt_toolkit.filters import has_focus, is_searching, Condition, has_arg from prompt_toolkit.key_binding.vi_state import InputMode from prompt_toolkit.layout import HSplit, VS...
# Copyright (c) 2017-2018, Neil Booth # # All rights reserved. # # See the file "LICENCE" for information about the copyright # and warranty status of this software. '''Peer management.''' import asyncio import random import socket import ssl import time from collections import Counter, defaultdict from ipaddress imp...
#!/usr/bin/env python # coding: utf-8 # # Notebook # # **Authors:** Colin Small (crs1031@wildcats.unh.edu), Matthew Argall (Matthew.Argall@unh.edu), Marek Petrik (Marek.Petrik@unh.edu) # [![MMS Mission Video](https://upload.wikimedia.org/wikipedia/commons/thumb/b/b3/Artist_depiction_of_MMS_spacecraft_%28SVS12239%29....
# Load CSV from URL using NumPy from numpy import loadtxt from urllib.request import urlopen url = 'https://goo.gl/bDdBiA' raw_data = urlopen(url) dataset = loadtxt(raw_data, delimiter=",") print(dataset.shape)
from torch import nn class GPT2LMHead(nn.Module): """ Language Model Head for the transformer """ def __init__(self, model_embeddings_weights, config): super(GPT2LMHead, self).__init__() self.n_embd = config.n_embd self.set_embeddings_weights(model_embeddings_weights) def set_emb...
# Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/) # # 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 -*- ''' /*************************************************************************** Importer2OSMbasemap A QGIS plugin ------------------- begin : 2022-03-03 git sha : $Format:%H$ cop...
import io import picamera import logging import socketserver from threading import Condition from http import server # width="640" height="480" PAGE="""\ <html> <head> <title>picamera MJPEG streaming demo</title> </head> <body> <h1>PiCamera MJPEG Streaming Demo</h1> <img src="stream.mjpg" width="84" height="84" /> </bo...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'help.ui' # # Created: Fri Aug 17 06:41:13 2018 # by: PyQt5 UI code generator 5.2.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dial...
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from memory_inspector.core import memory_map class MemoryMapTest(unittest.TestCase): def runTest(self): mmap = memory_map.Map() ...
from collections import ChainMap import arcade from arcade import Texture from arcade.experimental.uistyle import UIFlatButtonStyle from arcade.gui.widgets import UIInteractiveWidget, Surface class UITextureButton(UIInteractiveWidget): """ A button with an image for the face of the button. :param float ...
# 进度显示 使您可以测量和打印迭代过程的进度。这可以通过可迭代的界面或使用手动API来完成。使用可迭代的接口是最常见的。 import ubelt as ub from os.path import basename class 缓存(ub.Cacher): def __init__(self, 前缀='cache', key="", 缓存目录="./cache/", 扩展名=".pkl", 启用=True, 信息级别=3, ...
import json import requests def FetchAPI(address, requeststring): headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} params = '' try: response = requests.get(address + requeststring) data = response.json() return data; except: retur...
import tensorflow as tf import numpy as np import datetime from model.tensorflow.Wrapper import HierarchicalRNNCell from model.tensorflow.Loss import RankingLoss from pipeline.tensorflow.Datasets import Datasets from tensorflow.python.keras.layers.recurrent import RNN, GRUCell from tensorflow.python.keras.layers.embe...
from django.apps import AppConfig class BotConfig(AppConfig): name = '{{cookiecutter.project_slug}}.bot' label = 'bot' verbose_name = 'The Bot Core'
# Copyright 2014 Embrane, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
from django.apps import AppConfig from rolepermissions.loader import load_roles_and_permissions class RolePermissions(AppConfig): name = 'rolepermissions' verbose_name = "Django Role Permissions" def ready(self): load_roles_and_permissions()
# Limit the number of threads used by numpy import os os.environ["MKL_NUM_THREADS"] = "1" os.environ["NUMEXPR_NUM_THREADS"] = "1" os.environ["OPENBLAS_NUM_THREADS"] = "1" os.environ["OMP_NUM_THREADS"] = "1" import os import re import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.prepr...
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyFastcluster(PythonPackage): """Fast hierarchical clustering routines for R and Python.""...
# coding: utf-8 """ pollination-server Pollination Server OpenAPI Definition # noqa: E501 The version of the OpenAPI document: 0.16.0 Contact: info@pollination.cloud Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from pollination_sdk.configu...
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
import json from pathlib import Path def expand_dest_dir(dest): return Path(dest).expanduser() if dest else Path.cwd() def stringify_metadata(metadata): return json.dumps(metadata, indent=2, sort_keys=True, ensure_ascii=False)
import numpy as np from gym import Env from gym import spaces from gym import Wrapper class TimedEnvironmentWrapper(Wrapper): def __init__(self, env, max_steps): Wrapper.__init__(self, env) self._max_steps = max_steps def reset(self): self._n_steps = 0 return self._reset() ...
#! /usr/bin/env python # coding=utf-8 # Copyright (c) 2019 Uber Technologies, 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 # # Unles...
# -*- coding: utf-8 -*- # Copyright (c) 2020, Robin Rosenstock and Contributors # See license.txt from __future__ import unicode_literals # import frappe import unittest class TestExecution_sports_management(unittest.TestCase): pass
"""Utility module for the EEGBCI motor/imagery dataset.""" from multiprocessing.pool import RUN import numpy as np import pandas as pd import mne import torch from torch.utils.data import Dataset, DataLoader, ConcatDataset, Subset import pytorch_lightning as pl import sklearn from typing import Callable, Optional fro...
# coding: utf-8 """ Mux API Mux is how developers build online video. This API encompasses both Mux Video and Mux Data functionality to help you build your video-related projects better and faster than ever before. # noqa: E501 The version of the OpenAPI document: v1 Contact: devex@mux.com Gener...
"""Wrapper for matplotlib plotting functions. BSD 3-Clause License Copyright (c) 2020-2021, Daniel Nagel All rights reserved. """ # ~~~ IMPORT ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import warnings from os import path import numpy as np from matplotlib import legend as mlegend from matplo...
import cmd class TrainShell(cmd.Cmd): intro = '[[ Welcome to the shell. Type help or ? to list commands. ]]' prompt = '>' def __init__(self, _trainer): super().__init__() self.trainer = _trainer def do_save(self, _arg): self.trainer.agent.save( self.trainer.epoc...
#! /usr/bin/env python """ This file s based off the techniques from the example for python-docx -- http://github.com/mikemaccana/python-docx and uses that module to implement a docx generator. Currently it operates on a csv, but there is an attempt to make it modular enough that text data could come from other so...
import configparser import datetime import logging import os import unittest from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric i...
from ...models import UserProfile from django.core.management.base import BaseCommand def list_organization_names(): orgs = [] user_profiles = UserProfile.objects.all() for up in user_profiles: if up.organization_name: orgs.append(up.organization_name) return orgs class Command(B...
#copy of j25 import numpy as np from collections import namedtuple from functools import partial from PIL import Image import data_transforms import data_iterators import pathfinder import utils import app import torch import torchvision import torch.optim as optim import torch.nn as nn from torch.nn import init ...
""" WSGI config for api project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` sett...
import unittest import qcodes import qcodes.tests.data_mocks import qtt.data #%% class TestData(unittest.TestCase): def test_transform(self): dataset = qcodes.tests.data_mocks.DataSet2D() # print(dataset) tr = qtt.data.image_transform(dataset, arrayname='z') istep = tr.istep()...
# Copyright 2015, Ansible, Inc. # Luke Sneeringer <lsneeringer@ansible.com> # # 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...
import grpc from tiktorch.proto import inference_pb2, inference_pb2_grpc class FlightControlServicer(inference_pb2_grpc.FlightControlServicer): def __init__(self, *, done_evt=None) -> None: self.__done_evt = done_evt def Ping(self, request: inference_pb2.Empty, context) -> inference_pb2.Empty: ...
from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, DeleteView, UpdateView from django.views.generic.list import ListView # 클래스형 뷰의 이름은 자유 from .models import Bookmark class BookmarkList(ListView): model = Bookmark # _list # 템플릿 종류를 바꾸거나 읽어오는 데이터,문 #...
# -*- coding: utf-8 -*- from __future__ import absolute_import from .orbit import OrbitCamera __all__ = ['OrbitCamera']
import requests import pandas as pd import ftplib import io import re import json import datetime try: from requests_html import HTMLSession except Exception: print("""Warning - Certain functionality requires requests_html, which is not installed. Install ...
import asyncio import math import os import random import textwrap from collections import namedtuple import discord from discord.ext import menus from discord.ext.commands import Paginator as CommandPaginator from settings import constants from utilities import cleaner # Embed limits TITLE_LIMIT = 256 DESC_LIMIT = ...
from ..util import _is_na, _is_true, deprecated from anndata import AnnData from typing import Union, Sequence, Tuple import numpy as np from scanpy import logging @deprecated("Use `tl.chain_qc` instead.") def chain_pairing( adata: AnnData, *, inplace: bool = True, key_added: str = "chain_pairing" ) -> Union[None...
import fnmatch import os import textwrap from collections import OrderedDict from contextlib import contextmanager from conans.client.subsystems import deduce_subsystem, WINDOWS, subsystem_path from conans.errors import ConanException from conans.util.files import save class _EnvVarPlaceHolder: pass def enviro...
import numpy as np import os, csv, re, datetime import sys, getopt import h5py from h5shape import * from keras import models from keras.models import load_model #prediction times in test sets) utcPlus2 = [30, 69, 126, 186, 234] utcPlus3 = [57, 114, 174, 222, 258] def load_test_data(file_path, indices): """Load d...
""" author comger@163.com 交易请求逻辑 用户允许自由发布问题, 问题允许被多个答复者进行交易报价, 用户只能选择一个答复者进行交易, 交易是一个线上交流及线上交线同步的过程,一但用户确认解决了问题,用户将按交易价格进行支付。 """ from peewee import CharField, ForeignKeyField, TextField, IntegerField, FloatField from pydantic import BaseModel, Field from cms.core.db import DBBaseModel from cms.logic.common.user import...
from django.conf import settings from . import views from django.contrib.auth import views as auth_views from django.conf.urls.static import static from django.urls import path urlpatterns = [ path('', views.index, name='index'), path('register', views.register, name="register-authentication"), path('ac...
__author__ = 'mslabicki' import pygmo as pg # from pyltes.powerOptimizationProblemsDef import maximalThroughputProblemRR from pyltes.powerOptimizationProblemsDef import local_maximalThroughputProblemRR from pyltes.powerOptimizationProblemsDef import maximalMedianThrProblemRR from pyltes.powerOptimizationProblem...
import torch from torch import nn import torch.nn.functional as F class ConvNormLReLU(nn.Sequential): def __init__(self, in_ch, out_ch, kernel_size=3, stride=1, padding=1, pad_mode="reflect", groups=1, bias=False): pad_layer = { "zero": nn.ZeroPad2d, "same": nn.Repli...
import numpy res, iterations = 100, 10000 dt = 0.1 V = 0*numpy.empty((res, res)) phi = (1.0 + 1.0j) + 0*V a = (0.0 + 0.0j) + 0*V grad = (0.0 + 0.0j) + 0*V phi[0, :] = (0.0 + 0.0j) phi[res - 1, :] = (0.0 + 0.0j) phi[:, 0] = (0.0 + 0.0j) phi[:, res - 1] = (0.0 + 0.0j) phi = phi/numpy.sqrt(numpy.sum(numpy.conj(phi)*phi...
import assembly_x86 import assembly_arm import assembly_mips import assembly_ppc import os class AsmFactory: def get_type(self, asm_type, input_path, b_online=False, i_list=[]): if asm_type == 'X86': return assembly_x86.X86Asm(input_path, b_online, i_list) elif asm_type == 'ARM': ...
# Copyright 2008-2015 Nokia Networks # Copyright 2016- Robot Framework Foundation # # 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 ...
# -*- coding: utf-8 -*- ''' # Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. # # This file was generated and any changes will be overwritten. ''' from __future__ import unicode_literals from ..one_drive_object_bas...
## Based on https://keras.io/examples/vision/grad_cam/ import numpy as np import tensorflow as tf from tensorflow import keras # Display from IPython.display import Image import matplotlib.pyplot as plt import matplotlib.cm as cm def get_img_array(img_path, size): # `img` is a PIL image of size 299x299 img =...
#!/usr/bin/env python3 import pyglet import glooey import autoprop import datetime from pyglet.gl import * from vecrec import Vector, Rect @autoprop class LineClock(glooey.Widget): custom_radius = 50 custom_color = 'green' custom_hour_hand_width = 3 custom_minute_hand_width = 2 custom_second_hand_...
# -*- coding: utf-8 -*- # Copyright (c) 2020. Distributed under the terms of the MIT License. from itertools import cycle from pathlib import Path from monty.design_patterns import singleton from vise.user_settings import UserSettings @singleton class Defaults: def __init__(self): self._symmetry_length_...
# requires python3 # requires pysam-0.11.2.1 import sys import pysam chromToUse = sys.argv[1] # 0 for all chromosomes norm_hetpsns = sys.argv[2] bam_file = sys.argv[3] #ref_file = sys.argv[4] base_quality = int(sys.argv[4]) map_quality = int(sys.argv[5]) vcf_quality = int(sys.argv[6]) positions = {} # add (position...
import _plotly_utils.basevalidators class NamelengthValidator(_plotly_utils.basevalidators.IntegerValidator): def __init__( self, plotly_name="namelength", parent_name="heatmap.hoverlabel", **kwargs ): super(NamelengthValidator, self).__init__( plotly_name=plotly_name, ...
from collections import deque # Time Complexity: O(N * K). # The outer loop runs n-k+1 times and the inner loop runs k times for every iteration of outer loop. # So time complexity is O((n-k+1)*k) which can also be written as O(N * K). # Space Complexity: O(1). # No extra space is required. def max_val_sub_arrays(arr...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Setup script for spyder-black.""" import os import os.path as osp from setuptools import find_packages, setup def get_version(): """Get the version.""" with open("spyder_black/__init__.py") as f: lines = f.read().splitlines() for l in lines: ...
import os import uuid import json import datetime import requests from flask import Flask, Response, request, Blueprint, url_for, render_template app = Flask(__name__) VERSION = 1 PLUGIN_USERNAME = 'labmanager' PLUGIN_PASSWORD = 'password' LAB_ID = 'sample lab' LAB_URL = 'http://localhost:5001/lab' LAB_LOGIN = 'myp...
"""rfid_last URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/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-bas...
from thefeck.rules.ls_all import match, get_new_command from thefeck.types import Command def test_match(): assert match(Command('ls', '')) assert not match(Command('ls', 'file.py\n')) def test_get_new_command(): assert get_new_command(Command('ls empty_dir', '')) == 'ls -A empty_dir' assert get_new...
import json import uuid from typing import TYPE_CHECKING, Iterable, Optional import graphene from django.db.models import F, QuerySet from ..account.models import User from ..checkout.models import Checkout from ..core.utils import build_absolute_uri from ..core.utils.anonymization import ( anonymize_checkout, ...
# Copyright 2020 by B. Knueven, D. Mildebrath, C. Muir, J-P Watson, and D.L. Woodruff # This software is distributed under the 3-clause BSD License. # Demonstrate some uses of listener_util.py for asynchronous computing. # This very silly and of limited value. # DLW March 2019 # NOTE: If you have runtime error in this ...
import sys from flask import Flask, render_template, jsonify, redirect import pymongo import scrape_mars sys.setrecursionlimit(2000) app = Flask(__name__) client = pymongo.MongoClient() db = client.mars_db collection = db.mars_facts @app.route('/scrape') def scrape(): # db.collection.remove() mars = scrape_...
from pygks.utils import csv_reader from pygks.ui_isoinn import data_block from numpy import array r = csv_reader('wine_train.csv') data = r.get_all() nn_model = data_block(data, age_max = 200, nn_lambda = 70) nn_model.draw_2d()