filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_9526
# coding=utf-8 # Copyright 2022 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 ...
the-stack_0_9527
import tensorflow as tf import numpy as np import csv import random from keras.optimizers import Adam from keras.layers import ( Flatten, Dense, Dropout, Convolution2D, Activation, BatchNormalization ) from keras.models import Model, Sequential, model_from_json from scipy.misc import imread, imresize from sklearn.m...
the-stack_0_9528
from discord.ext import commands import discord import youtube_dl import asyncio from discord import utils import sqlite3 class Player(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot self.db = sqlite3.connect('playlist.db') @commands.command(name="정크랫") async def 정크랫(...
the-stack_0_9532
#!/usr/bin/python # --------------------------------------------------------------------------- # File: indefqpex1.py # Version 12.8.0 # --------------------------------------------------------------------------- # Licensed Materials - Property of IBM # 5725-A06 5725-A29 5724-Y48 5724-Y49 5724-Y54 5724-Y55 5655-Y21 # C...
the-stack_0_9533
import logging from os.path import join from starlette.applications import Starlette from starlette.endpoints import HTTPEndpoint from starlette.middleware.base import BaseHTTPMiddleware from starlette.responses import PlainTextResponse, RedirectResponse from starlette.staticfiles import StaticFiles import opsi from ...
the-stack_0_9534
import numpy as np import torch from torch.autograd import Variable from networks.losses import CombinedLoss from torch.optim import lr_scheduler import os def per_class_dice(y_pred, y_true, num_class): avg_dice = 0 y_pred = y_pred.data.cpu().numpy() y_true = y_true.data.cpu().numpy() for i in range(n...
the-stack_0_9535
import os import torch import torch.nn as nn from torch.utils.data import Dataset import cv2 import numpy as np from PIL import Image from math import ceil class VOCDataset(Dataset): def __init__(self, root_path="data/VOCdevkit", dataset="voc2012", image_size=321, is_training=True): self.dataset = dataset...
the-stack_0_9536
import bisect import json import logging import random from pathlib import Path import discord from discord.ext import commands from bot.constants import Colours log = logging.getLogger(__name__) with Path("bot/resources/halloween/spooky_rating.json").open() as file: SPOOKY_DATA = json.load(file) SPOOKY_DAT...
the-stack_0_9539
from ctypes import byref, windll from ctypes.wintypes import DWORD, HANDLE from typing import Any, Optional, TextIO from prompt_toolkit.data_structures import Size from prompt_toolkit.renderer import Output from prompt_toolkit.utils import is_windows from prompt_toolkit.win32_types import STD_OUTPUT_HANDLE from .colo...
the-stack_0_9541
# Copyright 2015 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.org/licenses/LICENSE-2.0 # # Unless required by applica...
the-stack_0_9542
import random import json from sqlalchemy import Boolean from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.sql.expression import cast from dallinger.models import Info from dallinger.models import Transformation from dallinger.nodes import Agent from dallinger.nodes import Source class MCMCPAgent(Age...
the-stack_0_9543
from __future__ import absolute_import from __future__ import unicode_literals try: from collections import MutableSequence, MutableMapping except ImportError: from collections.abc import MutableSequence, MutableMapping from collections import OrderedDict import ast from functools import reduce from inflectio...
the-stack_0_9544
# Copyright (c) 2018-2020, Manfred Moitzi # License: MIT License import pytest from math import radians import ezdxf from ezdxf.math import Vector, BoundingBox from ezdxf.render.forms import cube from ezdxf.render.mesh import MeshVertexMerger, MeshBuilder, MeshTransformer, MeshAverageVertexMerger from ezdxf.addons impo...
the-stack_0_9545
import datetime from unittest import TestCase from tarentsocialwall.WordpressConnector import WordpressConnector class TestWordpressConnector(TestCase): service = None def setUp(self): self.service = WordpressConnector() def test_convert_to_socialpost_from_event_empty(self): event = []...
the-stack_0_9546
# 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_0_9547
# SECUREAUTH LABS. Copyright 2018 SecureAuth Corporation. All rights reserved. # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # -*- mode: python; tab-width: 4 -*- # # Copyright (C) 2001 Michael Teo <mi...
the-stack_0_9548
# -*- coding: utf-8 -*- """ Doc serving from Python. In production there are two modes, * Serving from public symlinks in nginx (readthedocs.org & readthedocs.com) * Serving from private symlinks in Python (readthedocs.com only) In development, we have two modes: * Serving from public symlinks in Python * Serving fro...
the-stack_0_9549
import re def get_message(fault): match = re.match(r"<class 'Exception'>:([\w\s]+)", fault.faultString) return 'Server error: "{0}"'.format(match.group(1)) def ask_user(message): while True: print(message) answer = input() if re.match(r'\w', answer): re...
the-stack_0_9550
#!/usr/bin/env python # # Copyright 2014 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. """Pack relocations in a library (or copy unchanged). If --enable-packing and --configuration-name=='Release', invoke the relocation...
the-stack_0_9551
# -*- coding: utf-8 -*- import datetime from iemlav import logger import multiprocessing import netfilterqueue from iemlav.lib.firewall.packet_filter import PacketFilter from iemlav.lib.firewall.firewall_monitor import FirewallMonitor from iemlav.lib.firewall import utils class FirewallEngine(object): def __in...
the-stack_0_9553
from collections import defaultdict, Counter, deque from functools import cache from itertools import product, pairwise from multiprocessing import Pool import math import re non_digits = re.compile('[^0-9]+') def sign(a, b, step=1): return int(math.copysign(step, b-a)) def autorange(a,b, step=1): if a == b:re...
the-stack_0_9554
import numpy as np import matplotlib.pyplot as plt from math import ceil from random import randint import pickle,glob, cv2,os def get_input_shape(dataPath, segmentationScheme): imgLoc = "{}/segmentation/{}/training/images/".format(dataPath,segmentationScheme) labelLoc = "{}/segmentation/{}/labels.pickle".for...
the-stack_0_9556
import GCRCatalogs from GCRCatalogs import GCRQuery import pandas as pd import numpy as np # We load the catalog with addons cat = GCRCatalogs.load_catalog('dc2_object_run2.2i_dr6_with_addons') columns_to_get0 = ["objectId", "Ixx_pixel", "Iyy_pixel", "Ixy_pixel", "IxxPSF_pixel", "IyyPSF_pixel", 'IxyPSF_pixel'] #colum...
the-stack_0_9557
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2018, Bruce Smith <Bruce.Smith.IT@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_vers...
the-stack_0_9564
from web3 import Web3, HTTPProvider, IPCProvider, WebsocketProvider import sys sys.path.insert(0,"W3CR") from writer import writer from reader import reader import hashlib import json import time import random import string from datetime import datetime class W3CR(): Writer = None Reader = None T...
the-stack_0_9565
import datetime import hashlib from urllib.parse import urlparse import json class Blockchain(): def __init__(self): self.chain = [] self.nodes = set() self.create_block(proof = 1, previous_hash = '0') def create_block(self, proof, previous_hash): block = {'index': len(self...
the-stack_0_9566
#!/usr/bin/env python from nose.tools import * import cynetworkx as nx class TestFloyd: def setUp(self): pass def test_floyd_warshall_predecessor_and_distance(self): XG = nx.DiGraph() XG.add_weighted_edges_from([('s', 'u', 10), ('s', 'x', 5), ('u', ...
the-stack_0_9567
import os, sys, pygame from pygame.locals import * from Pellet import Pellet from Pacman import Pacman from Box import Box # Initialize Pygame pygame.init() # Initialize Clock mainClock = pygame.time.Clock() # Constants WINDOWWIDTH = 448 #(16 * 28) (row numbers range from 0 - 27) WINDOWHEIGHT = 512 #(16 * 32) (col...
the-stack_0_9570
# -*- coding: utf-8 -*- # # Copyright 2014 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 requir...
the-stack_0_9571
import requests import argparse import sys import os import bs4 import csv import re import enum from datetime import datetime class LogType(enum.Enum): crime = "crime" noncrime = "noncrime" def _process_html(string, output_writer, log_type): soup = bs4.BeautifulSoup(string, features="lxml") table = s...
the-stack_0_9573
import json import zlib def compress(message): try: return zlib.compress( json.dumps(message, separators=(',', ':')), 9 ) except: return '' def decompress(message): try: return json.loads( zlib.decompress(message) ...
the-stack_0_9574
import graphgallery import tensorflow as tf graphgallery.set_memory_growth() print("GraphGallery version: ", graphgallery.__version__) print("TensorFlow version: ", tf.__version__) ''' Load Datasets - cora/citeseer/pubmed ''' from graphgallery.datasets import Planetoid data = Planetoid('cora', root="~/GraphData/data...
the-stack_0_9575
''' Simulation Based on Hippocampus Recordings Copyright Nate Sutton 2015 References: Data from CRCNS.org hc3 . Izhikevich neuron parameters from: http://f1000research.com/articles/3-104/v1 ''' import pylab import nest import math as math import numpy as np ''' Create objects to run experiment with ''' multimeter = ...
the-stack_0_9576
""" Copyright 2021 SAP SE 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, softwar...
the-stack_0_9577
import pipes from galaxy import exceptions from galaxy.util.none_like import NoneDataset from galaxy.util import odict from galaxy.util.object_wrapper import wrap_with_safe_string from logging import getLogger log = getLogger( __name__ ) # Fields in .log files corresponding to paths, must have one of the following # ...
the-stack_0_9578
# !/usr/bin/env python2.7 # File: taxii_parser.py # # Copyright (c) 2014-2016 Splunk 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 # ...
the-stack_0_9579
# Copyright 2008-2015 Nokia Networks # Copyright 2016- Robot Framework 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 ...
the-stack_0_9580
from __future__ import absolute_import import logging import re from django.core.urlresolvers import RegexURLResolver, RegexURLPattern from django.conf.urls import patterns, include, url from sentry.plugins.base import plugins logger = logging.getLogger("sentry.plugins") def ensure_url(u): if isinstance(u, (t...
the-stack_0_9585
""" Since we also expect the answers in the SQuAD format, we reuse its code """ """ Official evaluation script for v1.1 of the SQuAD dataset. """ from collections import Counter import string import re import argparse import json import sys def normalize_answer(s): """Lower text and remove punctuation, articles ...
the-stack_0_9586
#! /usr/bin/env python3 """Simple module/script showing argparse""" from argparse import ArgumentParser def get_args(): """argument parser for argparse_example""" parser = ArgumentParser() parser.add_argument("--datadir", required=False, type=str, default="/logs/MECS", help="path ...
the-stack_0_9587
#!/usr/bin/env python3 import os # requires prompt-toolkit > 2 from prompt_toolkit import PromptSession, HTML from prompt_toolkit.application.current import get_app from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.styles import Style global_kb = KeyBindings() # if bottom toolbar is visible gl...
the-stack_0_9588
from datetime import date from datetime import timedelta import pandas as pd import numpy as np import matplotlib.pyplot as plt class CovidNineteen: def get_latest_daily_report(self): """ Get latest daily report(world) from: https://github.com/CSSEGISandData/COVID-19/tree/master/csse_covid_...
the-stack_0_9593
# Pyrogram - Telegram MTProto API Client Library for Python # Copyright (C) 2017-2018 Dan Tès <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 S...
the-stack_0_9594
from models.app_config import ApplicationGroupConfig from modules.configs.config_factory import ConfigFactory from modules.runner.app_runner import ApplicationRunner from pick import pick def pick_config(app_configs: list[ApplicationGroupConfig]): title = 'Choose which workflow config to start: ' config_opti...
the-stack_0_9597
import pandas as pd import matplotlib.pyplot as plt import csv query = "query-1" auto_scaler = "HPA" percentage = "80" path_to_file = "../experiment_data_processed/full_data/" + query + "_" + auto_scaler + "_" + percentage + ".csv" df = pd.read_csv(path_to_file) taskmanager = df['taskmanager'].tolist() latency = df[...
the-stack_0_9599
""" Current-flow closeness centrality measures. """ # Copyright (C) 2010 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. __author__ = """Aric Hagberg <aric.hagberg@gmail.com>""" __all__ = ['current_flow_cl...
the-stack_0_9600
""" disk_dict.py Copyright 2012 Andres Riancho This file is part of w3af, http://w3af.org/ . w3af 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 version 2 of the License. w3af is distributed in the hope that i...
the-stack_0_9603
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ploting tools.""" import numpy as np import nibabel as nb import pandas as pd from nilearn.signal import clean import matplotlib.pyplot as plt from matplotlib import gridspec as mgs import seaborn as sn...
the-stack_0_9606
#from YourClassParentDir.YourClass import YourClass from math import floor import cv2 import numpy as np import pandas as pd #import multiprocessing as mp from video_process.tracktor import Tracktor class VideoCapture: """ VideoCapture is a class that takes a video, processes it, and returns it. This mean...
the-stack_0_9608
# This file is part of the Reproducible and Reusable Data Analysis Workflow # Server (flowServ). # # Copyright (C) 2019-2021 NYU. # # flowServ is free software; you can redistribute it and/or modify it under the # terms of the MIT License; see LICENSE file for more details. """Helper method to create a API generator b...
the-stack_0_9611
from zope.security.interfaces import Unauthorized from zope.testbrowser.browser import LinkNotFoundError import pytest EVENT_VIEW_CONFIGURATION_ADD_TEXT = 'event view configuration' def test_masterdata__Table__1(address_book, browser): """It allows to navigate to the event views list.""" browser.login('cal-v...
the-stack_0_9612
from setuptools import setup, find_packages PACKAGE_NAME = "lintreview" VERSION = "0.14.0" requirements = open('./requirements.txt', 'r') setup( name=PACKAGE_NAME, version=VERSION, description=""" Lint Review, an automated code review tool that integrates with github. Integrates with the github A...
the-stack_0_9613
from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from scrapy.http import Request, HtmlResponse from scrapy.utils.url import urljoin_rfc from product_spiders.items import Product, ProductLoaderWithNameStrip as ProductLoader class DialaphoneSpider(BaseSpider): name = 'dialaphone.co...
the-stack_0_9614
#!/usr/bin/env python # -*- coding: utf-8 -*- """The setup script.""" from setuptools import setup, find_packages with open('README.md') as readme_file: readme = readme_file.read() with open('HISTORY.md') as history_file: history = history_file.read() install_requires = [ 'torch<2,>=1.0', 'torchvis...
the-stack_0_9617
#!/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. ''' This is a poor man's port of set_up_volume.sh to allow `image_package` to emit btrfs loopbacks. In ~1 weeks' time,...
the-stack_0_9618
import numpy as np import chainer import chainer.functions as F from chainer import initializers import chainer.links as L from models.connections.conv_2d_bn_activ import Conv2DBNActiv from models.connections.resblock import ResBlock from chainercv.links import PickableSequentialChain class SERes2Net(PickableSequen...
the-stack_0_9619
#!/usr/bin/env python # -*- coding:utf-8 -*- """ Date: 2021/12/14 16:30 Desc: 申万指数-申万一级、二级和三级 http://www.swsindex.com/IdxMain.aspx https://legulegu.com/stockdata/index-composition?industryCode=851921.SI """ import time import json import pandas as pd from akshare.utils import demjson import requests from bs4 import Be...
the-stack_0_9620
import pytorch_lightning as pl from torch.utils.data import DataLoader, Dataset from sklearn.model_selection import train_test_split from torchvision import transforms import torch # read data import os import numpy as np from PIL import Image # utils TYPE = ['VA_Set', 'EXPR_Set', 'AU_Set'] CLASS = [2, 1, 12] MEAN = ...
the-stack_0_9621
# 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...
the-stack_0_9623
import os import sys import shutil import jsbeautifier from utils.content import getContent from utils.formatter import Formatter from utils.merge import Merge from utils.classify import Classifier class Process: def main(self, file, argvs): path = sys.path[0] print("************...
the-stack_0_9624
import os import shutil import yaml from six import iteritems from ..base import PackageJson, BasePackageManager, PackageManagerError from .lockfile import PnpmLockfile from .workspace import PnpmWorkspace from .utils import build_pj_path, build_lockfile_path, build_ws_config_path, build_nm_bundle_path class PnpmPa...
the-stack_0_9625
import unittest from models import articles Articles = articles.Articles class ArticlesTest(unittest.TestCase): ''' Test Class to test the behaviour of the Articles class ''' def setUp(self): ''' Set up method that will run before every test ''' self.new_articles = Articles('id','author','desc...
the-stack_0_9626
# -*- coding: utf-8 -*- from seleniumbase import BaseCase class ChinesePdfTests(BaseCase): def test_chinese_pdf(self): pdf = ( "https://github.com/seleniumbase/SeleniumBase/" "files/3895614/unittest.pdf" ) # Get and print PDF text pdf_text = self.get_pdf_t...
the-stack_0_9627
import unittest from yoti_python_sdk.doc_scan.session.retrieve.frame_response import FrameResponse from yoti_python_sdk.doc_scan.session.retrieve.media_response import MediaResponse class FrameResponseTest(unittest.TestCase): def test_should_parse_correctly(self): data = {"media": {}} result = F...
the-stack_0_9630
from synapseclient.activity import Activity # SYNPY-744 def test_private_getStringList(): act = Activity() url_string = \ 'https://github.com/Sage-Bionetworks/ampAdScripts/blob/master/Broad-Rush/migrateROSMAPGenotypesFeb2015.R' act.used([{'wasExecuted': True, 'concreteType': 'org.sa...
the-stack_0_9631
# base16-qutebrowser (https://github.com/theova/base16-qutebrowser) # Base16 qutebrowser template by theova # darkmoss scheme by Gabriel Avanzi (https://github.com/avanzzzi) base00 = "#171e1f" base01 = "#252c2d" base02 = "#373c3d" base03 = "#555e5f" base04 = "#818f80" base05 = "#c7c7a5" base06 = "#e3e3c8" base07 = "#e...
the-stack_0_9632
from datetime import datetime, date from six import iteritems, PY2, PY3, u import json import pytz from enum import Enum if PY3: from datetime import timezone # compat from six.moves import map dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime) or isinstance(obj, date) else None class OutputMo...
the-stack_0_9633
import hashlib import os def upload_path(instance, filename, **kwargs): hasher = hashlib.md5() for chunk in instance.image.chunks(): hasher.update(chunk) hash = hasher.hexdigest() base, ext = os.path.splitext(filename) return '%(first)s/%(second)s/%(hash)s/%(base)s%(ext)s' % { 'fir...
the-stack_0_9634
import os import sys import django import logging sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) profile = os.environ.get('HELLOFAMILYCLUB', 'develop') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hellofamilyclub.settings.{}'.format(profile)) django.setup() from...
the-stack_0_9635
import os from appi2c.ext.database import db def init_app(app): app.config["SECRET_KEY"] = "appi2c_from_raspberry" basedir = os.path.abspath(os.path.dirname('ext/database/')) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'database.db') app.config['SQLALCHEMY_TRACK_MO...
the-stack_0_9637
import pathlib import os import unittest from explainaboard import FileType, Source, TaskType, get_loader, get_processor artifacts_path = os.path.dirname(pathlib.Path(__file__)) + "/artifacts/" class TestTextPairClassification(unittest.TestCase): def test_snli(self): metadata = {"task_name": TaskType....
the-stack_0_9638
import numpy as np import os import sys sys.path.append('mytorch') from loss import * from activation import * from batchnorm import * from linear import * class MLP(object): """ A simple multilayer perceptron """ def __init__(self, input_size, output_size, hiddens, activations, weight_init_fn, ...
the-stack_0_9639
from ._city_transformer_postscripts import CityTransformerPostscripts from ._city_transformer_inverse_postscripts import CityTransformerInversePostscripts def get_postscripts(name): POST_SCRIPTS = { 'CityTransformer': CityTransformerPostscripts, 'CityTransformerInverse': CityTransformerInversePosts...
the-stack_0_9641
import math from typing import Optional import torch from falkon.options import BaseOptions import falkon from falkon.mmv_ops.utils import _setup_opt, _get_cpu_ram from falkon.sparse.sparse_tensor import SparseTensor from falkon.utils.helpers import select_dim_over_d, sizeof_dtype, select_dim_over_m from falkon.utils...
the-stack_0_9642
# Copyright (c) 2012 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. """Defines a set of constants shared by test runners and other scripts.""" # TODO(jbudorick): Split these constants into coherent modules. # pylint: di...
the-stack_0_9644
# Note: Before running this from your laptop, you must run "ray attach cluster.yaml -p 8000" to setup a port-forward from the laptop's port 8000 to the cluster's internal port 8000 # The other option is to use "ray submit" to run this on the cluster as-is without a port-forward import requests input_text_list = ["R...
the-stack_0_9647
import pytest from gitlabform.gitlabform import GitLabForm from gitlabform.gitlabform.test import create_group, create_project_in_group, get_gitlab, GROUP_NAME PROJECT_NAME = 'project_settings_project' GROUP_AND_PROJECT_NAME = GROUP_NAME + '/' + PROJECT_NAME @pytest.fixture(scope="module") def gitlab(request): ...
the-stack_0_9648
# -*- coding: utf-8 -*- import json import requests from openerp import http from openerp.http import request def s2human(time): """Convert a time in second into an human readable string""" for delay, desc in [(86400,'d'),(3600,'h'),(60,'m')]: if time >= delay: return str(int(time / delay...
the-stack_0_9653
# 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_0_9655
""" Скрипт, выводящий информацию о таблице экспорта PE-файла. Для каждой экспортируемой функции выводит имя функции и ее RVA. Также выводит общее количество экспортируемых функций. Пример использования: python get_export_info.py d:/file.exe """ import sys import pefile try: file_path = sys.a...
the-stack_0_9658
import time import cv2 class DetectHumanMovement(object): def __init__(self): self.faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") self.handCascade = cv2.CascadeClassifier("haarcascade_hand_default.xml") self.video_capture = cv2.VideoCapture(0) while True:...
the-stack_0_9659
import os import time import torch import torch.nn as nn from model.utils.general import init_dir, get_logger class BaseModel(object): """Generic class for our model Usage: 1. init 2. build_train() or build_pred() 3. save and restore 4. train and evaluate """ # 1. init def ...
the-stack_0_9663
import _plotly_utils.basevalidators class YanchorValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name='yanchor', parent_name='mesh3d.colorbar', **kwargs ): super(YanchorValidator, self).__init__( plotly_name=plotly_name, parent_n...
the-stack_0_9665
from __future__ import print_function import numpy as np import pytest def pytest_runtest_setup(item): seed = np.random.randint(1000) print("Seed used in np.random.seed(): %d" % seed) np.random.seed(seed) def pytest_addoption(parser): parser.addoption( "--block", action="store", ...
the-stack_0_9666
from rest_framework import status from rest_framework.reverse import reverse from tests.test_profile.test_quota.base_test_quota import BaseTestQuota from tests.utils import check_data_in_dict class TestApiQuotaCreate(BaseTestQuota): def setUp(self): super(TestApiQuotaCreate, self).setUp() self.p...
the-stack_0_9671
from flask.ext.classy import FlaskView, route from flask import render_template, redirect, url_for, flash from flask_menu.classy import classy_menu_item from flask_login import current_user, login_required from Application.models import User from Application.models import Project from .forms import UserEditForm from ...
the-stack_0_9672
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2021, Shreyas Srish (@shrsr) <ssrish@cisco.com> # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_v...
the-stack_0_9674
# # POC FTP Browser for Enigma2 # # for localized messages from . import _ # Config from Components.config import config, ConfigInteger, ConfigSubList, \ ConfigSubsection, ConfigText, ConfigPassword, ConfigYesNo config.plugins.ftpbrowser = ConfigSubsection() config.plugins.ftpbrowser.server = ConfigSubList() c...
the-stack_0_9675
from __future__ import absolute_import import os import re import json import base64 import inspect import requests import mimetypes from contextlib import contextmanager from datetime import datetime, timedelta from django.conf import settings from django.db import transaction from pytz import utc from random import...
the-stack_0_9676
import setuptools with open("README.md", "r", encoding="utf-8") as f: long_description = f.read() setuptools.setup( name="better-ffmpeg-progress", version="2.0.0", author="GitHub.com/CrypticSignal", author_email="theaudiophile@outlook.com", description="Run FFmpeg & see percentage progress + E...
the-stack_0_9677
# 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 appli...
the-stack_0_9678
import os os.environ['DGLBACKEND'] = 'mxnet' import mxnet as mx from mxnet import nd, gluon, autograd import dgl import numpy as np import pandas as pd import time import logging import pickle import math from estimator_fns import * from graph import * from data import * from utils import * from model.mxnet import ...
the-stack_0_9679
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.exceptions import ImproperlyConfigured from django.utils.translation import ugettext_lazy as _ from django_fsm import transition, RETURN_VALUE from shop.models.order import BaseOrder, OrderModel from .base import PaymentProvider class...
the-stack_0_9680
""" Rate expressions only for A+B=R (ABtoR) """ import numpy as np from pmutt import constants as c species_names = ['A', 'B', 'R'] #%% Define the form of the rate constant class RateConstant(): def __init__(self, name = 'k'): self.name = name def value(self, para_dict, temperature=None, ener...
the-stack_0_9681
""" NOTE: This file is not using to.testing.assert_allclose because most methods need to work for both torch and numpy. """ import pytest import numpy as np import torch as to import itertools import pickle from typing import NamedTuple from pyrado.algorithms.utils import ReplayMemory from pyrado.sampling.step_sequenc...
the-stack_0_9683
# Copyright 2017 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_0_9684
import collections as co import itertools as it #argument_parser = argparse.ArgumentParser() #argument_parser.add_argument("jff_path", metavar="jff-file", type=str) #args = argument_parser.parse_args() _Original = co.namedtuple('_Original', ('symbol',)) _Term = co.namedtuple('_Term', ('symbol',)) _Bin = co.namedtupl...
the-stack_0_9685
#!/usr/bin/env python """ Tables dependencies in an Oracle query """ import lib_oracle import lib_common import lib_sql from sources_types.sql import query as sql_query from sources_types.oracle import query as oracle_query def Main(): # cgiEnv = lib_common.CgiEnv() cgiEnv = lib_oracle.OracleEnv() grph = cgiEnv...
the-stack_0_9688
from decimal import Decimal from typing import Optional, Dict, List from django import forms from django.utils.translation import gettext as _ from rest_framework.request import Request from polaris.integrations import WithdrawalIntegration, calculate_fee from polaris.models import Transaction, Asset from polaris.sep...
the-stack_0_9689
import csv import os.path import matplotlib import numpy as np from matplotlib import pyplot as plt matplotlib.rcParams.update({'font.size': 15}) n_trial = 5 top_k = 1 batch_size = 4000 max_step = np.inf max_reward = np.inf min_reward = -np.inf exp_name = 'CartpoleNd' exp_param = 'D1K05A05Ec10' extra_name = '' prep...