filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_106_27259
# Sharon Gibbons, 12-03-2018 # Project Euler Problem 5: Smallest multiple # https://projecteuler.net/problem=5 # https://www.programiz.com/python-programming/examples/lcm # Python program to find the least common multiple for a range of numbers # defines function # https://codility.com/media/train/10-Gcd.pdf def ...
the-stack_106_27261
# 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 required by appli...
the-stack_106_27262
""" A two-step (registration followed by activation) workflow, implemented by emailing an HMAC-verified timestamped activation token to the user on signup. """ from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.sites.shortcuts import get_current_site from django.core i...
the-stack_106_27264
import logging from galaxy.web.form_builder import SelectField from tool_shed.util import hg_util, metadata_util log = logging.getLogger( __name__ ) def build_approved_select_field( trans, name, selected_value=None, for_component=True ): options = [ ( 'No', trans.model.ComponentReview.approved_states.NO ), ...
the-stack_106_27265
# -*- coding: utf-8 -*- # @Time : 19-8-21 上午11:29 # @Author : Redtree # @File : r13.py # @Desc : 狼人 from data import skills DATA = { 'code':12, 'name':'狼人', 'attack':3, 'defend':0, 'hp':8, 'skill':skills.DATA[13], 'desc':'一个人的夜我的心,应该放在哪里' }
the-stack_106_27266
# -*- coding: utf-8 -*- import sys from pyqtgraph.Qt import QtCore, QtGui from visualizer import NMF4DVisualizer from nmf import * from generator import * def main(): # params # ========================= N = 10 M = 50 K = 3 T = 10 lr_pgd1 = 0.02 lr_pgd2 = 0.15 nmf_iter = 100 nm...
the-stack_106_27267
# SPDX-FileCopyrightText: 2021 easyCore contributors <core@easyscience.software> # SPDX-License-Identifier: BSD-3-Clause # © 2021 Contributors to the easyCore project <https://github.com/easyScience/easyCore> __author__ = 'github.com/wardsimon' __version__ = '0.1.0' from easyCore.Symmetry.SymOp import SymmOp cl...
the-stack_106_27268
import numpy as np from sampling import madowSampling from scipy.special import comb from decimal import * from sacred import Experiment from config import initialise from easydict import EasyDict as edict getcontext().prec = 100 ex = Experiment() ex = initialise(ex) class sageHedge: def __init__(self, args): ...
the-stack_106_27270
# Python program to find largest, smallest, # second largest and second smallest in a # list with complexity O(n) def Range(list1): #largest = list1[0] lowest = list1[0] #largest2 = None lowest2 = None for item in list1[1:]: #if item > largest: #largest2 = largest #largest = item #...
the-stack_106_27271
#!/usr/bin/env python """Tests for grr.parsers.sqlite_file.""" import os import StringIO from grr.lib import flags from grr.parsers import sqlite_file from grr.test_lib import test_lib class SQLiteFileTest(test_lib.GRRBaseTest): """Test parsing of sqlite database files.""" query = "SELECT * FROM moz_places;"...
the-stack_106_27275
#!/usr/bin/env python # 1 dragon with 1 point light # Copyright (c) 2011-2020 Hiroshi Tsubokawa import fujiyama si = fujiyama.SceneInterface() #plugins si.OpenPlugin('constant_shader', 'ConstantShader') si.OpenPlugin('plastic_shader', 'PlasticShader') si.OpenPlugin('stanfordply_procedure', 'StanfordPlyProcedure') ...
the-stack_106_27278
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ from azure.core.pipeline.policies import ContentDecodePolicy from azure.core.pipeline.policies import SansIOHTTPPolicy from ._models import TextDocumentBatchStatistics ...
the-stack_106_27279
from tkinter import * ventana= Tk() ventana.geometry("700x400") ventana.title("Formularios en Tkinter | Pilar Goonzález") # Texto Encabezado encabezado = Label(ventana, text="Formularios con Tkinter - Pilar G") encabezado.config( fg="white", bg="darkgray", font=("Open Sans",18), padx=10, pady=10 ...
the-stack_106_27282
""" Represents a bundle. In the words of the Apple docs, it's a convenient way to deliver software. Really it's a particular kind of directory structure, with one main executable, well-known places for various data files and libraries, and tracking hashes of all those files for signing purposes. For is...
the-stack_106_27284
from django.urls import path # views(url for home page) from . import views urlpatterns = [ path('', views.index, name='listings'), path('<int:listing_id>', views.listing, name='listing'), path('search', views.search, name='search'), ]
the-stack_106_27285
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
the-stack_106_27287
### ### Copyright (C) 2018-2019 Intel Corporation ### ### SPDX-License-Identifier: BSD-3-Clause ### from ....lib import * from ....lib.gstreamer.vaapi.util import * from ....lib.gstreamer.vaapi.decoder import DecoderTest spec = load_test_spec("vp8", "decode") @slash.requires(*platform.have_caps("decode", "vp8")) @sl...
the-stack_106_27288
"""Django settings for Pontoon.""" from __future__ import absolute_import import re import os import socket from django.utils.functional import lazy import dj_database_url _dirname = os.path.dirname ROOT = _dirname(_dirname(_dirname(os.path.abspath(__file__)))) def path(*args): return os.path.join(ROOT, *ar...
the-stack_106_27289
import numpy as np import pytest import pandas.util._test_decorators as td import pandas as pd import pandas._testing as tm from pandas.arrays import SparseArray from pandas.core.arrays.sparse import SparseDtype class TestSparseDataFrameIndexing: def test_getitem_sparse_column(self): # https://github.co...
the-stack_106_27290
# -*- coding: utf-8 -*- from textwrap import dedent import logging import sys import pytest from parso.utils import split_lines from parso import cache from parso import load_grammar from parso.python.diff import DiffParser, _assert_valid_graph from parso import parse ANY = object() def test_simple(): """ ...
the-stack_106_27291
import re import json import requests import termcolor from .info import load_login_info, encrypt from .utils import Page QUOTE = re.compile('(?<!\\\\)\'') def auth(): user, pwd = load_login_info() encrypted, key = encrypt(pwd) url = 'http://1.1.1.3/ac_portal/login.php' data = { 'opr': 'pw...
the-stack_106_27292
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os from os.path import abspath, realpath, split, dirname import collections from datetime import datetime, timedelta import time import jinja2 import json import logging import pytz import shutil import sys import logging from jinja2.exceptions import UndefinedEr...
the-stack_106_27295
from __future__ import unicode_literals import frappe import re def execute(): for srl in frappe.get_all('Salary Slip',['name']): if srl.get("name"): substring = re.search("\/(.*?)\/",srl.get("name")).group(1) emp = frappe.db.get_value('Employee',{'name':substring},'user_id') ...
the-stack_106_27296
#!/usr/bin/env python # 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. from __future__ import absolute_import, division, print_function, unicode_literals import argparse import os import pla...
the-stack_106_27297
import itertools import logging from det3d.utils.config_tool import get_downsample_factor tasks = [ dict(num_class=1, class_names=["car"]), dict(num_class=2, class_names=["truck", "construction_vehicle"]), dict(num_class=2, class_names=["bus", "trailer"]), dict(num_class=1, class_names=["barrier"]), ...
the-stack_106_27299
# Copyright (c) 2018 Uber Technologies, 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 ag...
the-stack_106_27301
# -*- coding: utf-8 -*- """ Created on Wed Aug 8 08:33:28 2018 @author: pgallego """ import pydicom as dicom #Bladder, Rectum, Body Fermoales, PTV RdPath = 'C:\\Users\\pgallego\\Desktop\\Prostate1\\RD.1.2.246.352.71.7.2101921327.432885.20121219084743.dcm' RsPath = 'C:\\Users\\pgallego\\Desktop\\Prostate1\\RS.1.2.246....
the-stack_106_27302
#!/usr/bin/env python3 import sys import json import os import argparse columns = [ 'count', 't_sum', 't_avg', 'operation', 'key' ] parser = argparse.ArgumentParser() parser.add_argument("--hide", choices=['count', 't_sum','t_avg','key'], na...
the-stack_106_27303
""" PDBBind dataset loader. """ from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import multiprocessing import os import re import time import deepchem import numpy as np import pandas as pd def featurize_pdbbind(data_dir=None, feat="grid"...
the-stack_106_27305
import json import logging import re from datetime import datetime from funcy.colls import walk_values, get_in from funcy.flow import silent from funcy.seqs import flatten from hivebase.exceptions import ( PostDoesNotExist, VotingInvalidOnArchivedPost, ) from hivebase.operations import CommentOptions from .am...
the-stack_106_27306
"""A parser for reading NASA JPL GipsyX timeseries file Example: -------- from analyx import parsers p = parsers.parse_file(parser_name='gipsyx_series', file_path='NYA1.series') data = p.as_dict() Description: ------------ Reads data from files in GipsyX timeseries format. """ # Standard library import...
the-stack_106_27307
# -*- coding: utf-8 -*- ''' Jinja loading utils to enable a more powerful backend for jinja templates ''' # Import python libs from __future__ import absolute_import import json import pprint import logging from os import path from functools import wraps # Import third party libs import salt.ext.six as six from jinja...
the-stack_106_27310
"""A benchmark to be run externally. Executes a program that might make heavy use of Result/Option types in one of two ways: classically, with exceptions, or using result types. The program checks several data stores (in memory to minimize interference from slow IO &c.) in order for a key. If it finds it, it gets the...
the-stack_106_27312
# -*- coding: utf-8 -*- ''' Package support for openSUSE via the zypper package manager :depends: - ``rpm`` Python module. Install with ``zypper install rpm-python`` .. important:: If you feel that Salt should be using this module to manage packages on a minion, and it is using a different module (or gives a...
the-stack_106_27313
import json from http import HTTPStatus import responses # type: ignore from flask import current_app import pytest import sqlalchemy # type: ignore from sqlalchemy.exc import OperationalError from lighthouse.constants import ( FIELD_COG_BARCODE, FIELD_ROOT_SAMPLE_ID, MLWH_LH_SAMPLE_ROOT_SAMPLE_ID, ...
the-stack_106_27315
""" Copyright (c) 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 writin...
the-stack_106_27316
import bokeh.plotting import bokeh.layouts import bokeh.models def main(): columns = [] color_mappers = [] for name in bokeh.palettes.mpl: figures = [] for number in bokeh.palettes.mpl[name]: palette = bokeh.palettes.mpl[name][number] color_mapper = bokeh.models.Li...
the-stack_106_27317
# Copyright (c) 2020, 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 License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
the-stack_106_27319
# encoding: utf-8 """ @author: liaoxingyu @contact: sherlockliao01@gmail.com """ from torch import nn class SELayer(nn.Module): def __init__(self, channel, reduction=16): super(SELayer, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Sequential( nn.Linea...
the-stack_106_27320
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 1 15:24:54 2020 @author: magnus """ import numpy as np #from randomSequence import * # xvals = np.random.rand(-1,1,len(xvals)) # yvals = np.random.rand(-1,1,len(yvals)) # vals = [[x, y] for x, y in zip(xvals, yvals)] # print(vals) def cir...
the-stack_106_27323
# Copyright 2020 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_27324
""" Python implementation of the fast ICA algorithms. Reference: Tables 8.3 and 8.4 page 196 in the book: Independent Component Analysis, by Hyvarinen et al. """ # Authors: Pierre Lafaye de Micheaux, Stefan van der Walt, Gael Varoquaux, # Bertrand Thirion, Alexandre Gramfort, Denis A. Engemann # License: BS...
the-stack_106_27326
# ============================================================================= # Copyright 2020 NVIDIA. 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://ww...
the-stack_106_27327
import json import scrapy from locations.hourstudy import inputoutput def process_hours(hours): if 'Hours' not in hours: return None opening_hours = '' days = hours['Hours'] for day in days: shortname = day['ShortName'] if '-' in shortname: startday, endday = short...
the-stack_106_27328
# 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. # -----------------------------------------------------...
the-stack_106_27329
""" Data container for ligand-kinase data. """ import logging import pandas as pd from src.evaluation.data.base_data import BaseData logger = logging.getLogger(__name__) class LigandVsKinaseData(BaseData): """ Prepare data to compare ligand- and kinase-focused data. Attributes ---------- lig...
the-stack_106_27330
""" This script is used to write `sqf/dababase.py`, that contains all valid SQF expressions. It reads a file from here: https://raw.githubusercontent.com/intercept/intercept/master/src/client/headers/client/sqf_pointers_declaration.hpp """ import urllib.request from sqf.interpreter_types import ForType, IfType, Switc...
the-stack_106_27331
import io from datetime import timedelta import numpy as np import matplotlib import matplotlib.pyplot as plt from matplotlib.ticker import StrMethodFormatter matplotlib.use("Agg") matplotlib.style.use("seaborn") def _moving_avg(data, days=7): # Use 1d convolution for moving average, as explained in https://st...
the-stack_106_27334
from typing import List from homecomp.models import AssetMixin from homecomp.models import BudgetItem from homecomp.models import BudgetLineItem from homecomp.models import MonthlyBudget from homecomp.models import MonthlyExpense from homecomp import const class Investment(AssetMixin, BudgetItem): """ Simple...
the-stack_106_27335
import logging from mpfmc.tests.MpfMcTestCase import MpfMcTestCase from unittest.mock import MagicMock, ANY from mpfmc.widgets.video import VideoWidget try: from mpfmc.core.audio import SoundSystem from mpfmc.assets.sound import SoundStealingMethod except ImportError: SoundSystem = None SoundStealingM...
the-stack_106_27337
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np from astropy.units import Quantity from astropy.io import fits from astropy import log from astropy.table import Table from astropy.extern import six from...
the-stack_106_27338
try: from io import StringIO from io import BytesIO except ImportError: from cStringIO import StringIO # NOQA try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser # NOQA from circus.tests.support import TestCase from circus.tests.support import EasyT...
the-stack_106_27339
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test processing of unrequested blocks. Setup: two nodes, node0+node1, not connected to each other. Nod...
the-stack_106_27340
import asyncio import random import discord from discord.ext.buttons import Paginator class Pag(Paginator): async def teardown(self): try: await self.page.clear_reactions() except discord.HTTPException: pass async def GetMessage( bot, ctx, contentOne="Default Message...
the-stack_106_27341
import weakref from collections import namedtuple import operator from functools import partial from llvmlite.llvmpy.core import Constant, Type, Builder from numba import _dynfunc from numba.core import (typing, utils, types, ir, debuginfo, funcdesc, generators, config, ir_utils, cgutils) from...
the-stack_106_27342
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ start = List...
the-stack_106_27343
from robolearn.utils.samplers import rollout from robolearn.torch.core import PyTorchModule from robolearn.torch.utils.pytorch_util import set_gpu_mode from robolearn.envs.normalized_box_env import NormalizedBoxEnv from robolearn_gym_envs.pybullet import CentauroTrayEnv from robolearn.torch.policies import MultiPolicyS...
the-stack_106_27344
import numpy as np from . import is_scalar_nan from .fixes import _object_dtype_isnan def _get_mask(X, value_to_mask): """Compute the boolean mask X == missing_values.""" if is_scalar_nan(value_to_mask): if X.dtype.kind == "f": return np.isnan(X) elif X.dtype.kind in ("...
the-stack_106_27348
import pickle import os from os.path import join, expanduser from invoke.util import six from mock import patch, call, Mock import pytest from pytest_relaxed import raises from invoke.runners import Local from invoke.config import Config from invoke.exceptions import ( AmbiguousEnvVar, Uncastable...
the-stack_106_27349
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
the-stack_106_27350
# Copyright 2017 Mycroft AI 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 writin...
the-stack_106_27351
# coding=utf-8 # Copyright 2020 The ML Fairness Gym 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_27353
""" Plotting imports for PyDSTool, from Matplotlib's pyplot library. Robert Clewley, March 2006. """ from __future__ import absolute_import, print_function from numpy import Inf, NaN, isfinite, int, int8, int16, int32, int64, float, float32, float64 try: import matplotlib ver = matplotlib.__version__...
the-stack_106_27354
""" Following DeepRobust repo https://github.com/DSE-MSU/DeepRobust """ """ FGA: Fast Gradient Attack on Network Embedding (https://arxiv.org/pdf/1809.02797.pdf) Another very similar algorithm to mention here is FGSM (for graph data). It is mentioned in Zugner's paper, Adversarial Attacks on Neural Netw...
the-stack_106_27356
from __future__ import annotations import collections from datetime import timedelta import functools import gc from io import StringIO import json import operator import pickle import re from typing import ( TYPE_CHECKING, Any, Callable, Dict, FrozenSet, Hashable, List, Mapping, Op...
the-stack_106_27357
import win32api from lib.pywin32_keys import VK #check which key is pressed def check_key_pressed(): try: while True: for i in VK: if win32api.GetAsyncKeyState(VK[i]) !=0: return i except: print("Something went wrong while checking which key is p...
the-stack_106_27360
# -*- coding: utf-8 -*- # Copyright 2018-2019 Streamlit Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
the-stack_106_27362
import math import tensorflow as tf import numpy as np import dnnlib.tflib as tflib from functools import partial def create_stub(name, batch_size): return tf.constant(0, dtype='float32', shape=(batch_size, 0)) def create_variable_for_generator(name, batch_size, tiled_dlatent, model_scale=18): if tiled_dlat...
the-stack_106_27363
# -*- coding: utf-8 -*- #@+leo-ver=5-thin #@+node:ekr.20171123135539.1: * @file ../commands/commanderEditCommands.py #@@first """Edit commands that used to be defined in leoCommands.py""" import re from typing import List from leo.core import leoGlobals as g #@+others #@+node:ekr.20171123135625.34: ** c_ec.addComments ...
the-stack_106_27364
"""OpenAQ Air Quality Dashboard with Flask.""" from flask import Flask from flask_sqlalchemy import SQLAlchemy import openaq import aq_functions APP = Flask(__name__) APP.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3' DB = SQLAlchemy(APP) class Record(DB.Model): id = DB.Column(DB.Integer, primary_key=...
the-stack_106_27365
import tensorflow as tf import experience as xp import numpy as np import dqn_model import os class Agent: def __init__(self, env, replay_size, optimizer, batch_size, n_steps, gamma, use_double=True, use_dense=None, dueling=False, use_categorical=False, n_atoms=None, v_min=None, v_max=None, use_p...
the-stack_106_27367
#!/usr/bin/env python3 # Copyright (c) the JPEG XL Project Authors. All rights reserved. # # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. """build_cleaner.py: Update build files. This tool keeps certain parts of the build files up to date. """ import argparse i...
the-stack_106_27368
import torch def unitwise_norm(x, norm_type=2.0): if x.ndim <= 1: return x.norm(norm_type) else: # works for nn.ConvNd and nn,Linear where output dim is first in the kernel/weight tensor # might need special cases for other weights (possibly MHA) where this may not be true retur...
the-stack_106_27369
import json from django.contrib import messages class AjaxMessagesMiddleware(object): """ Middleware to handle messages for AJAX requests. If the AJAX response is already JSON, add a "messages" key to it (or append to an existing "messages" key) a list of messages (each message is an object with...
the-stack_106_27373
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
the-stack_106_27374
import pytest from unittest import mock import json from django.core.exceptions import ValidationError from awx.main.models import ( UnifiedJob, InventoryUpdate, Inventory, Credential, CredentialType, InventorySource, ) def test_cancel(mocker): with mock.patch.object(UnifiedJob, 'cancel'...
the-stack_106_27377
from typing import List, Tuple, Type, Union, Callable, Optional, Dict, Any import torch as th import torch.nn.functional as F import numpy as np from stable_baselines3.common import logger from stable_baselines3.common.off_policy_algorithm import OffPolicyAlgorithm from stable_baselines3.common.type_aliases import Gym...
the-stack_106_27380
""" For each train, we check all the other trains to check how many collide, and we choose the case where there is maximum collision. """ def minimumPlatform(n,arr,dep): ''' :param n: number of activities :param arr: arrival time of trains :param dep: corresponding departure time of trains :return...
the-stack_106_27381
from __future__ import absolute_import, print_function, unicode_literals import inspect from wolframclient.utils.functional import flatten # original idea by Guido in person. # https://www.artima.com/weblogs/viewpost.jsp?thread=101605 class Dispatch(object): """ A method dispatcher class allowing for multiple ...
the-stack_106_27384
import logging import operator import os from collections import namedtuple import numpy as np import gc import torch import torch.nn as nn import torch.utils import torch.nn.functional as F import torchvision.datasets as dset from torch.utils.tensorboard import SummaryWriter import utils as project_utils import nasws...
the-stack_106_27385
import os import errno import pytest from dvc.cache import NamedCache from dvc.path_info import PathInfo from dvc.remote.local import RemoteLOCAL def test_status_download_optimization(mocker): """When comparing the status to pull a remote cache, And the desired files to fetch are already on the local ca...
the-stack_106_27388
import unittest import struct from zttf.utils import fixed_version, binary_search_parameters, ttf_checksum, glyph_more_components, glyf_skip_format class TestUtils(unittest.TestCase): def test_fixed_version(self): cases = [ (0x00005000, 0.5), (0x00010000, 1.0), (0x0003...
the-stack_106_27390
import _plotly_utils.basevalidators class TicklenValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name='ticklen', parent_name='splom.marker.colorbar', **kwargs ): super(TicklenValidator, self).__init__( plotly_name=plotly_...
the-stack_106_27391
import json from dataclasses import dataclass from datetime import datetime, timedelta from enum import Enum from typing import Dict, List, Optional, Tuple, Union import requests from model.track import Track class Groups(Enum): """Enum for group domains.""" JAZZVE = 'jazzve' SOUNDFIELDS = 'soundfields'...
the-stack_106_27395
import numpy as np import torch from torch import nn from collections import OrderedDict import torchvision class Resnet18(nn.Module): def __init__(self, bottleneck_connection_channel=32): """ bottleneck_connection_channel: connection channel for VOneBlock """ super(Resnet18, sel...
the-stack_106_27408
import Cifras.bases_numericas as bases_numericas import dicionarios def codificar_texto_para_UTF8(texto): if not texto: return dicionarios.retorna_erro_mensagem() codigo_final_utf8 = '' for caractere in texto: num_binario = bases_numericas.converter_decimal_para_binario(ord(caractere))...
the-stack_106_27409
# Copyright 2015 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Tests the gce module.""" from __future__ import print_function import os from chromite.lib import cros_test_lib from chromite.lib import gce from ch...
the-stack_106_27410
""" FIN module customisations for RLPPTM License: MIT """ from collections import OrderedDict from gluon import current, A, DIV, IS_EMPTY_OR, IS_INT_IN_RANGE, TAG from core import FS, IS_ONE_OF, s3_str ISSUER_ORG_TYPE = "pe_id$pe_id:org_organisation.org_organisation_organisation_type.organisation_type_id" ...
the-stack_106_27412
#!/usr/bin/env python # ------------------------------------------------------------------------------------------------------% # Created by "Thieu Nguyen" at 14:50, 20/04/2020 % # ...
the-stack_106_27414
# Implements a quick and dirty genetic algorithm to search hyperparameters # Would be better (and more general) with object-oriented re-implementation # each hyperparameter is its own class with methods on how it varies, is randomly generated, etc # overall hyperparameters class that has a dictionary of its hyperparam...
the-stack_106_27416
from subprocess import call from subprocess import check_output def find_group_id() -> str: """ Finds primay group ID and returns as string """ cmd = 'dscl . -list /groups PrimaryGroupID|grep staff|tr -s [:space:]' out = check_output([cmd], shell=True) res = out.decode('UTF-8').strip('\n').spli...
the-stack_106_27417
import logging import time from abc import abstractmethod, ABC, ABCMeta from spaceone.core import config, utils, cache from spaceone.core.manager import BaseManager from spaceone.core.auth.jwt.jwt_util import JWTUtil from spaceone.identity.error.error_authentication import * __all__ = ['TokenManager', 'JWTManager']...
the-stack_106_27419
import logging import os import tempfile from contextlib import contextmanager from typing import TYPE_CHECKING, Optional from funcy import cached_property, first from dvc.exceptions import DvcException from dvc.utils import dict_sha256, relpath if TYPE_CHECKING: from dvc.objects.db.base import ObjectDB logger ...
the-stack_106_27421
"""Test that the horizontal font metrics are calculated correctly. Some text in various fonts will be displayed. Green vertical lines mark the left edge of the text. Blue vertical lines mark the right edge of the text. """ import os import unittest from pyglet.gl import * from pyglet import font from . import ba...
the-stack_106_27423
import os import logging import json import requests from SPARQLWrapper import JSON, SPARQLWrapper def download(): logging.basicConfig(level=logging.INFO) endpoint = SPARQLWrapper("https://materialsmine.org/wi/sparql") endpoint.setQuery( """ SELECT DISTINCT ?article WHERE { ?do...
the-stack_106_27424
import cv2 import numpy as np from datetime import datetime import array import fcntl import os import argparse from utils import ArducamUtils import time def resize(frame, dst_width): width = frame.shape[1] height = frame.shape[0] scale = dst_width * 1.0 / width return cv2.resize(frame, (int(scale * w...
the-stack_106_27425
"""API targets module for rbkcli.""" import copy from rbkcli.base import CONSTANTS, RbkcliBase, RbkcliException from rbkcli.core.handlers.environment import EnvironmentHandler from rbkcli.core.handlers.inputs import InputHandler from rbkcli.core.handlers.outputs import OutputHandler class ApiTarget(Rbkcli...
the-stack_106_27426
import json class ValidationResult(object): ERROR = 1 WARNING = 2 def __init__(self, namespace, classname): super(ValidationResult, self).__init__() self.warnings = [] self.errors = [] self.namespace = namespace self.classname = classname def add_error(self, w...
the-stack_106_27428
#!/usr/bin/env python # -*- coding: utf-8 -*- test_data = [12,5,8,10,2,16,259,1] def merge_sort_not_recursion(data): step = 1 while step <= len(data)//2: for i in range(0, len(data), step*2): res = [] left = data[i:min(i+step, len(data))] right = data[min(i+step, le...
the-stack_106_27429
from typing import List import dask.dataframe as dd from nvtx import annotate from dask_sql.utils import new_temporary_column @annotate("GROUPBY_GET_GROUPBY_WITH_NULL_COLS", color="green", domain="dask_sql_python") def get_groupby_with_nulls_cols( df: dd.DataFrame, group_columns: List[str], additional_column_na...