input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
itertools.product(*y)]
# The expanded selectors must comprise the same number of identifiers:
assert len(ids_1) == len(ids_3)
p[0] = [a+b for (a, b) in zip(ids_1, ids_3)]
@classmethod
def p_selector_selector_plus_level(cls, p):
'selector : selector PLUS level'
p[0] = [x+[p[3]] for x in p[1]]
@classmethod
... | |
<reponame>watanka/CRAFTS_implementation
from config import config
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
import time, string
import re, random, itertools
from PIL import Image, ImageDraw
import scipy.io as scio
import Polygon as plg
from glob import glob
import matpl... | |
<filename>symbols/blimp.py
"""
BLIMP (Ben's Layertastic Image Manipulation Program)
"""
# Copyright (c) 2019 <NAME>. All rights reserved.
import math
import json
import os
import sys
import time
from typing import Dict, Any, Tuple
import cv2
from PIL import Image, ImageFont, ImageDraw
import numpy as np
from symb... | |
<filename>code/tf_v2/model.py
import os, json
import numpy as np
from functools import partial
import tensorflow as tf
from tensorflow.python.keras import layers, metrics, models
#from tensorflow.python.framework.ops import disable_eager_execution
#disable_eager_execution()
from utils import BatchNorm, batchnorm, Leaky... | |
import os
import random
import re
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from threading import Thread
from typing import NoReturn, Tuple
import requests
from bs4 import BeautifulSoup
from googlehomepush import GoogleHome
from googlehomepush.http_ser... | |
& ~0x3f) == 0 and ((1 << _la) & ((1 << MiniJavaParser.T__1) | (1 << MiniJavaParser.T__18) | (1 << MiniJavaParser.T__20) | (1 << MiniJavaParser.T__21) | (1 << MiniJavaParser.Identifier))) != 0):
self.state = 93
self.statement()
self.state = 98
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 99
s... | |
for multi-objective
optimization: NSGA-II", 2002.
"""
pareto_fronts = sortFastND(individuals, k)
for front in pareto_fronts:
assignCrowdingDist(front)
chosen = list(chain(*pareto_fronts[:-1]))
k = k - len(chosen)
if k > 0:
sorted_front = sorted(pareto_fronts[-1], key=attrgetter("fitness.crowding_dist"), reve... | |
"a name"}
mock_post.return_value = {}, {}
self.resource_client.create(dict_to_create, timeout=-1)
mock_post.assert_called_once_with(self.URI, dict_to_create, custom_headers=None)
@mock.patch.object(connection, 'post')
def test_create_uri_with_force(self, mock_post):
dict_to_create = {"resource_name": "a name", ... | |
<filename>8-PDEs.py
# coding: utf-8
# In[1]:
import numpy as np
get_ipython().magic('matplotlib inline')
from matplotlib import pyplot as plt
# Adapted from http://kitchingroup.cheme.cmu.edu/pycse/pycse.html#sec-10-4
#
# ## Plane Poiseuille flow - BVP solve by shooting method
#
# One approach to solving BVPs is ... | |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2015 SUSE Linux GmbH
#
# 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
#... | |
# python version of falco_gen_dm_poke_cube.m
import sys
import os
import numpy as np
import scipy
import scipy.io as sio
from falco import utils # ceil_even, ceil_odd
sys.path.append('y:/src/Falco/falco-python/falco/')
def sind(tdeg):
return np.sin((np.pi / 180.) * tdeg)
def cosd(tdeg):
return ... | |
Argument("packages", str, "", value=[]),
"services": Argument("services", str, "",
value=['tripleo_heat_engine']),
"topology": Argument("topology", str, "", value=[]),
"release": Argument("release", str, "", value=[]),
"infra_type": Argument("infra_type", str, "", value=[]),
"nodes": Argument("nodes", str, "", va... | |
<reponame>gtataranni/bcc
#!/usr/bin/python
# @lint-avoid-python-3-compatibility-imports
#
# cpuunclaimed Sample CPU run queues and calculate unclaimed idle CPU.
# For Linux, uses BCC, eBPF.
#
# This samples the length of the run queues and determine when there are idle
# CPUs, yet queued threads waiting their turn. Rep... | |
instances. The instance arguement is
used to indicate that if this is a per-instance color set, you are
interested in the name of the color set that applies to the
specified instance. When the index is not specified, the current
color set will be returned regardless of which instance it is for.
If there is no curr... | |
#!python
# ERROR.py
# An Interactive Fiction game by Christopher "avarisclari" Weigle
# IFID = 74E76D9D-C7A3-4F28-BF45-A4C00C59D9B2
import textwrap
import sys
import string
import os
sys.stdout.write("\x1b]2;ERROR\x07")
scenes = {
"title": {
"description": " ____ ____ ____ __ ____ \n"
"( __)( _ \( _ \ / \( _ \ \n... | |
<reponame>matteocarde/pyspel<filename>pyspel.py<gh_stars>0
import subprocess
import sys
import tempfile
import uuid
from dataclasses import dataclass
from dataclasses import field
import os
import json
from time import sleep
from types import FunctionType, CodeType
from typing import Any, ClassVar
__version__ = "1.0.0... | |
= f'{ct.default_int64_field_name} in []'
collection_w, vectors = self.init_collection_general(prefix, insert_data=True)[0:2]
res, _ = collection_w.query(term_expr)
assert len(res) == 0
@pytest.mark.tags(CaseLabel.L1)
def test_query_expr_inconsistent_mix_term_array(self):
"""
target: test query with term expr th... | |
model.
Returns a group_args object containing list of the map_model_manager
objects and a list of the selection objects that define which atoms
from the working model are in each object.
Normally do work on each map_model_manager to create a new model with
the same atoms, then use merge_split_maps_and_models() t... | |
<filename>tp5/PSO.py
#! /usr/bin/python3.5
# -* coding:utf-8 -*-
import neuralNet
import numpy as np
import copy
import matplotlib.pyplot as plt
import tqdm
import line_profiler
class Particule():
"""
Il s'agit de la classe particule. Elle dispose de diffรฉrents attributs:
- index -> pour identifier de maniรจre uni... | |
identical
for file_name in file_names:
full_path = pkg_resources.resource_filename(__name__, rel_path + file_name)
copy_full_path = pkg_resources.resource_filename(__name__, "./out/" + file_name)
with open(full_path, mode="rb") as source_file:
binary = source_file.read()
with open(copy_full_path, mode="rb") as f... | |
ival_ = self.gds_parse_integer(sval_, node, 'actionDayOfWeek')
ival_ = self.gds_validate_integer(ival_, node, 'actionDayOfWeek')
self.actionDayOfWeek = ival_
self.actionDayOfWeek_nsprefix_ = child_.prefix
elif nodeName_ == 'actionDate':
sval_ = child_.text
dval_ = self.gds_parse_date(sval_)
self.actionDate = dva... | |
<gh_stars>0
#!bin/python
"""
Program to extract features GROMACS-generated
MD trajectory files and save them to numpy
binary file format, to be used as the ECP CANDLE
project benchmarks.
Authors: <NAME> (<EMAIL>),
<NAME> (<EMAIL>),
<NAME> (<EMAIL>)
Date: 06/06/2017 (MM/DD/YYYY)
Copyright 2017 Lawrence Liver... | |
linear mapping with (n x n) matrix representation
A = A_mv(*A_args) gmres_m solves
Ax = b (1)
where x and b are length-n vectors, using the method of
Generalized Minimum RESiduals with M iterations per restart (GMRES_M).
Args:
A_mv: A function v0 = A_mv(v, *A_args) where v0 and v have the same shape.
A_args: A ... | |
<filename>keras2onnx/parser.py
###############################################################################
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
####################################################... | |
usegwosc = True
inputs.require_gwosc = True
# if segment list files are not provided create the lists
# now rather than relying on each job doing it
segdir = os.path.join(self.basedir, "segments")
check_directory_exists_and_if_not_mkdir(segdir)
seginfo["segmentlist"] = os.path.join(
segdir,
"segments_{0:d}-{1:... | |
( ) ) :
if ( ooO == None or ooO . is_ipv6_link_local ( ) ) :
ooO = None
else :
O00O0 . itr_rloc_count = 1 if ( oOOo == None ) else 0
O00O0 . itr_rlocs . append ( ooO )
if 9 - 9: I11i % i1IIi / ooOoO0o % iII111i - oO0o - II111iiii
if 29 - 29: ooOoO0o . II111iiii . i1IIi % oO0o
if 11 - 11: OoOoOO00 . OoO0O00 % I1... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Python framework for developing neural network emulators of RRTMGP gas optics
scheme, the RTE radiative transfer solver, or their combination RTE+RRTMGP (a
radiative transfer scheme).
This file provides functions for loading and preprocessing data so that it
may be u... | |
aside part of the training set for validation."""
train_size = len(self.train_trees)
# select validation instances so there's no DA-wise overlap
if self.validation_no_overlap:
valid_size = self.validation_size
if self.multiple_refs: # this works naturally with multi-ref systems (just multiply size)
num_refs, _ =... | |
**kwargs)
port2 = self.deserialize(fmt, res)
self.assertEquals(res.status_int, 409)
def test_requested_subnet_delete(self):
fmt = 'json'
with self.subnet() as subnet:
with self.port(subnet=subnet) as port:
ips = port['port']['fixed_ips']
self.assertEquals(len(ips), 1)
self.assertEquals(ips[0]['ip_address'], '... | |
name is updated, we need
# to update the DNS records for this network in DNS OVN NB DB table.
# (https://bugs.launchpad.net/networking-ovn/+bug/1777978)
# Eg. if the network n1's dns domain name was "test1" and if it has
# 2 bound ports - p1 and p2, we would have created the below dns
# records
# ================... | |
import datetime
import unittest
from pathlib import Path, PosixPath
from tempfile import mkdtemp
from dateutil.tz import tzoffset
from .common import (
parse_paths,
relate_path_details,
)
from .common_test import _TZINFO, _PATH_DETAILS_BY_KEY_IMMEDIATE_MATCH, _SORTED_EVENTS, _JSON_LINES
from .event_store_rebuilder_... | |
f in self.files_sex if f.band != 'i'],
guid=self.guid)
@property
def files_merged(self):
def gen_merged():
for im in self.files_sex_i:
name = im.name.split('.stk.')[0]
name = f'{name}.stk.mag{Str("igrz"):u}.fits'
abspath = os.path.join(glo.DIR_INTERIM_CATALOGS, name)
cat = MergedCatalog(self, name, 'interim',... | |
2 ** 20
if megs != self.memory_size_bytes / 2 **20:
print >>sys.stderr, \
"warning: rounding up memory size of %i bytes to %i megabytes" \
% (self.memory_size_bytes, megs)
return megs
def configure_child(self, child):
# Log reads from child
child.logfile_read = multifile([self.unstructured_log_f, Logger('recv'... | |
enumerate(data_list):
times[i] = dd.io.load(d, '/meta_data/Time')
# now select which data sets to average
if tmin is None and tmax is None:
data_list = data_list
elif tmin is None:
data_list = data_list[ times < tmax ]
times = times[times<tmax]
elif tmax is None:
data_list = data_list[ times >= tmin ]
times ... | |
import numpy as np
import math
import os,sys
from moments.LD import Numerics
from moments.LD import Util
import copy
import moments
from moments.Misc import perturb_params
from moments.Misc import delayed_flush
from moments.LD.LDstats_mod import LDstats
from scipy.special import gammaln
import scipy.optimize
"""
Ad... | |
(temporary fix to allow
# custom data to be imported into CHNOSZ for energy calculations)
# TODO: remove this and have code find custom data automatically. It's a tricky problem!
if isinstance(custom_obigt, str):
if os.path.exists(custom_obigt) and os.path.isfile(custom_obigt):
pass
else:
err = ("Could not find ... | |
copula
# values[values <= 0.0] = np.finfo(np.float64).eps # Remove the warning for creating np.inf values
values = -np.log(values)
self.neg_log_likelihood_gaussian = np.nansum(values)
self.copula_fitted = True # Gaussian copula only need the covariance matrix
# Calculate AIC and BIC for 't-student' and 'Gaussian... | |
artifact that applies a Policy assignment.
Variables are only populated by the server, and will be ignored when
sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: String Id used to locate any resource on Azure.
:vartype id: str
:ivar type: Type of this resource.
... | |
"""
newbitmap = self.getEmpty()
if is_number(other):
cv.MaxS(self.getBitmap(), other.getBitmap(), newbitmap)
else:
cv.Max(self.getBitmap(), other.getBitmap(), newbitmap)
return Image(newbitmap, colorSpace=self._colorSpace)
def _clearBuffers(self, clearexcept = "_bitmap"):
for k, v in self._initialized_buffe... | |
<reponame>dirigeant/psono-server<gh_stars>10-100
from django.conf import settings
from django.contrib.auth.hashers import check_password, make_password
from django.core.cache import cache
from django.db import connection
from typing import Optional
import os
import bcrypt
import time
from ..models import User, User_S... | |
precision
self.extensiontype_ = extensiontype_
def factory(*args_, **kwargs_):
if CurrentSubclassModule_ is not None:
subclass = getSubclassFromModule_(
CurrentSubclassModule_, BasePaymentMethod)
if subclass is not None:
return subclass(*args_, **kwargs_)
if BasePaymentMethod.subclass:
return BasePaymentMethod... | |
str - The leading whitespace.
"""
return WrapFixer._WHITESPACE_REGEX.match(str_, start).group()
def _end_point_excluding_whitespace(self, str_, region):
"""Return the latest point in "region" that is a whitespace character.
Return the point of (or rather, immediately before) the latest
character in "region" tha... | |
toolkit_precedence=[AmberToolsToolkitWrapper, RDKitToolkitWrapper]
)
molecule = toolkit_registry.call("from_smiles", smiles)
molecule.assign_fractional_bond_orders(
toolkit_registry=toolkit_registry, bond_order_model=bond_order_model
)
# TODO: Add test for equivalent Wiberg orders for equivalent bonds
# Sanity... | |
import os
import glob
import time
import functools
import contextlib
import numpy as np
import tensorflow as tf
from timeit import default_timer as timer
import horovod.tensorflow.keras as hvd_keras
from .apps import TFLSTM, TFConvLSTM, TFOptimizedSGPU, TFOptimizedEncoder, TFOptimizedModelTrainer
from .apps.timeserie... | |
<reponame>jasonnIguazio/mlrun
import json
import os
import pathlib
import random
import string
import tempfile
import uuid
from datetime import datetime, timedelta, timezone
from time import sleep
import fsspec
import numpy as np
import pandas as pd
import pyarrow.parquet as pq
import pytest
from pandas.util.testing i... | |
#!/usr/bin/env python3
#
# Run these tests with: nosetests -v -d <file>.py
# This will run all functions even if one throws an assertion.
#
# For debugging: ./<file>.py
# Easier to print statements.
# This will exit qfter the first assertion.
import torch
from torch.autograd import Variable
import numpy as np
import ... | |
total field anomaly data, works best if the data is
reduced to the pole.
It's useful to plot the zero contour line of the tilt to represent possible
outlines of the source bodies. Use matplotlib's ``pyplot.contour`` or
``pyplot.tricontour`` for this.
.. note::
Requires gridded data if ``xderiv``, ``yderiv`` an... | |
import time
import copy
import warnings
import itertools
import numpy as np
import pandas as pd
from tqdm import tqdm
from boruta import BorutaPy
from shap import TreeExplainer
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestClassif... | |
<filename>smutLayer/powerVM.py
# Power functions for Systems Management Ultra Thin Layer
#
# Copyright 2017 IBM 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... | |
yield self.env.process(self.next_level_cache.write(addr, data, line_write=line_write))
def invalidate_cache(self):
""" Invalidate the cache"""
self.tag = [None for _ in range(self.num_cache_lines)] if(self.associativity==math.inf) else [[None for _ in range(self.associativity)] for _ in range(self.num_cache_lines)]... | |
<filename>python/tf_cnn_benchmarks/benchmark_cnn_distributed_test.py
# 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://w... | |
"""
This method is called once the `Task` has reached status S_OK.
Subclasses should provide their own implementation
Returns:
Dictionary that must contain at least the following entries:
returncode:
0 on success.
message:
a string that should provide a human-readable description of what has been performed.... | |
import sys
from pathlib import Path
sys.path.append(str(Path().absolute().parent.parent / "pylode"))
from pylode.ontdoc import OntDoc
from pylode import __version__
from rdflib import Graph
import pytest
import re
from pylode.utils import de_space_html
# scope="session" so that this is reused
# without regeneration i... | |
# -*- coding: utf-8 -*-
"""
pretty
~~
Python advanced pretty printer. This pretty printer is intended to
replace the old `pprint` python module which does not allow developers
to provide their own pretty print callbacks.
This module is based on ruby's `prettyprint.rb` library by `<NAME>`.
Example Usage
====... | |
# coding: utf-8
#
# Copyright 2014 The Oppia 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 b... | |
ATTRIBUTE, 'str' , None, None,
[], [],
''' Configure threshold of infinity for switching to
SPT on last-hop
''',
'spt_threshold_infinity',
'Cisco-IOS-XR-ipv4-pim-cfg', False),
_MetaInfoClassMember('ssm', REFERENCE_CLASS, 'Ssm' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ipv4_pim_cfg', 'Pim.DefaultContext.Ipv6.Ssm'... | |
# Copyright (c) 2009, 2010, 2011, 2012 Nicira, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | |
_getter_ : t.value = property ( _getter_ , _setter_ , None , doc1 )
doce1 = """The current error, associated with the variable,
>>> var = ...
Get error:
=========
>>> print (var.error) ## getter
"""
doce2 = """The current error, associated with the variable,
>>> var = ...
Get error:
=========
... | |
self._funcs = {}
else:
self._funcs = copy.copy(userfns)
self.indepvar = indepvar
self.indepvarname = self.indepvar[0]
self.eventmaps = {}
if reuseTerms is None:
self.reuseTerms = {}
else:
self.reuseTerms = copy.copy(reuseTerms)
if inputs is None:
self.inputs = {}
else:
self.inputs = copy.copy(inputs)
if p... | |
of artifacts' GAVs which we want to exclude along with their subgraphs
:param preset: preset used while creating the urlmap
:param mutator: mutator used for dependency graph mutation
:param patcherIds: list of patcher ID strings for Cartographer
:param injectedBOMs: list of injected BOMs used with dependency manage... | |
+ sep_length + ob_leg_length)
sep_frac = sep_length / (ib_leg_length + sep_length + ob_leg_length)
ob_frac = ob_leg_length / (ib_leg_length + sep_length + ob_leg_length)
xi_ib_div = np.linspace(0,
ib_frac + sep_frac * self.ib_trim_off,
self.xi_ib_pts,
endpoint=False)
xi_sep = np.linspace(ib_frac + sep_frac * s... | |
import os
import logging
import traceback
from collections import namedtuple
from funcy.objects import cached_property
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import QApplication
from PyQt5 import uic
from PyQt5.QtCore import QDir
from hexview import HexViewWidget
from vstructui im... | |
<reponame>robostok/opengpv
# Green Pass Parser
# Copyright (C) 2021 <NAME> -- <<EMAIL>>
# Modified by <NAME> -- <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of th... | |
a.shape[-1]
value = unfold_tensor(value, dim=2, window_sz=window_sz).transpose(-1, -2) # [B, H, T, W, d_value]
updated_values = torch.matmul(a, value) # [B, H, T, 1, d_value]
if rpr_value is not None:
rpr_value = rpr_value.unsqueeze(0).unsqueeze(0).unsqueeze(0) # [1, 1, 1, W, d_value]
update_rpr_values = torch.mat... | |
= Var(within=Binary,bounds=(0,1),initialize=0)
m.b597 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b598 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b599 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b600 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b601 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b... | |
import demistomock as demisto
from CommonServerPython import *
import ast
# disable insecure warnings
requests.packages.urllib3.disable_warnings()
""" GLOBAL VARS """
APP_NAME = "ms-azure-sc"
SUB_ID_REQUIRING_CMD = (
"azure-sc-get-alert",
"azure-sc-list-alert",
"azure-sc-update-alert",
"azure-sc-list-location",
... | |
to use in place of the term total.
CREDIT_NOTE_NUMBER: The value to use in place of the term credit
note number.
INVOICE_DATE: The value to use in place of the term issue
date.
ITEM: The value to use in place of the term item.
AMOUNT: The value to use in place of the term amount.
CREDITNOTE: The value to use in ... | |
#! /usr/bin/env python
"""
This module provides classes for querying Google Scholar and parsing
returned results. It currently *only* processes the first results
page. It is not a recursive crawler.
"""
# ChangeLog
# ---------
#
# 2.11 The Scholar site seems to have become more picky about the
# number of results reque... | |
import re, inspect, os.path
from difflib import SequenceMatcher
try:
import colorama
colorama.init()
WARNING = colorama.Fore.LIGHTYELLOW_EX
ERROR = colorama.Fore.LIGHTRED_EX
def cprint(color, *args, **kwargs):
print(end=(color))
print(*args, **kwargs)
print(end=(colorama.Fore.RESET + colorama.Back.RESET))
exc... | |
130034000000000000000),
("0x91050a5cffadedb4bb6eaafbc9e5013428e96c80", 1700000000000000000000),
("0x24586ec5451735eeaaeb470dc8736aae752f82e5", 17600000000000000000),
("0x51039377eed0c573f986c5e8a95fb99a59e9330f", 1970000000000000000000),
("0xfbb161fe875f09290a4b262bc60110848f0d2226", 2000000000000000000000),
("0xe... | |
<filename>qelos/scripts/lm/rnnlm_distill.py
import torch
import qelos as q
import os
import numpy as np
import math
from functools import partial
def load_data(p="../../../datasets/wikitext2/",
batsize=100, eval_batsize=10, seqlen=35):
class Dictionary(object):
def __init__(self):
self.word2idx = {}
self.idx2wo... | |
not in enums.SearchType:
raise ValueError('Variable search_type ({}) is not one of the values: {}'.format(search_type, ', '.join(map(str, enums.SearchType))))
if filter_variable is not None and filter_variable not in enums.FilterVariable:
raise ValueError('Variable filter_variable ({}) is not one of the values: {}'... | |
from __future__ import division
from __future__ import absolute_import
import numpy as np
import pandas as pd
import scipy as sp
from rankit.Table import Table
from scipy.sparse import coo_matrix
from scipy.sparse.linalg import lsqr
from .matrix_build import fast_colley_build
from numpy.linalg import norm
class Unsupe... | |
import pytest
import json
import keras
import keras.backend as K
import numpy as np
import os
def test_dense_legacy_interface():
old_layer = keras.layers.Dense(input_dim=3, output_dim=2, name='d')
new_layer = keras.layers.Dense(2, input_shape=(3,), name='d')
assert json.dumps(old_layer.get_config()) == json.dumps(... | |
import os
from collections import OrderedDict
from concurrent.futures import ThreadPoolExecutor
from io import BytesIO
from logging import getLogger as get_logger
from math import ceil
from statistics import mean
from typing import Optional
from megfile.errors import S3FileChangedError, patch_method, raise_s3_error, s... | |
<filename>mindspore/python/mindspore/ops/_op_impl/_custom_op/batch_matmul_impl.py<gh_stars>1000+
# 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
... | |
<reponame>AzharRISC-V/pulp-dronet
#-------------------------------------------------------------------------------#
# Copyright (C) 2020-2021 ETH Zurich, Switzerland, University of Bologna, Italy.#
# All rights reserved. #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this fi... | |
def mode(self, x_start, u_start):
"""
Returns the mode of x_start, u_start, namely
self.P[mode] * (x_start, u_start) <= self.q[mode].
If x_start, u_start is on the boundary of the neighbouring modes,
return the mode with the smaller index.
@param x_start The state.
@param u_start The control
@return mode If (x_... | |
# -*- coding: utf-8 -*-
"""Tests for PlateRecording subclass.
To create a file to look at: python3 -c "import os; from curibio.sdk import PlateRecording; PlateRecording([os.path.join('tests','h5','v0.3.1','MA20123456__2020_08_17_145752__A1.h5')]).write_xlsx('.',file_name='temp.xlsx')"
To create a file to look at: pyth... | |
<reponame>kucars/kuri_mbzirc_challenge_3<filename>kuri_task_allocation/scripts/task_allocator.py
#!/usr/bin/env python
import pylab
from mpl_toolkits.mplot3d import Axes3D
import math
import actionlib
import rospy
from std_msgs.msg import String
import random
import numpy
import yaml
import matplotlib.pyplot as plt
i... | |
"""
logger.debug("SYS 0x{:03X}".format(self.current_instruction.nnn))
# just ignore for now
pass
def one(self):
"""
1nnn - JP addr
Jump to location nnn.
The interpreter sets the program counter to nnn.
"""
logger.debug("JP 0x{:03X}".format(self.current_instruction.nnn))
self.program_counter = self.current_i... | |
plotting information as properties.
"""
import networkx as nx
if variables is not None:
if isinstance(variables, LazyArray):
variables = (variables,)
variables = set(variables)
def is_variable(node):
return node in variables
else:
def is_variable(_):
return False
def extract_props(node, **kwargs):
v =... | |
<reponame>octurion/ecoop-artifact<filename>op2orig/translator/c/python/op2_gen_openmp_simple.py
##########################################################################
#
# OpenMP code generator
#
# This routine is called by op2 which parses the input files
#
# It produces a file xxx_kernel.cpp for each kernel,
# plu... | |
error.
:param node: node name
:type node: str
:param fullDeviceName: fully qualified device name
:type fullDeviceName: str
:param device: device
:type device: :class:`~c4.system.configuration.DeviceInfo`
:returns: device info with database ids
:rtype: :class:`~c4.system.configuration.DeviceInfo`
"""
nodeInf... | |
await common.async_set_hvac_mode(hass, HVAC_MODE_OFF)
await common.async_set_temperature(hass, 25)
_setup_sensor(hass, 30)
await hass.async_block_till_done()
calls = _setup_switch(hass, False)
await common.async_set_hvac_mode(hass, HVAC_MODE_COOL)
assert 1 == len(calls)
call = calls[0]
assert HASS_DOMAIN == cal... | |
<reponame>karelvaculik/pyreball<gh_stars>1-10
import os
import re
from pathlib import Path
from unittest import mock
import xml.etree.ElementTree as ET
import altair as alt
from bokeh.plotting import figure as bokeh_figure
from matplotlib import pyplot as plt
import pandas as pd
import plotly.express as px
import pyte... | |
timeouts.
:return: Returns the result object.
If the method is called asynchronously,
returns the request thread.
:rtype: FlowLog
"""
kwargs['_return_http_data_only'] = True
return self.datacenters_natgateways_flowlogs_patch_with_http_info(datacenter_id, nat_gateway_id, flow_log_id, nat_gateway_flow_log_properti... | |
# encoding: utf-8
"""This module contains :class:`Terminal`, the primary API entry point."""
# pylint: disable=too-many-lines
# Too many lines in module (1027/1000)
import codecs
import collections
import contextlib
import curses
import functools
import io
import locale
import os
import select
import struct
import sys
... | |
"{0}({1}, {2}, {3}, {4}, {5}, {6}, {7})".format(
type(self).__name__,
self._location,
self._begin_location,
self._begin_num_bytes,
self._data_location,
self._data_num_bytes,
self._parent_location,
repr(self._uuid),
)
@property
def begin_location(self):
return self._begin_location
@begin_location.setter
... | |
import torch
import numpy as np
import argparse
import time
import util
import os
import matplotlib.pyplot as plt
import torch.nn as nn
import pandas as pd
from fastprogress import progress_bar
import torch.nn.functional as F
from model_stgat import stgat
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
os.environ["CUDA_V... | |
<filename>emat_verspm.py<gh_stars>1-10
import os
import numpy as np
import pandas as pd
import logging
import tempfile
import re
import shutil
import platform
import subprocess
import json
from distutils.dir_util import copy_tree
from emat import Scope, SQLiteDB
from emat.model.core_files import FilesCoreModel
from e... | |
#
# epydoc.css: default epydoc CSS stylesheets
# <NAME>
#
# Created [01/30/01 05:18 PM]
# $Id: html_css.py 1194 2006-04-09 18:11:11Z edloper $
#
"""
Predefined CSS stylesheets for the HTML outputter (L{epydoc.docwriter.html}).
@type STYLESHEETS: C{dictionary} from C{string} to C{(string, string)}
@var STYLESHEETS: A ... | |
get_opts(self):
"""Get options set for this runner, as a dict."""
log.warning('get_opts() is deprecated and will be removed in v0.7.0')
return copy.deepcopy(self._opts)
def get_job_key(self):
"""Get the unique key for the job run by this runner.
This has the format ``label.owner.date.time.microseconds``
"""
re... | |
<filename>tensorflow_probability/python/distributions/power_spherical.py
# Copyright 2020 The TensorFlow Probability 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.ap... | |
it should re-send the PARAM_SET message.
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
param_id : Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have... | |
for duels
async def statusduels(ctx): await serverstatus(ctx, "duels", "192.168.100.70:25573")
@client.command(aliases=['bedwars', 'bedwar', 'bw']) # Status cmd for bedwars
async def statusbedwars(ctx): await serverstatus(ctx, "bedwars", "192.168.100.70:25571")
@client.command(aliases=['lobby', 'hub']) # Status cmd f... | |
###############################
# #
# Global variables for BOSS #
# #
###############################
from collections import OrderedDict
import os
import modules.active_cfg as active_cfg
exec("import configs." + active_cfg.module_name + " as cfg")
# ~~~~~ BOSS global variables and containers ~~~~~
gambit_backend... | |
<reponame>hsokooti/RegNet
import copy
import logging
import matplotlib.pyplot as plt
import numpy as np
import os
import dill
from scipy.stats import wilcoxon
import SimpleITK as sitk
import time
import xlsxwriter
import functions.setting.setting_utils as su
from .image import landmark_info
def calculate_write_landma... | |
to 1e-4:
d_accp[d_accp == 0] = 1e-4
d_accn[d_accn == 0] = 1e-4
twi_names = [
'betax', 'alphax', 'etax', 'etapx',
'betay', 'alphay', 'etay', 'etapy']
edteng_names = [
'beta1', 'alpha1', 'eta1', 'etap1',
'beta2', 'alpha2', 'eta2', 'etap2']
names = twi_names if \
self.type_optics == self.OPTICS.Twiss else edten... | |
bar = tqdm(enumerate(dataloader), total=len(dataloader))
for step, data in bar:
ids = data['ids'].to(device, dtype = torch.long)
mask = data['mask'].to(device, dtype = torch.long)
targets = data['target'].to(device, dtype=torch.long)
batch_size = ids.size(0)
outputs = model(ids, mask)
loss = criterion(outp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.