filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_106_16803
import os import logging import azure.storage.blob import azure.core.exceptions from ubiops_connector import OutputConnector, ConnectorError, RecoverableConnectorError, get_variable, retry logger = logging.getLogger('Azure Blob Storage Connector') class Deployment(OutputConnector): def __init__(self, base_dir...
the-stack_106_16805
"""Class module to interface with Square. """ import os from aracnid_logger import Logger from dateutil import tz, utils from dateutil.parser import parse from square.client import Client # initialize logging logger = Logger(__name__).get_logger() class SquareInterface: """Interface to Square. Environment ...
the-stack_106_16807
from unitsofmeasure import decprefix def test(): items = decprefix.prefixes.items() assert len(items) == 20 # there are 20 decimal prefixes for (key, prefix) in items: print(key, prefix) assert key == prefix.symbol assert prefix.base == 10 assert prefix.exponent >= -24 ...
the-stack_106_16810
import os import pymysql import requests as r from multiprocessing.dummy import Pool as ThreadPool connection = pymysql.connect(host='localhost', user='root', password='root', db='kinglee-info', charset...
the-stack_106_16815
# # encoders for various output formats # # the dumps() method will be called # import io import csv import dicttoxml from datetime import datetime import uuid import pow_vue def pow_json_serializer(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime): ...
the-stack_106_16816
# Model validation metrics import matplotlib.pyplot as plt import numpy as np def fitness(x): # Model fitness as a weighted combination of metrics w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95] return (x[:, :4] * w).sum(1) def fitness_p(x): # Model fitness as a weighted combi...
the-stack_106_16819
from model.contact import Contact testdata = [ Contact(first_name="first", last_name="last", email="em", email2="em2", email3="em3", day="day", month="mon", year="year", notes="no", homephone="home", mobilephone="mob", workphone="work", secondaryphone="sec", ...
the-stack_106_16821
#!/usr/bin/env python # # Copyright (c) 2001 - 2016 The SCons Foundation # # 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 us...
the-stack_106_16823
from ows_refactored.ows_legend_cfg import legend_idx_0_1_5ticks style_ls_simple_rgb = { "name": "simple_rgb", "title": "Simple RGB", "abstract": "Simple true-colour image, using the red, green and blue bands", "components": {"red": {"red": 1.0}, "green": {"green": 1.0}, "blue": {"blue": 1.0}}, ...
the-stack_106_16825
# Copyright (c) 2018 luozhouyang # # 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, modify, merge, publish, distrib...
the-stack_106_16828
import os import sys import yaml VERSION = os.environ.get("VERSION", "latest") OPENSTACK_VERSION = os.environ.get("OPENSTACK_VERSION", "latest") BUILD_TYPE = os.environ.get("BUILD_TYPE", "all") OPENSTACK_CORE_PROJECTS = [ "cinder", "designate", "glance", "heat", "horizon", "keystone", "ne...
the-stack_106_16830
from rlberry.envs.benchmarks.grid_exploration.nroom import NRoom from rlberry.agents.dynprog import ValueIterationAgent env = NRoom(nrooms=9, remove_walls=False, room_size=9, initial_state_distribution='center', include_traps=True) horizon = env.observation_space.n agen...
the-stack_106_16835
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import json import logging import os import pkgutil import threading import xml.etree.Ele...
the-stack_106_16838
from logging import WARN from discord import Embed from discord.ext.commands import Group from yaml import YAMLError, safe_load from core.api import split_camel def __resolve_alias(cmd): return set([cmd.name] + cmd.aliases) def get_help(bot) -> tuple: """ Return a general Embed onject for help. :p...
the-stack_106_16840
#============================================================================== # Import packages #============================================================================== import numpy as np import pandas as pd # Utilities from sklearn.utils import resample # Transformer to select a subset of the Pandas DataFram...
the-stack_106_16842
import torch import torch.optim as optim import torch.nn as nn import torch.nn.functional as F from torch.nn.functional import relu, avg_pool2d from torch.autograd import Variable import torchvision from torchvision import datasets, transforms import os import os.path from collections import OrderedDict import matpl...
the-stack_106_16844
from django.conf.urls import patterns, url from views import * urlpatterns = patterns('', url(r'^$', contact_list, name='contacts'), url(r'^list/$', contact_list, name='contact_list'), url(r'^add/$', contact_add, name='contact_add'), url(r'^edit/$', contact_edit, name='contact_edit'), url(r'^de...
the-stack_106_16845
""" Encapsulate the methodology to process a segment from the moves-api. Builds rdf triples based on: http://motools.sourceforge.net/event/event.html """ import logging from rhobot.components.storage import StoragePayload from move_bot.components.update_service.interval_handler import IntervalHandler from move_bot.c...
the-stack_106_16847
# Copyright (c) 2018 PaddlePaddle 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 app...
the-stack_106_16848
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals class LRScheduler(object): """Base class of a learning rate scheduler. A scheduler returns a new learning rate based on the number of updates that have...
the-stack_106_16849
""" Utility for creating a Python repl. :: from prompt_toolkit.contrib.repl import embed embed(globals(), locals(), vi_mode=False) """ # Warning: don't import `print_function` from __future__, otherwise we will # also get the print_function inside `eval` on Python 2.7. from __future__ import unicod...
the-stack_106_16850
#!/usr/bin/env python3 # Copyright (c) 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. """Test bitcoin-cli""" from test_framework.test_framework import BitcoinTestFramework from test_framework.util ...
the-stack_106_16851
from django.conf.urls import url from paying_for_college.views import * urlpatterns = [ # url(r'^$', # BuildComparisonView.as_view(), name='worksheet'), url(r'^offer/$', OfferView.as_view(), name='offer'), url(r'^offer/test/$', OfferView.as_view(), {'test': True}, name='offer_te...
the-stack_106_16853
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import division ## # Copyright (C) Benjamin D. McGinnes, 2013-2017 # ben@adversary.org # OpenPGP/GPG key: 0x321E4E2373590E5D # # Version: 0.0.1 # # BTC: 1KvKMVnyYgLxU1HnLQmbWaMpDx3Dz15DVU # # # # Requirements: #...
the-stack_106_16854
import re from difflib import SequenceMatcher from rapidfuzz import string_metric def cal_true_positive_char(pred, gt): """Calculate correct character number in prediction. Args: pred (str): Prediction text. gt (str): Ground truth text. Returns: true_positive_char_num (int): The...
the-stack_106_16855
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `temp` package.""" import datetime import pytest import random from click.testing import CliRunner from temp import cli from temp import temp @pytest.fixture def response(): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fix...
the-stack_106_16856
# Copyright 2015 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 agreed to in writing, s...
the-stack_106_16857
import pyglet # noqa from pyglet.gl import * # noqa from collections import OrderedDict # noqa from time import time # noqa from os.path import abspath # noqa from pyglet.window import key # noqa import cProfile # noqa import pstats # noqa import StringIO # noqa from time import time, sleep # noqa from utility imp...
the-stack_106_16859
""" Support for Nest thermostats. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/climate.nest/ """ import logging import voluptuous as vol from homeassistant.components.nest import DATA_NEST, SIGNAL_NEST_UPDATE from homeassistant.components.climate imp...
the-stack_106_16866
import os import random import argparse import torch import numpy as np import Core.Constants as Constants from Core.Utils import build_vocab_idx, convert_instance_to_idx_seq,\ set_seed_everywhere from Core.Dataset import read_instances_from_file def parse_args(): """ Wrapper function of argument parsing ...
the-stack_106_16869
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import json import logging import warnings from typing import Any, Dict, List, Optional, Tuple, Union import ax.service.utils.best_point as best_point_utils import numpy as np import pandas as pd from ax.core.arm import Arm...
the-stack_106_16870
"""Testing for imputers.""" # Author: Johann Faouzi <johann.faouzi@gmail.com> # License: BSD-3-Clause import numpy as np import pytest import re from pyts.preprocessing import InterpolationImputer X = [[np.nan, 1, 2, 3, np.nan, 5, 6, np.nan]] @pytest.mark.parametrize( 'params, error, err_msg', [({'missing...
the-stack_106_16871
"""Select platform for Advantage Air integration.""" import logging from homeassistant.components.ffmpeg import CONF_INPUT from homeassistant.components.number import NumberEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_NAME, Platform from homeassistant.core import Hom...
the-stack_106_16872
# encoding: utf-8 """ @author: liaoxingyu @contact: sherlockliao01@gmail.com """ import copy import logging import time import itertools from collections import OrderedDict import numpy as np import torch import torch.nn.functional as F from sklearn import metrics from fastreid.utils import comm from fastreid.utils....
the-stack_106_16876
# __init__.py is a special Python file that allows a directory to become # a Python package so it can be accessed using the 'import' statement. from datetime import datetime import os import logging from flask_script import Manager from flask import Flask, request from flask_sqlalchemy import SQLAlchemy from flask_m...
the-stack_106_16877
""" This file offers the methods to automatically retrieve the graph Deltaproteobacteria bacterium RIFCSPLOWO2_12_FULL_40_28. The graph is automatically retrieved from the STRING repository. References --------------------- Please cite the following if you use the data: ```bib @article{szklarczyk2019string, ti...
the-stack_106_16879
#!/usr/bin/env python3 import re import heapq with open("input.txt") as f: depth_line, target_line = f.read().strip().split("\n") depth = int(re.findall("[0-9]+", depth_line)[0]) coords = re.findall("[0-9]+", target_line) tx, ty = int(coords[0]), int(coords[1]) erosion = {} # just go way beyond the target, hop...
the-stack_106_16882
#!/usr/bin/python3 # Copyright (C) 2020 Sam Steele # 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...
the-stack_106_16883
import unittest import result class TestCodeSlice(unittest.TestCase): SOURCE_CODE = "#include <stdio.h>\n" \ "\n" \ "int main(void) {\n" \ " printf(\"Hello, world!\\n\");\n" \ " \n" \ " return 0;\n" \ "}...
the-stack_106_16885
# Copyright (c) 2013 OpenStack 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 # # Unless required by applicable law or agreed to in ...
the-stack_106_16886
import datetime import hashlib import time from collections import namedtuple, OrderedDict from copy import copy from itertools import chain import os import csv import signal import gevent from .exception import StopUser, CatchResponseError import logging console_logger = logging.getLogger("locust.stats_logger") "...
the-stack_106_16888
#!/usr/bin/env python """ Node converts joystick inputs into commands for Turtlesim """ import rospy from geometry_msgs.msg import Twist from sensor_msgs.msg import Joy from move_circle import move_circle def joy_listener(): # start node rospy.init_node("turtlesim_joy", anonymous=True) # subscribe to j...
the-stack_106_16889
import torch import torchvision from PIL import Image from matplotlib import pyplot as plt import random model = torchvision.models.__dict__['vgg19']() print(model) img = torch.rand(1,3,256,256) out = model.features(img) print(out.size()) import torchvision.transforms as trans crop = trans.RandomCrop(224) img = tor...
the-stack_106_16890
#!/usr/bin/env python import re import sys import logging import argparse from unicon.mock.mock_device import MockDevice, MockDeviceTcpWrapper logger = logging.getLogger(__name__) class MockDeviceSpitfire(MockDevice): def __init__(self, *args, **kwargs): super().__init__(*args, device_os='iosxr', **kwa...
the-stack_106_16891
import os import os.path import numpy as np import copy import torch from .base import BaseDataset from . import augmentation as psp_trsform from torch.utils.data import DataLoader from torch.utils.data.distributed import DistributedSampler import random class city_dset(BaseDataset): def __init__(self, data_root...
the-stack_106_16893
# -*- coding: utf-8 -*- # # Copyright (C) 2019 Esteban J. Garcia Gabancho. # Copyright (C) 2020 Mojib Wali. # # invenio-shibboleth is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Module tests.""" from __future__ import absolute_impo...
the-stack_106_16894
import pathlib import json import pytest scriptDir = pathlib.Path(__file__).parent.resolve() test_data_dir = str(scriptDir) + "/test_data/" class Helpers: @staticmethod def getQueryForTest(filename): global test_data_dir f1 = open(test_data_dir + filename + '/query.sql', "r") ...
the-stack_106_16895
#!/usr/bin/python # created: Marc 2020 # author: Marc Torrent # modified: import numpy as np import pandas as pd pi = np.pi def power_spectral_density(x, time_step, freq_range=None, N_pieces=None): """ returns the *single sided* power spectral density of the time trace x which is sampled at intervals time_s...
the-stack_106_16900
import json import requests class TelegramApi(object): """ """ URL = "https://api.telegram.org/bot" def __init__(self, token): self.token = token def get_me(self, save=False): """ :param save: :return: """ _url = self.URL + s...
the-stack_106_16903
import argparse import csv import re import random from cycler import cycler from pathlib import Path from matplotlib.cm import get_cmap from matplotlib.lines import Line2D import matplotlib.pyplot as plt def cactus_plot(args): colors = list(get_cmap('tab20').colors) colors = colors[:-1:2] + colors[1::2] ...
the-stack_106_16904
# -*- coding: utf-8 -*- # Copyright 2021 Cohesity Inc. class UdaRestoreObjectParams(object): """Implementation of the 'UdaRestoreObjectParams' model. Attributes: new_object_name (string): The new name of the object, if it is going to be renamed. overwrite (bool): Whether to overwr...
the-stack_106_16905
# Modified from: https://github.com/pliang279/LG-FedAvg/blob/master/models/Nets.py # credit goes to: Paul Pu Liang #!/usr/bin/env python # -*- coding: utf-8 -*- # Python version: 3.6 import torch from torch import nn import torch.nn.functional as F from torchvision import models import json import numpy as np from mo...
the-stack_106_16908
from typing import Iterator, Optional, Set, Union from google.cloud.storage import Bucket from storage_bucket.client import get_client def list_buckets( max_results: Optional[int] = None, page_token: Optional[str] = None, prefix: Optional[str] = None, fields: Optional[Set] = None, projection: st...
the-stack_106_16913
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test new Arvcoin multisig prefix functionality. # from test_framework.test_framework import BitcoinT...
the-stack_106_16917
## @package attention # Module caffe2.python.attention from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals class AttentionType: Regular, Recurrent = range(2) def s(scope, name): # We have to manually scope due t...
the-stack_106_16918
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) The James Hutton Institute 2017-2019 # (c) The University of Strathclyde 2019 # Author: Leighton Pritchard # # Contact: # leighton.pritchard@strath.ac.uk # # Leighton Pritchard, # Strathclyde Institute of Pharmaceutical and Biomedical Sciences # The University of Stra...
the-stack_106_16919
# Copyright 2013-2019 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 SicmHigh(CMakePackage): """SICM's high-level interface. Seeks to automatically profile...
the-stack_106_16920
import pathlib import random import shutil import subprocess import sys from abc import abstractmethod from dataclasses import dataclass from typing import Dict, Tuple, Callable import tabsave TEST_ROOT_DIR = pathlib.Path.home() / '.tabsave_test' TEST_GAME_SAVE_DIR = TEST_ROOT_DIR / 'They Are Billions' / 'Saves' CONF...
the-stack_106_16921
from checkov.common.models.enums import CheckCategories, CheckResult from checkov.terraform.checks.resource.base_resource_value_check import BaseResourceValueCheck class RDSClusterSnapshotEncrypted(BaseResourceValueCheck): def __init__(self): name = "Ensure that RDS database cluster snapshot is encrypted"...
the-stack_106_16922
""" A trainer class. """ import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np from model.aggcn import GCNClassifier from utils import torch_utils class Trainer(object): def __init__(self, opt, emb_matrix=None): raise NotImplementedErro...
the-stack_106_16923
# 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 ...
the-stack_106_16924
from sentiment import TweetAnalyser from unittest.mock import patch from unittest import mock import pytest def test_classify_tweet(): ta = TweetAnalyser("matthieu_run") result = ta.classify_tweet("All is happy and well.") assert result == 1 @patch("sentiment.pickle") @patch("sentiment.os.path.abspath")...
the-stack_106_16925
import datetime from pathlib import Path import pytest from dateutil.parser import isoparse from pystarport.ports import rpc_port from .utils import ( cluster_fixture, wait_for_block_time, wait_for_new_blocks, wait_for_port, ) """ slashing testing """ # use custom cluster, use an unique base port @...
the-stack_106_16927
import bpy import bmesh import numpy as np import utils from mathutils import Vector, Matrix from math import pi def PCA(data, num_components=None): # mean center the data data -= data.mean(axis=0) # calculate the covariance matrix R = np.cov(data, rowvar=False) # calculate eigenvectors & eigenval...
the-stack_106_16928
# -*- coding: utf-8 -*- from __future__ import unicode_literals from contrail_api_cli.utils import printo, parallel_map from contrail_api_cli.exceptions import ResourceNotFound from ..utils import CheckCommand, PathCommand class CleanSIScheduling(CheckCommand, PathCommand): """On some occasion a SI VM can be sc...
the-stack_106_16930
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os import numpy as np from fairseq.data import ( data_utils, Dictionary, AppendTokenDataset, ConcatDat...
the-stack_106_16931
# -*- coding: utf-8 -*- # Copyright 2015 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Routines and a delegate for dealing with locally worked on packages.""" from __future__ import print_function import collecti...
the-stack_106_16932
import numpy as np from math import sqrt, log from Bandit import Bandit #from maze import Sets ''' def get_nearby_set_to_ban(set_index_list, bandit_index, ban_to_set_dict): sets = ban_to_set_dict[str(bandit_index)] min_index = set_index_list[0] min = abs(sets[0]-min_index) for i in set_...
the-stack_106_16934
import json import pickle import numpy as np from tensorflow import keras from tensorflow.keras.models import load_model from config import * model = load_model("saved/model.h5") with open('saved/tokenizer.pickle', 'rb') as handle: tokenizer = pickle.load(handle) with open('saved/lbl_encoder.p...
the-stack_106_16935
#!/usr/bin/python3 import random import sys g = int() h = int() def gh_gt_0(g, h): try: if (g / h) > 0: return '(A) g: {g} h: {h}, g/h > 0'.format(g=g, h=h) else: return False except: return print('''Can't divide by {} or {}'''.format(g, h)) def hg_de...
the-stack_106_16936
''' Created on Jul 5, 2013 @author: Yubin Bai All rights reserved. ''' import time from multiprocessing.pool import Pool from heapq import * parallelSolve = False INF = 1 << 31 def solve(par): graph = {1: [2, 3, 5], 2: [1, 3, 5], 3: [1, 2, 4, 5], 4: [3, 5], 5: [1, 2, 3, 4]} edges = set() f...
the-stack_106_16937
from django.shortcuts import render, redirect from django.views import View from datetime import datetime from task_manager.models import Project from .models import ProjectInfo, UserInfo, UserInProject class Report(View): def get(self, request): if not request.user.is_authenticated: return re...
the-stack_106_16938
from codecs import open from os import path from setuptools import setup HERE = path.abspath(path.dirname(__file__)) # Get version info ABOUT = {} with open(path.join(HERE, "datadog_checks", "marathon", "__about__.py")) as f: exec(f.read(), ABOUT) # Get the long description from the README file with open(path....
the-stack_106_16941
# Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. version_info = (7, 4, 2, 'final', 0) _specifier_ = {'alpha': 'a', 'beta': 'b', 'candidate': 'rc', 'final': ''} __version__ = '%s.%s.%s%s'%(version_info[0], version_info[1], version_info[2], '' if version_info[3]=='...
the-stack_106_16942
import numpy as np def distance(a: int, b: int) -> float: """[Calculate l2 norm which is Euclidean distance between a and b] Args: a (int): [1st point] b (int): [2nd point] Returns: float: [Distance between a and b] """ return np.linalg.norm(a-b) ...
the-stack_106_16947
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import cProfile import decimal import os import tempfile from wolframclient.cli.utils import SimpleCommand from wolframclient.language import wl from wolframclient.serializers import export from wolframclient.utils.debug...
the-stack_106_16948
import argparse import logging import os import random import torch from envs import HOME_DATA_FOLDER, HOME_OUTPUT_FOLDER logger = logging.getLogger(__name__) def boolean_string(s): if s not in {'False', 'True'}: raise ValueError('Not a valid boolean string') return s == 'True' def is_folder_empty...
the-stack_106_16949
import _plotly_utils.basevalidators class RangeValidator(_plotly_utils.basevalidators.InfoArrayValidator): def __init__( self, plotly_name='range', parent_name='layout.scene.yaxis', **kwargs ): super(RangeValidator, self).__init__( plotly_name=plotly_name, parent_name=...
the-stack_106_16950
#!/usr/bin/env python3 # # Copyright (c) 2016 Roberto Riggio # # 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...
the-stack_106_16952
# Copyright 2017 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...
the-stack_106_16954
from rest_framework import viewsets from .models import ListModel from . import serializers from utils.page import MyPageNumberPagination from rest_framework.filters import OrderingFilter from django_filters.rest_framework import DjangoFilterBackend from rest_framework.response import Response from .filter import Filte...
the-stack_106_16957
# 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...
the-stack_106_16958
import dq11s.save import sys import struct DRACONIAN_FLAG_IDENTIFIER = "DLC_00".encode() DRACONIAN_FLAG_OFFSET_FROM_IDENTIFIER = -0x30 DRACONIAN_FLAG_STRUCT = struct.Struct('<IIIIIIII') DRACONIAN_FLAGS_TO_ADD = [ 1, # flag 0 1, # flag 1 1, # flag 2 1, # flag 3 1, # flag 4 1, ...
the-stack_106_16960
from Instrucciones.TablaSimbolos.Instruccion import Instruccion from Instrucciones.TablaSimbolos.Simbolo import Simbolo class Declare(Instruccion): def __init__(self, id, operacion, id2, linea, columna): Instruccion.__init__(self,None,linea,columna) self.identificador = id self.valor = id2...
the-stack_106_16961
import asyncio import errno import datetime import logging import os import socket import sys from django.conf import settings from django.contrib.staticfiles.management.commands.runserver import Command as BaseCommand from django.utils import autoreload from django.utils.encoding import force_text from aiodjango imp...
the-stack_106_16964
from app import db from app.models.user import User from app.forms.auth import EditProfileForm from flask import current_app, Blueprint, render_template, request, redirect, url_for, flash from flask_login import current_user, login_required user = Blueprint('user', __name__, url_prefix='/user') @user.route('/<usernam...
the-stack_106_16965
__author__ = 'patras' from domain_springDoor import * from timer import DURATION from state import state, rv DURATION.TIME = { 'unlatch1': 5, 'unlatch2': 5, 'holdDoor': 2, 'passDoor': 3, 'releaseDoor': 2, 'closeDoors': 3, 'move': 7, 'take': 2, 'put': 2, } DURATION.COUNTER = { ...
the-stack_106_16968
import os import torch from collections import OrderedDict from abc import ABC, abstractmethod from . import networks from tqdm import tqdm class BaseModel(ABC): """This class is an abstract base class (ABC) for models. To create a subclass, you need to implement the following five functions: -- <__in...
the-stack_106_16969
import csv import datetime import re import os import logging import glob #import app.models import app.database import sqlalchemy DB_ENGINE = app.database.engine DB_METADATA = sqlalchemy.MetaData() #1998-02-09 DATEFORMAT = '%Y-%m-%d' LOGGER = logging.getLogger() class TypeMap: """used to map specific types de...
the-stack_106_16971
import os settings = { 'base_dir': os.path.dirname(__file__), # cash True or False 'cash': False, # set name for apps dir 'apps_dir': os.path.abspath(os.path.dirname(__file__) + '/apps'), # set apps folder name 'apps_folder_name': 'apps', # set routes file 'routes_file': 'routes.p...
the-stack_106_16972
""" Copyright (c) 2011 Jeff Garzik AuthServiceProxy has the following improvements over python-jsonrpc's ServiceProxy class: - HTTP connections persist for the life of the AuthServiceProxy object (if server supports HTTP/1.1) - sends protocol 'version', per JSON-RPC 1.1 - sends proper, incr...
the-stack_106_16976
# -*- coding: utf-8 -*- from collections import MutableMapping import inspect def _ipython(local, banner): from IPython.terminal.embed import InteractiveShellEmbed from IPython.terminal.ipapp import load_default_config InteractiveShellEmbed.clear_instance() shell = InteractiveShellEmbed.instance( ...
the-stack_106_16978
# coding: utf-8 """Jupyter Lab Launcher handlers""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import json import os from tornado import web, template from notebook.base.handlers import IPythonHandler, FileFindHandler from jinja2 import FileSystemLoader, Templ...
the-stack_106_16980
# Copyright 2016 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 os def PostUploadHook(cl, change, output_api): return output_api.EnsureCQIncludeTrybotsAreAdded( cl, [ 'master.tryserver.chromium.lin...
the-stack_106_16984
#!/usr/bin/python # @lint-avoid-python-3-compatibility-imports # # threadsnoop List new thread creation. # For Linux, uses BCC, eBPF. Embedded C. # # Copyright (c) 2019 Brendan Gregg. # Licensed under the Apache License, Version 2.0 (the "License"). # This was originally created for the BPF Performance ...
the-stack_106_16985
#!/usr/bin/env python """ Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import os import re import select import sys import tempfile import time from subprocess import PIPE from extra.cloak.cloak import cloak from extra.cloak.cloak import decloa...
the-stack_106_16986
class Solution: def maxValue(self, events: List[List[int]], k: int) -> int: e = sorted(events) @lru_cache(None) def dp(i, k): if k == 0 or i == len(e): return 0 # binary search events to find the first index j s.t. e[j][0] > e[i][1] j = bisect.bisect(e, [e[i][1], math.inf, math...
the-stack_106_16987
# Copyright (c) 2021 Adam Souzis # SPDX-License-Identifier: MIT import collections import re import six import shlex from .util import ( lookup_class, load_module, find_schema_errors, UnfurlError, UnfurlTaskError, ) from .result import serialize_value from .support import Defaults import logging lo...
the-stack_106_16989
import configparser import numpy as np import os import subprocess import time from scipy.io import wavfile CFG_FILE = os.path.join(os.environ['HOME'], 'soundcard.cfg') WAV_FILE_OUT = '/tmp/out.wav' WAV_FILE_IN = '/tmp/in.wav' SAMPLE_RATE = 44100 BIT_DEPTH = np.int16 WAV_FORMAT = 's16ne' VOL_PLAY = 2 ** 16 - 1 DURATIO...
the-stack_106_16990
# Copyright 2016 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 required by applicable law or a...