filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_106_23380
""" Plist Service - handles parsing and formatting plist content """ from .exceptions import MuxError from ..util import Log import plistlib import re import ssl import struct from socket import socket from typing import Optional, Dict, Any from .usbmux import USBMux, MuxDevice __all__ = ['PlistService'] log = Log.g...
the-stack_106_23382
class Solution: def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ sett = set(nums) dic = {} for i in sett: dic[i]=nums.count(i) for i in dic: if dic[i]>(len(nums)/2): return i
the-stack_106_23384
#!/usr/bin/env python import time import os import sys import logging from logging.handlers import TimedRotatingFileHandler logger = logging.getLogger(__name__) FORMATTER = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") LOG_FILE = os.path.expanduser("~") + "/isybridge.log" console_handle...
the-stack_106_23386
# 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 agreed to in writing, ...
the-stack_106_23391
# Copyright 2010 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...
the-stack_106_23392
# Copyright 2017 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 applicable law or agreed to in writing, ...
the-stack_106_23394
import sublime import sublime_plugin import re from collections import namedtuple # py3 import compatibility. Better way to do this? try: from .helpers import BaseBlockCommand except ValueError: from helpers import BaseBlockCommand # NOQA # reference: # http://docutils.sourceforge.net/docs/ref/rst/restru...
the-stack_106_23396
import os, sys, math, time import numpy as np from collections import Counter sys.path.append("../IAD-Generator/iad-generation/") from csv_utils import read_csv from sklearn import metrics from sklearn.linear_model import SGDClassifier import scipy import matplotlib import matplotlib.pyplot as plt from itr_sklearn ...
the-stack_106_23397
# Authors: Adam Li <adam2392@gmail.com> # # License: BSD (3-clause) import os from mne.annotations import Annotations from mne.epochs import BaseEpochs from mne.io.meas_info import create_info import numpy as np import pandas as pd import pytest from numpy.testing import assert_array_equal from mne.io import RawArray...
the-stack_106_23398
# coding=utf8 """ webhook.py - Sopel GitHub Module Copyright 2015 Max Gurela Copyright 2019 dgw _______ __ __ __ __ | __|__| |_| |--.--.--.| |--. | | | | _| | | || _ | |_______|__|____|__|__|_____||_____| ________ __ __ __ | | | |.-----.| |--.| |--.-...
the-stack_106_23399
#BattleShip Game # There is randomly oriented ship in the grid either horizontal or vertical. # Ask user to target and sink it for game to over # Provide the user with the accuracy of sinking the ship #Process # 1. Define and initialize grid # 2. Display Grid with col, row names # 3. Randomly assign 4 bloc...
the-stack_106_23400
""" SiamRPN metrics """ import numpy as np from ..filesystem import try_import_colorama def Iou(rect1, rect2): """ caculate interection over union Parameters ---------- rect1: list or np.array, rectangle1 rect2: list or np.array, rectangle2 Returns ------- iou """ ...
the-stack_106_23401
#!/usr/bin/env python # Contributors: # Christopher P. Barnes <senrabc@gmail.com> # Andrei Sura: github.com/indera # Mohan Das Katragadda <mohan.das142@gmail.com> # Philip Chase <philipbchase@gmail.com> # Ruchi Vivek Desai <ruchivdesai@gmail.com> # Taeber Rapczak <taeber@ufl.edu> # Nicholas Rejack <nrejack@ufl.edu> # ...
the-stack_106_23409
from .whatsapp_object import WhatsappObjectWithId class NumberStatus(WhatsappObjectWithId): """ Class which represents a User phonenumber status in WhatsApp service. """ def __init__(self, js_obj, driver=None): super(NumberStatus, self).__init__(js_obj, driver) if "status" in js_obj:...
the-stack_106_23410
# -*- coding: utf-8 -*- """Tools used in **Igniter** GUI.""" import os from typing import Union from urllib.parse import urlparse, parse_qs from pathlib import Path import platform import certifi from pymongo import MongoClient from pymongo.errors import ( ServerSelectionTimeoutError, InvalidURI, Configura...
the-stack_106_23414
# -*- coding: utf-8 -*- # Copyright (c) 2018-2020 Linh Pham # stats.wwdt.me is relased under the terms of the Apache License 2.0 """Location name formatting functions used by the Stats Page""" from typing import Dict #region Formatting Functions def format_location_name(location: Dict): """Returns a string with a...
the-stack_106_23415
import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import os import gc import keras as k from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras.callbacks import ModelCheckpoint...
the-stack_106_23419
# Imports from scipy.io import loadmat from scipy.signal import fftconvolve import numpy as np import gc as garbageCollector ######################################################################################################################## # Load signals from a specific file in the source files # Convenience fu...
the-stack_106_23422
import os with open('./spider/summary.txt', 'r') as sample: f = open('./spider/summary_pretrain.txt','w+') for line in sample.readlines(): if ':' not in line: continue curLine = line.strip().split(":") speaker = curLine[0].strip() sentence = curLine[1].strip() ...
the-stack_106_23425
"""Interactive figures in the Jupyter notebook""" from base64 import b64encode import json import io import os from IPython.display import display, HTML from ipywidgets import DOMWidget, widget_serialization from traitlets import ( Unicode, Bool, CInt, Float, List, Any, Instance, CaselessStrEnum, Enum, defau...
the-stack_106_23427
class TrieNode: def __init__(self, w): self.label = w self.children = {} self.index, self.parent, self.depth = None, None, None def add_child(self, child): self.children[child.label[0]] = child child.parent = self def get_all_leaves(self, f): if len(self.children) == 0: return [f(s...
the-stack_106_23428
#!/usr/bin/env python3 # 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 asyncio import importlib.resources import logging import os import shlex import subprocess import sys import tem...
the-stack_106_23432
# -*- coding: utf-8 -*- ''' The ssh client wrapper system contains the routines that are used to alter how executions are run in the salt-ssh system, this allows for state routines to be easily rewritten to execute in a way that makes them do the same tasks as ZeroMQ salt, but via ssh. ''' # Import python libs from __...
the-stack_106_23433
# -*- coding: utf-8 -*- # # Copyright (c), 2018-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author ...
the-stack_106_23435
import numpy as np import os import pickle import pytest import re import time import shutil from copy import deepcopy from numpy import allclose, isclose from flare import struc, env, gp from flare.parameters import Parameters from flare.mgp import MappedGaussianProcess from flare.lammps import lammps_calculator fro...
the-stack_106_23436
import os import glob import h5py import numpy as np from torch.utils.data import Dataset def download(): BASE_DIR = os.path.dirname(os.path.abspath(__file__)) DATA_DIR = os.path.join(BASE_DIR, 'data') if not os.path.exists(DATA_DIR): os.mkdir(DATA_DIR) if not os.path.exists(os.path.join(DATA_D...
the-stack_106_23445
#--**coding:utf-8**-- # Author : Mark # time : 2021/7/13 16:02 # File : follow_nosignaljuntioncrossing_vehicle.py import random import py_trees import carla from srunner.scenariomanager.carla_data_provider import CarlaDataProvider from srunner.scenariomanager.scenarioatomics.atomic_behaviors import (ActorTransf...
the-stack_106_23446
import re import logging from localstack.utils.common import to_str from localstack.services.generic_proxy import ProxyListener LOG = logging.getLogger(__name__) def fix_creation_date(method, path, response): try: content = to_str(response._content) except Exception: LOG.info('Unable to conve...
the-stack_106_23447
import csv from datetime import datetime from django.core.exceptions import ObjectDoesNotExist from core.utils import to_mg from .models import Category, Glucose import numpy as np import pandas as pd import matplotlib.pyplot as plt import mpld3 DATE_FORMAT = '%m/%d/%Y' TIME_FORMAT = '%I:%M %p' def import_gluco...
the-stack_106_23451
""" Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists: A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3 begin to intersect ...
the-stack_106_23453
from io import StringIO from django.core.management import call_command from .base import UnitTest from unittest.mock import patch, call from tests.helpers import JsonData from django.core.management.base import CommandError from status.models import Block class DownloadBlocksTest(UnitTest): '''Unit tes...
the-stack_106_23454
from keras import backend as K from keras.engine import InputSpec, Layer from keras import initializers, regularizers, constraints # From a PR that is not pulled into Keras # https://github.com/fchollet/keras/pull/3677 # I updated the code to work on Keras 2.x class MinibatchDiscrimination(Layer): """Concatenates...
the-stack_106_23455
""" Local settings - Run in Debug mode - Use console backend for emails - Add Django Debug Toolbar - Add django-extensions as app """ from .base import * # noqa # DEBUG # ------------------------------------------------------------------------------ DEBUG = env.bool('DJANGO_DEBUG', default=True) TEMPLATES[0]['OPT...
the-stack_106_23456
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lice...
the-stack_106_23458
import typing as t from .abc import Node from .exceptions import ParserException, ConstructionException T = t.TypeVar('T') backslash = '\\' split_dept = {'(': ')', '[': ']', '{': '}', '\'': '\'', '"': '"'} def tokenize(string: str, sep: str) -> t.Iterator[str]: assert len(sep) == 1 start = 0 dept = []...
the-stack_106_23460
from apas.util.logging import LogHandler import pathlib import json import os class ConfigHandler: HEADER = "{0: <20}".format("(ConfigHandler):") config_dict = None secrets_dict = None VERBOSITY_OPTIONS = {"Detailed": True, "Standard": False} EMPTY_SECRETS_FILE_CONTENT = { "AMAZON_ACCESS...
the-stack_106_23461
# Copyright The 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 in ...
the-stack_106_23463
from convokit import Corpus, CorpusObject, Transformer from typing import Callable from sklearn.feature_extraction.text import CountVectorizer as CV class BoWTransformer(Transformer): """ Bag-of-Words Transformer for annotating a Corpus's objects with the bag-of-words vectorization of some textual element....
the-stack_106_23465
from collections import namedtuple, OrderedDict from input import parse import tensorflow as tf import numpy as np import json import copy import gensim import subprocess import re import logging def parsing(file, wordvecpath, numpypath, ckptpath,Yp, Yd, H, X, XL, Hin, keep_prob): logging.info('parsing started') ...
the-stack_106_23466
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
the-stack_106_23467
# -*- coding: utf-8 -*- # !/usr/bin/env python """ ------------------------------------------------- File Name: ProxyApi.py Description : Author : JHao date: 2016/12/4 ------------------------------------------------- Change Activity: 2016/12/4: ---------------------...
the-stack_106_23471
# Copyright 2019 Kakao Brain # # 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. """Static skip connection layout of ``@skippable`` modules.""" from typing import Dict, Ite...
the-stack_106_23472
# -*- coding: utf-8 -*- """ Created on Wed Nov 30 22:18:02 2020 @author: Soundarya Ganesh """ import sys import random import threading import json from socket import * import time import numpy as np from time import * from datetime import * import os w_id = sys.argv[2] class Task: def __init...
the-stack_106_23474
""" api.video api.video is an API that encodes on the go to facilitate immediate playback, enhancing viewer streaming experiences across multiple devices and platforms. You can stream live or on-demand online videos within minutes. # noqa: E501 Contact: ecosystem@api.video """ import re # noqa: F401 i...
the-stack_106_23475
# Authors: Manoj Kumar <manojkumarsivaraj334@gmail.com> # Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Joel Nothman <joel.nothman@gmail.com> # License: BSD 3 clause from __future__ import division import warnings import numpy as np from scipy import sparse from math import sqrt fro...
the-stack_106_23479
#!/usr/bin/env python3 # Copyright (c) 2014-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 proper accounting with an equivalent malleability clone # from test_framework.test_framework im...
the-stack_106_23481
import argparse # noqa from typing import List, Tuple, Union import vapoursynth as vs from lvsfunc.misc import source from lvsfunc.types import Range from vardautomation import FileInfo, PresetAAC, PresetWEB, VPath from project_module import encoder as enc from project_module import flt # noqa core = vs.core make...
the-stack_106_23483
# Version: 0.15 """ The Versioneer ============== * like a rocketeer, but for versions! * https://github.com/warner/python-versioneer * Brian Warner * License: Public Domain * Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, and pypy * [![Latest Version] (https://pypip.in/version/versioneer/badge.svg?style=flat) ](ht...
the-stack_106_23485
import traci import numpy as np import timeit import torch from torch.autograd import Variable # phase codes based on environment.net.xml PHASE_NS_GREEN = 0 # action 0 code 00 PHASE_NS_YELLOW = 1 PHASE_NSL_GREEN = 2 # action 1 code 01 PHASE_NSL_YELLOW = 3 PHASE_EW_GREEN = 4 # action 2 code 10 PHASE_EW_Y...
the-stack_106_23487
#!/usr/bin/env python '''A script which returns the mutual information between the predictions of a model and a test data set.''' from __future__ import division #Our standard Modules import argparse import numpy as np import scipy as sp import sys import pandas as pd #Our miscellaneous functions #This module wil...
the-stack_106_23489
# Copyright The PyTorch Lightning team. # # 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...
the-stack_106_23490
from __future__ import unicode_literals import re from .common import InfoExtractor from ..compat import ( compat_urlparse, ) from ..utils import ( ExtractorError, ) class NovaMovIE(InfoExtractor): IE_NAME = 'novamov' IE_DESC = 'NovaMov' _VALID_URL_TEMPLATE = r'http://(?:(?:www\.)?%(host)s/(?:f...
the-stack_106_23491
from flask import Flask, render_template, request from flask_sqlalchemy import SQLAlchemy from send_email import send_mail app = Flask(__name__) ENV = 'prod' if ENV == 'dev': app.debug = True app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:Shree2001@localhost/feedback' else: app.debug = Fa...
the-stack_106_23493
from __future__ import unicode_literals, division, absolute_import import re import urllib import logging from flexget import plugin from flexget.config_schema import one_or_more from flexget.entry import Entry from flexget.event import event from flexget.plugins.plugin_urlrewriting import UrlRewritingError from flex...
the-stack_106_23495
# 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 ...
the-stack_106_23498
""" :copyright: Alistair Muldal :license: Unknown, shared on StackOverflow and Pastebin Reference: P. Perona and J. Malik. Scale-space and edge detection using ansotropic diffusion. IEEE Transactions on Pattern Analysis and Machine Intelligence, 12(7):629-639, July 1990. <http://www.cs.berkeley.edu/~malik/papers/MP-an...
the-stack_106_23500
# -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in: # https://doc.scrapy.org/en/latest/topics/spider-middleware.html import random import requests import execjs from scrapy import signals from scrapy.http import HtmlResponse from scrapy.downloadermiddlewares.useragent...
the-stack_106_23502
import sys import h5py import numpy as np import struct f = h5py.File(sys.argv[1], 'r') print(f.keys()) dataset = f['train'][:] print(dataset.shape, dataset.dtype) queries = f['test'][:] print(queries.shape, queries.dtype) answers = f['neighbors'][:] print(answers.shape, answers.dtype) def serialize(a, file_name): ...
the-stack_106_23505
# -*- coding: utf-8 -*- from odoo import api, models, fields class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' is_edi_proxy_active = fields.Boolean(compute='_compute_is_edi_proxy_active') @api.depends('company_id.account_edi_proxy_client_ids', 'company_id.account_edi_prox...
the-stack_106_23508
# Copyright 2018-2020 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" fil...
the-stack_106_23509
import pygame import pygame_menu from pygame_menu import sound from pygame_menu.themes import Theme class Menu: menu = None screen = None my_theme = None my_image = None sound = None def my_theme(self): font = pygame_menu.font.FONT_8BIT styl = pygame_menu.widgets.MENUBAR_STYLE...
the-stack_106_23511
"""empty message Revision ID: 8ebeb4c2e02f Revises: 2ef21fa29d1b Create Date: 2020-01-30 15:43:59.227314 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "8ebeb4c2e02f" down_revision = "2ef21fa29d1b" branch_labels = None depends_on = None def upgrade(): # ...
the-stack_106_23514
""" Copyright (c) 2018-2020 Intel Corporation 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 wri...
the-stack_106_23515
from fontTools.ttLib import TTFont from afdko.pdflib.fontpdf import (doTitle, FontPDFParams) from afdko.pdflib.otfpdf import txPDFFont from afdko.pdflib.pdfgen import Canvas from test_utils import get_input_path OTF_FONT = 'OTF.otf' # ----- # Tests # ----- def test_doTitle_pageIncludeTitle_1(): with TTFont(ge...
the-stack_106_23517
from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import hashlib import inspect import json import traceback import ray.cloudpickle as pickle import ray.local_scheduler import ray.signature as signature import ray.worker from ray.utils import (Fun...
the-stack_106_23520
#!/usr/bin/env python3 # Copyright 2014 Gaurav Kumar. Apache 2.0 # Gets the unique speakers from the file created by fsp_make_trans.pl # Note that if a speaker appears multiple times, it is categorized as female tmpFileLocation = "data/local/tmp/spk2gendertmp" tmpFile = None try: tmpFile = open(tmpFileLocat...
the-stack_106_23521
from git import Repo # Usage: python3 misc/make_changelog.py 0.5.9 import sys ver = sys.argv[1] g = Repo('.') commits = list(g.iter_commits('master', max_count=200)) begin, end = -1, 0 def format(c): return f'{c.summary} (by **{c.author}**)' print('Notable changes:') notable_changes = {} all_changes = [] ...
the-stack_106_23522
# 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_23523
from flask import jsonify def avg(arr): n = len(arr) sum = 0 # Traverse through all array elements for i in range(n): sum = sum + arr[i] return sum/n def handle(event, context): if event.method == 'POST': x = [int(i) for i in str(event.body,'utf-8').split(",")] result=a...
the-stack_106_23525
""" elasticapm.base ~~~~~~~~~~ :copyright: (c) 2011-2017 Elasticsearch Large portions are :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import datetime import logging import os import platform import soc...
the-stack_106_23526
# Copyright 2019 The Cirq Developers # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
the-stack_106_23528
__author__ = 'mp911de' import paho.mqtt.client as mqtt MQTT_HOST = 'localhost' MQTT_PORT = 1883 # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) # Subscribing in on_connect() means that...
the-stack_106_23529
# Write results to this file OUTFILE = 'runs/snort/100KB/src1-tgt1/ftp-par-ftp-iter00200.result.csv' # Source computers for the request SOURCE = ['10.0.0.1'] # Target machines for the requests (aka server) TARGET = ['10.0.0.2'] # IDS Mode. (ATM: noids, min, max, http, ssl, ftp, icmp, mysql) IDSMODE = 'ftp' # Conne...
the-stack_106_23530
def start(kind, opts, area, grid, scale, iter_raster): kwargs = {} if kind == 'text': if 'flat' in opts: kwargs['spec'] = {'*': 'XX'} from ._text import render as start elif kind == 'tk': kwargs['static'] = True from ._tk import ui as start else: rai...
the-stack_106_23535
# Copyright 2011 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 l...
the-stack_106_23536
import scipy.spatial.distance as spdist import scipy.signal as spsig import numpy as np import matplotlib from applications.eeg.bci_dataset import SAMPLING_FREQUENCY, MONTAGE, load_subject, load_run_from_subject, get_trial, \ get_subject_dataset matplotlib.use("Agg") import matplotlib.pyplot as plt import mne fr...
the-stack_106_23537
import os import glob import math import argparse from PIL import Image ######## # Defs # ######## ## Brightness boost to ensure no content becomes transparent in D2 d2darkest = 4 # RGB: 4 / 256 is the darkest non-transparent black in d2 color palette def boost_brightness(img: Image.Image): # Get a mask from alph...
the-stack_106_23538
# Time: O(n) # Space: O(n) class Solution(object): def repeatedSubstringPattern(self, str): """ :type str: str :rtype: bool """ def getPrefix(pattern): prefix = [-1] * len(pattern) j = -1 for i in xrange(1, len(pattern)): ...
the-stack_106_23540
# Copyright (c) 2014 ITOCHU Techno-Solutions Corporation. # # 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...
the-stack_106_23541
#gui/configProfiles.py #A part of NonVisual Desktop Access (NVDA) #Copyright (C) 2013 NV Access Limited #This file is covered by the GNU General Public License. #See the file COPYING for more details. import wx import config import api import gui from logHandler import log import appModuleHandler import gl...
the-stack_106_23542
import pandas as pd import matplotlib.pyplot as plt import numpy as np import seaborn as sns import os def compute_stats_ar(results, ar_params, verbose=False): weights = results["weights"] error = results["predicted"] - results["actual"] stats = {} abs_error = np.abs(weights - ar_params) symmetr...
the-stack_106_23544
#!/usr/bin/env python3 # Copyright © 2012-13 Qtrac Ltd. All rights reserved. # This program or module is free software: you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any ...
the-stack_106_23545
import tensorflow as tf """Adapted from https://github.com/tkipf/gcn""" def masked_softmax_cross_entropy(preds, labels, mask): """Softmax cross-entropy loss with masking.""" loss = tf.compat.v1.nn.softmax_cross_entropy_with_logits_v2(logits=preds, labels=labels) mask = tf.cast(mask, dtype=tf.float32) ...
the-stack_106_23550
import math hour = int(input()) min = int(input()) min = min + 15 if min >= 60: plus_hour = math.floor(min / 60) min = min%60 hour += plus_hour if hour > 24: hour = math.floor(hour / 24) elif hour==24: hour=0 if min < 10: print(str(hour) + ':0' + str(min)) else: print(str(hour) + ':' + ...
the-stack_106_23551
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutControlStatements(Koan): def test_if_then_else_statements(self): if True: result = 'true value' else: result = 'false value' self.assertEqual(__, result) def test_...
the-stack_106_23552
from fabric.api import sudo, settings from . import system from .containers import conf from .task import Task from .utils import upload_config_template __all__ = [ 'install', 'restart', 'reload', ] class AddPpa(Task): def do(self): sudo('add-apt-repository ppa:nginx/stable') system...
the-stack_106_23553
try: import requests except Exception: print(chr(69)) import os import sys os.system(f"{sys.executable} -m pip install requests") import requests import subprocess import shutil import json import sys import os def download(url:str) -> None: get_responce = requests.get(url, s...
the-stack_106_23554
import logging import itertools import os from typing import List, Tuple, Optional, Iterable from copy import deepcopy from tqdm import tqdm import pandas as pd import numpy as np import torch import gin from ariadne.tracknet_v2.model import TrackNETv2 from ariadne.tracknet_v2.metrics import point_in_ellipse from ari...
the-stack_106_23555
from typing import Any, Dict, List, Optional, Set, Callable, Tuple import torch import copy import warnings from torch.fx import ( GraphModule, ) from torch.fx.graph import ( Graph, Node, Argument, ) from ..utils import ( activation_is_statically_quantized, weight_is_quantized, get_qparam_di...
the-stack_106_23556
# qubit number=2 # total number=3 import cirq import qiskit from qiskit.providers.aer import QasmSimulator from qiskit.test.mock import FakeVigo from qiskit import IBMQ from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer, execute, transpile from pprint import pprint from q...
the-stack_106_23557
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import, division, print_function import re import random import itertools import functools from decimal import Decimal from pathlib import Path from cached_property import cached_property from ._common import PokerEnum, _ReprMixin from .card imp...
the-stack_106_23559
#!/usr/bin/python #imports import string import sys import os import shutil import copy import math #the usage string, printed when the user is abusing our tool, lol usage = """usage: ptcl2vms.py [options] <infile1> [[options] <infile2>] ... <outfile> valid options are... -stride (int) adjusts with what stride we ...
the-stack_106_23561
import tkinter as tk from tkinter import * root = tk.Tk() root.title("C语言中文网") root.geometry('450x180+300+200') root.iconbitmap('C:/Users/Administrator/Desktop/C语言中文网logo.ico') # 创建一个滚动条控件,默认为垂直方向 sbar1 = tk.Scrollbar(root) # 将滚动条放置在右侧,并设置当窗口大小改变时滚动条会沿着垂直方向延展 sbar1.pack(side=RIGHT, fill=Y) # 创建水平滚动条,默认为水平方向,当拖动窗口时会沿着X...
the-stack_106_23562
# Copyright 2016-2017 Capital One Services, 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 ...
the-stack_106_23564
import flask,os from tqdm import tqdm from flask import render_template,jsonify,request,redirect,url_for import graphDataBuilder as gdb import dependancyManager as dm import clustering as cl import mimetypes mimetypes.add_type('application/javascript', '.mjs') app = flask.Flask(__name__) @app.route('/', methods=[...
the-stack_106_23565
#!/usr/bin/env python """ @package ion.agents.agent_alert_manager @file ion/agents/agent_alert_manager.py @author Edward Hunter @brief Class for managing alerts and aggregated alerts based on data streams, state changes, and command errors, for opt-in use by agents. """ __author__ = 'Edward Hunter' # Pyon imports ...
the-stack_106_23567
from __future__ import print_function, division import os, os.path, sys, re, glob import itertools from copy import deepcopy import json from .config import on_rtd from .logger import getLogger logger = getLogger() if not on_rtd: import numpy as np import pandas as pd import numpy.random as rand f...
the-stack_106_23571
# Usage:: # # {{thumbnail:.files/img/favicon.png 200x100 exact_size}} # # where width = 200 & height = 100 # # By default, the macro preserves the aspect ratio of the image. If you set 'exact_size', then the generated thumbnail # will be of the same passed size exactly. 'exact_size' is optional import os ...
the-stack_106_23572
#!/usr/bin/python # # Copyright 2019 Polyaxon, 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...
the-stack_106_23573
""" Test growfactors.csv file contents. """ def test_growfactor_start_year(growfactors): """ Check that growfactors.csv can support Tax-Calculator Policy needs. """ first_growfactors_year = growfactors.index.min() first_taxcalc_policy_year = 2013 assert first_growfactors_year <= first_taxcalc_...