filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_9857
# Copyright (c) 2013 Pratik Kumar Sahu, Nagendra Chowdary, Anish Mathuria # Ported to Python by Gallopsled from __future__ import division import os import random import struct # +------------------------------------------------------------------------+ # | RANDOM NUMBERS FUNCTIONS ...
the-stack_0_9858
""" Interfaces to various optimizers. """ from __future__ import print_function, division import sys from copy import copy import warnings # CRUFT: time.clock() removed from python 3.8 try: from time import perf_counter except ImportError: from time import clock as perf_counter import numpy as np from . imp...
the-stack_0_9859
# # Copyright 2020 IBM Corp. 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_0_9862
# -*- coding: utf-8 -*- """ flask_jsondash.db ~~~~~~~~~~~~~~~~~~~~~~~~~~ A translation adapter for transparent operations between storage types. :copyright: (c) 2016 by Chris Tabor. :license: MIT, see LICENSE for more details. """ import json from datetime import datetime as dt from pymongo import MongoClient fro...
the-stack_0_9863
from django.urls import path from .views import BookmarkDetail, BookmarkDelete, BookmarkCreate, BookmarkUpdate, BookmarkList # namespace = 이름 공간 # 다른 앱들과 url pattern 이름이 겹치는 것을 방지하기 위해서 사용 # 2.x버전 이전에는 namespace라는 인수가 존재 app_name = 'bookmark' urlpatterns = [ # 함수형 뷰 : 이름만 쓴다 # 클래스형 뷰 : 이름.as_view() path('...
the-stack_0_9866
# Colorama module: pip install colorama from colorama import init, Fore, Style # Selenium module imports: pip install selenium from selenium import webdriver from selenium.common.exceptions import TimeoutException as TE from selenium.common.exceptions import ElementClickInterceptedException as ECIE from selenium.webdr...
the-stack_0_9867
# -*- coding: utf-8 -*- # Copyright (c) 2016-2022 by University of Kassel and Fraunhofer Institute for Energy Economics # and Energy System Technology (IEE), Kassel. All rights reserved. import os import numpy as np from pandapower.auxiliary import ppException try: import pplog as logging except I...
the-stack_0_9868
#!/usr/bin/env python # _*_ coding: utf-8 _*_ from setuptools import setup, find_packages import os import imp def non_python_files(path): """ Return all non-python-file filenames in path """ result = [] all_results = [] module_suffixes = [info[0] for info in imp.get_suffixes()] ignore_dirs = ['cvs...
the-stack_0_9872
import json import boto3 import sys from datetime import datetime from decimal import Decimal from boto3.dynamodb.conditions import Key, Attr import logging logger = logging.getLogger() logger.setLevel(logging.INFO) today=datetime.today() curyear=today.year curmonth=today.month curday=today.day start_of_day = int(date...
the-stack_0_9873
# # @lc app=leetcode.cn id=946 lang=python3 # # [946] 验证栈序列 # from typing import List class Solution: # 模拟思路即可 def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: try: if len(pushed) == 0 or len(pushed) == 1: return True # 模拟的栈 ...
the-stack_0_9875
import json from flask import Response from flask import Blueprint from flask import request from financespy import Transaction from financespy import parse_month from datetime import date def month_weeks(backend, year, month): return [ [trans.to_dict() for trans in week.records()] for week in bac...
the-stack_0_9877
"""Mock documents, used for integration testing.""" from dataclasses import dataclass, replace from itertools import chain from pathlib import Path from typing import List, Optional, Sequence, Tuple from bp.document import Document from bp.entity import Page from bp.build_document import InputPage, build_document fro...
the-stack_0_9880
import numpy as np import torch from torch.utils.data import Dataset, TensorDataset, DataLoader from sklearn.utils import shuffle class SequenceBucketCollator(): def __init__(self, choose_length, maxlen, sequence_index, length_index, label_index=None): self.choose_length = choose_length self.seque...
the-stack_0_9881
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
the-stack_0_9883
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # create a rendering window and renderer ren1 = vtk.vtkRenderer() ren1.SetBackground(0,0,0) renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) renWin.SetSize(300,300) ...
the-stack_0_9884
#!/usr/bin/env python # -*- coding: utf-8 -*- """Collection of tests for :mod:`orion.core.worker.consumer`.""" import logging import os import shutil import signal import subprocess import tempfile import time import pytest import orion.core.io.experiment_builder as experiment_builder import orion.core.io.resolve_con...
the-stack_0_9885
#!/usr/bin/env python import json from run_tests_stats import execute import optparse import os import subprocess import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt def parseresults(log_file, plot_data, t, duration): fp = open(log_file).readlines() i = 0 plot_data[t] = {} plot_dat...
the-stack_0_9892
# coding:utf-8 # 2019/9/21 import sys sys.path.append(r"C:\Study\github\Lookoops\MachineLearning\TensorFlow\image-clssifier") import logging import pickle import os from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from keras import backend as K import numpy as np import tensorflow a...
the-stack_0_9893
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
the-stack_0_9894
""" Copyright 2020 The OneFlow 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 applicable law or agr...
the-stack_0_9895
"""Binary classes""" import binascii import gzip import io import json import logging import os import shutil import struct import subprocess import sys import tarfile import tempfile import zipfile from json import dumps from typing import Optional import h5py import numpy as np import pysam import pysam.bcftools fr...
the-stack_0_9897
import os import sfepy from sfepy.base.base import load_classes, insert_static_method from solvers import * from eigen import eig solver_files = sfepy.get_paths('sfepy/solvers/*.py') remove = ['setup.py', 'solvers.py', 'petsc_worker.py'] solver_files = [name for name in solver_files if os.path.basename...
the-stack_0_9898
import datetime import os from cryptography.x509.oid import NameOID from cryptography.hazmat.primitives.serialization import Encoding from .logger import logger class StorageEngineCertificateConflict(Exception): """ Raise when a StorageEngine implementation is asked to persist a certificate with a seria...
the-stack_0_9899
import datetime from docxtpl import DocxTemplate from docxtpl import InlineImage from docx.shared import Cm from docxtpl import DocxTemplate, InlineImage def get_context(brand, model, fuel_consumption, price): return { 'brand': brand, 'model': model, 'fuel_consumption': fuel_consumption, ...
the-stack_0_9901
""" Python 3.9 функция для запуска процесса обучения нейронной сети Название файла train_c4.py Version: 0.1 Author: Andrej Marinchenko Date: 2021-12-20 """ #!/usr/bin/env python from alpha_net_c4 import ConnectNet, AlphaLoss, board_data import os import pickle import datetime import numpy as np import torch import to...
the-stack_0_9902
import unittest import numpy as np import matplotlib.pyplot as plt from scipy.stats import multivariate_normal from pyrolite.util.plot.density import ( percentile_contour_values_from_meshz, plot_Z_percentiles, ) from pyrolite.util.plot.legend import proxy_line from matplotlib.lines import _get_dash_pat...
the-stack_0_9904
import numpy as np # linear algebra import skimage.io import os import sys np.random.seed(1234) import scipy.misc import skimage.morphology as mph from skimage import color dd = sys.argv[1] STAGE1_TRAIN = "../inputs/"+dd STAGE1_TRAIN_IMAGE_PATTERN = "%s/{}/images/{}.png" % STAGE1_TRAIN STAGE1_TRAIN_MASK_PATTERN = "%s...
the-stack_0_9905
# @Time : 12/07/21 1:05 PM # @Author : Fabrice Harel-Canada # @File : rick_and_morty_stories.py import torch from transformers import pipeline, set_seed from transformers.pipelines import TextGenerationPipeline class RickAndMortyStories: def __init__(self, mask_bad_words=True): self.pipeline = pipe...
the-stack_0_9906
# NASBench 301 stuff here import sys from pathlib import Path sys.path.append('./darts/cnn') lib_dir = (Path(__file__).parent / 'darts' / 'cnn').resolve() if str(lib_dir) not in sys.path: sys.path.insert(0, str(lib_dir)) import genotypes from model_search import Network, NetworkNB import utils import time import math...
the-stack_0_9907
# -*- coding: utf-8 -*- """DNACenterAPI non_fabric_wireless API fixtures and tests. Copyright (c) 2019-2020 Cisco and/or its affiliates. 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 re...
the-stack_0_9908
# coding=utf-8 from __future__ import absolute_import, print_function import os import numpy as np from suanpan.app import app from suanpan.storage import storage from suanpan.utils import image from arguments import Images @app.input(Images(key="inputImage")) @app.output(Images(key="outputImage")) def SPRemoveWater...
the-stack_0_9909
#!/usr/bin/env python3 """ Prompt: Loop through all numbers from 1 to 100. If the number is divisible by 3, print out "Fizz" instead. If the number is divisible by 5, print out "Buzz" instead. """ from typing import Iterable from typing import Union def fizz_buzz(n: int) -> Iterable[Union[int, str]]: for i in ran...
the-stack_0_9910
from gi.repository import Gtk, Gdk css = """ #top GtkComboBox { background-color: #000000; } GtkWindow { color: black; background: black; background-color: black; } GtkComboBox { color: black; background: black; background-color: black; } """ class ComboBoxWindow(Gtk.Window): def __i...
the-stack_0_9913
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * import os class Templight(CMakePackage): """Templight is a Clang-based tool to profile the time ...
the-stack_0_9916
from __future__ import print_function, division import sys, os sys.path.append(os.path.abspath(".")) from problems.problem import * from helper.pom3 import pom3 __author__ = 'panzer' class POM3BSansComp(Problem): """ POM 3B without Completion """ def __init__(self): Problem.__init__(self) self.name = ...
the-stack_0_9918
def dobro(num, formatado=False): if formatado: return f'R${num * 2:.2f}' else: return num * 2 def metade(num, formatado=False): if formatado: return f'R${num / 2:.2f}' else: return num / 2 def adicionar(num, index, formatado=False): if formatado: return f'...
the-stack_0_9920
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
the-stack_0_9925
# Django settings for demo project. import os settings_path, settings_module = os.path.split(__file__) import sys sys.path.append('../../') DEBUG = True #TEMPLATE_DEBUG = DEBUG USE_TZ=True #TIME_ZONE = 'America/Chicago' LANGUAGE_CODE = 'en-us' SECRET_KEY = '8(o*lht586wqr9hp5env&n!h!gu@t5g4*$$uupbyd*f+61!xjh' TE...
the-stack_0_9931
import fire import os import tensorflow as tf import matplotlib.pyplot as plt import os import time import datetime from dcgan.discriminator import make_discriminator_model, discriminator_loss from dcgan.generator import make_generator_model, generator_loss from dcgan.dataset import make_dataset from dcgan.utils imp...
the-stack_0_9932
# -*- coding: utf-8 -*- import logging import re from urllib.parse import quote_plus from requests.exceptions import RequestException from flexget import plugin from flexget.components.sites.utils import normalize_scene, torrent_availability from flexget.config_schema import one_or_more from flexget.entry import Entr...
the-stack_0_9933
"""Progress bars for SDGym compatible with logging and dask.""" import io import logging from datetime import datetime, timedelta LOGGER = logging.getLogger(__name__) class TqdmLogger(io.StringIO): _buffer = '' def write(self, buf): self._buffer = buf.strip('\r\n\t ') def flush(self): ...
the-stack_0_9935
import pickle import itertools import os import math from sklearn.preprocessing import normalize import re from operator import add import matplotlib.pyplot as plt #%matplotlib inline import numpy as np import argparse import pylab as pl import random def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1')...
the-stack_0_9937
# # This is Seisflows # # See LICENCE file # ############################################################################### # Import system modules import system import subprocess from glob import glob from os.path import join import sys # Import Numpy import numpy as np # Local imports import seisflows.plugins.sol...
the-stack_0_9938
""" DataFrame --------- An efficient 2D container for potentially mixed-type time series or other labeled data series. Similar to its R counterpart, data.frame, except providing automatic data alignment and a host of useful data manipulation methods having to do with the labeling information """ import collections fro...
the-stack_0_9939
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals, print_function import frappe import unittest, json, sys, os import xmlrunner import importlib from frappe.modules import load_doctype_module, get_module_name from frappe.utils i...
the-stack_0_9941
"""Functions for converting between color spaces. The "central" color space in this module is RGB, more specifically the linear sRGB color space using D65 as a white-point [1]_. This represents a standard monitor (w/o gamma correction). For a good FAQ on color spaces see [2]_. The API consists of functions to conver...
the-stack_0_9942
# Code from Chapter 7 of Machine Learning: An Algorithmic Perspective # by Stephen Marsland (http://seat.massey.ac.nz/personal/s.r.marsland/MLBook.html) # You are free to use, change, or redistribute the code in any way you wish for # non-commercial purposes, but please maintain the name of the original author. # Thi...
the-stack_0_9943
import typing import inspect import functools from base64 import b64decode from types import FunctionType import httpx from rpcpy.serializers import BaseSerializer, JSONSerializer from rpcpy.utils.openapi import set_type_model __all__ = ["Client"] Function = typing.TypeVar("Function", bound=FunctionType) class Cl...
the-stack_0_9944
""" Expressions ----------- Offer fast expression evaluation through numexpr """ import warnings import numpy as np from pandas._config import get_option from pandas._libs.lib import values_from_object from pandas.core.dtypes.generic import ABCDataFrame from pandas.core.computation.check import _NUMEXPR_INSTALL...
the-stack_0_9945
from __future__ import with_statement from time import time from fabric.api import cd, run, env, roles from fabric.decorators import task from fabric.contrib.files import exists env.use_ssh_config = True releases_dir = "/home/deploy/issadmin/releases" git_branch = "master" git_repo = "https://github.com/wgerez/iss-...
the-stack_0_9947
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
the-stack_0_9948
"""Utilities for calculating and reporting statistics about types.""" import cgi import os.path import re from typing import Any, Dict, List, cast, Tuple from mypy.traverser import TraverserVisitor from mypy.types import ( Type, AnyType, Instance, FunctionLike, TupleType, Void, TypeVarType, TypeQuery, ANY_TY...
the-stack_0_9949
#025: Crie um programa que leia o nome de uma pessoa e diga se ela tem "SILVA" no nome. nome = str(input('Escreva seu nome: ')) nome = nome.title() nome = nome.strip() nomeA = nome.split() if ('Silva' in nome): print('Seu nome tem Silva!') else: print('Seu nome não tem Silva!')
the-stack_0_9950
"""String functions in R""" import re import numpy as np from pipda import register_func from ..core.backends import pandas as pd from ..core.backends.pandas import Series from ..core.backends.pandas.core.base import PandasObject from ..core.backends.pandas.core.groupby import SeriesGroupBy from ..core.backends.panda...
the-stack_0_9952
#!/usr/bin/env python """Basic pipeline building blocks. This modules provides the basic building blocks in a JIP pipeline and a way to search and find them at run-time. The basic buiding blocks are instances of :py:class:`Tool`. The JIP library comes with two sub-classes that can be used to create tool implementation...
the-stack_0_9954
"""Gitlab service support. API docs: https://docs.gitlab.com/ee/api/ """ from dateutil.parser import parse as parsetime from snakeoil.klass import aliased, alias from urllib.parse import urlparse, urlunparse, quote_plus from ._jsonrest import JsonREST from ..exceptions import RequestError, BiteError from ..objects i...
the-stack_0_9955
# pylint: disable=wildcard-import, unused-wildcard-import """Model store which handles pretrained models from both mxnet.gluon.model_zoo.vision and gluoncv.models """ from mxnet import gluon from .ssd import * from .faster_rcnn import * from .fcn import * from .pspnet import * from .cifarresnet import * from .cifarresn...
the-stack_0_9957
from functools import wraps import tensorflow as tf from tensorflow import keras from tensorflow.keras.losses import ( BinaryCrossentropy, CategoricalCrossentropy, MeanAbsoluteError, MeanSquaredError, ) def distributed_sum_over_batch_size(batch_size: int): def _distributed_sum_over_batch_size(fun...
the-stack_0_9958
#!/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. # Download and build the data if it does not exist. import parlai.core.build_data as build_data import gzip imp...
the-stack_0_9959
import itertools as it, operator as op, functools as ft from xml.sax.saxutils import escape as xml_escape import html.parser, html.entities import os, re, collections as cs, urllib.request as ulr import gi gi.require_version('Gtk', '3.0') gi.require_version('Gdk', '3.0') from gi.repository import Gtk, Gdk, GdkPixbuf, ...
the-stack_0_9960
# ============================================================================= # PROJECT CHRONO - http://projectchrono.org # # Copyright (c) 2021 projectchrono.org # All rights reserved. # # Use of this source code is governed by a BSD-style license that can be found # in the LICENSE file at the top level of the distr...
the-stack_0_9962
from django import forms from .models import Comment, Review class ReviewForm(forms.ModelForm): class Meta: model = Review fields = ('rating', 'experience', 'description') def clean_rating(self): data = self.cleaned_data['rating'] if not data >= 1 and data <= 5: r...
the-stack_0_9964
# Read file, create an array of its values after removing the \n from each line with open('input') as file: values = file.readlines() values = [int(value[:len(value)-1]) for value in values] # PART 1: # Create a hashmap of every value's complements to reach 2020. # When you encounter that complement in the fut...
the-stack_0_9965
#!/usr/bin/env python from __future__ import division from __future__ import print_function # from keras.layers.merge import Concatenate, Add, Dot, Multiply import glob import os import zipfile import keras import numpy as np import tensorflow as tf from PIL import Image from keras import backend as K from sklearn.me...
the-stack_0_9967
from statement import Statement def main(): feature = "project_creation" with open(f"./features/{feature}.feature", "r") as file, open(f"{feature}.steps.ts", "w") as outfile: outfile.write('import { Given, When, Then, TableDefinition } from "cucumber";\n\n\n') antecessors = [] previous...
the-stack_0_9968
from utils import detector_utils as detector_utils import cv2 import tensorflow as tf import multiprocessing from multiprocessing import Queue, Pool import time from utils.detector_utils import WebcamVideoStream import datetime import argparse frame_processed = 0 score_thresh = 0.2 # Create a worker thread that loa...
the-stack_0_9971
from sqlalchemy import * from migrate import * from migrate.changeset import schema pre_meta = MetaData() post_meta = MetaData() collections = Table('collections', pre_meta, Column('id', INTEGER, primary_key=True, nullable=False), Column('user_id', INTEGER), Column('collection_id', INTEGER), ) users = Ta...
the-stack_0_9972
############################### # # Created by Patrik Valkovic # 3/9/2021 # ############################### import unittest import ffeat class EachArgTest(unittest.TestCase): def test_oneparam(self): p = ffeat.flow.EachArg(lambda x: x + 1) result, kargs = p(8) self.assertSequenceEqual(resu...
the-stack_0_9975
import tensorflow as tf import os from niftynet.application.base_application import BaseApplication from niftynet.engine.application_factory import \ ApplicationNetFactory, InitializerFactory, OptimiserFactory from niftynet.engine.application_variables import \ CONSOLE, NETWORK_OUTPUT, TF_SUMMARIES from niftyn...
the-stack_0_9978
from __future__ import annotations from typing import Optional, TYPE_CHECKING from components.base_component import BaseComponent from equipment_types import EquipmentType if TYPE_CHECKING: from entity import Actor, Item class Equipment(BaseComponent): parent: Actor def __init__(self, weapon: Optional...
the-stack_0_9979
#!/usr/bin/env python3 import ecc_ed25519 import sys, getopt from cryptography.hazmat.primitives.asymmetric import ed25519 msg = "" public_key_hex = "" encoded_signature = "" try: opts, args = getopt.getopt(sys.argv[1:],"hm:k:s:",["message=","publickeyhex=", "signature="]) except getopt.GetoptError: print('v...
the-stack_0_9981
from django.shortcuts import redirect from django.http import HttpResponse from .models import Link def index(request): return HttpResponse("Hello, world. You're at the polls index.") def openLink(request, temp): redirectLink = Link.objects.get(name=temp) link = redirectLink.redirect print(link) ...
the-stack_0_9983
import gym from gym import spaces import numpy as np # from os import path import snakeoil3_gym as snakeoil3 import numpy as np import copy import collections as col import os import time import sys class TorcsEnv: terminal_judge_start = 50 #1000 # If after 100 timestep still no progress, terminated terminat...
the-stack_0_9985
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: © 2012-2013 by the SaltStack Team, see AUTHORS for more details :license: Apache 2.0, see LICENSE for more details. tests.integration.shell.call ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ''' # Import python libs i...
the-stack_0_9986
# Copyright (c) 2019-2021 CRS4 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribut...
the-stack_0_9987
import os from torchnlp.download import download_file_maybe_extract def wmt_dataset(directory='data/wmt16_en_de', train=False, dev=False, test=False, train_filename='train.tok.clean.bpe.32000', dev_filename='newstest2013.tok.bpe.32000', ...
the-stack_0_9991
import sys import gym.spaces import itertools import numpy as np import random import tensorflow as tf import tensorflow.contrib.layers as layers from collections import namedtuple from dqn_utils import * OptimizerSpec = namedtuple("OptimizerSpec", ["constructor", "kwargs", "lr_schedule"]) def learn(en...
the-stack_0_9992
# -*- coding: utf-8 -*- """ Module with logic for the Environment sub-process """ __author__ = 'Samir Adrik' __email__ = 'samir.adrik@gmail.com' from source.util import Assertor, Tracking, Debugger from .finn_environment_process import FinnEnvironmentProcess from .engine import SubModel class FinnEnvironmentSubMo...
the-stack_0_9993
# Copyright 2013 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_0_9994
import sys import inspect from scenic import scenarioFromString from scenic.core.simulators import DummySimulator, RejectSimulationException import scenic.syntax.veneer as veneer ## Scene generation utilities # Compilation def compileScenic(code, removeIndentation=True, scenario=None): if removeIndentation: ...
the-stack_0_9995
# Created by Ilia # https://www.tensorflow.org/tutorials/keras/regression#the_auto_mpg_dataset import matplotlib.pyplot as plt import numpy as np import pandas as pd import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.layers.experimental import preprocessing ...
the-stack_0_10001
import base64 import io import logging import os import numpy as np import torch from PIL import Image from torch.autograd import Variable from torchvision import transforms logger = logging.getLogger(__name__) class DIYSegmentation: """ DIYSegmentation handler class. """ def __init__(self): ...
the-stack_0_10002
import os from zipfile import ZipFile bag_of_words = open('spans-pred_charbert.txt', 'r') charBert = open('40_0.4_spans-pred.txt', 'r').readlines() zipObj = ZipFile('spans-pred.zip', 'w') def charList_to_intList(line): line = line.split('\t') line = line[1][1:-1].split(' ') span = [] for elem in line: if len(el...
the-stack_0_10003
# To test a single translator use the -k parameter followed by either # timescale or crate. # See https://docs.pytest.org/en/stable/example/parametrize.html from datetime import datetime from conftest import crate_translator, timescale_translator from utils.common import TIME_INDEX_NAME from utils.tests.common import ...
the-stack_0_10004
import random print("BEM VINDO AO JOGO DO PARA OU IMPAR") print("--"*15) vit = 0 while True: palpite = int(input('Diga um valor entre zero e 9: ')) jogador = '' while jogador not in ['P', 'I']: jogador = str(input('Quer Par ou Impar? ')).strip().upper()[0] jogada = random.choice(['PAR','IMPAR'])...
the-stack_0_10005
"""The dhcp integration.""" from abc import abstractmethod from datetime import timedelta import fnmatch from ipaddress import ip_address as make_ip_address import logging import os import threading from aiodiscover import DiscoverHosts from aiodiscover.discovery import ( HOSTNAME as DISCOVERY_HOSTNAME, IP_AD...
the-stack_0_10006
# -*- coding: utf-8 -*- """ Created on Wed Sep 27 15:06:40 2017 @author: Diogo Leite """ # here the FK values was selected in lastas positions according to Species_new object class from DAL import * from configuration.configuration_data import * class _Species_sql_new(object): """ This class manipulate the ...
the-stack_0_10008
# Copyright 2015 Lukas Lalinsky # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
the-stack_0_10009
import numpy as np import scipy as sp from ._model import Model from ..utils import safe_isinstance, record_import_error from ..utils.transformers import parse_prefix_suffix_for_tokenizer from .. import models from .._serializable import Serializer, Deserializer try: import torch except ImportError as e: recor...
the-stack_0_10010
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from __future__ import print_function import os import re import llnl.util.tty as tty from llnl.util.filesystem import m...
the-stack_0_10012
#! /usr/bin/env python # # Example program using irc.client. # # Copyright (C) 1999-2002 Joel Rosdahl # # This library 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 Software Foundation; either # version 2.1 of the Licens...
the-stack_0_10013
# 5550 # <!*[^<>]*> # POLYNOMIAL # nums:4 # POLYNOMIAL AttackString:"<"+"!"*10000+"! _1_POA(i)" import re from time import perf_counter regex = """<!*[^<>]*>""" REGEX = re.compile(regex) for i in range(0, 150000): ATTACK = "<" + "!" * i * 10000 + "! _1_POA(i)" LEN = len(ATTACK) BEGIN = perf_counter() ...
the-stack_0_10014
#!/usr/bin/env python3 import os import re import sys import urllib.request from time import strptime # Regular Expressions CVE_RE = re.compile('CVE-[0-9]{4}-[0-9]{4,}') HTML_RE = re.compile('<[^<]+?>') BOUNTY_RE = re.compile('\[\$([0-9\.]|TBD|N/A)+\]') BUG_RE = re.compile('\[[0-9]+\]') DESCRIPTION_RE = re.compile('[...
the-stack_0_10015
import unittest from argparse import ArgumentTypeError from streamlink.utils.args import ( boolean, comma_list, comma_list_filter, filesize, keyvalue, num ) class TestUtilsArgs(unittest.TestCase): def test_boolean_true(self): self.assertEqual(boolean('1'), True) self.assertEqual(boolean('on')...
the-stack_0_10016
#!/usr/bin/env vpython # # Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import collections import json import logging import os import pipes import re import shutil import signal import so...
the-stack_0_10017
# импортируем специальные поля Алхимии для инициализации полей таблицы from sqlalchemy import Column, Float, String, Integer # импортируем модуль инициализации декларативного класса Алхимии from DB.dbcore import Base class Client(Base): __tablename__ = 'clients' id = Column(Integer, primary_key = True) ad...
the-stack_0_10020
import cv2 import numpy as np from PIL import Image def anahtarOlustur(gorsel,gelen): r, c ,t= gorsel.shape keyGen = np.random.randint(0, 256, size=(r, c, t ), dtype=np.uint8) key = np.random.choice(gelen,size=(r, c,t)) mylist = [] for i in key: arr = np.array(i, dtype=np.uint8) my...
the-stack_0_10022
_base_ = [ '../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/voc0712.py', '../_base_/default_runtime.py' ] model = dict(roi_head=dict(bbox_head=dict(num_classes=20))) # optimizer optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) ...
the-stack_0_10023
import torch from torch import Tensor from torch.nn import Parameter as Param from torch_geometric.nn.conv import MessagePassing from ..inits import uniform class GatedGraphConv(MessagePassing): r"""The gated graph convolution operator from the `"Gated Graph Sequence Neural Networks" <https://arxiv.org/abs/1...
the-stack_0_10024
import os from pathlib import Path from allennlp.data.iterators import BasicIterator from allennlp.nn.util import move_to_device from pytorch_pretrained_bert import BertTokenizer, BertModel, BertAdam import config from bert_model_variances.bert_multilayer_output import BertMultiLayerSeqClassification from data_utils....