text
stringlengths
2
999k
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst import pytest import numpy as np from astropy import units as u from astropy.coordinates.distances import Distance from astropy.coordinates.builtin_frames import ICRS, FK5, Galactic, AltAz, SkyOffsetFrame from astropy.coordinates ...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys,os import multiprocessing import xmlrpc.client import zipfile import shutil def main_input(stream_name, argv): command = 'python scan.py ' + stream_name print(command) for i in range(len(argv)-2): command += ' \''+argv[i+2]+'\'' ret = os.syst...
# coding: utf-8 # ----------------------------------------------------------------------------------- # <copyright company="Aspose Pty Ltd" file="PpsxConvertOptions.py"> # Copyright (c) 2003-2019 Aspose Pty Ltd # </copyright> # <summary> # Permission is hereby granted, free of charge, to any person obtaining a cop...
#!/usr/bin/python3 '''Copyright (c) 2018 Mozilla 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 the above copyright notice, this list of conditions and the follow...
# -*- coding: utf-8 -*- # # Copyright (C) 2014 Google 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 applicabl...
from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class IEC_61883_1(Base): __slots__ = () _SDM_NAME = 'iec61883-1' _SDM_ATT_MAP = { 'CIP 1': 'iec61883-1.header.CIP-1', 'CIP 2': 'iec61883-1.header.CIP-2', 'Select FDF': 'iec61883-1.header.selectFDF', ...
from google.appengine.ext import db from handlers.handler import Handler from models.like import Like from utilities import Utils class NewLikeHandler(Handler): def get(self, post_id): key = db.Key.from_path('Post', int(post_id), parent=Utils.blog_key()) post = db.get(key) if self.user a...
from rbnfrbnf.passes.ir_constructs import * from rbnfrbnf.core.utils import * from rbnfrbnf.core import syntax_graph from typing import Dict, List from collections import defaultdict from functools import reduce from rbnfrbnf.core.tokenizer import InternedString def test_fn(elem): if isinstance(elem, Chain): ...
# Copyright 2019, OpenTelemetry 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 law or agreed to i...
# Copyright 2019 Canonical Ltd # # 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, s...
from starlette.testclient import TestClient from example.annotation.app import app as annotation_app from example.router.app import app as router_app from example.custom_default_version.app import app as default_version_app def test_annotation_app(): test_client = TestClient(annotation_app) assert test_clien...
from dataclasses import dataclass from bindings.gmd.point_property_type import PointPropertyType __NAMESPACE__ = "http://www.opengis.net/gml" @dataclass class Position(PointPropertyType): class Meta: name = "position" namespace = "http://www.opengis.net/gml"
import argparse import os import pathlib from multiprocessing import Process from npbench.infrastructure import (Benchmark, generate_framework, LineCount, Test, utilities as util) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-f", ...
"""/** * @author [Jai Miles] * @email [jaimiles23@gmail.com] * @create date 2020-08-16 17:40:01 * @modify date 2020-08-18 17:31:04 * @desc [ Class to save user profiles to csv. ] */ """ ########## # Imports ########## import os from datetime import datetime from typing import Union, Any ## NOTE: Could...
import random as rand from typing import List, Dict from pulpo.bandits.dataclasses import BanditConfig from pulpo.bandits.dataclasses import EpsilonGreedyArm, Arm, Feedback from pulpo.bandits.online_bandits import OnlineBandit from pulpo.constants import fields class EGreedy(OnlineBandit): _DEFAULT_N = 1 _DE...
#!/bin/env/python3 #-*- encdoing: utf-8 -*- """ """ from __future__ import print_function from __future__ import division import collections import functools import time import sys import os from clusterweb.interfaces import ssh __author__ = "Stephen Offer" """ ======================================================...
import sys import glob import re def simplify_credits(html): """ Replace the credit part of the HTML footer. Return the new text. """ s = r'<a class="muted-link" href="https://pradyunsg\.me">@pradyunsg</a>\'s' pattern = re.compile(s) html = pattern.sub(r'', html) s = r'Copyright &#169; 20...
# __init__.py -- The tests for dulwich # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net> # # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribut...
import pytest TEST_HASHES = { "test": "Jnh+8wNnELksNFVbxkya8RDrxJNL13dUWTXhp5DCx/quTM2/cYn7azzl2Uk3I2zc", "test2": "sh33L5uQeLr//jJULb7mAnbVADkkWZrgcXx97DCacueGtEU5G2HtqUv73UTS0EI0", "testing100" * 10: "5rznDSIcDPd/9rjom6P/qkJGtJSV47y/u5+KlkILROaqQ6axhEyVIQTahuBYerLG", } @pytest.mark.parametrize(('passwo...
''' Created on 28 Jul 2017 @author: julianporter ''' import unittest import traceback VERBOSE=False class TestFramework(unittest.TestCase): testName='test' def setUp(self): self.nTests=1000 self.errors=[] self.good=0 self.count=0 self.crashes=0 d...
# Allows the user to view the constructed HWP bacxground images. Shows all four # HWP rotations associated with a single IPPA angle # import os import sys import numpy as np from astropy.io import ascii from astropy.table import Table as Table from astropy.table import Column as Column from astropy.convolution import ...
import pygame, math, sys, time, main from pygame.locals import * import argparse # Process any arguments passed in through command line parse = argparse.ArgumentParser() parse.add_argument("-f", "--file", help="File that contains any number of gene sets, must be in pre-existing list notation.") parse.add_argument("-n...
# -*- coding: utf-8 -*- #***************************************************************************** # Copyright (C) 2003-2006 Gary Bishop. # Copyright (C) 2006 Jorgen Stenarson. <jorgen.stenarson@bostream.nu> # # Distributed under the terms of the BSD License. The full license is in # the file ...
# Licensed to Modin Development Team under one or more contributor license agreements. # See the NOTICE file distributed with this work for additional information regarding # copyright ownership. The Modin Development Team licenses this file to you under the # Apache License, Version 2.0 (the "License"); you may not u...
"""Wykop API JSON praser module.""" from __future__ import absolute_import try: import simplejson as json except ImportError: import json from wykop.api.parsers.base import BaseParser, Error class JSONParser(BaseParser): def __init__(self, exception_resolver, **json_kwargs): super(JSONParser, se...
import csv import json df = open("bridgeData3.csv",'r').readlines() fin = open('final.csv','r').readlines() # Skips the header of the csv finCsv = fin[1:] finalCsv = df[1:] obj = {} # loop through the csv with images for i in finalCsv: x = i.split(',') obj[x[1]] = {'bridge_name':x[0],'proj_code':x[1],'before_i...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/tasks_v2beta2/proto/cloudtasks.proto import sys _b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode("latin1")) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from ...
import httpx import pytest import six from ddtrace import config from ddtrace.contrib.httpx.patch import patch from ddtrace.contrib.httpx.patch import unpatch from ddtrace.pin import Pin from ddtrace.settings.http import HttpConfig from ddtrace.vendor.wrapt import ObjectProxy from tests.utils import override_config fr...
from __future__ import unicode_literals import unittest import os import shutil import tempfile from psutil import Process from textwrap import dedent #Local Import from yaksh import grader as gd from yaksh.grader import Grader from yaksh.scilab_code_evaluator import ScilabCodeEvaluator from yaksh.evaluator_tests.test...
import copy import platform import random from functools import partial import numpy as np from mmcv.parallel import collate from mmcv.runner import get_dist_info from mmcv.utils import Registry, build_from_cfg from mmcv.utils.parrots_wrapper import DataLoader, PoolDataLoader from torch.utils.data import DistributedSa...
from collections import namedtuple import chainer.functions as F import math from chainer.functions.connection.convolution_2d import Convolution2DFunction from chainer.functions.pooling.pooling_2d import Pooling2D from chainer.utils import conv ReceptiveField = namedtuple('ReceptiveField', ['n', 'jump', 'size', 'sta...
# # Copyright (c) 2021 salesforce.com, inc. # All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause # import logging from os.path import abspath, dirname, join import sys import unittest import numpy a...
import copy import os import torch from torch import nn from torch import optim from ray.tune import Trainable N_LBFGS_STEPS_VALIDATION = 15 class PytorchTrainable(Trainable): """Abstract Trainable class for Pytorch models, which checkpoints the model and the optimizer. Subclass must initialize self.m...
from .ptu import *
# Generated by Django 3.0.2 on 2020-01-27 08:49 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Banks', fields=[ ...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: datahub/resource/v1alpha2/resource.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _messa...
import tkinter import sys from .customtkinter_tk import CTk from .customtkinter_frame import CTkFrame from .appearance_mode_tracker import AppearanceModeTracker from .customtkinter_theme_manager import CTkThemeManager from .customtkinter_canvas import CTkCanvas from .customtkinter_settings import CTkSettings from .cus...
"""Resource manager for apache-solr-jetty-server 4.1 """ # Common stdlib imports import sys import os import os.path import urllib from contextlib import closing # fix path if necessary (if running from source or running as test) try: import engage.utils except: sys.exc_clear() dir_to_add_to_python_path ...
# encoding: utf-8 import json from nose.tools import assert_equal import ckan.lib.search as search import ckan.model as model from ckan.lib.create_test_data import CreateTestData from ckan.tests.legacy import WsgiAppCase from ckan.tests.legacy import StatusCodes class TestAction(WsgiAppCase): @classmethod de...
from microbit import display length = float(input('Enter length: ')) width = float(input('Enter width: ')) square_footage = length * width print('Your room size is {0} square feet.'.format(square_footage)) display.scroll('Your room size is {0} square feet.'.format(square_footage))
# Copyright 2013 Cloudbase Solutions Srl # # 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 l...
# Pyrogram - Telegram MTProto API Client Library for Python # Copyright (C) 2017-2021 Dan <https://github.com/delivrance> # # This file is part of Pyrogram. # # Pyrogram is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import absolute_import from django.conf.urls import url, include from django.utils.translation import ugettext as _ from wiki.core.plugins import registry from wiki.core.plugins.base import BasePlugin from wiki.plugins.attachments import v...
# -*- coding: utf-8 -*- # # Copyright 2018-2020 Data61, CSIRO # # 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 django.test import TestCase from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status CREATE_USER_URL = reverse('user:create') TOKEN_URL = reverse('user:token') def create_user(**params): return get_user_model...
#!/usr/bin/python # -*- coding:utf-8 -*- import time from display import Display import apis.psutil_metrics import apis.darksky_weather import RPi.GPIO as GPIO KEYPRESS_DELAY = 5000 def handle_button_press(channel): print("Pressed button on channel {0}".format(channel)) channel_page_mapping[channel]() def...
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. # # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. # Copyright 2019 Kakao Brain # # you may not use this file except in compliance with the License. # You may obtain a cop...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
"""Provides the repository macro to import TFRT.""" load("//third_party:repo.bzl", "tf_http_archive") def repo(): """Imports TFRT.""" # Attention: tools parse and update these lines. TFRT_COMMIT = "39a5480e146ef2c20063a6e700d4344d052bc3ca" TFRT_SHA256 = "5fec22def29aabacb3797a26a10d7889b316ba293dc1e1...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import urllib from datetime import date import django.dispatch from dj.choices import Country from django.core.urlresolvers import reverse from...
import numpy as np import matplotlib.pyplot as plt from matplotlib import animation def init_byouga(plt): """ 迷路の初期描画""" # 迷路を描画 fig = plt.figure(figsize=(5, 5)) ax = plt.gca() # 壁の描画 plt.plot([1,1], [0,1], color='red', linewidth=2) plt.plot([1,2], [2,2], color='red', lin...
from globomap_auth_manager import exceptions from jsonschema.exceptions import ValidationError from werkzeug.exceptions import BadRequest from globomap_loader_api.api import util from globomap_loader_api.api.v2 import api from globomap_loader_api.api.v2.auth.exceptions import AuthException @api.errorhandler(exceptio...
import unittest import sys from os import path sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) ) from musictheory.musutility import rotate, enl_seq, multislice, norm_seq, repseq, rotate_and_zero, scalar_addition from musictheory.temperament import M_SHARP, M_FLAT, M_NATURAL, seq_dict, NSEQ_SCALE...
# rm *.txt & ./bash.sh # experiments/base_model/params.json # cd /Users/xiaofengzhu/Documents/continual_learning/src # tensorboard --logdir import argparse import logging import os import time import glob import tensorflow as tf from model.utils import Params from model.utils import set_logger from model.utils import c...
#!/usr/bin/env python ##### -*- coding: cp1252 -*- #Extension import os try: from madgraph.madweight.MW_fct import * import madgraph.madweight.diagram_class as diagram_class import madgraph.madweight.mod_file as mod_file import madgraph.madweight.Cards as Cards import madgraph.various.misc as misc...
import time def measure_target(): time.sleep(5) return def measure_elapsed_time(f, *args): time1 = time.perf_counter() obj_return = f(*args) time2 = time.perf_counter() print('{:s} took {:.9f} ms to run'.format(f.__name__, (time2-time1)*1e3 )) # print( obj_return ) return obj_return...
from bs4 import BeautifulSoup, NavigableString, Comment import multiprocessing from tqdm import tqdm from lib.common import getRaw, strToDate, connectDB from operator import is_not from functools import partial sectionName = {'정치': 'politics', '경제': 'economy', '사회': 'society', '생활': 'live', '세계': 'world', 'IT': 'it', ...
from model.group import Group def test_deposit_check(app): app.session.login(Group(username="annaTest50", password="annaTest50")) app.session.deposit_check() app.session.logout()
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
import pywaves import axolotl_curve25519 as curve import os import pywaves.crypto as crypto import time import struct import json import base58 import logging import math wordList = ['abandon', 'ability', 'able', 'about', 'above', 'absent', 'absorb', 'abstract', 'absurd', 'abuse', 'access', 'accident', 'ac...
#!/usr/bin/python import sys import os import codecs import datetime import shutil import re day = datetime.date.today().strftime("%Y%m%d") dir = os.listdir("C:/Users/TokuharM/Desktop/Python_Scripts/AppServerLogs") key_word = sys.argv[1] arg_num = len(sys.argv) d_sum = [] if arg_num != 2: print...
# Copyright 2019, OpenCensus 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 law or agreed to in w...
import re import os import sys import inspect import time import functools import shutil import imp from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.button import Button from kivy.base import runTouchApp from kivy.factory import Factory, Facto...
from __future__ import division ''' Author : Lyubimov, A.Y. Created : 05/01/2016 Last Changed: 05/24/2017 Description : PRIME GUI Initialization module ''' import os import wx from wxtbx import bitmaps from libtbx import easy_run import iotbx.phil as ip from iota import prime_description, prime_license fro...
import logging from datetime import datetime import pytest from pydriller import RepositoryMining logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO) # It should fail when no URLs are specified def test_no_url(): with pytest.raises(Exception): list(RepositoryMini...
#!/usr/bin/env python3 from .hash_table import HashTable class QuadraticProbing(HashTable): """ Basic Hash Table example with open addressing using Quadratic Probing """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _colision_resolution(self, key, data=N...
# Copyright (c) Yiming Wang # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging from typing import Any, Dict, List, Optional import torch from torch import Tensor import torch.nn as nn from fairseq import utils from fairseq.mode...
"""Auto-generated file, do not edit by hand. PM metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_PM = PhoneMetadata(id='PM', country_code=508, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='[45]\\d{5}', possible_number_pattern='\\...
from datetime import datetime class App_Logger: def __init__(self): pass def log(self, file_object, log_message): self.now = datetime.now() self.date = self.now.date() self.current_time = self.now.strftime("%H:%M:%S") file_object.write(str(self.date) + "/" + str(self.c...
# __init__.py from .msid import msid_score
# Copyright 2018 The Cornac 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 applicable ...
#!/bin/python3 import sys """ We can make the ladybugs happy in two cases: a) there is at least one empty cell and there are at least two ladybugs for each color. b) the initial configuration is happy (i.e. it is already composed of happy ladybugs) """ if __name__ == '__main__': q = int(input().strip()) fo...
#!/usr/bin/env python3 # Copyright (c) 2013-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import biplist from ds_store import DSStore from mac_alias import Alias import sys output_file = sys.argv...
"""Unit test module for Procedure API and model""" from __future__ import unicode_literals # isort:skip from datetime import datetime, timedelta import json import os import dateutil from flask import current_app import pytest import pytz from sqlalchemy.orm.exc import NoResultFound from portal.extensions import db...
""" Run: python3 zipsrc.py This will create a file `source.zip` which you can upload to Coursys (courses.cs.sfu.ca) as your source code submission. To customize the files used by default, run: python3 zipsrc.py -h """ import sys, os, optparse, shutil, iocollect if __name__ == '__main__': optparser = op...
from unittest import TestCase import logging import mock from twitter_monitor import basic_stream import tweepy logger = logging.getLogger("twitter_monitor") # A mock of the signal module without SIGUSR class FakeSignal(object): signal = mock.Mock() class TestBasicStreamSignals(TestCase): def setUp(self): ...
# # Copyright (C) Stanislaw Adaszewski, 2019 # https://github.com/sadaszewski/named_collection # https://algoholic.eu # https://adared.ch # # License: BSD 2-clause "Simplified" License # from .named_collection import *
"""Utilities for saving/loading Trackable objects.""" # 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.o...
class WordDictionary(object): def __init__(self): """ initialize your data structure here. """ self.trie = {} def addWord(self, word): """ Adds a word into the data structure. :type word: str :rtype: void """ trie=self.trie ...
# Copyright (c) 2014-present PlatformIO <contact@platformio.org> # # 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...
import boto3 import json import os IDENTITY_POOL_ID = os.environ['IDENTITY_POOL_ID'] COGNITO_USER_POOL = os.environ['COGNITO_USER_POOL'] S3_BUCKET = os.environ['S3_BUCKET'] dynamodb = boto3.resource('dynamodb') table = dynamodb.Table(os.environ['TABLE']) s3 = boto3.resource('s3') bucket = s3.Bucket(S3_BUCKET) cognit...
# Copyright (c) 2015 Mirantis 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 or agreed to in writi...
"""A Class for manages a Palantir configuration file""" from datetime import datetime import yaml def format_time_string(time_string): return datetime.strptime(time_string, '%d/%m/%Y') class ConfigurationManager: """Represents a configuration file""" def __init__(self, configuration_filepath): ...
#!/usr/bin/env python3 # Usage: # PYTHONPATH=src ./encode.py <file|directory|glob> /path/to/output.npz # PYTHONPATH=src ./train --dataset /path/to/output.npz import argparse import numpy as np import encoder from load_dataset import load_dataset parser = argparse.ArgumentParser( description='Pre-encode text fi...
import os from django.apps import AppConfig from django.conf import settings class WebConfig(AppConfig): name = "web" def ready(self): debug = settings.DEBUG run_main = os.environ.get("RUN_MAIN") != "true" # When using the development server, `ready` is invoked twice; since ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import os import sys import textwrap import shutil import subprocess import json from pathlib import Path as p from distutils import dir_util as du with open("pathdefine.json", 'r', encoding='utf-8') as f: d = json.load(f) spx_prj_dir = d["spx_prj_dir"] spx_src_dir = d...
import torch import torch.nn as nn import random as rd import sys sys.path.insert(0, 'networks') from Attention import TempAttention from memory_rand import MemoryRamTwoStreamModule, MemoryRamModule, MMModule class HME(nn.Module): def __init__(self, vid_encoder, qns_encoder, ans_decoder, max_len_v, max_len_q, dev...
LAN_DEVICE = 1 WAN_DEVICE = 0 h2 = pop_header(ipv4, on_mismatch=([],[])) # Malformed IPv4 if (h2.vihl & 15) < 5 or packet_size - 14 < (((h2.len & 0xFF) << 8) | ((h2.len & 0xFF00) >> 8)): return ([],[]) h1 = pop_header(ether, on_mismatch=([],[])) if received_on_port == LAN_DEVICE: return ([WAN_DEVICE],[ether(h...
# Copyright Contributors to the Amundsen project. # SPDX-License-Identifier: Apache-2.0 from http import HTTPStatus from typing import Any, Iterable, Mapping, Tuple, Union from flasgger import swag_from from flask import current_app as app from flask_restful import Resource, fields, marshal from metadata_service.ent...
# -*- coding: utf-8 -*- def resolve(obj, path, fallback=None): """ Retrieve nested properties safely Example: resolve( {"out":{"middle":{"in":"Balue"}}}, "out.middle.in" ) → "Balue" :param obj: Dictionary :param path: cot notation representation of dictionary :param fallback: w...
"""ndg_httpsclient HTTPS module containing PyOpenSSL implementation of httplib.HTTPSConnection PyOpenSSL utility to make a httplib-like interface suitable for use with urllib2 """ __author__ = "P J Kershaw (STFC)" __date__ = "09/12/11" __copyright__ = "(C) 2012 Science and Technology Facilities Council" __license__ =...
# -*- coding: utf-8 -*- ### # (C) Copyright (2012-2017) Hewlett Packard Enterprise Development LP # # 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...
import random import rlp from rlp.sedes import big_endian_int, binary, Binary from rlp.utils import int_to_big_endian from eth_utils import ( decode_hex, force_bytes, coerce_args_to_bytes, is_string, to_canonical_address, to_normalized_address, pad_left, keccak, ) from .encoding impor...
def pick_peaks(arr): pos = [] prob_peak = False for i in range(1, len(arr)): if arr[i] > arr[i-1]: prob_peak = i #if the peak is a plateau, it should only return the position of the first element of the plateau elif arr[i] < arr[i-1] and prob_peak: pos.app...
from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): email = forms.CharField(max_length=254, required=True, widget=forms.EmailInput()) class Meta: model = User fields = ('username', 'ema...
"""Support for deCONZ binary sensors.""" from pydeconz.sensor import CarbonMonoxide, Fire, OpenClose, Presence, Vibration, Water from homeassistant.components.binary_sensor import ( DEVICE_CLASS_GAS, DEVICE_CLASS_MOISTURE, DEVICE_CLASS_MOTION, DEVICE_CLASS_OPENING, DEVICE_CLASS_SMOKE, DEVICE_CL...
import pytest from gaphor.core.modeling import NamedElement, Presentation from gaphor.diagram.general import Box, CommentLineItem, Ellipse, Line from gaphor.diagram.presentation import Classified, Named from gaphor.diagram.support import get_model_element from gaphor.UML import Classifier, diagramitems def _issubcla...
# encoding: utf-8 import paths from _crc_algorithms import Crc from _shortcut_generator import ShortcutGenerator from _shortcut_parser import ShortcutParser def shortcut_app_id(shortcut): """ Generates the app id for a given shortcut. Steam uses app ids as a unique identifier for games, but since shortcuts don...
# Copyright 2004-2010 Grant T. Olson. # See license.txt for terms. # # Some of this code was ripped from the logging example # Presumably licensed under the python license # import cPickle import logging import logging.handlers import SocketServer import struct class LogRecordStreamHandler(SocketServer.StreamRequest...
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...