filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_106_27090
#!usr/bin/env python3 # -*- coding: utf-8 -*- """ Simple demo of solution of race conditions with locks. Note that the race conditions in this demo are also amplified by fuzzing technique In order to be away with race conditions, we need to 1. Ensure an explicit ordering of the operations (on the shared resources) ...
the-stack_106_27091
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from pyrigidbody3d import quaternion import unittest class QuaternionTest(unittest.TestCase): def test_identity(self): q = quaternion.identity() self.assertLess( np.linal...
the-stack_106_27092
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license """ PyTorch utils """ import datetime import logging import math import os import platform import subprocess import time from contextlib import contextmanager from copy import deepcopy from pathlib import Path import torch import torch.backends.cudnn as cudnn import torch.d...
the-stack_106_27097
#! python """MS²ReScore: Sensitive PSM rescoring with predicted MS² peak intensities and RTs.""" import logging import os import subprocess import tempfile from multiprocessing import cpu_count from typing import Dict, Optional, Union from ms2rescore import id_file_parser, rescore_core, setup_logging from ms2rescore....
the-stack_106_27099
# coding=utf-8 __author__ = 'jamon' import copy from obespoir.share.ob_log import logger from share.message_ids import * from service.mahjong.models.playeract.base_player_act import BasePlayerAct from service.mahjong.constants.gamedefine import Act, SettleType from service.mahjong.models.actrecord import ActRecord fr...
the-stack_106_27100
# 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_27101
# those modules are all taken from ParlAI import numpy as np import numbers import warnings import torch import torch.nn as nn import torch.nn.functional as F import math from typing import Dict, Tuple, Optional from core.modules.treesearch import GreedySearch, BeamSearch, TopKSampling, \ NucleusSampling, DelayedB...
the-stack_106_27102
"""Manages Git.""" from __future__ import unicode_literals import os import logging from dvc.utils.compat import str, open from dvc.utils import fix_env from dvc.scm.base import ( Base, SCMError, FileNotInRepoError, FileNotInTargetSubdirError, ) from dvc.scm.git.tree import GitTree logger = logging...
the-stack_106_27104
import tensorflow as tf import os import numpy as np from model.postprocess import postprocess from tensorflow.keras import callbacks from utils.coco_eval import CocoEvalidation from model.nms import yolov4_nms from tqdm import tqdm class CocoMapCallback(callbacks.Callback): def __init__(self, pred_generator,mod...
the-stack_106_27105
import transaction from datetime import timedelta from pyramid.exceptions import ConfigurationConflictError from ptah.testing import PtahTestCase class TestTokenType(PtahTestCase): _init_ptah = False _auto_commit = False def test_token(self): from ptah import token tt = token.TokenType...
the-stack_106_27106
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import pickle from fvcore.common.checkpoint import Checkpointer from fvcore.common.file_io import PathManager import detectron2.utils.comm as comm from .c2_model_loading import align_and_update_state_dicts class DetectionCheckpointer(Checkpointe...
the-stack_106_27107
#!/usr/bin/python3 import json from argparse import ArgumentParser def get_args(): p = ArgumentParser(description='Merge CLOSURE xdconf.ini files') p.add_argument('-f', '--files', required=True, type=str, help='Input files') p.add_argument('-o', '--outfile', required=False, type=str, default='xdconf.ini',...
the-stack_106_27108
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import os from setuptools import find_packages, setup from url_filter import __author__, __version__ def read(fname): with open(os.path.join(os.path.dirname(__file__), fname), "rb") as fid: return fid.read().decode("utf-...
the-stack_106_27109
# coding=utf-8 # Copyright 2021 The Google Research 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 applicab...
the-stack_106_27110
"""Tools for helping with ANSI color codes.""" import re import sys import warnings import builtins import typing as tp from xonsh.platform import HAS_PYGMENTS from xonsh.lazyasd import LazyDict, lazyobject from xonsh.color_tools import ( RE_XONSH_COLOR, BASE_XONSH_COLORS, make_palette, find_closest_co...
the-stack_106_27111
#!/usr/bin/env python """ Created on Thu Jun 18 10:42:49 2015 Author: Oren Freifeld Email: freifeld@csail.mit.edu """ from of.utils import ObsoleteError raise ObsoleteError("Moved to Tessellation.py") import numpy as np from itertools import product # since we have an unknown number of lists from numpy import binary...
the-stack_106_27113
# 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_27116
#!/usr/bin/env python """ Plots related to the response matrix. .. codeauthor:: Raymond Ehlers <raymond.ehlers@cern.ch>, Yale University """ import logging import ctypes import matplotlib import matplotlib.pyplot as plt import numpy as np import os import seaborn as sns from typing import Any, cast, Dict, Iterator,...
the-stack_106_27117
import enum import logging from typing import Optional, Union, Tuple, Iterable import numpy as np from .azimuthalcurve import AzimuthalCurve from .curve import Curve from .header import Header from ..algorithms.matrixaverager import ErrorPropagationMethod, MatrixAverager from ..algorithms.radavg import radavg, autoq,...
the-stack_106_27119
""" Build statically rendered files. SPDX-FileCopyrightText: 2021 Birger Schacht <schacht@cert.at>, Mikk Margus Möll <mikk@cert.ee>, Sebastian Wagner <wagner@cert.at> SPDX-License-Identifier: AGPL-3.0-or-later """ import argparse import pathlib import shutil from mako.lookup import TemplateLookup def render_page(pag...
the-stack_106_27120
# Copyright 2012 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_27122
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup ------------------------------------------------------------...
the-stack_106_27124
import torch import torch.nn as nn from torchstat import ModelHook from collections import OrderedDict from torchstat import StatTree, StatNode, report_format def get_parent_node(root_node, stat_node_name): assert isinstance(root_node, StatNode) node = root_node names = stat_node_name.split('.') for ...
the-stack_106_27125
# Copyright 2020,2021 Sony Corporation. # Copyright 2021 Sony Group 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 ...
the-stack_106_27126
''' Take picture ============ .. author:: Mathieu Virbel <mat@kivy.org> Little example to demonstrate how to start an Intent, and get the result. When you use the Android.startActivityForResult(), the result will be dispatched into onActivityResult. You can catch the event with the android.activity API from python-fo...
the-stack_106_27127
# Copyright 2014 - Rackspace Hosting # # 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_27128
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setuptools.setup( name="update_camera_offset-SamGoodwin", # Replace with your own username version="0.0.1", author="Sam Goodwin + Bob Dimmock", author_email="support@vicon.com", description="Sna...
the-stack_106_27129
""" The MIT License (MIT) Copyright (c) 2017-2020 TwitchIO 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...
the-stack_106_27130
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: (c) 2017, F5 Networks Inc. # 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 DOCUMENTATION = r''' --- module: bigip_gtm_monitor_bigip...
the-stack_106_27131
from PIL import Image import os import requests import time # converts the image into a square and converts RGBA to RGB def make_square(im, min_size=0): x, y = im.size size = max(min_size, x, y) new_im = Image.new('RGBA', (size, size), "WHITE") new_im.paste(im, (int((size - x) / 2), int((size - y) / 2))...
the-stack_106_27132
import os import sys import glob import argparse from astropy.config import paths import pandas as pd import numpy as np from astropy.wcs import WCS from astropy.io import fits, ascii from astropy.visualization import ImageNormalize, ZScaleInterval import matplotlib.pyplot as plt import datetime as dt import time from ...
the-stack_106_27133
"""Database backed models for the asset store.""" import json import re import six from flask_sqlalchemy import SQLAlchemy from sqlalchemy import Column, Integer, JSON, String from sqlalchemy.exc import IntegrityError from sqlalchemy_utils import ChoiceType from asset_store.utils import get_choice_list, ResourceConf...
the-stack_106_27136
import os import string import numpy as np import pandas as pd from .auth import get_config_file from .exceptions import CufflinksError def scattergeo(): """ Returns """ path=os.path.join(os.path.dirname(__file__), '../data/scattergeo.csv') df=pd.read_csv(path) del df['Unnamed: 0'] df['text'] = df['airport'...
the-stack_106_27138
from copy import deepcopy import random def find_path(scanner, memory): DIR_reverse = {"N": 'S', "S": 'N', "W": 'E', "E": 'W'} DIR = {"N": (-1, 0), "S": (1, 0), "W": (0, -1), "E": (0, 1)} memory_binary = bin(memory)[2:] memory_binary = '0'*(100-len(memory_binary)) + memory_binary memory_list = [[j ...
the-stack_106_27139
# -*- coding: utf-8 -*- ''' Data Handler Module This module contains a class for managing a data processing pipeline ''' from time import time from datetime import timedelta import numpy as np import pandas as pd from scipy.stats import mode, skew from scipy.interpolate import interp1d from sklearn.cluster import DBS...
the-stack_106_27141
# -*- coding: utf-8 from __future__ import unicode_literals, absolute_import import django DEBUG = True USE_TZ = True # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "ok!d=o_mv%g^s+!y65w32dtc2-mz#j-@kxk)hfm*)y5-)^l=q)" DATABASES = { "default": { "ENGINE": "django.db.backe...
the-stack_106_27142
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, modules class Users(models.Model): _name = 'res.users' _inherit = ['res.users'] @api.model def systray_get_activities(self): """ Update the systray icon of res.par...
the-stack_106_27143
import os import pickle osp = os.path import numpy as np import tensorflow as tf import tensorflow_probability as tfp tfd = tfp.distributions tfk = tf.keras from rlfd import memory, normalizer, policies from rlfd.agents import agent, sac, sac_networks class CQL(sac.SAC): """Default online training algorithm of CQ...
the-stack_106_27145
# Copyright 2020 MONAI Consortium # 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_27146
from exetera.core.utils import Timer from exetera.core import fields as fld def merge_daily_assessments_v1(s, src_group, dest_group, overrides=None): """ Organize the assessment dataset to group record of patients in each day. :param s: The Exetera session instance. :param src_group: The source datafr...
the-stack_106_27148
#!/usr/bin/env python # Copyright 2018 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
the-stack_106_27152
""" Problem 46: https://projecteuler.net/problem=46 It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2 × 12 15 = 7 + 2 × 22 21 = 3 + 2 × 32 25 = 7 + 2 × 32 27 = 19 + 2 × 22 33 = 31 + 2 × 12 It turns out that the conjecture was fals...
the-stack_106_27153
from rest_framework import viewsets, permissions, status from rest_framework.decorators import action from rest_framework.response import Response from longclaw.contrib.productrequests.serializers import ProductRequestSerializer from longclaw.contrib.productrequests.models import ProductRequest from longclaw.utils imp...
the-stack_106_27154
""" Astra-Viso star camera module. """ from __future__ import division import numpy as np from astraviso import worldobject from astraviso import starmap from astraviso import imageutils from astraviso import projectionutils class StarCam(worldobject.WorldObject): """ Star camera class. """ def __init...
the-stack_106_27155
#!/usr/bin/env python # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2010 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this fil...
the-stack_106_27156
import requests import json from bs4 import BeautifulSoup class RAWG: def __init__(self): self.base_url = 'https://api.rawg.io/api' self.session = requests.Session() def get_game(self, name): game = {} id = self.__request_id(name) if not id: return game ...
the-stack_106_27157
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from dora import Explorer import treetable as tt class MyExplorer(Explorer): def get_grid_metrics(self): retu...
the-stack_106_27158
import asyncio async def foo(): for i in range(5): print("foo") await asyncio.sleep(1) async def bar(): for i in range(10): print("bar") await asyncio.sleep(1) loop = asyncio.get_event_loop() # The event loop is executed until the task is completed. loop.run_until_complete...
the-stack_106_27159
import os import os.path as osp import sys import pdb import argparse import librosa import natsort import numpy as np import mmcv import random from mir_eval.separation import bss_eval_sources from glob import glob from tqdm import tqdm import h5py from PIL import Image import subprocess from options.test_options impo...
the-stack_106_27164
import asyncio import awaitwhat.blocker from awaitwhat.stack import task_get_stack async def a(): await asyncio.gather(asyncio.sleep(0.01), asyncio.sleep(999 + 1)) def fixme_dont_test_sleep(): async def test(): t = asyncio.create_task(a()) try: await asyncio.sleep(0.11) ...
the-stack_106_27167
import numpy as np from pycocotools.coco import COCO from .custom import CustomDataset from .registry import DATASETS @DATASETS.register_module class CocoDataset(CustomDataset): CLASSES = ('plane', 'ship', 'storage tank', 'baseball diamond', 'tennis court', 'basketball court', 'ground track field', 'harbor', 'b...
the-stack_106_27168
from __future__ import unicode_literals import re from .common import InfoExtractor from ..compat import ( compat_str, ) from ..utils import ( ExtractorError, clean_html, ) class MovieClipsIE(InfoExtractor): _VALID_URL = r'https?://movieclips\.com/(?P<id>[\da-zA-Z]+)(?:-(?P<display_id>[\da-z-]+))?' ...
the-stack_106_27169
""" A minimal character-based 2-layer Vanilla RNN model. This is derived from the following scripts: - https://gist.github.com/karpathy/d4dee566867f8291f086 - https://github.com/eliben/deep-learning-samples/blob/master/min-char-rnn/min-char-rnn.py And you might find the following materials helpful: - http://karpathy.gi...
the-stack_106_27173
# -*- coding: utf-8 -*- from python_pachyderm.client.pps import pps_pb2 as proto from python_pachyderm.client.pps import pps_pb2_grpc as grpc from python_pachyderm.util import commit_from, get_address, get_metadata class PpsClient(object): def __init__(self, host=None, port=None, auth_token=None, root_certs=None...
the-stack_106_27175
import tensorflow as tf from functools import reduce from operator import mul from string import ascii_lowercase import numpy as np import tensorflow as tf from ordered_set import OrderedSet # These are constants: # max k = 9 ascii_chi = ascii_lowercase[:9] ascii_f = ascii_lowercase[9:18] # max feature vector dimensi...
the-stack_106_27176
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
the-stack_106_27179
def double_sort(lst): """this sorting algorithm sorts an array using the principle of bubble sort, but does it both from left to right and right to left, hence i decided to call it "double sort" :param collection: mutable ordered sequence of elements :return: the same collection in ascending or...
the-stack_106_27180
#encoding=utf8 # Copyright (c) 2021 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 requi...
the-stack_106_27183
import numpy as np from scipy.linalg import orth from sklearn.preprocessing import normalize def gen_union_of_subspaces(ambient_dim, subspace_dim, num_subspaces, num_points_per_subspace, noise_level=0.0): """This funtion generates a union of subspaces under random model, i.e., subspaces are independen...
the-stack_106_27184
"""Depth Measures Module. This module includes different methods to order functional data, from the center (larger values) outwards(smaller ones).""" import itertools import scipy.integrate import numpy as np from . import multivariate from .multivariate import Depth __author__ = "Amanda Hernando Bernabé" __emai...
the-stack_106_27186
# -*- coding: UTF-8 -*- # A part of NonVisual Desktop Access (NVDA) # Copyright (C) 2007-2019 NV Access Limited, Peter Vágner, Renaud Paquay, Babbage B.V. # This file is covered by the GNU General Public License. # See the file COPYING for more details. import os import queue from ctypes import ( c_short, ...
the-stack_106_27188
from __future__ import unicode_literals import os import codecs from subprocess import call from SourceFile import SourceFile class ReconstructionBlock: def __init__(self, name, nextBlock=None): self.name = name self.nextBlock = nextBlock os.makedirs("output/"+self.name) def process...
the-stack_106_27191
# Copyright 2021 solo-learn development team. # 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, publ...
the-stack_106_27192
""" Data schema, each record represents a file in a google bucket. """ from schemas.fastq_schema import FASTQ_SCHEMA DATA = { 'public_methods': [], 'resource_methods': ['GET'], 'item_methods': ['GET'], 'allowed_roles': ['admin', 'user', 'uploader', 'system'], 'allowed_item_roles': ['admin', 'user'...
the-stack_106_27193
import requests from bs4 import BeautifulSoup from re import search from flask import Flask ,jsonify app = Flask(__name__) app.url_map.strict_slashes = False def getNotesAndBooks(title): url = f'https://doku.pub/search/{title}?sort=popular' header = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKi...
the-stack_106_27196
"""Test for tackle.utils.command""" import pytest from tackle.utils.command import unpack_args_kwargs_string, unpack_input_string TEMPLATES = [ ('foo bar baz', 3, 0, 0), ('foo --bar baz bing', 2, 1, 0), ('foo bar --baz foo', 2, 1, 0), ('foo bar --baz foo --bing baz', 2, 2, 0), ('foo --bar baz', 1,...
the-stack_106_27197
# File: P (Python 2.4) from direct.controls.GravityWalker import GravityWalker from direct.showbase.InputStateGlobal import inputState from pandac.PandaModules import * from direct.task.Task import Task class PiratesGravityWalker(GravityWalker): notify = directNotify.newCategory('PiratesGravityWalker') d...
the-stack_106_27198
""" This module provides the ``FlyteRemote`` object, which is the end-user's main starting point for interacting with a Flyte backend in an interactive and programmatic way. This of this experience as kind of like the web UI but in Python object form. """ from __future__ import annotations import logging import os imp...
the-stack_106_27201
import torch import torch.nn as nn from fixed_gru import FixedGru from fixed_rnn import FixedRnn class CharCnnRnn(nn.Module): # Char-cnn-rnn text embedding def __init__(self, rnn_type='fixed_rnn', model_type='cvpr'): super().__init__() if model_type == 'cvpr': rnn_dim = 256 ...
the-stack_106_27202
import asyncio import copy import logging import os import random import shutil import ssl import sys import tempfile import time from argparse import Namespace from dataclasses import replace from pathlib import Path from typing import Callable, Dict, List, Optional, Tuple, Any from blspy import AugSchemeMPL, G1Eleme...
the-stack_106_27203
import logging import math import re import hikari import lightbulb from peacebot.core.utils.embed_colors import EmbedColors logger = logging.getLogger("error_handler") async def on_error(event: lightbulb.CommandErrorEvent) -> None: error = event.exception if isinstance(error, lightbulb.CommandNotFound): ...
the-stack_106_27204
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('browser', '0024_compare_add_info'), ] operations = [ migrations.RemoveField( model_name='compare', n...
the-stack_106_27205
import sysv_ipc # Create a shared memory segment and write the (English) alphabet to the shared memory. mem = sysv_ipc.SharedMemory(None, sysv_ipc.IPC_CREX, size=sysv_ipc.PAGE_SIZE) ASCII_A = 0x61 alphabet = ''.join([chr(ASCII_A + i) for i in range(26)]) alphabet = bytes(alphabet, 'ASCII') mem.write(alphabet) # Crea...
the-stack_106_27207
import json from investing_algorithm_framework import OrderSide, \ OrderType, OrderStatus, Order from tests.resources import TestBase, TestOrderAndPositionsObjectsMixin from tests.resources.serialization_dicts import position_serialization_dict class Test(TestBase, TestOrderAndPositionsObjectsMixin): def se...
the-stack_106_27208
from datetime import datetime from decimal import Decimal from django.contrib.sites.models import Site from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from l10n.utils import moneyfmt from payment.modules.giftcertificate.utils import generate_certifi...
the-stack_106_27210
"""Module containing the attributes for describe-get-system proof of concept module.""" from os import path from textwrap import dedent import yaml import templateapp import regexapp import dlapp import pytest import robot import xmlrunner from dgspoc.utils import File from dgspoc.utils import Misc __version__ = '...
the-stack_106_27211
import argparse import json from torch.utils.data import DataLoader from utils import google_utils from utils.datasets import * from utils.utils import * def test(data, weights=None, batch_size=16, imgsz=640, conf_thres=0.001, iou_thres=0.6, # for NMS save_json...
the-stack_106_27214
import tensorflow as tf def init_inputs(num_features, selection_methods): inputs = dict() for selection_method in selection_methods: with tf.name_scope('input_' + selection_method): inputs[selection_method] = tf.placeholder(dtype=tf.float32, ...
the-stack_106_27216
import asyncio, discord try: from _command import Command except: from coms._command import Command import pathlib class Com(Command): def __init__(self): self.usage = "!help" self.description = "Gives some basic help info about kermi" self.keys = ["!help", "bot help", ".help", "!...
the-stack_106_27222
import pickle import sys def parse(files): parsed = {} binding = {} for fname in files: f = open(fname) for line in f: splitted = line.split('\t') split_size = len(splitted) id = splitted[0] domain = splitted[4] if id in parsed.keys(): parsed[id].append(domain) else: parsed[id] = [dom...
the-stack_106_27225
#!/usr/bin/env python3 from contextlib import closing import random import subprocess import os from typing import Optional def xclip(*args: list, data: Optional[bytes] = None) -> Optional[str]: base_command = ["xclip", "-selection", "CLIPBOARD", *args] if "-o" in args: with closing( sub...
the-stack_106_27226
from django.urls import path from .views import ( # CommentView, CommentListCreateView, CommentRetrieveUpdateDestroyView, BlogListCreateView, BlogRetrieveUpdateDestroyView ) urlpatterns = [ path('post/', BlogListCreateView.as_view()), # path('post/<blog_id>/', BlogRetrieveUpdateDestroyView....
the-stack_106_27228
""" RDS utilities functions for bdd """ # pylint: disable=wrong-import-position,no-value-for-parameter import time import mysql.connector from botocore.exceptions import ClientError from mysql.connector import errorcode from sls.retry.api import retry from sls.utils.exceptions import ClusterExists, DatabaseNotAvai...
the-stack_106_27229
# importing the necessary modules import requests from bs4 import BeautifulSoup import zipfile from io import BytesIO # Creating a new file to store the zip file links newfile = open('zipfiles.txt','w') newdir = "C:/Users/mattp/Desktop/WorkFiles/XMLFiles/2021Tiger/Zip" #Set variable for page to be opened an...
the-stack_106_27230
from PySide6.QtWidgets import QMainWindow from monitorcontrol_gui.controller import Controller from monitorcontrol_gui.model import Model, Monitor from monitorcontrol_gui.ui.main_window import Ui_MainWindow class View(QMainWindow): """Class handling the main window of the app.""" def __init__(self, ctrl: Cont...
the-stack_106_27231
# # (c) Copyright 2015 Hewlett Packard Enterprise Development LP # (c) Copyright 2017-2018 SUSE 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-...
the-stack_106_27232
import unittest from tests.test_base import * from rfho.models import * class TestModelVectorization(unittest.TestCase): def test_augmented_gradient(self): iris, x, y, model, w, model_y, error, accuracy = iris_logistic_regression(2) d = int(w.tensor.get_shape()[0].value/3) self.assertEqu...
the-stack_106_27238
import requests import ast import json import glob base_url = "https://developers.zomato.com/api/v2.1/" def initialize_app(config): return Zomato(config) class Zomato: def __init__(self, config): self.user_key = config["user_key"] def get_categories(self): """ ...
the-stack_106_27239
dataset_type = 'IcdarDataset' data_root = '/home/atom/Research_STD/Datasets/mmocr/ctw1500' train = dict(type=dataset_type, ann_file=f'{data_root}/instances_training.json', img_prefix=f'{data_root}/imgs', pipeline=None) test = dict(type=dataset_type, ann_file=f'{data_root}/instances_test.json', img_prefix=f'{data_root...
the-stack_106_27241
#====================================================================== # # This module contains routines to postprocess the VFI # solutions. # # Simon Scheidegger, 01/19 # Cameron Gordon, 11/21 - updates to Python3 (print statements + pickle) #==========================================================...
the-stack_106_27242
from pytorch_lightning import callbacks import yaml import argparse import numpy as np import cv2 from models import * from experiments.vae_experiment import VAEXperiment from experiments.vae_pix2pix_exp import Pix2pixExperiment import torch.backends.cudnn as cudnn from pytorch_lightning import Trainer from pytorch_lig...
the-stack_106_27244
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: lenovo @file: CyclicCoordinate.py @time: 2021/5/22 10:26 """ import math import time import matplotlib.pyplot as plt import numpy as np from matplotlib import ticker def f(x, y): return (1 - x) ** 2 + 100 * (y - x * x) ** 2 def H(x, y): return np...
the-stack_106_27246
# 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 (t...
the-stack_106_27248
# # 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...
the-stack_106_27250
from time import time import os _startTime = None def loadInput(day): global _startTime day = str(day) filename = "input" + day.zfill(2) + ".txt" filepath = os.path.join("inputs", filename) with open(filepath) as f: content = [l.rstrip("\n") for l in f.readlines()] _startTime = time...
the-stack_106_27251
import os import shlex import subprocess import sys import parse from PySide2.QtCore import QFile, QObject, QTimer from PySide2.QtUiTools import QUiLoader from PySide2.QtWidgets import QApplication, QGraphicsScene, QLabel from . import xrandr from .monitor_item import MonitorItem class Window(QObject): def __in...
the-stack_106_27253
from tkinter import * from PIL import Image, ImageTk root = Tk() root.geometry("1200x700") load = Image.open("Network-Monitoring.jpg") render = ImageTk.PhotoImage(load) img = Label(image=render) img.place(x=0, y=0) label = Label(root , text="Welcome To The Network!",font=("bold,italic",25) , width=70,) label...
the-stack_106_27254
# -*- coding: utf-8 -*- ''' Control of entries in SSH authorized_key files ============================================== The information stored in a user's SSH authorized key file can be easily controlled via the ssh_auth state. Defaults can be set by the enc, options, and comment keys. These defaults can be overridd...
the-stack_106_27255
from time import time from cutqc.helper_fun import check_valid from cutqc.cutter import find_cuts, cut_circuit from cutqc.evaluator import run_subcircuit_instances from cutqc.post_process import generate_summation_terms, build from cutqc.verify import verify class CutQC: ''' The main module for CutQC cut ...
the-stack_106_27257
class Warrior(object): def __init__(self, health=50, attack=5): self.health = health self.attack = attack self.is_alive = True if health > 0 else False """Getting damage.""" def BishBashBosh(self, damage): self.health -= damage self.is_alive = True if self.h...