input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
np.mean(nll_M_var_val)] +
list(np.mean(np.array(kl_list_val), axis=0)) +
list(np.mean(np.array(kl_var_list_val), axis=0)) +
# list(np.mean(np.array(KLb_blocks_val),axis=0))
[np.mean(acc_var_val)] + list(np.mean(np.array(acc_var_blocks_val), axis=0))
)
perm_writer.writerow(list(np.mean(np.array(perm_train), axis=0... | |
import numpy as np
import matplotlib.pyplot as plt
import theano
# By convention, the tensor submodule is loaded as T
import theano.tensor as T
class Layer(object):
def __init__(self, W_init, b_init, activation):
'''
A layer of a neural network, computes s(Wx + b) where s is a nonlinearity and x is the input vect... | |
"""Convert XFL edges to SVG paths.
If you just want to convert, use `xfl_edge_to_svg_path()`. If you're interested
in how everything works, read on.
"""
# Read these links first, as there is no official documentation for the XFL
# edge format:
#
# * https://github.com/SasQ/SavageFlask/blob/master/doc/FLA.txt
# * http... | |
#!/usr/bin/python
#-*- coding: utf-8 -*-
#Developer by Bafomet
import os
import time as t
import subprocess
from module.utils.banner import show_banner
WHSL = '\033[1;32m'
ENDL = '\033[0m'
REDL = '\033[0;31m'
GNSL = '\033[1;34m'
arrow = f" {REDL}└──>{WHSL}"
connect = f"{REDL}│{WHSL}"
page_1 = '''{0}
{1}Использовать... | |
of values as JobState.
"""
pulumi.set(__self__, "current_state_time", current_state_time)
pulumi.set(__self__, "execution_stage_name", execution_stage_name)
pulumi.set(__self__, "execution_stage_state", execution_stage_state)
@property
@pulumi.getter(name="currentStateTime")
def current_state_time(self) -> str:... | |
<filename>pyiron_atomistics/atomistics/structure/analyse.py
# coding: utf-8
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department
# Distributed under the terms of "New BSD License", see the LICENSE file.
import numpy as np
from sklearn.cluster import Agglomerative... | |
MeshVertexIndices(self, topologyVertexIndex):
""" MeshVertexIndices(self: MeshTopologyVertexList, topologyVertexIndex: int) -> Array[int] """
pass
def SortEdges(self, topologyVertexIndex=None):
"""
SortEdges(self: MeshTopologyVertexList, topologyVertexIndex: int) -> bool
SortEdges(self: MeshTopologyVerte... | |
layer_id = 'None'
# Get metric name, first get metric id from the features profile
# record
try:
metric_list = [row[2] for row in ionosphere_summary_list if row[0] == fp_id]
metric = metric_list[0]
except:
metric = 'UNKNOWN'
uri_to_matched_page = 'None'
matches.append([metric_human_date, match_id, matched_by, ... | |
<filename>src/pkgcore/ebuild/portage_conf.py
"""make.conf translator.
Converts portage config files into :obj:`pkgcore.config` form.
"""
__all__ = (
'PortageConfig', 'SecurityUpgradesViaProfile',
)
import configparser
import errno
import os
import sys
from collections import OrderedDict
from snakeoil.bash import r... | |
<gh_stars>0
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. impo... | |
must be a list-like with numeric or'
'date-like values: %s', list_check)
def _get_f_dummy_from_calendar(calendar):
# Generate dummy model function from a pandas HolidayCalendar
def f_dummy_calendar(a_x, a_date, **kwargs):
# TODO: If we can pass dict_cal as an argument,
# use pre-loaded list of dates for perform... | |
#!/usr/bin/env python
from __future__ import print_function
import sys
import os
from ROOT import *
from copy import deepcopy
from array import array
import six
gROOT.SetBatch() # don't pop up canvases
#Find Data files
def getFileInPath(rfile):
import os
for dir in os.environ['CMSSW_SEARCH_PATH'].split(":"):
if... | |
= self._player.night_mode
speech_enhance = self._player.dialog_mode
is_radio_stream = \
current_media_uri.startswith('x-sonosapi-stream:') or \
current_media_uri.startswith('x-rincon-mp3radio:')
if is_playing_tv or is_playing_line_in:
# playing from line-in/tv.
support_previous_track = False
support_next_tra... | |
While 'I' is less than the number of instances of behavior:
file.write(self.name) # Write the event name.
file.write(",")
file.write(str(I+1)) # Write the event instance.
file.write(",")
file.write(str(self.onset[I])) # Write the time measurement.
file.write(",")
file.write(str(self.offset[I])) # Write the data... | |
debug=kwargs.get(
'debug', 1), cache=kwargs.get('cache', 'False'))
elif solvename == 'newton':
solveout = partial(self.outsolve2dcunk, databank, chunk=chunk,
ljit=ljit, debug=kwargs.get('debug', 1), type='res')
elif solvename == 'res':
solveout = partial(self.outsolve2dcunk, databank, chunk=chunk,
ljit=ljit, deb... | |
<gh_stars>1-10
# -*- coding: utf-8 -*-
import xbmc, xbmcgui, xbmcplugin, xbmcaddon, urllib2, urllib, re, string, sys, os, zlib
from uuid import uuid4
from random import random,randint
from math import floor
import hashlib
import time
import simplejson
# Plugin constants
__addonname__ = "奇艺视频(QIYI)"
__addonid__ = "plu... | |
<gh_stars>1-10
import logging
import multiprocessing
from contextlib import closing
import scipy.sparse as ssp
import random
import pandas as pd
from math import ceil
from tqdm import tqdm
import contextlib
batcher_instance = None
log = logging.getLogger(__name__)
class Batcher(object):
"""Scheduler to handle para... | |
# coding=utf-8
# Copyright 2018 The HuggingFace Inc. team.
#
# 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... | |
unconditional wait (see p274 of Tjims)
equivalent_uncond_prob = 1.0 - (1.0 - prob) * erlangc(load, c)
# Compute conditional wait time percentile for M/M/c system to use in approximation
condwaitq_pctile_mmc = mmc_qwait_pctile(equivalent_uncond_prob, arr_rate, svc_rate, c)
# First order approximation for conditional... | |
self: TNGraph const *
"""
return _snap.TNGraph_EndEI(self)
def GetEI(self, *args):
"""
GetEI(TNGraph self, int const & SrcNId, int const & DstNId) -> TNGraph::TEdgeI
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TNGraph_GetEI(self, *args)
def GetRndNId(self, *args):
"""
GetRndNI... | |
<gh_stars>0
# Copyright 2013-present Barefoot Networks, 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 l... | |
# Copyright The PyTorch Lightning team.
#
# 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 wr... | |
"""
Copyright (c) 2020 <NAME>
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, distribute, sublic... | |
<filename>Src/Tests/test_interactive.py
#####################################################################################
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# This source code is subject to terms and conditions of the Microsoft Public License. A
# copy of the license can be found in the... | |
<filename>xline/elements.py<gh_stars>0
import numpy as np
from .base_classes import Element
from .be_beamfields.beambeam import BeamBeam4D
from .be_beamfields.beambeam import BeamBeam6D
from .be_beamfields.spacecharge import SCCoasting
from .be_beamfields.spacecharge import SCQGaussProfile
from .be_beamfields.spacecha... | |
<reponame>duplico/qc15_statemaker
"""The game state object implementations for QC15's Statemaker tool.
"""
from __future__ import print_function
import sys
import csv
import textwrap
import struct
import networkx as nx
from chardet.universaldetector import UniversalDetector
from qc15_game import *
_... | |
<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
# Script for updating SPIR-V dialect by scraping information ... | |
0, 1)
# Integrate over energy
with np.errstate(divide='ignore', invalid='ignore'):
y = self._U**(3/2) / (1 - self._U)**(7/2)
y = np.where(np.isfinite(y), y, 0)
coeff = 1e6 * (2/self.mass)**(3/2) / (N * kB / K2eV) * (self.E0*eV2J)**(5/2)
Vij = np.array([[V[0]*V[0], V[0]*V[1], V[0]*V[2]],
[V[1]*V[0], V[1]*V[1]... | |
from __future__ import print_function
from builtins import str
from builtins import range
from builtins import object
import test_v1
from common import isolated_creds
from vn_test import *
from vm_test import *
from policy_test import *
import fixtures
from future.utils import with_metaclass
sys.path.append(os.path.rea... | |
<reponame>DucVinh2609/mtb_admin<filename>app/views.py<gh_stars>0
from flask import render_template, request, url_for, redirect, send_from_directory, jsonify, session
from flask_login import login_user, logout_user, current_user, login_required
from werkzeug.exceptions import HTTPException, NotFound, abort
from flask_re... | |
<reponame>mitdo/o2ac-ur
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Software License Agreement (BSD License)
#
# Copyright (c) 2021, Chukyo University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
#... | |
import pymongo
import os
import base64
import datetime
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler
import threading
import getpass
import json
import logging
import ast
import time
from urllib import request, parse
import requests
import operator
from queue import Queue
from d... | |
#!/usr/bin/python
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list ... | |
#!/usr/bin/env python
# coding: utf-8
# # A Tutorial on HashMap
# (In addition to having fun) We write programs to solve real world problems. Data structures help us in representing and efficiently manipulating the data associated with these problems.
#
# Let us see if we can use any of the data structures that we ... | |
= start_point
continue
# Draw Line
match = self.draw_line_re.search(pline)
if match:
current_subpath = 'lines'
x = float(match.group(1)) + offset_geo[0]
y = float(match.group(2)) + offset_geo[1]
pt = (x * self.point_to_unit_factor * scale_geo[0],
y * self.point_to_unit_factor * scale_geo[1])
subpath['lines']... | |
Set the new value
if self.myProperties[name]['multivalue']:
# Check if the new value is s list.
if type(value) != list:
raise TypeError(C.make_error('ATTRIBUTE_INVALID_LIST', name))
new_value = value
else:
new_value = [value]
# Eventually fixup value from incoming JSON string
s_type = self.myProperties[name]... | |
<reponame>zyberguy/cord19
import pickle
import re
import time
from pathlib import Path, PurePath
import ipywidgets as widgets
import numpy as np
import pandas as pd
import requests
from IPython.display import display, clear_output
from rank_bm25 import BM25Okapi
from requests import HTTPError
from cord.core import re... | |
os.path.dirname( os.path.dirname(os.path.realpath(__file__)) )
build_path = os.path.join( repo_path, "build" )
# get the command to launch the driver
driver_command = get_command_line(
valgrind=valgrind,
manager=manager,
nproc1=2,
command1=[driver_name,
"-driver_nranks", "0",
"-plugin_nranks", "2",
"-plugin_... | |
return term1 + term2
else: return 4*np.abs(E/_c.g0)
def fZ1(E):
if np.abs(E)<np.abs(_c.g0):
return 4*np.abs(E/_c.g0)
else:
term1 = (1+np.abs(E/_c.g0))**2
term2 = -((E/_c.g0)**2 - 1)**2 / 4
return term1 + term2
dos = np.empty_like(E)
for j, e in np.ndenumerate(E):
Z0 = fZ0(e)
Z1 = fZ1(e)
ellip = speci... | |
= [True, [40]])
bound = Attack("Bound", 2, "A damage attack; with a Yellow Spike override, the target also loses 15 Strength", damage = [True, [30]], combo = [True, {"STR":15}], consumes = True)
snapshot = Attack("Snapshot", 3, "A damage attack that also swap-blocks the opponent for this and the next 2 rounds", damage... | |
<reponame>unseenme/mindspore<gh_stars>1-10
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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
#
# Unl... | |
= int(np.abs(np.log10(precision)))
qdesign_precision = self.design.template_options.PRECISION
all_idx_bad_fillet['reduced_idx'] = get_range_of_vertex_to_not_fillet(
coords, a_fillet, qdesign_precision, add_endpoints=True)
midpoints = list()
midpoints = [
QGDSRenderer.midpoint_xy(coords[idx - 1][0], coords[idx ... | |
iterate over
activate_list.append(k)
# Remove all loads that are started
for k in activate_list:
self.waiting_list.pop(k)
wait_lenght = len(self.waiting_list) # Number of waiting items
tries = 0
temp_waitlist = self.waiting_list.copy()
while ((self.current_power < self.threshold) and self.waiting_list):
#... | |
<reponame>talipovm/Terse
import Tools.HTML
if __name__ == "__main__":
import sys,os
append_path = os.path.abspath(sys.argv[0])[:-20]
print("Append to PYTHONPATH: %s" % (append_path))
sys.path.append(append_path)
import re
import copy
from Tools.file2 import file2
from Tools import ChemicalInfo
from Geometry impor... | |
lim_switch : int
forward limit switch or reverse limit switch:
- HOMELIMSW_FWD = 4 : Use forward limit switch for home datum.
- HOMELIMSW_REV = 1 : Use reverse limit switch for home datum.
velocity : float
velocity of the motor
zero_offset : float
zero offset
"""
err_code = _lib.MOT_SetHomeParams(self._serial_... | |
# -*- coding: utf-8 -*-
from __future__ import annotations
import json
from contextlib import suppress
from time import perf_counter
from time import sleep
from typing import Callable
from typing import Optional
import click
from pioreactor import error_codes
from pioreactor import exc
from pioreactor import hardwar... | |
# Copyright 2017 The TensorFlow Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | |
<filename>zemcy/support_lib.py<gh_stars>0
'''
window = (left, top, w, h)
box = ((center_x, center_y), (a, b), angle) // or rect
((0.0, 0.0), (0.0, 0.0), 0.0)
(-angle) is angle of vecto of a is created by center to right and Ox
! points is np.array
! points la contour
box <-> points -> window <-> two points:
cnt/poin... | |
from torch.utils.data import Dataset
import h5py
import numpy as np
import cv2
import torch
import math
from preprocessing.utils import incorporate_ratio
from preprocessing.utils import visualise_image
class DataFromH5py(Dataset):
def __init__(self, file_path, idx_sets, purpose, input_type, label_type, only_one_mask... | |
# Distributed under the Apache License, Version 2.0.
# See accompanying NOTICE file for details.
import numpy as np
import subprocess
# WGS84 constants
_a = 6378137
_f = 1/(298257223563/1000000000)
_e2 = _f*(2-_f)
_e2m = np.square(1-_f)
_e2a = abs(_e2)
_e4a = np.square(_e2)
epsilon = np.finfo(float).eps
_maxrad = 2 *... | |
<reponame>aitoralmeida/lus_stratification
import os
import numpy as np
import argparse
from sklearn import metrics
from random import shuffle, sample, seed
import tensorflow as tf
from tensorflow import keras
from tensorflow.random import set_seed
from tensorflow.keras.preprocessing import image
from tensorflow.keras... | |
#-----------------------------------------------------------------
# ** ATTENTION **
# This code was automatically generated from the file:
# setlx2py/setlx_ast.cfg
#
# Do not modify it directly. Modify the configuration file and
# run the generator again.
# ** ** *** ** **
#
# AST Node classes.
#
# Copyright (C) 2008-... | |
<gh_stars>10-100
"""Circuit visualization via the pyx package
This requires a working LaTeX installation.
"""
try:
import pyx
except ImportError as e:
print("PyX is not installed. Please install PyX for circuit visualization purposes.")
raise e
import shutil
import qnet.algebra.core.circuit_algebra as ca
from qne... | |
from __future__ import annotations
from typing import Union, Optional
import subprocess
from .option import EmulatorOptions
from .args import subprocess_args
from .opencv import get_pos_img
from .node import Node, By
import time
import os
import base64
import ctypes
import re
# type
position = Union[list[int, int], tu... | |
# The MIT License (MIT)
#
# Copyright (c) 2021
#
# 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, pu... | |
"gasket",
"deviate",
"castiel",
"behaviors",
"bide",
"eckhart",
"speakerphone",
"'t--i",
"christmases",
"philharmonic",
"jittery",
"percussion",
"dominates",
"unwrap",
"clovis",
"rwanda",
"jilted",
"deterrent",
"installations",
"valkyrie",
"informers",
"haughty",
"iwo",
"briar",
"audra",
"oakle... | |
import os
from os.path import dirname, join, basename, exists
from typing import List, Tuple, Callable, Union
import itertools
import numpy as np
import pandas as pd
from tqdm import tqdm
from PIL import Image, ImageDraw
from openslide import OpenSlide
from ._functional import (
get_thumbnail,
get_downsamples,
try... | |
from pyinflect import getInflection
from helper_functions import join_punctuation
# This is the function were the FIB type for verbs is generated
def generate_fib_verb(retrieved_tuple):
fib_sentences = []
original_sentences = []
for tup in retrieved_tuple:
sentences_solution = tup[0]
tokens = tup[1]
... | |
<filename>release/stubs/System/ComponentModel/Design/Serialization.py
# encoding: utf-8
# module System.ComponentModel.Design.Serialization calls itself Serialization
# from System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
# by generator 1.145
""" NamespaceTracker represent a CLS namespace.... | |
are also stripes, they are undivided stripes.
We assume the vertical bars split the page in two portions, and not more,
and that they occur more or less in the middle of the page.
If many vertical bars have been detected, we sort them by y1 ascending and then
y2 descending and then by x.
We filter the bars: if ... | |
<reponame>SaqibMamoon/GSDT<gh_stars>1-10
import glob
import os
import os.path as osp
import random
import cv2
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn.functional as F
from torchvision.ops import nms
import motmetrics as mm
# import maskrcnn_benchmark.layers.nms as nms
# Set pri... | |
= self._listeners.get(Signals.pre_delete, {}).get(self.__class__, [])
for listener in cls_listeners:
listeners.append(
listener(
self.__class__,
self,
using_db,
)
)
await asyncio.gather(*listeners)
async def _post_delete(
self,
using_db: Optional[BaseDBAsyncClient] = None,
) -> None:
listeners = []
cls_... | |
Optional[pulumi.Input[str]]):
pulumi.set(self, "region", value)
@property
@pulumi.getter
def source(self) -> Optional[pulumi.Input[str]]:
"""
A string representing the local path of a file which will be used
as the object's content. Conflicts with `source` and `copy_from`.
"""
return pulumi.get(self, "source"... | |
<gh_stars>1-10
from typing import Union, List, Optional
from pyspark.sql.types import (
StructType,
StructField,
StringType,
ArrayType,
IntegerType,
DataType,
)
# This file is auto-generated by generate_schema so do not edit manually
# noinspection PyPep8Naming
class ImagingStudySchema:
"""
Representation of... | |
Reads the status reports from the Bits# for the specified
usually short time period t. The script will wait for this time
to lapse so not ideal for time critical applications.
If t is less than 0.01 polling will continue until at least 1
data entry has been recorded.
If you don't want to wait while this does ... | |
import numpy as np
from math import sqrt
from scipy.optimize import minimize, Bounds
from .functions import gp, link_gp
class kernel:
"""
Class that defines the GPs in the DGP hierarchy.
Args:
length (ndarray): a numpy 1d-array, whose length equals to:
1. one if the lengthscales in the kernel function are assume... | |
from unittest.mock import patch, call, ANY, Mock
from mpf.core.rgb_color import RGBColor
from mpf.devices.segment_display.text_stack_entry import TextStackEntry
from mpf.devices.segment_display.transitions import NoTransition, PushTransition, CoverTransition, UncoverTransition, \
WipeTransition, TransitionRunner, Spl... | |
test_templates/resource.py ResourceLookupSession.get_resources_template
from dlkit.abstract_osid.repository.objects import CompositionList
if self.svc_mgr.supports_composition_query():
objects = self.catalog.get_compositions()
assert isinstance(objects, CompositionList)
self.catalog.use_federated_repository_view()... | |
Csdm = unop_dict(A, lambda aij: aij*b)
return A.new(Csdm, A.shape, A.domain)
def add(A, B):
"""
Adds two :py:class:`~.SDM` matrices
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices.sdm import SDM
>>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
>>> B = SDM({0:{0: ZZ(3)}, 1:{1:Z... | |
<reponame>ecmwf/pyeccodes
import pyeccodes.accessors as _
def load(h):
def wrapped(h):
discipline = h.get_l('discipline')
parameterCategory = h.get_l('parameterCategory')
parameterNumber = h.get_l('parameterNumber')
instrumentType = h.get_l('instrumentType')
satelliteSeries = h.get_l('satelliteSeries')
scale... | |
<gh_stars>1-10
"`vision.data` manages data input pipeline - folderstransformbatch input. Includes support for classification, segmentation and bounding boxes"
from ..torch_core import *
from .image import *
from .transform import *
from ..data_block import *
from ..data_block import _df_to_fns_labels
from ..basic_data ... | |
# pylint: disable=invalid-name
# pylint: disable=too-many-instance-attributes
# pylint: disable=too-many-arguments
"""
Class for managing integrating spheres.
import iadpython.sphere
s = iadpython.sphere.Sphere(250,20)
print(s)
"""
import numpy as np
class Sphere():
"""Container class for an integrating spher... | |
dtype np.uint32
Image decoded as a 32 bit RBGA image.
"""
# Ensure it has three channels
if im.ndim != 3 or im.shape[2] !=3:
raise RuntimeError('Input image is not RGB.')
# Make sure all entries between zero and one
if (im < 0).any() or (im > 1).any():
raise RuntimeError('All pixel values must be between 0 and... | |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
TODO:
- Speed tests, need to be certain the looping on all telescopes is not killing
performance
- Introduce new weighting schemes
- Make intersect_lines code more readable
"""
import numpy as np
import itertools
import astropy.units as u
from ctapip... | |
spawn
num_subprocesses = int(num_processes / our_num_processes)
# Similarly, the memory fraction for each process we will spawn
subprocess_mem_frac = mem_frac / our_num_processes
log.debug('flat_combine: {} num_processes = {}, mem_frac = {}, our_num_processes = {}, num_subprocesses = {}, subprocess_mem_frac = {}'.f... | |
<filename>venv/lib/python3.6/site-packages/ansible_collections/cloudscale_ch/cloud/plugins/modules/server.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2017, <NAME> <<EMAIL>>
# Copyright: (c) 2019, <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0... | |
from numpy import array
def scigrid_2011_01_06_00():
ppc = {"version": '2'}
ppc["baseMVA"] = 100.0
ppc["bus"] = array([
[586, 3, 0, 0, 0, 0, 0, 1.0, 0, 220.0, 0, 1.1, 0.9 ],
[589, 2, 0, 0, 0, 0, 0, 1.0, 0, 380.0, 0, 1.1, 0.9 ],
[590, 2, 0, 0, 0, 0, 0, 1.0, 0, 380.0, 0, 1.1,... | |
LA12_0 = self.input.LA(1)
if (LA12_0 == DIGIT) :
alt12 = 1
if alt12 == 1:
# bsdl.g:110:28: DIGIT
pass
self.match(self.input, DIGIT, self.FOLLOW_DIGIT_in_port_def927)
else:
if cnt12 >= 1:
break #loop12
eee = EarlyExitException(12, self.input)
raise eee
cnt12 += 1
self.match(self.input, TO, self.FO... | |
paths. This is calculated using
the value of ``platform``. Ex. ``local_path_mac``.
:ivar str py_version: Simple version of Python executable as a string. Eg. ``2.7``.
:ivar str ssl_version: Version of OpenSSL installed. Eg. ``OpenSSL 1.0.2g 1 Mar 2016``. This
info is only available in Python 2.7+ if the ssl module ... | |
<filename>recognition/lpr_model.py
import tensorflow as tf
from recognition.lpr_util import NUM_CHARS
def small_inception_block(x, im, om, scope='incep_block'):
#参考squeezenet的fire module,先squeeze,然后expand
with tf.variable_scope(scope):
x = conv(x,im,int(om/4),ksize=[1,1])
x = tf.nn.relu(x)
#参考inception v3
#bran... | |
# -*- coding: utf-8 -*-
"""
Feb 2018
ADAPTCAST
FORECAST PAKAGE
@author: <EMAIL>
"""
#Load utility libraries
# =============================================================================
import array
import random
#Data utilities
#import pandas as pd
import numpy as np
#To plot
# ===================... | |
path):
if self.isconst:
return self.value()
vals = []
for kid in self.kids:
vals.append(await tostr(await kid.compute(path)))
return '.'.join(vals)
class TagMatch(TagName):
'''
Like TagName, but can have asterisks
'''
def hasglob(self):
assert self.kids
return any('*' in kid.valu for kid in self.kids if i... | |
"""OpenMC transport operator
This module implements a transport operator for OpenMC so that it can be used by
depletion integrators. The implementation makes use of the Python bindings to
OpenMC's C API so that reading tally results and updating material number
densities is all done in-memory instead of through the fi... | |
are not correct")
values = [_[1] for _ in values[i1:i2]]
return self._private_getclass()(self.header, values)
def union(self, table):
"""
@param table table
@return table(with the same number of columns)
concatenates two tables by rows, they must have the same header, rows of both tables are merged into a sing... | |
<filename>wasm_bindgen/raze/crates.bzl<gh_stars>0
"""
@generated
cargo-raze crate workspace functions
DO NOT EDIT! Replaced on runs of cargo-raze
"""
load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository") # buildifier: disable=load
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive"... | |
Disks:",
"File Size", "Capacity", "Device"),
template.format("", "---------", "---------",
"--------------------")]
for file_obj in file_list:
(file_id, file_size,
disk_id, disk_cap, device_str) = self._info_strings_for_file(
file_obj)
href_str = " " + file_obj.get(self.FILE_HREF)
# Truncate to fit in availab... | |
<gh_stars>0
import pytest
import requests
import logging
import json
import copy
import random
import arrow
from faker import Faker
# ----------------------------------- vectors -----------------------------------
class TestHTTPVector:
small_size = 10000
normal_size = 100000
big_size = 50000000
def get_mode(s... | |
"""Return Oriented Programming
"""
import hashlib, os, sys, tempfile, re
from .elf import ELF
from .util import packing
from .log import getLogger
log = getLogger(__name__)
class ROP(object):
"""Class which simplifies the generation of ROP-chains.
Example:
.. code-block:: python
elf = ELF('ropasaurusrex')
ro... | |
<gh_stars>1000+
#!/usr/bin/env python
# Copyright 2021 The StackStorm 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 requir... | |
# 2021-03-23 / last updated on 2021-04-08
# This code was made for use in the Fu lab
# by <NAME>
import numpy as np
import pandas as pd
from ..InstrumentHandler import GPIBInstrument
from ..units.frequency import frequency_units_dict
from ..units.UnitClass import UnitClass
class DataGenerator2020AInstrument(GPIBIn... | |
#!/usr/bin/env python
"""API handlers for accessing hunts."""
import functools
import itertools
import logging
import operator
import re
from grr import config
from grr.gui import api_call_handler_base
from grr.gui import api_call_handler_utils
from grr.gui.api_plugins import client as api_client
from grr.gui.api_plu... | |
<filename>captum/attr/_utils/attribution.py<gh_stars>0
#!/usr/bin/env python3
import torch
import torch.nn.functional as F
from .common import (
_run_forward,
_format_input_baseline,
_format_tensor_into_tuples,
_format_additional_forward_args,
_validate_input,
_validate_target,
_tensorize_baseline,
)
from .grad... | |
'proxy': True,
'verbose_name_plural': '47 Foto ATL Perdagangan',
},
bases=('atl.fotoatl',),
),
migrations.CreateModel(
name='FotoATLPerikanan',
fields=[
],
options={
'verbose_name': '45 Foto ATL Perikanan',
'proxy': True,
'verbose_name_plural': '45 Foto ATL Perikanan',
},
bases=('atl.fotoatl',),
),
migr... | |
Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_onl... | |
<reponame>hi-artem/twistlock-py<filename>test/test_types_settings.py
# coding: utf-8
"""
Prisma Cloud Compute API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: 21.04.439
Generated by: https://openapi-ge... | |
elif event.type == MOUSEBUTTONDOWN:
# store current mouse position for mouse-steering
if event.button == 1:
self._mouse_steering_center = event.pos
elif event.type == MOUSEBUTTONUP:
if event.button == 1:
self._mouse_steering_center = None
if not self._autopilot_enabled:
prev_steer_cache = self._steer_cache
sel... | |
import copy
import json
import logging
import unittest
from collections import defaultdict
from datetime import datetime
from datetime import timedelta
from unittest import mock
import pika
import pika.exceptions
from freezegun import freeze_time
from parameterized import parameterized
from src.data_store.redis impor... | |
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.gridlayout import GridLayout
from kivy.properties import ObjectProperty
from kivy.clock import Clock
from kivy.graphics.texture import Texture
import cv2
import numpy as np
import tensorflow.keras as keras
import te... | |
<filename>apps/fund/migrations/0005_migrate_paymentlogs.py
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from bluebottle.utils.model_dispatcher import get_model_mapping
MODEL_MAP = get_model_mapping()
class Migration(DataMigration):
... | |
<filename>dataset2.py
from typing import Optional, Union, Callable, List
from collections import OrderedDict
import random
import tensorflow as tf
import numpy as np
import string
import addressnet.lookups as lookups
from addressnet.typo import generate_typo
# Schema used to decode data from the TFRecord file
_featu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.