content
stringlengths
5
1.05M
# Copyright 2020 Google LLC. 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 applicable law or a...
""" Copyright (c) Open Carbon, 2020 This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. backend/tools.py Provides range of backend tools that can be run from command line: importlocations: Imports location data from file that is used to geolocate s...
"""This module contains definitions and data structures for 2-, 4-, and 8-valued logic operations. 8 logic values are defined as integer constants. * For 2-valued logic: ``ZERO`` and ``ONE`` * 4-valued logic adds: ``UNASSIGNED`` and ``UNKNOWN`` * 8-valued logic adds: ``RISE``, ``FALL``, ``PPULSE``, and ``NPULSE``. T...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 1 14:46:51 2020 @author: gabriel """ #%% MATLAB Code to reproduce # function thresh_calc(nbeg,nend,n_noise,sig_fact,necdf_flag,nlbound) # % Calculate the threshold using one of two methods # % P=mean|W| + c sigma # % P is computed from the e...
from torch.utils import data import yaml from argparse import ArgumentParser from typing import Any, List, Tuple import pytorch_lightning as pl import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torch.distributions as dist from torch.utils.data import DataLoader, Ran...
""" Code for defining the architecture of the Encoder and the Decoder blocks. """ import tensorflow as tf class Encoder(): def __init__(self, vocab_size, embedding_dim, encoder_units): # print(vocab_size, embedding_dim, encoder_units, "##########################################ENCODER#####################...
''' Created on Mar 13, 2018 @author: abelit ''' import os import json from utils import filepath project_settings = { # 项目信息配置 'package': 'dev', 'version':'3.14', 'name':'__dbreport__.py', 'author':'abelit', 'email':'ychenid@live.com', 'description':'', } path_settings = { 'image'...
# -*- coding: utf-8 -*- # jvparidon@gmail.com from .timer import timer
import base64 import json import cv2 import numpy as np from decouple import config from flask import Flask, request from api.face import FaceVerification from db.mongo import FaceEncodings app = Flask(__name__) face_verification = FaceVerification( FaceEncodings( config("DATABASE_URI") ) ) @app.r...
import pocketcasts as pc import requests import re import configparser from pathlib import Path def get_valid_filename(s): s = str(s).strip() return re.sub(r"(?u)[^-\w. ]", "", s) def get_extension(url): if "?" in url: url, _ = url.split("?", 1) return url.split(".")[-1] print("Reading con...
import numpy as np from config import handTrackConfig as htconf from math import sin, cos, sqrt, atan2, radians import cv2 # 8 12 16 20 # | | | | # 7 11 15 19 # 4 | | | | # | 6 10 14 18 # 3 | | | | # | 5---9---13--17 # 2 \ / # \ ...
""" This module provides various utility functions. """ # ----------------------------------------------------------------------------- # IMPORTS # ----------------------------------------------------------------------------- from typing import Tuple import numpy as np # -------------------------------------------...
""" Based on https://github.com/ikostrikov/pytorch-a2c-ppo-acktr """ import gym import torch import random from environments.env_utils.vec_env import VecEnvWrapper from environments.env_utils.vec_env.dummy_vec_env import DummyVecEnv from environments.env_utils.vec_env.subproc_vec_env import SubprocVecEnv from environm...
""" Sets permission for the API (ONLY) """ from rest_framework import permissions # TODO: Add restriction to users (get token, refresh token, verify token, post request) class IsReadOnly(permissions.DjangoModelPermissions): """ Custom permission to only allow reading. """ def has_object_permission(se...
############################################################################### ## ## Copyright 2011 Tavendo GmbH ## ## 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 ## ## ht...
from typing import Set, List, Tuple, Dict def fibonacci(n: int) -> int: """ Returns n-th Fibonacci number n must be more than 0, otherwise it raise a ValueError. >>> fibonacci(0) 0 >>> fibonacci(1) 1 >>> fibonacci(2) 1 >>> fibonacci(10) 55 >>> fibonacci(-2) Tracebac...
from functools import wraps from . import environment as env import wx, os class VirtualEnvMustExistDecorator: """装饰器:虚拟环境必须存在!!!""" def __init__(self, *args, **kwargs): ... def __call__(self, func, e=None): @wraps(func) def decorator(obj, *args, **kwargs): env_path = env.getPyt...
import os, json, sys, shutil, distutils from distutils import dir_util if_block_template = '\tif(!strcmp(cmd, "{}")){{\n\ \t\treturn {}(argv, argc);\n\ \t}}else ' ending = '{\n\ \t\tstde("Not a command:");\n\ \t\tstde(argv[0]);\n\ \t}' set_driver_template = "\tdrivers[{}] = &{};\n" include_template = '#include...
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # import argparse from typing import Dict import torch from torch import optim from datasets import Dataset from models i...
# Author : BIZZOZZERO Nicolas # Completed on Sun, 24 Jan 2016, 23:11 # # This program find the solution of the problem 5 of the Project Euler. # The problem is the following : # # 2520 is the smallest number that can be divided by each of the # numbers from 1 to 10 without any remainder. # What is the smallest ...
from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg import numpy as np from communication import Communication import math from dataBase import data_base from PyQt5.QtWidgets import QPushButton pg.setConfigOption('background', (33, 33, 33)) pg.setConfigOption('foreground', (197, 198, 199)) # Interface variab...
import sys import click import os import datetime from unittest import TestCase, main from frigate.video import process_frames, start_or_restart_ffmpeg, capture_frames, get_frame_shape from frigate.util import DictFrameManager, SharedMemoryFrameManager, EventsPerSecond, draw_box_with_label from frigate.motion import Mo...
""" This module performs all basic DFA operations. It is an interface for pyfst. """ # /usr/bin/python from operator import attrgetter import fst from alphabet import createalphabet EPSILON = fst.EPSILON def TropicalWeight(param): """ Returns fst TropicalWeight Args: param (str): The input Re...
from singlecellmultiomics.universalBamTagger.digest import DigestFlagger from singlecellmultiomics.tagtools import tagtools class NlaIIIFlagger(DigestFlagger): def __init__(self, **kwargs): DigestFlagger.__init__(self, **kwargs) def addSite(self, reads, strand, restrictionChrom, restriction...
#!/usr/bin/env python2 import sys import time import logging import argparse def main(): """ Tumor Map Calc Agent """ parser = argparse.ArgumentParser(description=main.__doc__) parser.add_argument("-i", "--interval", type=int, default=0, help="Minutes between calc, default ...
# -*- coding: utf-8 -*- """SOG run processor. Do various operations related to running the the SOG bio-physical model of deep estuaries. Most notably, run the model. This module provides services to the SOG command processor. :Author: Doug Latornell <djl@douglatornell.ca> :License: Apache License, Version 2.0 Copy...
import datetime from dataclasses import asdict from dataclasses import dataclass from dataclasses import field from enum import Enum from typing import List from typing import Union try: from typing import Literal except ImportError: from typing_extensions import Literal from pglet import BarChart from pglet ...
from .home import bp as home from .dashboard import bp as dashboard from .api import bp as api # the .home syntax direct the program to find the module name home then import BP routes.
"""A class to hold data parsed from PDFs.""" import dataclasses @dataclasses.dataclass class Datum: """A class to hold data parsed from PDFs.""" text: str = "" traits: list[dict] = dataclasses.field(default_factory=list) reject: bool = False
import sounddevice as sd from scipy.io import wavfile from scipy import signal import sys import matplotlib.pyplot as plt import os import subprocess as sp from collections import defaultdict, Counter import pyprind import numpy as np import random from .utils import readwav output_seconds = 5 n_gram = 2 fname = 'Nigh...
#!/usr/bin/python3.7 import subprocess import sys v = sys.argv[1] subprocess.call(["amixer", "sset", "Speaker", v + "%"])
from PyQt5.QtWidgets import QWidget, QGridLayout, QComboBox, \ QLabel, QVBoxLayout, QSizePolicy, \ QCheckBox, QLineEdit, QPushButton, QHBoxLayout, \ QSpinBox, QTabWidget, QMessageBox from PyQt5.QtCore import Qt, pyqtSlot from PyQt5.QtG...
import twoLSTMcuda as t model = t.torch.load(open("twoLSTMentireModel.npy", 'rb')) print(t.checkAcc(model, t.data, t.labels)) print(t.checkAcc(model, t.valData, t.valLabels))
### ### Copyright (C) 2018-2019 Intel Corporation ### ### SPDX-License-Identifier: BSD-3-Clause ### from ....lib import * from ..util import * import os @slash.requires(have_ffmpeg) @slash.requires(have_ffmpeg_vaapi_accel) class TranscoderTest(slash.Test): def before(self): self.refctx = [] def transcode_1to...
from django.shortcuts import * from django.http import * from django.shortcuts import * from django.urls import * import traceback import json from .models import * from django.db.utils import IntegrityError from django.db.models import F from .crypto import * import math from account_info.models import User from walle...
#!/usr/bin/python import unittest from utils.logger import Logger class UtLogger(unittest.TestCase): def setUp(self): self.logger = Logger().getLogger("test.utils.UtLogger") def testLogger(self): self.logger.debug("1") self.logger.info("2") self.logger.warn("3") ...
from base_n_treble import db, auth from base_n_treble.models.user import User def setup_admin(): from tests.fixtures import TEST_ADMIN db._adapter.reconnect() admins = auth.id_group("admin") if auth.id_group("admin") else auth.add_group("admin") print("Admin group id: '{}'".format(admins)) db._ada...
#!/usr/bin/env python # -*- coding: UTF-8 -*- import sqlite3 from flask import Flask, request, session, g, redirect, url_for, \ abort, render_template, flash from contextlib import closing # configuration DATABASE = "/tmp/flaskr.db" DEBUG = True SECRET_KEY = "development key" USERNAME= "admin" PASSWORD = "default...
#! /usr/bin/env python import sys import os import disttools sys.path.append(os.path.abspath(os.path.dirname(__file__))) from strparser import * from filehdl import * from pyparser import * def make_string_slash_ok(s): sarr = re.split('\n', s) rets = '' for l in sarr: l = l.rstrip('\r\n') ...
import pytest import abjad import abjadext.nauert class Job: ### INITIALIZER ### def __init__(self, number): self.number = number ### SPECIAL METHODS ### def __call__(self): self.result = [ x for x in abjad.math.yield_all_compositions_of_integer(self.number) ] ...
""" =========== 04. Run ICA =========== This fits ICA on epoched data filtered with 1 Hz highpass, for this purpose only using fastICA. Separate ICAs are fitted and stored for MEG and EEG data. To actually remove designated ICA components from your data, you will have to run 05a-apply_ica.py. """ import itertools imp...
import logging import typing import copy from typing import Any, Dict, List, Text from rasa.nlu.components import Component from rasa.nlu.config import RasaNLUModelConfig from rasa.nlu.tokenizers.tokenizer import Token, Tokenizer from rasa.nlu.training_data import Message, TrainingData logger = logging.getLogger(__na...
import datetime import enum from sqlalchemy import ( Column, Integer, String, Enum, TIMESTAMP, ForeignKey, Index, Float, ) from sqlalchemy.orm import relationship from .base import Base class SystemUpdate(Base): __tablename__ = "system_update" pk = Column(Integer, primary_ke...
from italian_csv_type_prediction.simple_types import IntegerType import numpy as np def test_integer_type(): predictor = IntegerType() valids = [ 3, 6, 0, "1.000.000.00" ] invalids = [ "ciao", "12.12.94", "12.12.1994", False, Tru...
class Node: def __init__(self, data): self.data = data self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None def insert(self, data): new_node = Node(data) if self.root == None: self.root = new_node ...
"""Parameters for the model of marine particle microbial degradation and coupling of degradation with sinking speed, part of the paper "Sinking enhances the degradation of organic particle by marine bacteria" Uria Alcolombri, François J. Peaudecerf, Vicente Fernandez, Lars Behrendt, Kang Soo Lee, Roman Stocker Na...
import os import json import shutil import grp from pathlib import Path def change_key(my_json, old_key, new_key): if old_key in my_json: # store the value val = my_json[old_key] # delete the old key/value pair del my_json[old_key] # error checking if new_key in my_j...
from pytari2600.pytari2600 import new_atari emulator = new_atari("../../roms/dragster.a26", headless=False) while True: emulator.core.step() # print("---AFTER EXECUTION---" + str(emulator.stella.clocks.system_clock)) # print(emulator.stella.display_cache)
# # -*- coding: utf-8 -*- # """ # Created on Fri May 8 17:08:43 2020 #%% import numpy as np import matplotlib.pyplot as plt from scipy.constants import pi, c from numpy.fft import fft, ifft, fftshift #%% def calculate_spectrum(z, E, H, f=3.7e9): k0 = 2*pi*f/c lambda0 = c/f # fourier domain points B = ...
from dataclasses import dataclass from bindings.csw.animate_type import AnimateType __NAMESPACE__ = "http://www.w3.org/2001/SMIL20/Language" @dataclass class Animate1(AnimateType): class Meta: name = "animate" namespace = "http://www.w3.org/2001/SMIL20/Language"
import unittest import electricity class VersionTestCas(unittest.TestCase): def test_version(self): self.assertEqual(electricity.__version__, '0.1')
from keris.layers.merge import Concatenate, Sum from keris.layers.core import Input, Dense from keris.layers.convolution import Conv2D from keris.layers.dropout import Dropout from keris.layers.pool import MaxPooling2D, GlobalAveragePooling2D
from functools import wraps def tags(tag_name): def tags_decorator(func): @wraps(func) def func_wrapper(name): return "<{0}>{1}</{0}>".format(tag_name, func(name)) return func_wrapper return tags_decorator @tags("p") def get_text(name): """returns some text""" retur...
import os import torch import numpy as np from torch.autograd import Variable from .base_trainer import BaseTrainer from model import networks from model.loss import AttnDiscriminatorLoss, AttnGeneratorLoss, KLLoss from utils.util import convert_back_to_text from collections import OrderedDict dirname = os.path.dirname...
import os from setuptools import setup from pip.req import parse_requirements # parse requirements reqs = [str(r.req) for r in parse_requirements("requirements.txt", session=False)] # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README fi...
from packetbeat import BaseTest """ Tests for trimming long results in pgsql. """ class Test(BaseTest): def test_default_settings(self): """ Should store the entire rows but only 10 rows with default settings. """ self.render_config_template( pg...
# Generated by Django 2.0.3 on 2018-03-16 19:42 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('nps', '0021_auto_20180316_1239'), ] operations = [ migrations.RenameField( model_name='rawresults', old_name='role_type', ...
# Import Abaqus and External Modules from abaqusConstants import * from abaqus import * import random import regionToolset import mesh import step import part randomSeed=[41557] for eachModel in range(0,1): # # Create Model Database VerFile=Mdb(pathName="MStructure") VerModel=VerFile.models['Model-1']...
''' @author: Jakob Prange (jakpra) @copyright: Copyright 2020, Jakob Prange @license: Apache 2.0 ''' import sys import json import argparse as ap from pathlib import Path from .mode import Mode argparser = ap.ArgumentParser() mode = argparser.add_subparsers(help='mode', dest='mode') def str2bool(v): if isinst...
# SPDX-FileCopyrightText: 2020 Melissa LeBlanc-Williams, written for Adafruit Industries # # SPDX-License-Identifier: Unlicense """ `adafruit_matrixportal.network` ================================================================================ Helper library for the MatrixPortal M4 or Adafruit RGB Matrix Shield + Met...
"""Tests for the NumericValue data class.""" from onyx_client.data.animation_keyframe import AnimationKeyframe from onyx_client.data.animation_value import AnimationValue from onyx_client.data.numeric_value import NumericValue class TestNumericValue: def test_create(self): expected = NumericValue( ...
from .config_diff import Config import yaml def save(filename: str, config: Config): """Save configuraion to file""" with open(filename, 'w') as fh: yaml.dump(config, fh, default_flow_style=False)
import os SPREEDLY_AUTH_TOKEN = os.environ.get('SPREEDLY_AUTH_TOKEN','asdfasdf') SPREEDLY_SITE_NAME = 'jamesr-c-test'
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Advent of Code 2020 Day 25, Part 1 """ def main(): with open('in.txt') as f: card_key, door_key = map(int, f.readlines()) subject_number = 7 value = 1 card_loop = 0 while True: card_loop += 1 value *= subject_number ...
import threading from time import sleep lock = threading.Lock() # funcao que espera 1 segundo def wait(): global lock while True: sleep(1) lock.release() def LerVelocidade(): global lock while True: lock.acquire() print('Leitura da Velocidade') print('cheguei'...
print('gunicorn hook') hiddenimports = ['gunicorn.glogging', 'gunicorn.workers.sync']
from unittest import mock from bx_py_utils.test_utils.datetime import parse_dt from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db.utils import IntegrityError from django.test import TestCase from django.utils import timezone from bx_django_utils.models.m...
import bge scn = bge.logic.getCurrentScene() def CamAdapt(cont): lum = scn.objects['und.lum1'] nab = scn.objects['Naball_gerUnderground'] def LoadPart1(cont): loadObj = []
#!/usr/bin/env python3 '''Written by Corkine Ma 这个模块的大部分是子类化了一个QDialog,用来接受用户的输入,并且将其保存到daily.setting文件夹中 除此之外,还有一个函数,这个函数负责从daily.setting读取数据,并且使用checkandsend.py模块中的 两个函数来判断在数据库位置是否存在监视文件夹中符合正则表达式规则的文件,如果文件夹中有这样的文件 但是数据库中没有,就判定是一篇新日记,然后调用邮件发送程序发送邮件,其会返回一个bool值,大部分情况, 只要参数文件和日志文件不出问题,返回的都是true,至于发送邮件出错,依旧会返回true(因为考虑到可...
from flask import Blueprint from flask import Blueprint from flask_sqlalchemy import SQLAlchemy from sqlalchemy import or_,and_ from .form import * from utils import * from decorators import admin_required, permission_required # from .. import app from flask import current_app from wtforms import ValidationError, vali...
#!/usr/bin/env python from distutils.core import setup import uritemplate base_url = "http://github.com/uri-templates/uritemplate-py/" setup( name = 'uritemplate', version = uritemplate.__version__, description = 'URI Templates', author = 'Joe Gregorio', author_email = 'joe@bitworking.org', url = base_ur...
# # Copyright (C) 2019 Luca Pasqualini # University of Siena - Artificial Intelligence Laboratory - SAILab # # # USienaRL is licensed under a BSD 3-Clause. # # You should have received a copy of the license along with this # work. If not, see <https://opensource.org/licenses/BSD-3-Clause>. # Import scripts from .pass...
from appcontroller import AppController class CustomAppController(AppController): def __init__(self, *args, **kwargs): AppController.__init__(self, *args, **kwargs) def start(self): print "Calling the default controller to populate table entries" AppController.start(self) def sto...
import json import os, re import numpy as np import pandas as pd from scipy.stats import describe from tqdm import tqdm # Open a file path = "/home/ubuntu/model-inference/rayserve/gpt-optim" dirs = os.listdir(path) # This would print all the files and directories latency_list = [] requests = {} for file in dirs: ...
# Crei um programa que mostre na tela todos os números pares que estão no intervalo entre 1 e 50. """for contador in range(1, 51): if contador % 2 == 0: if contador == 50: print(f'{contador}.') else: print(f'{contador}, ', end='') """ for contador in range(2, 51, 2): ...
from functools import partial from copy import copy import numpy as np from PyQt5.QtWidgets import ( QGridLayout, QHBoxLayout, QVBoxLayout, QGroupBox, QCheckBox, QComboBox, QScrollArea, QLabel, QSlider, ) from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg from matplotl...
# # PySNMP MIB module RFC1407-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RFC1407-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:48:41 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 0...
# coding: utf8 """语音结果和指令比对""" from aip import AipNlp from nlp.configs import APP_ID, API_KEY, SECRET_KEY def match(voice2text, command): """匹配指令""" client = AipNlp(APP_ID, API_KEY, SECRET_KEY) nlp_result_grnn = client.simnet(voice2text, command, {"model": "GRNN"}) if nlp_result_grnn.get("score", 0.5...
from setuptools import setup setup(name='Numpyextension', version='1.1.1', description='A library focused functions that only require numpy.', url='https://www.github.com/pmp47/Numpyextension', author='pmp47', author_email='phil@zeural.com', license='MIT', packages=['numpyextension'], install_requires=['numpy==...
from cfg import * import socket import re from commands import commands def send_message(message): s.send(bytes("PRIVMSG #" + NICK + " :" + message + "\r\n", "UTF-8")) s = socket.socket() s.connect((HOST, PORT)) s.send(bytes("PASS " + PASS + "\r\n", "UTF-8")) s.send(bytes("NICK " + NICK + "\r\n", "UTF-8")) s.send...
from db_facts.jinja_context import pull_jinja_context import unittest from unittest.mock import patch from .mock_dbcli_config import mock_dbcli_config @patch('db_facts.env_jinja_context.os') class TestEnvJinjaContext(unittest.TestCase): def test_with_env_set(self, mock_os): config = { 'jinja_c...
# Generated by Django 3.1.2 on 2020-10-11 09:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('trainer', '0025_user_data_adaptivity'), ] operations = [ migrations.AddField( model_name='user', name='gamification'...
#!/usr/bin/env python """ Gaussian Distribution based two-tail error data reduction data-processing pipeline for dataframes """ # imports import matplotlib.pyplot as plt import numpy as np from scipy import stats __author__ = "Rik Ghosh" __copyright__ = "Copyright 2021, The University of Texas at Austin" __credi...
""" Module for version router Contains functions and api endpoints for version listing """ import sys from operator import attrgetter from typing import List from fastapi import APIRouter from tracktor.error import ItemNotFoundException from tracktor.models import VersionModel router = APIRouter(prefix="/versions",...
import argon2 import b64 from typing import Optional, Dict, Union, List from securerandom import rand_bytes from kdfs.kdf import Kdf class Argon2Kdf(Kdf): @staticmethod def sensitive(): return Argon2Kdf(12, 2 * 1024 * 1024, 8, argon2.Type.ID, rand_bytes(32)) @staticmethod def fast(): ...
#!/usr/bin/env python from __future__ import print_function import subprocess as sp import argparse import os import re def get_paths(root, extension): # scan directories paths = [] for root, dirs, files in os.walk(root): for name in files: if name.endswith(extension): ...
from class_names import CLASS_NAMES import json import numpy as np import scipy import re FEATURES = [ 'calls_to_batchCancelOrders', 'calls_to_batchFillOrKillOrders', 'calls_to_batchFillOrders', 'calls_to_batchFillOrdersNoThrow', 'calls_to_cancelOrder', 'calls_to_cancelOrdersUpTo', # 'calls...
import argparse import base64 from googleapiclient import discovery from oauth2client.client import GoogleCredentials def get_args(): """ Collect command-line arguments and return the argument values :return: A set of three values: image file name (and path), the operation mode, and the max number of res...
"""Data is typically multi-dimensional. :class:`~smif.metadata.spec.Spec` is used to describe each dataset which is supplied to - or output from - each :class:`~smif.model.model.Model` in a :class:`~smif.model.model.CompositeModel` """ from collections import defaultdict from smif.metadata.coordinates import Coordinat...
#!/usr/bin/env python # Copyright 2021 Google 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 require...
""" Transport for communicating with the LaunchKey API of HTTP""" import requests from .. import LAUNCHKEY_PRODUCTION from .base import APIResponse, APIErrorResponse class RequestsTransport(object): """ Transport class for performing HTTP based queries using the requests library. """ url = LAUN...
# Copyright (c) IOTIC LABS LIMITED. All rights reserved. Licensed under the Apache License, Version 2.0. from typing import Callable import base58 from iotics.lib.identity.api.advanced_api import AdvancedIdentityLocalApi from iotics.lib.identity.crypto.identity import make_identifier from iotics.lib.identity.crypto....
import re # machine snapshot platforms LINUX = "LINUX" MACOS = "MACOS" WINDOWS = "WINDOWS" ANDROID = "ANDROID" IOS = "IOS" IPADOS = "IPADOS" TVOS = "TVOS" PLATFORM_CHOICES = ( (LINUX, 'Linux'), (MACOS, 'macOS'), (WINDOWS, 'Windows'), (ANDROID, 'Android'), (IOS, 'iOS'), (IPADOS, 'iPadOS'), ...
from __future__ import absolute_import, print_function, division, unicode_literals import sys import os from subprocess import Popen, PIPE from time import time import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn import datasets from mlfromscratch.util import ( ...
''' Module defining the toolkit in use. Created on Feb 13, 2019 @author: albertgo ''' import os # determine toolkit to be used when loading o molecules TOOLKIT = os.environ.get("CDDLIB_TOOLKIT",None) if not TOOLKIT: # default is openeye but try falling back on rdkit if oe is not available try: import ...
__all__ = ['HighCardinalityStringIndexer'] import json import logging from typing import Dict, List import pyspark.sql.functions as F from pyspark import SparkContext, keyword_only from pyspark.ml import Estimator, Transformer from pyspark.ml.feature import IndexToString, StringIndexer from pyspark.ml.param import Pa...
from pathlib import Path import pandas as pd import ibis import ibis.expr.operations as ops import ibis.expr.types as ir from ibis.backends.tests.base import BackendTest, RoundHalfToEven class TestConf(BackendTest, RoundHalfToEven): check_names = False additional_skipped_operations = frozenset({ops.StringSQ...
from selenium import webdriver # https://askubuntu.com/questions/870530/how-to-install-geckodriver-in-ubuntu def start_firefox(): my_browser = webdriver.Firefox() # send the browser to a specif URL my_browser.get('https://pitpietro.github.io/') # simulate the click on a link (and redirect to that lin...
from indice_pollution.extensions import db class Zone(db.Model): __table_args__ = {"schema": "indice_schema"} id = db.Column(db.Integer, primary_key=True) type = db.Column(db.String) code = db.Column(db.String) @classmethod def get(cls, code, type_): return Zone.query.filter_by(code=...
from django import template import datetime from cart.cart import Cart from cart.settings import CART_TEMPLATE_TAG_NAME register = template.Library() @register.simple_tag(takes_context=True, name=CART_TEMPLATE_TAG_NAME) def get_cart(context, session_key=None): """ Make the cart object available in template. ...