text stringlengths 3.07k 22.1k |
|---|
"""This module supports puzzles where closed loops are filled into a grid."""
import itertools
from collections import defaultdict
from typing import Any, Dict, Iterable, List, Tuple
from z3 import (
And, ArithRef, BoolRef, Distinct, If, Implies, Int, Or, Xor
)
from .geometry import Direction, Lattice, Point
from... |
import numpy as np
from numpy import std, mean, sqrt
# Need to import IO
def overlap_function(base_arr, input_arr, input_ids_list, input_mode = 'separate',\
base_ids_list = None, basis = 'DICE'):
'''
Measures the overlap between the base and values of the the input.
The values of the input to be measur... |
import os.path
from collections import namedtuple
import pytest
from leapp.libraries import stdlib
from leapp.libraries.actor import forcedefaultboot
from leapp.libraries.common.config import architecture
from leapp.libraries.stdlib import api
from leapp.models import InstalledTargetKernelVersion
Expected = namedtup... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 18 13:13:55 2019
@author: arslan
"""
import numpy as np
import matplotlib.pyplot as plt
from pyit2fls import IT2FS_Gaussian_UncertStd, IT2Mamdani, min_t_norm, max_s_norm
import PyPSO
from time import time
def mackey_glass(tav, n, beta, gamma, step)... |
import os
import hashlib
import copy
import datetime
import random
import warnings
import git
import automatminer
from fireworks import Firework, Workflow, ScriptTask, LaunchPad, FWorker
from sklearn.model_selection import KFold
from benchdev.tasks import \
ConsolidatePipesToBenchmark, RunPipe, StorePipeResults, ... |
import json
from .utils import parse_dice_format
class Stat:
def __init__(self, value=10):
self._value = value
self.stat_modifier = 0
self.temp_stat_modifier = 0
def randomize(self):
self._value = parse_dice_format("4d6D1")
@property
def value(self):
return se... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
import sys
from google.protobuf.compiler import plugin_pb2 as plugin
from google.protobuf.descriptor_pb2 import FieldDescriptorProto as desc
LOCATION_MSG_TYPE = 4
LOCATION_ENUM_TYPE = 5
LOCAT... |
import threading
from engineio.payload import Payload
from flask import Flask, jsonify, redirect, render_template, request, url_for
from flask_socketio import SocketIO
from database.service import (create_update_chainpreset,
create_update_pedalpreset, database,
... |
import numpy as np
import warnings
import lenstronomy.Util.data_util as data_util
from lenstronomy.Data.psf import PSF
class Instrument(object):
"""
basic access points to instrument properties
"""
def __init__(self, pixel_scale, read_noise=None, ccd_gain=None):
"""
:param read_noise:... |
# -*- coding: utf-8 -*-
"""
Holds misc. utility methods which prove to be
useful throughout this library.
"""
__title__ = 'newspaper'
__author__ = '<NAME>'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014, <NAME>'
import codecs
import hashlib
import logging
import os
import pickle
import random
import re
import str... |
import os
import json
import socket
SERVER_HEADER = b'\n[== "CMake Server" ==[\n'
SERVER_FOOTER = b'\n]== "CMake Server" ==]\n'
class ServerWrapper:
"""
Class that emulates CMake Server Mode.
"""
def __init__(self, cmake):
self.cmake = cmake
self.meson = cmake.meson
self.logg... |
import os
import numpy as np
import logging
import gc
import re
import skimage.io as io
import SimpleITK as sitk
import h5py
from skimage import transform
import utils
import config.system_paths as sys_config
import subprocess
import csv
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
import m... |
from abc import abstractmethod
from protean import exceptions, utils
from protean.globals import current_domain
from protean.reflection import id_field
from .base import Field, FieldBase
from .mixins import FieldCacheMixin, FieldDescriptorMixin
class _ReferenceField(Field):
"""Shadow Attribute Field to back Ref... |
# -*- coding: utf-8 -*-
# * Copyright (c) 2009-2018. Authors: see NOTICE file.
# *
# * 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... |
import keras.backend as K
import keras.layers
from keras import optimizers
from keras.engine.topology import Layer
from keras.layers import Activation, Lambda
from keras.layers import Conv1D, SpatialDropout1D
from keras.layers import Convolution1D, Dense
from keras.models import Input, Model
from typing import List, Tu... |
import translation_extractor
from folder_converter import *
import text_converter
import openpyxl
import urllib.request
import urllib.parse
import settings
import json
import onscript
import ui
def validate_folder(folder_path: str):
result = True
for file_name in os.listdir(folder_path):
if not file_n... |
import hashlib
import tensorflow as tf
import os
import glob
import cv2
import random
from lxml import etree
from PIL import Image
from shutil import copyfile
from object_detection.utils import label_map_util
from object_detection.utils import dataset_util
RANDOM_SEED = 42
flags = tf.app.flags
flags.DEFINE_string('d... |
import numpy as np
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
import functools
from torch.autograd import Variable as V
from pytorch3d.structures import Meshes
from gcn import MeshRefinementHead
def lr_pad(x, padding=1):
''' Pad left/right-mos... |
import warnings
import numpy as np
import torch
class Evaluator(object):
def __init__(self):
pass
def __call__(self, predict, truth):
"""
:param predict: list of tensors, the network outputs from all batches.
:param truth: list of dict, the ground truths from all batch_y.
... |
#DS 3231 RTC Real Time Clock, Registerbelegung auf Datenblatt S.15
import smbus
import time
from datetime import datetime, time, date
#I2C-Adresse
address = 0x68
#Register für Aktuelle Zeit
register = 0x00 #Hierbei wird diesmal nicht write_byte_data verwendet um 7 Byte sofort am Stück in das Register zu schreiben, d... |
#
# Copyright (c) 2021, NVIDIA 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 ... |
"""Ray-Horovod Job unit tests.
This is currently not run on the Ray CI.
"""
import os
import sys
import socket
import pytest
import ray
from ray import services
import torch
from horovod.common.util import gloo_built
from horovod.ray.runner import (BaseHorovodWorker, NodeColocator, Coordinator,
... |
#----------------------------------
# lambda function: convertRawToJPG
# image convert(Bayer RAW Format->JPEG/TIFF) and
# push message via SNS(Amazon Simple Notification Service)
#
# save file
# Bucket: <BUCKET_NAME>
# filepath: photo/YYYYmm/yymmdd_HHMMSS.jpg
import json
import boto3
import cop... |
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.
# Example of training ResNet on CIFAR-10 using stochastic rounding
import sys
import time
import argparse
import tensorflow.compat.v1 as tf
from tensorflow.python import ipu
# Process command-line arguments
parser = argparse.ArgumentParser(
description='... |
import discord
import asyncio
import time
import requests
from discord import Spotify
from datetime import timedelta
from discord.ext import commands
starttime = time.time()
class InfoCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def userinfo(... |
import uuid, math
from compas.datastructures.mesh import Mesh, mesh_weld, meshes_join
from compas.geometry import Frame, Point, Vector
from compas.geometry import Box, Polyhedron, Line, Transformation, Translation
from compas.geometry import is_polygon_convex, transform_points, dot_vectors, angle_vectors
def create_... |
"""Weather data coordinator for the OpenWeatherMap (OWM) service."""
from datetime import timedelta
import logging
import async_timeout
from pyowm.commons.exceptions import APIRequestError, UnauthorizedError
from homeassistant.components.weather import (
ATTR_CONDITION_CLEAR_NIGHT,
ATTR_CONDITION_SUNNY,
A... |
from typing import Union, Iterable, Iterator, List
import pytest
from conftest import vcf_file, gtf_file, example_intervals_bed
import pyranges
from kipoiseq.dataclasses import Interval, Variant
from kipoiseq.extractors.vcf import MultiSampleVCF
from kipoiseq.extractors.vcf_matching import variants_to_pyranges, \
p... |
#
#
# Copyright (C) 2011, 2012 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of condition... |
from __future__ import print_function
import os
import gc
import hashlib
import random
from joblib import load as joblib_load, dump as joblib_save, Parallel, delayed
import numpy as np
from utils import checkFreeMemory, getFileSize, getTotalMemory, tryToRemove
from .resultsManager import ResultsManager
from codifyCom... |
'''
Function:
Visualize the segmentation results by using our segmentors
Author:
<NAME>
'''
import os
import cv2
import copy
import torch
import warnings
import argparse
import numpy as np
import torch.nn.functional as F
from tqdm import tqdm
from modules import *
from cfgs import BuildConfig
warnings.filterwar... |
from textwrap import wrap
from ansys.dpf.core.mapping_types import map_types_to_python
from ansys.dpf.core.outputs import _Outputs, Output
from ansys.dpf import core
class Input:
"""
Parameters
----------
spec :
pin :
operator :
count_ellipsis : optional
The default is ``-1``.
... |
"""
The MIT License (MIT)
Copyright (c) 2015-2021 Rapptz
Copyright (c) 2021-present Pycord Development
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 limit... |
from DirectVOLayer import DirectVO
from networks import VggDepthEstimator, PoseNet, PoseExpNet
from ImagePyramid import ImagePyramidLayer
import torch.nn as nn
import torch
from torch.autograd import Variable
import numpy as np
import itertools
from timeit import default_timer as timer
class FlipLR(nn.Module):
d... |
#!/usr/bin/env python
# <NAME>
"""
usage: %prog score_file interval_file chrom start stop [out_file] [options]
-b, --binned: 'score_file' is actually a directory of binned array files
-m, --mask=FILE: bed file containing regions not to consider valid
-c, --chrom_buffer=INT: number of chromosomes (default is... |
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.compat import basestring
from .core import blockwise, asarray, einsum_lookup
from ..utils import derived_from
einsum_symbols = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
einsum_symbols_set = set(einsum_symbols)... |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--batch_size', type=int, default=128)
parser.add_argument('--deterministic_init', action='store_true')
parser.add_argument('--deterministic_input', action='store_true')
parser.add_argument('--deterministic_tf', action='store_true')
parser.add_argum... |
""" Cisco_IOS_XR_pbr_bng_cfg
This module contains a collection of YANG definitions
for Cisco IOS\-XR pbr\-bng package configuration.
This module contains definitions
for the following management objects\:
bng\-pbr\: Subscriber PBR configuration
Copyright (c) 2013\-2018 by Cisco Systems, Inc.
All rights reserved.
... |
"""Unit tests for recordclass.py."""
import unittest, doctest, operator
from recordclass import recordclass, RecordclassStorage
from collections import OrderedDict
import pickle, copy
import keyword
import re
import sys
try:
from test import support
except:
from test import test_support as support
TestNT = r... |
""" Simple, robust SSH client(s) for basic I/O with remote hosts
"""
import asyncio
import logging
import os
import pty
import stat
import subprocess
import tempfile
import typing
from contextlib import contextmanager
import retrying
from dcos_test_utils import helpers
log = logging.getLogger(__name__)
SHARED_SSH_... |
#!/usr/bin/env python
from runtime_context import LOGGER
from lib.utils import pascal_case
from datetime import datetime
import boto3
import json
from lib import ddb, utils
from transitions import Machine, State
from transitions.extensions.states import add_state_features
LAMBDA_CLIENT = boto3.client('lambda')
DDB_CL... |
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
import numpy as np
from PIL import ImageFile, Image
import cv2
print(1)
plt.i... |
# Copyright 2021 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, ... |
import os
import math
from tqdm import tqdm
import textwrap
from PIL import Image
import numpy as np
import pandas as pd
import matplotlib.patches as patches
import matplotlib.pyplot as plt
def compute_nb_days(db, start):
"""
Compute the number of days of the project (days between start and the date of the la... |
#!/usr/bin/env python
####################################################################################
### Copyright (C) 2015-2019 by ABLIFE
####################################################################################
####################################################################################
###... |
import os
import numpy as np
import pandas as pd
from .utils import consensus_clustering, cv_cluster_stability, hydra_solver_svm_tl
from .base import WorkFlow
from pyhydra.utils import hydra_solver_svm
__author__ = "<NAME>"
__copyright__ = "Copyright 2019-2020 The CBICA & SBIA Lab"
__credits__ = ["<NAME>, <NAME>"]
__l... |
#!/usr/bin/env python
# encoding: utf-8
# The MIT License
# Copyright (c) 2018 Ina (<NAME> - http://www.ina.fr/)
# 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, includ... |
#!/usr/bin/env python
import logging
from collections import defaultdict
from textwrap import dedent
import numpy as np
LOGGER = logging.getLogger(__name__)
__all__ = ['find_nearest', 'iter_current_next', 'partition', 'iter_subclasses']
def find_nearest(array, value):
"""
Return the index of the value in `... |
# encoding: UTF-8
import sys
from time import sleep
from vncshshlp import *
import vncshshlp
branch_no = ''
#----------------------------------------------------------------------
def print_list(l):
""""""
for d in l:
print(d)
#---------------------------------------------------... |
# Copyright (c) 2001-2008 Twisted Matrix Laboratories.
# See LICENSE for details.
# The referred licence file contains:
#
#Copyright (c) 2001-2010
#<NAME>
#<NAME>
#<NAME>
#<NAME>
#Apple Computer, Inc.
#<NAME>
#<NAME>
#Canonical Limited
#<NAME>
#<NAME>
#<NAME>
#<NAME>
#<NAME>
#<NAME>-Trauring
#<NAME>
#<NAME>
#<NAME>
#... |
import dataclasses
import itertools
import typing
import sqlglot.expressions as exp
from sqlglot.errors import OptimizeError
from sqlglot.optimizer.helper import SelectParts
def qualify_columns(expression, schema):
"""
Rewrite sqlglot AST to have fully qualified columns.
Example:
>>> import sqlg... |
from __future__ import division, print_function
import numpy as np
import pandas as pd
from tqdm import tqdm
from scipy.special import erf
# ## constants
# # original values from email by <NAME> from 06/03/2016
# tess_scale = 20.25 / 3600.0 # arcsec / pixel --> deg / pixel
# # tess_fwhm = 2.0 * tess_scale # 2 p... |
# %%
import os
import sys
from datetime import datetime
from pathlib import Path
import alphashape
import folium
from folium.plugins import (BeautifyIcon, FloatImage, Fullscreen, HeatMap,
MarkerCluster, MeasureControl, Search)
from scipy.spatial import Delaunay
from shapely import wkt
from ... |
"""Implement a nonlinear MPC scheme using Casadi"""
import inspect
from math import pi
import os
import sys
import time
from typing import Dict, Any, List
import casadi
import torch
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import interp1d
from tqdm import tqdm
# Add the parent directo... |
"""Undo management for Gaphor.
Undoing and redoing actions is managed through the UndoManager.
An undo action should be a callable object (called with no arguments).
An undo action should return a callable object that acts as redo function.
If None is returned the undo action is considered to be the redo action as w... |
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import seaborn as sns
import scipy.cluster.hierarchy as sch
from scipy.stats import pearsonr, spearmanr, gaussian_kde
figsize = (5, 5)
#matplotlib.rcParams['pdf.fonttype'] = 42
#matplotlib.rcParams['ps.fonttype'... |
from helper import *
from config import hyperparams
import os
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from time import sleep
import re
import numpy as np
import time
import json
from glob import glob
import pickle
from tqdm import tqdm, trange
imp... |
#!/usr/bin/env python
"""Client actions related to administrating the client and its configuration."""
import os
import platform
import socket
import time
import traceback
from distorm3 import _distorm
import M2Crypto
import pkg_resources
import psutil
import pytsk3
import rekall
import logging
from grr.client im... |
from .gen_html import startHtmlPage
#===============================================
def formXLTreePage(output, title, common_title, html_base, xl_ds):
startHtmlPage(output, title, html_base,
css_files = ["xltree.css"],
js_files = ["xltree.js"])
print >> output, (
' <body onload="init... |
from pyrocko import eventdata
from pyrocko import model
from pyrocko import io
from tunguska import source
from tunguska import receiver
from tunguska import gfdb as gfdb_mod
from tunguska import seismosizer
from tunguska import gridsearch
import numpy as num
def get_nsl(x):
return x.network, x.station, x.locat... |
#!/usr/bin/env python3
# Copyright 2019 RnD Center "ELVEES", JSC
import argparse
import csv
import os
import matplotlib.pyplot as plt
import numpy
def group(lst, num_elem):
return list(zip(*[iter(lst)] * num_elem))
def count_rows(input_file):
with open(input_file) as file_:
reader = csv.DictReade... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 16 14:21:25 2018
@author: dberke
"""
import numpy as np
import scipy.stats
import matplotlib.pyplot as plt
import os.path
from glob import glob
from astropy.io import fits
def vac2air(wl_vac):
"""Take an input vacuum wavelength in nm and retur... |
# Copyright 2019-2020 Not Just A Toy Corp.
#
# 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... |
# ============================================================================
#
# Copyright (C) 2007-2016 Conceptive Engineering bvba.
# www.conceptive.be / <EMAIL>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
... |
#!/usr/bin/env python
#
# Copyright (C) 2014 Narf Industries <<EMAIL>>
#
# 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,... |
import pytest
from wikipedia_ql import media_wiki
@pytest.fixture
def wiki():
return media_wiki.Wikipedia(cache_folder='tests/_cache')
def test_rotten_tomatoes(wiki):
assert wiki.query(r'''
from "Nomadland (film)" {
section[heading="Critical response"] {
sentence["Rotten T... |
import os
import numpy as np
import scipy.sparse as sp
from sklearn.preprocessing import MultiLabelBinarizer, LabelBinarizer, normalize
def load_npz_to_sparse_graph(file_name):
"""Load a SparseGraph from a Numpy binary file.
Parameters
----------
file_name : str
Name of the file to load.
... |
import base64
import json
import logging
import six
from . import credentials
from . import errors
from .utils import config
INDEX_NAME = 'docker.io'
INDEX_URL = 'https://index.{0}/v1/'.format(INDEX_NAME)
TOKEN_USERNAME = '<token>'
log = logging.getLogger(__name__)
def resolve_repository_name(repo_name):
if '... |
from typing import Any, Dict, List, Optional
import catalogue
import contextlib
import copy
import itertools
from io import BytesIO
import numpy
from ..backends import Ops, get_current_ops, get_array_ops
from ..optimizers import Optimizer
from ..types import ArgsKwargs, ArrayXd
from ..util import tensorflow2xp
from .s... |
# Helper script which connects to GPSDO UART3 over given serial port,
# receives data, decodes it and prints to console.
import datetime
import os
import serial
import time
PORT = 'COM4'
def ignore_ongoing_transmission(port):
start_time = time.time()
while True:
current_time = time.time()
rec... |
from tensorflow.keras import layers, models, Model, Sequential
def InceptionV1(im_height=224, im_width=224, class_num=1000, aux_logits=False):
# tensorflow中的tensor通道排序是NHWC
input_image = layers.Input(shape=(im_height, im_width, 3), dtype="float32")
# (None, 224, 224, 3)
x = layers.Conv2D(64, kernel_si... |
# 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... |
from common_python.tests.classifier import helpers as test_helpers
from common_python.classifier import feature_analyzer
from common_python.classifier.feature_set \
import FeatureSet, FeatureVector
from common_python.classifier import feature_set
from common_python.testing import helpers
from common_python import ... |
#------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------------------------------------------------... |
#!/usr/bin/python
# Copyright (c) 2020, 2021 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... |
# pylint: disable=duplicate-code
# noqa: B950,F841
import logging
from pathlib import Path
from typing import Any, Dict, List as ListType
import boto3
import yaml
from taskcat._cfn._log_stack_events import _CfnLogTools
from taskcat._cfn.threaded import Stacker
from taskcat._cfn_lint import Lint as TaskCatLint
from ta... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import hashlib
import os
from django.conf import settings
from django.core import urlresolvers
from django.core.files.base import ContentFile
from django.db import models
from django.utils.translation import ugettext_lazy as _
from filer.utils.compatibil... |
__all__ = ["Monitor", "ResultsWriter", "get_monitor_files", "load_results"]
import csv
import json
import os
import time
from glob import glob
from typing import Dict, List, Optional, Tuple, Union
import gym
import numpy as np
import pandas
from stable_baselines3.common.type_aliases import GymObs, GymStepReturn
cl... |
from itertools import combinations
# Essa biblioteca é nativa do próprio python, ela não é científica
# puramente lida com operações de natureza iterativa
def legendre(x, n):
"""
Calcula o valor do polinômio de Legendre de qualquer grau
utilizando a fórmula de Bonnet:
$$ (n + 1) P_{n+1}(x) = (2n... |
import os
import time
from argparse import ArgumentParser
import pytorch_lightning as pl
import torch
import torchmetrics as tm
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint, LearningRateMonitor
from pytorch_lightning.plugins import DDPPlugin
from torch import nn
from torch.optim.lr_scheduler ... |
import configparser
import logging
import numpy as np
import os
# from envs.real_net_env import RealNetEnv
ILD_POS = 50
def write_file(path, content):
with open(path, 'w') as f:
f.write(content)
def output_flows(flow_rate, seed=None):
if seed is not None:
np.random.seed(seed)
FLOW_NUM =... |
#!/usr/bin/env python3
# 2020, Technische Universität München; <NAME>
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Sinc convolutions for raw audio input."""
from collections import OrderedDict
from espnet2.kws.preencoder.abs_preencoder import AbsPreEncoder
from espnet2.layers.sinc_conv import LogC... |
from django.db import models
from django.db.models import (
get_model,
Sum,
Max,
)
from django.db.models.query import QuerySet
from .constants import *
class SecurityQuerySet(QuerySet):
@property
def authorized(self):
securities = self.select_related()
return sum(filter(
... |
import argparse
import numpy as np
import os
import csv
import imutils
import cv2
import random
import operator
# print(cv2.__version__)
def parse_args():
desc = "Smarter crops using object detection (Runway YOLOv4, Colab YOLOv5)"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('--verbose'... |
import os,time,cv2,argparse,multiprocessing
import numpy as np
from mvnc import mvncapi as mvnc
from skimage.transform import resize
from utils.app_utils import FPS, WebcamVideoStream
from multiprocessing import Queue, Pool
import cv2
classes = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "c... |
# A 165 LINE TOPOLOGY OPTIMIZATION CODE BY <NAME> AND <NAME>, JANUARY 2013
#Edited by <NAME>, May 2018
from __future__ import division
import numpy as np
from scipy.sparse import coo_matrix
from scipy.sparse.linalg import spsolve, lgmres, spilu, LinearOperator
from scipy import linalg as LA
from matplotlib import cm,py... |
# -*- coding: utf-8 -*-
"""
Evaluate objective on a set of parameters
=========================================
Call user's script as a black box process to evaluate a trial.
"""
import copy
import json
import logging
import os
import subprocess
import tempfile
import orion.core
from orion.core.io.convert import JSO... |
import datetime
import sys
import pandas as pd
## convert HTML table to Pandas dataframe
def parse_html_table(table):
"""
takes in an html table from the cheshire database and transforms it into
a pandas.Dataframe
Parameters
----------
table : bs4.BeautifulSoup
A data structure obtai... |
import copy
import threading
import asyncio
import six
from django.http import HttpResponseBadRequest
from channels.generic.http import AsyncHttpConsumer
from channels.http import AsgiRequest
from channels.db import database_sync_to_async
from .utils import add_default_headers
MAX_PENDING = 10
class Listener(object):... |
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... |
#!/usr/bin/env python3
#Needs PIP3 install pandas numpy
from slickrpc import Proxy
import time
import sys
import datetime
import os
from subprocess import check_output, CalledProcessError
import json
import re
import platform
import calendar
import pandas as pd
import numpy as np
from threading import Thread
utxoamt... |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import inspect
from types import FrameType
from typing import (
Iterator,
Optional,
)
import pytest
from django... |
#! /usr/bin/env python
# This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) <NAME> <<EMAIL>>
# This program is published under a GPLv2 license
# scapy.contrib.description = Helper class for tracking ECU states (ECU)
# scapy.contrib.status = loads
import time
im... |
#!/usr/bin/env python
"""Simple parsers for configuration files."""
import os
import re
import stat
import logging
from grr.lib import lexer
from grr.lib import parsers
from grr.lib import utils
from grr.lib.rdfvalues import anomaly as rdf_anomaly
from grr.lib.rdfvalues import client as rdf_client
from grr.lib.rdfval... |
#!/usr/bin/env python
#
# Copyright (c) 2014 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list o... |
'''
Trabalho de conclusão do curso de Programação Orientada a Objetos
Faculdades Integradas de Diamantino
Prof. Esp. <NAME>
-----------------------------------------------------------------
(se você fez algo com estas funções, passou!!) ;'-)
(achando algum bug, corrija!)
'''
import sys
'''
Classe Produto
... |
"""
wind.web.app
~~~~~~~~~~~~
Web application serving http requests.
"""
import json
import types
import hashlib
import traceback
from wind.web.codec import encode, to_str
from wind.log import wind_logger, LogType
from wind.web.httpmodels import (
HTTPRequest, HTTPResponse, HTTPMethod,
HTTPStatu... |
# Python Version 2.7.3
# File: minesweeper.py
from tkinter import *
from tkinter import messagebox as tkMessageBox
from collections import deque
import random
import platform
import time
from datetime import time, date, datetime
SIZE_X = 10
SIZE_Y = 10
STATE_DEFAULT = 0
STATE_CLICKED = 1
STATE_FLAGGED = 2
BTN_CLICK... |
# Copyright (c) 2022 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... |
""" Functions for locating Goddard nasateam files on a filesystem.
"""
import datetime as dt
import fnmatch
import os
from calendar import monthrange
from functools import lru_cache
import pandas as pd
from .errors import SeaIceDataInvalidSearchPathsError
import seaice.nasateam as nt
from .cache import SeaiceFsCache... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.