text
stringlengths
3.07k
22.1k
from collections import namedtuple from contextlib import contextmanager import os import random import re import numpy as onp import tqdm import jax from jax import jit, lax, ops, vmap from jax.interpreters.batching import BatchTracer from jax.interpreters.partial_eval import JaxprTracer from jax.lib.xla_bridge impo...
import copy import nose.tools as nt import numpy as np import theano import theano.tensor as T import treeano import treeano.nodes as tn fX = theano.config.floatX def test_reference_node_serialization(): tn.check_serialization(tn.ReferenceNode("a")) tn.check_serialization(tn.ReferenceNode("a", reference="b...
# Copyright 2018, FBPIC contributors # Authors: <NAME>, <NAME> # License: 3-Clause-BSD-LBNL """ This file is part of the Fourier-Bessel Particle-In-Cell code (FB-PIC) It defines a class for continuous particle injection with a moving window. """ import warnings import numpy as np from scipy.constants import c import sy...
import torch.nn.functional as F import torch import random import numpy as np from fastNLP import Const from fastNLP import CrossEntropyLoss from fastNLP import AccuracyMetric from fastNLP import Tester import os from fastNLP import logger def should_mask(name, t=''): if 'bias' in name: return False if ...
from django.core.exceptions import ImproperlyConfigured from django.core.serializers import json from django.template import loader, Context from django.utils import simplejson from django.utils.encoding import force_unicode from tastypie.exceptions import UnsupportedFormat from tastypie.representations.simple import R...
import tempfile import uuid from enum import Enum from pathlib import Path from typing import NamedTuple, Dict from django.contrib.auth.models import User from django.contrib.postgres.fields import JSONField from django.db import models from django.db.models import Sum, Max, QuerySet import ppe.dataclasses as dc from...
import grlc.static as static from grlc.queryTypes import qType import grlc.glogging as glogging import json import requests import yaml from os import path from glob import glob from github import Github from github.GithubObject import NotSet from github.GithubException import BadCredentialsException from configparser...
""" Functionality that can: * identify two CKANData.CKANDataSet ( or subclasses of these ) and identify differences between the two * Using the CKAN module, update one or the other. """ # pylint: disable=logging-format-interpolation, logging-not-lazy import abc import logging import operator import con...
from typing import Dict, List, Optional, Set import sqlalchemy as sa from aiopg.sa.result import ResultProxy from models_library.clusters import ( CLUSTER_ADMIN_RIGHTS, CLUSTER_MANAGER_RIGHTS, CLUSTER_NO_RIGHTS, CLUSTER_USER_RIGHTS, Cluster, ) from models_library.users import GroupID from pydantic....
import numpy as np from keras.callbacks import Callback from keras.optimizers import SGD from keras.models import Sequential from keras.layers import Dense from scipy.stats import logistic from copy import deepcopy, copy from sklearn.metrics import r2_score, explained_variance_score from keras import backend as K from ...
# Copyright (c) 2015, 2014 Computational Molecular Biology Group, Free University # Berlin, 14195 Berlin, 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 ...
# # For all new plots, check to see if a plotman analyze exists # Store most recent plot times in the stats database. # import datetime import json import pathlib import os import sqlite3 import time import traceback from flask import g from sqlalchemy import or_ from common.models import plots as p, plottings as pl...
import requests import cachecontrol from bs4 import BeautifulSoup from sortedcontainers import SortedList from collections import defaultdict import os import json DATA_PATH = '../../data/raw/courses/' # Path for writing data to BACHELOR_DISCIPLINES_URL = "https://www.bachelorsportal.com/disciplines/" SEARCH_FACETS_U...
# # tokenize.py # # Part of the "perky" Python library # Copyright 2018-2020 by <NAME> # import ast import sys WHITESPACE = '<whitespace_token>' STRING = '<string_token>' EQUALS = '<equals_token>' LEFT_CURLY_BRACE = '<left_curly_brace_token>' RIGHT_CURLY_BRACE = '<right_curly_brace_token>' LEFT_SQUARE_BRACKET = '<lef...
import os import shutil import subprocess import tarfile import threading import time import zipfile from multiprocessing import cpu_count from os.path import exists, isdir, isfile, islink, join from subprocess import STDOUT, check_output import pytest from conda_pack.compat import PY2, on_linux, on_mac, on_win from ...
""" Python Character Mapping Codec generated from 'LATIN2.TXT' with gencodec.py. Written by <NAME> (<EMAIL>). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 <NAME>. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return ...
import datetime import logging import boto3 from django.conf import settings from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractUser from django.contrib.gis.db import models as gis_models from django.core.exceptions import FieldError from django.db import Integrity...
#!/usr/bin/env python3 """ bulb.py ~~~~~~~ """ import colorsys import socket from abc import abstractmethod from datetime import datetime from typing import Dict import sys from astral import Astral from flask_login import current_user from flask_socketio import emit, disconnect from pyHS100 import SmartBulb from time...
# coding=utf-8 # Copyright 2018-2020 EVA # # 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 ...
from decimal import Decimal from django.db.models import Count, Sum from django.conf import settings from rest_framework import viewsets, mixins, decorators from rest_framework.response import Response from rest_framework.views import APIView, status from rest_framework.permissions import IsAuthenticated, IsAdminUser f...
# <NAME> # Copyright (c) 2018 - 2019 AXeL import sys import os import gi gi.require_version('Gtk', '3.0') gi.require_version('Wnck', '3.0') from gi.repository import Gtk, Gdk, GdkX11, Wnck from datetime import datetime from Xlib import display, X from PIL import Image from . import parser import pyautogui import time ...
""" Designed and Developed by- <NAME> https://github.com/Udayraj123 """ import cv2 import json import numpy as np from globals import * ### Coordinates Part ### class Pt(): """ Container for a Point Box on the OMR """ """ qNo is the question's property- It can be used as a roll number column...
from typing import Dict, List, Set, Union import numpy as np from webdnn.backend.code_generator.allocator import MemoryLayout, Allocation, BufferType from webdnn.backend.webgl.attributes.channel_mode import ChannelMode, ChannelModeEnum from webdnn.backend.webgl.attributes.texture_shape import TextureShape from webdnn...
import meraki import pprint import json import re import sqlite3 import sys from base64 import b64decode from nacl.secret import SecretBox import requests pp = pprint.PrettyPrinter(indent=4) sqlite_file = 'db/merakihooks.sqlite' # name of the sqlite database file portConnectChecks = [] #add to DB - or get via API ...
#!/usr/bin/env python """ This module provides a 313MHz/434MHz radio interface compatible with the Virtual Wire library used on Arduinos. It has been tested between a Pi, TI Launchpad, and Arduino Pro Mini. """ # 2014-08-14 # vw.py import time import pigpio MAX_MESSAGE_BYTES=77 MIN_BPS=50 MAX_BPS=10000 _HEADER=[0...
#!/usr/bin/env python3 """ Processes Kappa logs. See command line help for details. Note that timeline plotting needs the `plotly` package. """ import argparse from collections import defaultdict import csv from datetime import datetime from enum import Enum, auto import fileinput import logging import math from oper...
import keras.backend as K from keras.metrics import get from keras import Model from keras.layers import Dense, Dropout, Input, Flatten, Add, BatchNormalization, Concatenate from keras import regularizers, initializers, constraints, activations import numpy as np class FFNN: def __init__(self, la...
import random import copy J = ([ [0, 1], [1, 1] ],[ [1, 0], [1, 1] ],[ [1, 1], [1, 0] ],[ [1, 1], [0, 1] ]) I = ([ [2, 0], [2, 0] ],[ [2, 2], [0, 0] ],[ [0, 2], [0, 2] ],[ [0, 0], [2, 2] ]) O = ([ [3, 3], [3, 3] ],[ [3, 3], [3, 3] ],[ [3, 3], [3, 3] ],[ [3, 3], [3, 3] ]) Z = ([ [4, 0], [0,...
from torch._C import dtype from model import EstDepth_Model, Distance_DS, Detect_Model, Detect_DS, Detect_Model1 from tools import Visualization from sklearn.model_selection import KFold import torch import torch.optim as optim from torch.utils.data import DataLoader from engine import train_one_epoch, evaluate import ...
import tensorflow as tf import numpy as np from scipy.interpolate import interp1d def weight_variable(shape, name=None): return tf.get_variable(name=name, shape=shape, dtype=tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.001)) def bias_variable(shape, name=None): return tf.get_variable(...
import numpy as np import matplotlib matplotlib.use("TkAgg") import matplotlib.pyplot as plt import matplotlib.animation as animation from scipy.spatial import distance # wagi - współrzędne punktu # TODO: # przeczytać uważnie całą prezentację class KohonenOrNeuralGas: # alfa - wpsolczynnik uczenia, neighbour...
# MIT License # # Copyright (c) 2018 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, mo...
...
import matplotlib import matplotlib.pyplot as plt import numpy as np import numpy.testing as npt import pytest import util from numpy.lib import NumpyVersion from test_managedarray import ManagedArrayTestBase import freud matplotlib.use("agg") class TestRDF: def test_generateR(self): r_max = 5 f...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import datetime import logging import os import time import torch import torch.distributed as dist from tqdm import tqdm from maskrcnn_benchmark.utils.comm import get_world_size, synchronize from maskrcnn_benchmark.utils.metric_logger import Metr...
from types import FunctionType, MethodType # from rest_framework_mongoengine.generics import GenericAPIView as MongoGenericAPIView from django.core.exceptions import ValidationError from django.http.response import Http404 from django.shortcuts import get_object_or_404 as _get_object_or_404 from django_filters.rest_fr...
import tensorflow_probability as tfp from models.layers import * class SparseBasicBlock(object): def __init__(self, in_units, out_units, p_init, stride, name='block'): super(SparseBasicBlock, self).__init__() self.layers = [] self.shortcut = [] self.equalInOut = (in_units == out_un...
#!/usr/bin/env python3 import boto3 import traceback import random import argparse import sys import os def generate_s3_bucket_name(base_name: str='terraform-state-')->str: bucket_name = base_name chars = 'abcdefghijklmnopqrstuvwxyz1234567890' random_bit = '' while len(random_bit) < 8: random_...
# Copyright 2014 Insight Software Consortium. # Copyright 2004-2008 <NAME>. # Distributed under the Boost Software License, Version 1.0. # See http://www.boost.org/LICENSE_1_0.txt """ defines C++ parser configuration classes """ import os import sys import copy import types from .. import utils class parser_configu...
# coding=utf-8 # Copyright 2022 The Meta-Dataset Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
import os import torch import numpy as np import scipy.misc import imageio import torch.nn.functional as F from PIL import Image from utils.dcrf import crf_inference from datasets.pascal_voc_ms import MultiscaleLoader, CropLoader class ResultWriter: def __init__(self, cfg, palette, out_path, verbose=True)...
''' Utilities for `optics_line_text_reducer` ---------------------------------------- This module provides utilities used to reduce the polygon-text extractions for :mod:`panoptes_aggregation.reducers.optics_line_text_reducer`. It assumes that all extracts are full lines of text in the document. ''' import numpy as np...
import json import math import os import cv2 from PIL import Image import numpy as np from keras import layers from keras.applications import DenseNet121 from keras.callbacks import Callback, ModelCheckpoint from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from k...
from airflow import DAG import datetime from airflow.hooks.S3_hook import S3Hook from elasticsearch import Elasticsearch import json import gzip import io import logging import base64 from elasticsearch.helpers import bulk from airflow.operators.python_operator import PythonOperator from airflow.models import Variable ...
# encoding: utf-8 """ @author: huayuxiu """ """Train the model using traffic matrices.""" import argparse import math import os import time from datetime import datetime from functools import partial # import matplotlib.pyplot as plt import numpy as np import torch from torch import nn, optim # from torch.autograd...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Copyright (c) 2021 Cisco and/or its affiliates. This software is licensed to you under the terms of the Cisco Sample Code License, Version 1.1 (the "License"). You may obtain a copy of the License at https://developer.cisco.com/docs/licenses All use of t...
import asyncio import os from typing import Dict, Union, List, Callable, NoReturn from pydantic import BaseModel from aiohttp import ClientSession from motor.motor_asyncio import AsyncIOMotorClient from packages.aria2 import Options, GID from packages.aria2.ws_rpc import WSAria2RPC from utils.logger import Logg...
# -*- coding: utf-8 -*- """Godot scene file from COLLADA. @author MizunagiKB """ # ------------------------------------------------------------------ import(s) import sys import logging import argparse import xml.dom.minidom import collada.collada_type as co_type import collada.collada_util as co_util import coll...
#!/usr/bin/env python # coding: utf-8 # In[1]: import os import pandas as pd import glob import numpy as np # ## Gather subjects files and IDs # In[18]: paths = sorted(glob.glob('/cubric/data/c1639425/Monkey_Brains/derivatives/*/dwi/')) subject_ids = [x[48:54] for x in paths] print(subject_ids) print(paths) ...
""" MIT License Copyright (c) 2019 WebKide [d.id @323578534763298816] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modi...
import logging from flask import Flask, render_template, request, flash, redirect, url_for, session, make_response, abort from flaskext.markdown import Markdown from forms import ProjectCreateForm, PeopleForm, WhoAreYouForm, TaskForm, CommentForm from humantime import pretty_date from model import Project, Task from ...
""" Command line interface for training classifiers on YATSM output """ from datetime import datetime as dt import logging import os import click import matplotlib.pyplot as plt import numpy as np from osgeo import gdal from sklearn.cross_validation import KFold, StratifiedKFold from sklearn.externals import joblib ...
from collections import OrderedDict import logging import logging.config # onnx lib import onnx import onnxruntime from onnx import helper, shape_inference from onnxparser._transformers import ConvAddFuser, ConstantsToInitializers import config as cfg from onnxparser._graph import Graph logging.config.fileConfig(cf...
#!/usr/bin/env python3 import flask import json import os import sqlite3 from datetime import datetime from urllib import request db = 'db/roster.db' slack_webhook_url = os.environ['SLACK_WEBHOOK_URL'] holiday_api_url = 'http://timor.tech/api/holiday/info/' app = flask.Flask(__name__) app.config["DEBUG"] = False ...
# --------------------------------------------------------------------- # Juniper.JUNOS.get_metrics # --------------------------------------------------------------------- # Copyright (C) 2007-2022 The NOC Project # See LICENSE for details # --------------------------------------------------------------------- # Pytho...
# -*- coding: utf-8 -*- import datetime from flask import current_app, flash, redirect, url_for, render_template from purchasing.extensions import db from purchasing.notifications import Notification from purchasing.scout.forms import FeedbackForm, SearchForm from purchasing.users.models import Department, User, Ro...
# -*- coding:utf-8 -*- # Copyright 2017 Xiaomi, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
#! python3 """ Purpose: Get flight info using Kiwi.com API Flights: https://docs.kiwi.com Bookings: https://docs.kiwi.com/booking Dominant airlines by hub: https://www.nasdaq.com/article/airline-hubs-which-carrier-dominates-your-airport-cm863860 General parameters: origin: string representing the ...
"""Script using Cyberwatch API to export vulnerabilities of servers with details to XLSX""" import os from configparser import ConfigParser import xlsxwriter from cbw_api_toolbox.cbw_api import CBWApi def connect_api(): '''Connect to the API and test connection''' conf = ConfigParser() conf.read(os.path.j...
import logging from argparse import ArgumentParser from collections import OrderedDict import numpy as np import pandas as pd from ampligraph.datasets import load_wn18 from ampligraph.latent_features import ComplEx, HolE, TransE from ampligraph.evaluation import evaluate_performance, mrr_score, hits_at_n_score from amp...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # Meta-info Author: <NAME> Created: 01/06/2015 Updated: 02/04/2018 # Description ## What's a hash map (or hash table)? A hash map is a data structure which is used to implement the so-called associative array, which is an abstract data type composed of a collect...
from __future__ import print_function import networkx as nx from copy import copy from math import log import numpy as np import multiprocessing from functools import partial from copy import deepcopy def _UCT(mu_j, c_p, n_p, n_j): if n_j == 0: return float("Inf") return mu_j + 2 * c_p * (2 * log(...
# Copyright 2020 The ASReview 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 applicabl...
from __future__ import annotations import asyncio import functools import logging import re from typing import Any, Awaitable, Callable, Dict, List, Optional, Union import aioify import requests from ddp_asyncio import DDPClient from ddp_asyncio.exceptions import RemoteMethodError from ddp_asyncio.subscription import...
#!/usr/bin/env python3 import spotipy from spotipy.oauth2 import SpotifyClientCredentials from utils import display_num, convert_num, download_image from tweet import twitter_post, twitter_post_image hashtags= "\n@The Weeknd #theweeknd #music #abel tesfaye" module = "Spotify" def login(): """Logs in to Spotify ...
# -*- coding: utf-8 -*- # ATM SimCLR Multi-GPU 버전, Incomplete.. import numpy as np import torch from torch import nn from torch.utils.data import DataLoader import torch.backends.cudnn as cudnn from torch.optim.lr_scheduler import CosineAnnealingLR import torchvision from torchvision.transforms import transforms from ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019-1-29 17:11:00 # @Author : suke1900 (<EMAIL>) # @Link : http://www.makcyun.top # @Version : $Id$ """ 爬取 1983 至 2018 年 共 36 年春晚的节目趣事,包括这些内容: 谁导演春晚次数最多? 谁主持春晚次数最多? 哪两年的除夕刚好是同一天? 谁上春晚次数最多,堪称「钉子户」? 港台明星上春晚次数对比 歌曲、小品、相声类节目数量对比 "...
# -*- coding: utf-8 -*- """ MiniTwit ~~~~~~~~ A microblogging application written with Flask and sqlite3. :copyright: (c) 2010 by <NAME>. :license: BSD, see LICENSE for more details. """ import sys import os sys.path.append(os.path.dirname(os.path.abspath(__file__))) import time from...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Base class for all FHIR elements. ## This file has been modified for use in the Fhirbug project. ## You can find the original file and its License at ## https://github.com/smart-on-fhir/fhir-parser import sys import logging logger = logging.getLogger(__name__) cla...
## ## common parsing tools ## import os import re import numpy as np import pandas as pd from lxml.etree import XMLPullParser ## ## xml parsing ## # get descendent text def get_text(parent, tag, default=''): child = parent.find(tag) if child is None: return default elif child.text is None: ...
import unittest from colors import RGBColor as rgb from colors import HSVColor as hsv from colors import HexColor as hex from colors import random from colors import RGBFloatColor as rgbf class TestColors(unittest.TestCase): def test_rgb_color_object(self): colors = rgb(100, 100, 100) self.assertT...
from __future__ import division import math import os import cv2 import numpy as np import matplotlib.pyplot as plt from keras.preprocessing.image import Iterator from keras.utils.np_utils import to_categorical import keras.backend as K def angle_difference(x, y): """ Calculate minimum difference between t...
"""Module consists of certain type checking punishment conventions in a way of defining metaclasses. Allows to examine the contents of a class at the time of definition. """ from collections import OrderedDict from dataclasses import dataclass from functools import wraps from inspect import Signature, signature from t...
from solana.publickey import PublicKey from proxy.indexer.indexer_base import IndexerBase, logger from proxy.indexer.pythnetwork import PythNetworkClient from solana.rpc.api import Client as SolanaClient import requests import base58 import logging from datetime import datetime from decimal import Decimal import os tr...
#!/usr/bin/env python # coding: utf-8 # In[1]: # Copyright © 2020 Intel Corporation. # # This software and the related documents are Intel copyrighted # materials, and your use of them is governed by the express # license under which they were provided to you (License). Unless # the License provides otherwise, you m...
# Copyright 2012 OpenStack Foundation # 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 requ...
# json_views.views # Generic View classes for JSON in Django # # Author: <NAME> <<EMAIL>> # Created: Tue Jun 4 12:16:51 2013 -0400 # # Copyright (C) 2014 B<EMAIL> # For license information, see LICENSE.txt # # ID: views.py [] <EMAIL> $ """ Generic View classes for JSON in Django """ #############################...
import argparse import collections import csv import itertools import json import pathlib from typing import Dict, List, NamedTuple import matplotlib.pyplot as plt # type: ignore def main() -> None: args = parse_args() files = [ "kite-go/navigation/recommend/recommend.go", "kite-go/client/int...
#!/usr/bin/env python3 import os import math import numpy as np from common.realtime import sec_since_boot from selfdrive.swaglog import cloudlog from selfdrive.modeld.constants import T_IDXS from selfdrive.controls.lib.drive_helpers import MPC_COST_LONG, CONTROL_N from selfdrive.controls.lib.radar_helpers import _LEA...
#!/usr/bin/env python import warnings warnings.filterwarnings("ignore") import numpy as np import pandas as pd import seaborn as sns from seaborn import plotting_context import matplotlib.pyplot as plt def load_label_sets(filepath, num_sets): with open(filepath, 'r') as f: label_list = [] for ro...
# Data Loading and Feature Extraction from skimage.segmentation import slic from skimage.util import img_as_float from skimage.measure import perimeter from skimage import io import numpy as np from copy import deepcopy import cv2 import matplotlib.pyplot as plt import os os.chdir('../left') def readCa...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import json from datetime import datetime, timezone import requests import configparser ## Django Setup import django import pymysql pymysql.install_as_MySQLdb() conffile = os.path.join(os.path.dirname(__file__), "../conf/insert2db.conf") conf = confi...
from collections import namedtuple import pytest import numpy as np from idelib import importer from idelib.dataset import Dataset from idelib.transforms import Transform, AccelTransform, Univariate, Bivariate, CombinedPoly from .file_streams import makeStreamLike @pytest.fixture() def genericTransform(): yield...
import boto3 import tenacity import taskqueue import time import uuid import multiprocessing import functools import json from collections import defaultdict from taskqueue import RegisteredTask as TQRegisteredTask import mazepa retry = tenacity.retry( reraise=True, stop=tenacity.stop_after_attempt(4), wait=te...
########################################################################## # # pgAdmin 4 - PostgreSQL Tools # # Copyright (C) 2013 - 2020, The pgAdmin Development Team # This software is released under the PostgreSQL Licence # ########################################################################## """Defines views ...
from io import BytesIO import json import logging import struct from typing import List from fastavro import parse_schema, schemaless_writer from kafka import KafkaProducer, KafkaAdminClient from kafka.admin import NewTopic from kafka.errors import TopicAlreadyExistsError, NoBrokersAvailable from requests import reque...
import tkinter as tk import tkinter.ttk as ttk import pandas from tkinter import messagebox struct = {'name': 'Name', 'serving size': 'Serving Size (g/ml)', 'calories': 'Calories (Kcal)', 'carbohydrates': 'Carbohydrates (g)', 'proteins': 'Proteins (g)', 'fats': 'Fats (g)', 'salt': 'Salt (g)', 'pric...
# Standard library packages import codecs import json import logging import os import re import textwrap import traceback import numpy as np # Convoluted import for StringIO in order to support: # # - Python 3 - io.StringIO # - Python 2 (optimized) - cStringIO.StringIO # - Python 2 (all) - StringIO.StringIO try: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 2 11:47:44 2019 @author: Aayush This file contains the dataloader and the augmentations and preprocessing done Required Preprocessing for all images (test, train and validation set): 1) Gamma correction by a factor of 0.8 2) local Contrast limite...
""" The format table for standard sizes and alignments. """ # Note: we follow Python 2.5 in being strict about the ranges of accepted # values when packing. import struct from rpython.rlib.objectmodel import specialize from rpython.rlib.rarithmetic import r_uint, r_longlong, r_ulonglong from rpython.rlib.rstruct imp...
import json import os import tempfile import unittest import unittest.mock from pathlib import Path import requests from ..context import zoia from ..fixtures.metadata import ZoiaUnitTest import zoia.backend.add import zoia.backend.json class TestValidateResponse(unittest.TestCase): def test__validate_response(...
'''The console script''' import logging import sys import subprocess import platform import re from os import mkdir, makedirs, chdir, getcwd, listdir from os.path import join as pjoin from os.path import dirname, isdir, normpath, abspath, isfile from shutil import copytree, copyfile from argparse import ArgumentParser...
# Copyright (c) 2016, The Bifrost Authors. All rights reserved. # Copyright (c) 2016, NVIDIA CORPORATION. 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 r...
# Copyright 2017 ProjectQ-Framework (www.projectq.ch) # # 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 app...
import webbrowser import os import re import sys reload(sys) sys.setdefaultencoding('UTF8') # Styles and HTML Header for the page main_page_head = ''' <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-widt...
# TODO: should probably use tox --recreate because currently # pip+tox not necessarily sync'ing env changes properly. # TODO: missing test package task for pip. Current workaround is build package each time. import warnings from doit.action import CmdAction from .util import _options_param, test_group, get_env, tes...
from time import sleep from labjack import ljm def calculateSleepFactor(scansPerRead, LJMScanBacklog): """Calculates how much sleep should be done based on how far behind stream is. @para scansPerRead: The number of scans returned by a eStreamRead call @type scansPerRead: int @para LJMSc...
import pytest import array from uintset import UintSet WORD_SIZE = 64 def test_new(): s = UintSet() assert len(s) == 0 def test_new_from_iterable(): s = UintSet([1, 100, 3]) # beyond word 0 assert len(s) == 3 def test_add(): s = UintSet() s.add(0) assert len(s) == 1 def test_add_mu...
import os import fcntl import yaml import json import subprocess import time from jsonschema import validate from .config import INSTANCES_PATH, ADDONS_PATH REGISTRY_CONFIG_SUFFIX = '.config/helm/registry.json' REPOSITORY_CACHE_SUFFIX = '.cache/helm/repository' REPOSITORY_CONFIG_SUFFIX = '.config/helm/repository' ...
#!/usr/bin/env python from openmmtools import utils from simtk import unit, openmm # constants DEFAULT_TEMPERATURE = 300.0 * unit.kelvin ENERGY_DIFFERENCE_TOLERANCE = 1e-2 DEFAULT_LAMBDA0s = {'lambda_MM_angles': 1.0, 'lambda_MM_bonds': 1.0, 'lambda_MM_torsions': 1.0, ...