input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
"""Validate the full schema (property, source and referenced)."""
from ..... import exceptions
from ..... import types as oa_types
from .....helpers import foreign_key as foreign_key_helper
from .....helpers import peek
from .....helpers import relationship
from ....helpers import backref as backref_helper
from ....he... | |
"""Tests for accounts.views."""
# pylint: disable=no-value-for-parameter,maybe-no-member,invalid-name
from datetime import datetime
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied
from django.core.ur... | |
<reponame>PRECISE/SMEDL
# Copyright (c) 2021 The Trustees of the University of Pennsylvania
#
# 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... | |
<reponame>sdnit-se/intersight-python
# coding: utf-8
"""
Cisco Intersight OpenAPI specification.
The Cisco Intersight OpenAPI specification.
OpenAPI spec version: 1.0.9-1461
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
c... | |
Concatenate(funcs, self.axis)
def evalf(self, *arrays):
shape = list(builtins.max(arrays, key=len).shape)
shape[self.axis+1] = builtins.sum(array.shape[self.axis+1] for array in arrays)
retval = numpy.empty(shape, dtype=self.dtype)
n0 = 0
for array in arrays:
n1 = n0 + array.shape[self.axis+1]
retval[(slice(No... | |
description = "No categories found."
embed = discord.Embed(
title=f"{ctx.guild.name} whitelisted channels",
description= description
)
await ctx.send(embed=embed)
else:
embed=discord.Embed(
description="Command not found. Try using `add` to add channels and `remove` to remove channels.",
color=0xd80000,
)... | |
* this.scaleOffsetY;
/** @type {number} */
var i = 0;
var l = this.canvases.length;
for (;i < l;i++) {
this.canvases[i].translate(x, y, z);
}
},
/**
* @param {number} x
* @param {number} y
* @param {boolean} dataAndEvents
* @return {undefined}
*/
scale : function(x, y, dataAndEvents) {
/** @type {number}... | |
the
former case.
Parameters
----------
item :
The item to search for links with.
category :
The category to search in.
Return
------
labels : tuple
The item labels in `category` that `item` can still link to.
"""
pos1, cat1 = self.item_to_pos(item)
cat2 = self.categories.index(category)
links = self.li... | |
points with stc.plot."""
sample_src = read_source_spaces(src_fname)
kwargs = dict(subjects_dir=subjects_dir, smoothing_steps=1)
vertices = [s['vertno'] for s in sample_src]
n_time = 5
n_verts = sum(len(v) for v in vertices)
stc_data = np.random.RandomState(0).rand((n_verts * n_time))
stc_data.shape = (n_verts, ... | |
# vim: set encoding=utf-8
# Copyright (c) 2016 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | |
<gh_stars>0
# -*- coding: utf-8 -*-
import numpy as np
import pylab as pb
import os
import math
class MCMetropolis(object):
"""A class to calculate the SHO velocity autocorrelation function using MC"""
# creates an instance of a Metropolis MC sampler class
def __init__(self, name, config):
np.random.seed() # giv... | |
3.82;
# to work around this issue a smart way to proceed is just putting the ? wildcard instead of spaces:
list_of_files.append(fullpath.replace(' ', '?'))
list_of_files = sorted(list_of_files)
text = rpm_file + ": \\\n\t" + " \\\n\t".join(list_of_files) + "\n"
# According to the GNU make User’s Manual sectio... | |
-> None:
primitive_step = self._get_primitive_step(primitive_step_id)
primitive_step.hyperparams = hyperparams
primitive_step.pipeline_hyperparams = set(pipeline_hyperparams.keys())
def set_primitive_step_random_seed(self, primitive_step_id: int, random_seed: int) -> None:
primitive_step = self._get_primitive_ste... | |
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incor... | |
<filename>torchuq/transform/conformal.py
import pandas as pd
import numpy as np
import itertools, math
from matplotlib import pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim import lr_scheduler
import numpy as np
from functools import partial... | |
# -*- coding: utf-8 -*-
# parser.py
"""Parses command-line options"""
from __future__ import print_function
import argparse
import os
import re
import sys
from copy import deepcopy
from .print_tools import print_date
from ..notes import RESOURCE_LIST
__author__ = '<NAME>, PhD'
__email__ = '<EMAIL>, <EMAIL>'
__date__... | |
import logging
import math
import time
from datetime import date, datetime, timedelta
import numpy as np
import pandas as pd
from analysis.models import StockHistoryDaily, StockStrategyTestLog, StockIndexHistory
from analysis.stock_hist import download_hist_data
from analysis.utils import (generate_task, get_analysis_... | |
"""
a list of static routes. A `cidr` and a `gateway` must
be provided. The `gateway` must be reachable via the bridge interface.
"""
return pulumi.get(self, "routes")
@routes.setter
def routes(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['NetworkRouteArgs']]]]):
pulumi.set(self, "routes", value)
... | |
ib_contract.exchange = symbol_fields[2]
elif symbol_fields[1] == 'CASH':
ib_contract.symbol = symbol_fields[0][0:3] # EUR
ib_contract.secType = symbol_fields[1] # CASH
ib_contract.currency = symbol_fields[0][3:] # GBP
ib_contract.exchange = symbol_fields[2] # IDEALPRO
elif symbol_fields[1] == 'FUT':
ib_contract.... | |
<reponame>hyker/codechecker<filename>tools/report-converter/codechecker_report_converter/report/output/html/html.py
# -------------------------------------------------------------------------
#
# Part of the CodeChecker project, under the Apache License v2.0 with
# LLVM Exceptions. See LICENSE for license information.
... | |
= [f]
else:
for subc in corpus:
to_iterate_over[(subc.name, subc.path)] = subc.files
elif corpus[0].level == 'f':
for f in corpus:
to_iterate_over[(f.name, f.path)] = [f]
elif corpus.singlefile:
to_iterate_over = {(corpus.name, corpus.path): [corpus]}
elif not hasattr(corpus, 'subcorpora') or not corpus.subcor... | |
#!/usr/bin/env python3
# predmet: PDS 2018/2019
# projekt: Hybridní chatovací P2P síť
# autor: <NAME> (xsuhaj02)
import socket
import sys
import threading
import os
import json
import time
import errno
import signal
import arg_parser
from my_bencode import *
BUFFSIZE = 65536
node_socket = None
# pre ulozenie a... | |
already_processed.add('_subtype')
if value in ('true', '1'):
self._subtype = True
elif value in ('false', '0'):
self._subtype = False
else:
raise_parse_error(node, 'Bad boolean attribute')
value = find_attr_value_('DataFormat', node)
if value is not None and 'DataFormat' not in already_processed:
alre... | |
dtype = int)
grid.cols_for_split_pillars_cl = np.array((1, 3, 4), dtype = int)
grid.write_hdf5()
grid.create_xml(title = 'G13 lower layer half thickness; throw 0.75 except for -0.25 on one wing')
grid_fcs, grid_fa = rqtr.fault_connection_set(grid)
assert grid_fcs is not None
assert grid_fa is not None
# show_... | |
> first_destroy_idx:
# this device is preexisting
start = first_destroy_idx + 1
stop_action = creates[-1]
if start is None:
continue
# remove all actions on this from after the first destroy up
# to the last create
prune_actions = self.findActions(devid=a.device.id)
for rem in prune_actions:
if rem == stop_... | |
\dot{z} = \frac{d}{dt} z = A z +
\begin{pmatrix} 0 \\ \frac{1}{\tau_w} \delta_L \end{pmatrix}
where A takes different forms depending on the selected dynamics.
The four possible A are returned:
* :math:`\tilde{A}_I = \begin{pmatrix} \frac{-1}{\tau_v} (I - \hat{J}) & \frac{1}{\tau_v} \bar{Q} \\
\frac{-1}{\... | |
# Copyright (c) 2020 Cisco and/or its affiliates.
# 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... | |
<gh_stars>0
# Copyright (C) 2021 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd 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 the License, or
# (at your option) any later versi... | |
#coding:utf-8
'''
图像几何变换
Copyright (C) 2018 <NAME>
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... | |
+= 1
self._global_build_failure_count += 1
logger.warning('BUILD FAILURE: %s' % uid)
if not keep_variant:
try:
logger.info('removing %s...' % dest_dir)
shutil.rmtree(dest_dir)
except Exception as e:
logger.warning('%s' % e)
return DD.UNRESOLVED
# test application
logger.info('testing %s...' % uid)
res... | |
plt.savefig(gdat.pathimag + 'diffionrdiffenph.pdf')
plt.close()
liststrg = ['ionrbolt.csv', 'ionrbeck.csv', 'ionrfauc.csv']
listlabl = ['Bolton & Haehnelt (2007)', 'Becker et al. (2007)', 'Faucher-Giguere (2008)']
listmrkr = ['o', 'D', 'x']
figr, axisrows = plt.subplots(1, gdat.numbmpol, sharey='all', figsize... | |
tf.float32)
varm_init = 0.8*tf.ones([self.n_tasks,self.n_latent], dtype = tf.float32)
loc_init = tf.zeros(self.n_tasks)
varc_init = 1.0
else:
beta_init, varm_init, loc_init, varc_init = initial_state
beta_cur = tf.Variable(beta_init, name = 'beta_cur', trainable = False)
varm_cur = tf.Variable(varm_init, name =... | |
('u2u64', b), 32)), 'options->lower_pack_64_2x32_split'),
(('pack_32_2x16_split', a, b), ('ior', ('u2u32', a), ('ishl', ('u2u32', b), 16)), 'options->lower_pack_32_2x16_split'),
(('unpack_64_2x32_split_x', a), ('u2u32', a), 'options->lower_unpack_64_2x32_split'),
(('unpack_64_2x32_split_y', a), ('u2u32', ('ushr', a,... | |
# This file is autogenerated by `applaudgen` from `app_store_connect_api.json`.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
from enum import Enum
class StringEnum(str, Enum):
"""
Making Enums (as always, arguably) more Pythonic:
https://www.cosmicpython.com/blog/2020-10-27-i-hate-enums.html
"""
def... | |
wait["Bot"] == True:
gid = cl.getGroup(to)
cl.sendMessage(to, "[ID Group : ]\n" + gid.id)
elif text.lower() == 'grouppicture':
if msg._from in admin:
if wait["Bot"] == True:
group = cl.getGroup(to)
path = "http://dl.profile.line-cdn.net/" + group.pictureStatus
cl.sendImageWithURL(to, path)
elif text.lower() ==... | |
<filename>pycode/tinyflow/VGG16_test_leo.py
import os
GPU = 0
os.environ['CUDA_VISIBLE_DEVICES'] = f'{GPU}'
import sys
sys.path.append('../../')
from pycode.tinyflow import autodiff as ad, autodiff
from pycode.tinyflow.get_result import get_result
from util import *
from line_profiler import LineProfiler
class VGG1... | |
<gh_stars>1-10
"""
A ctags wrapper, parser and sorter.
"""
import codecs
import re
import os
import sys
import subprocess
import bisect
import mmap
if sys.version_info < (2, 7):
from helpers.check_output import check_output
else:
from subprocess import check_output
#
# Contants
#
TAGS_RE = re.compile(
r'(?P<symb... | |
from __future__ import print_function
import functools
import tensorflow as tf
import numpy as np
import math
import numbers
def stddev(init_scale, feature_size):
return np.sqrt(init_scale/feature_size)
def weight_bias(W_shape, b_shape, bias_init=0.1):
W = tf.Variable(tf.random.truncated_normal(W_shape, stddev=0.... | |
# -*- coding: utf-8 -*-
"""
This module
"""
import attr
import typing
from ..core.model import (
Property, Resource, Tag, GetAtt, TypeHint, TypeCheck,
)
from ..core.constant import AttrMeta
#--- Property declaration ---
@attr.s
class PropIntegrationScheduledTriggerProperties(Property):
"""
AWS Object Type = "AW... | |
from django.shortcuts import render,redirect
from django.http import HttpResponse
from model.community import *
from model.oss import *
from view.common import *
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from django.db.models import Sum, Count
from operator import itemgetter
from django.htt... | |
the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
# Construct URL
u... | |
g_conv_temp = g_conv_temp * g_feii_rel_int
# Sum templates along rows
g_template = np.sum(g_conv_temp, axis=1)
g_template[(lam_gal <4472) & (lam_gal >5147)] = 0
# Z template
# Perform the convolution
z_conv_temp = convolve_gauss_hermite(z_feii_fft, npad, float(velscale),\
[opt_feii_voff, opt_feii_fwhm/2.3548], ... | |
# shape=(nlst,ndays,ntriads,nlags=1)
if nsamples_coh > 1:
awts_shape = tuple(NP.ones(cpds[smplng]['whole']['dspec']['mean'].ndim, dtype=NP.int))
awts = NP.ones(awts_shape, dtype=NP.complex)
awts_shape = NP.asarray(awts_shape)
for caxind,caxis in enumerate(cohax):
curr_awts_shape = NP.copy(awts_shape)
curr_awts_... | |
<reponame>TugberkArkose/MLScheduler
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate Leakage': 0.00662954,
'Peak Dyna... | |
'''
.. console - Comprehensive utility library for ANSI terminals.
.. © 2018, <NAME> - Released under the LGPL, version 3+.
Tables for known ANSI color palettes.
In order for "color palette downgrade by proximity" to work well, we need
to know what the standard 16 color palette of the platform is. Many are
reco... | |
contours
for i,cnt1 in enumerate(contour_TT):
x = i
if i != NB_TT-1:
for j,cnt2 in enumerate(contour_TT[i+1:]):
x = x+1
dist = self.find_if_close(cnt1,cnt2, self.para_r1)
if dist == True:
val = min(status_TT[i],status_TT[x])
status_TT[x] = status_TT[i] = val
else:
if status_TT[x]==status_TT[i]:
... | |
scores.append(temp_p)
else:
scores.append(0.000)
except:
if not lig_name:
scores.append(0.000)
else:
scores.append("None")
# Cscore
elif i_score in ['dC','C','avgC','medC']:
try:
if dist == 'dice':
temp_scores = DataStructs.BulkDiceSimilarity(c_fps[c],x)
elif dist == 'tani':
temp_scores = DataStructs.Bulk... | |
np.zeros(len(self.rfV1))
sig = np.zeros((len(H), len(k), len(self.phases)))
pws = np.zeros((len(H), len(k), len(self.phases)))
for ih in _progressbar(range(len(H)), 'Computing: ', 15):
for ik, kk in enumerate(k):
for ip, ph in enumerate(self.phases):
for i in range(len(self.rfV1)):
if self.rfV2 and (ph == 'pps... | |
<filename>news/tests/test_api_views.py<gh_stars>0
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
from django.test import TestCase, Client, override_settings
from django.contrib.auth.models import User, Permission, Group
from django.utils import timezone
import json
from da... | |
not wait for responses here.
send_all_status_requests()
#Test whether there is a command or status response ready to read,
# timeout in 5 seconds.
readable_list = get_ercs()
readable_list.append(u.get_tsd().socket)
try:
#readable, unused, unused = select.select(
# [erc.sock, u.get_tsd().socket], [], [], SELECT... | |
initiate_rpool(wf, config, session)
config.pipeline_setup[
'pipeline_name'] = f'longitudinal_{orig_pipe_name}'
rpool = ingress_output_dir(config, rpool, long_id,
creds_path=input_creds_path)
select_node_name = f'select_{unique_id}'
select_sess = pe.Node(Function(input_names=['session',
'output_brains',
'warps... | |
"brakeman",
"bramble",
"brambly",
"branch",
"branched",
"branchlike",
"brand",
"brander",
"brandish",
"brandy",
"brash",
"brashly",
"brashness",
"brass",
"brasserie",
"brassiere",
"brassily",
"brassiness",
"brassy",
"bratty",
"bratwurst",
"bravado",
"brave",
"bravely",
"braveness",
"bravery",
... | |
['int32', 'int64',
'float32', 'float64']
dims = [1, 2, 3]
ctx = self._current_context()
count = 0
shapes = [(), (17), (17, 17), (17, 17, 17)]
root_ranks = list(range(size))
for dtype, dim, root_rank in itertools.product(dtypes, dims,
root_ranks):
tensor = mx.nd.ones(shapes[dim], ctx=ctx) * rank
root_tensor =... | |
<filename>bot.py
__author__ = 'RAEON'
from session import Session
from buffer import Buffer
from cell import Cell
import random
import time
import math
class Bot(object):
def __init__(self, game):
self.game = game
# core variables
# self.running = False # no point, is there? we have is_connected(... | |
<filename>aiosonic/__init__.py
"""Main module."""
import asyncio
import random
import re
import codecs
from functools import partial
from json import dumps
from json import loads
from ssl import SSLContext
import gzip
import zlib
from io import IOBase
from os.path import basename
from urllib.parse import urlparse
fro... | |
# Copyright (c) 2019 Cisco and/or its affiliates.
# 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... | |
a batch of builds
:param [Build] builds:
:param str project: Project ID or project name
:rtype: [Build]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
content = self._serialize.body(builds, '[Build]')
response = self._send(http_method='PAT... | |
g():
yield 1
yield 2
raise StopIteration(3) # py2.7 compat.
f1 = e.map(lambda x: x, g())
assert isinstance(f1, Iterator)
start = time() # ensure that we compute eagerly
while not s.tasks:
yield gen.sleep(0.01)
assert time() < start + 5
g1 = g()
try:
while True:
f = next(f1)
n = yield f._result()
assert... | |
"""The dialog for calculating minimal cut sets"""
import io
import traceback
import scipy
from qtpy.QtCore import Qt, Slot
from qtpy.QtWidgets import (QButtonGroup, QCheckBox, QComboBox, QCompleter,
QDialog, QGroupBox, QHBoxLayout, QHeaderView,
QLabel, QLineEdit, QMessageBox, QPushButton,
QRadioButton, QTableWidge... | |
<reponame>JHU-Econ-Choice-2018/brock-mirman-etc-jacalin1<gh_stars>0
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.2'
# jupytext_version: 0.8.6
# kernelspec:
# display_name: Python 3
# language: python
... | |
- 1,
vm0_region[1] + 1,
vm0_region[2] - 1,
vm0_region[3] + 1,
)
# proportion in ocean
if xlen0 <= 0 or ylen0 <= 0:
logger.debug(f"Optimising skipped for {srf_meta['name']}. 100% Land coverage")
land0 = 100
optimise = False
else:
land0 = get_vm_land_proportion(o1, o2, o3, o4, wd=temp_dir)
logger.debug(f"Lan... | |
'result_count': result_count,
'querystring': querystring,
'qs_combined': qs_combined,
'ordering_str': ordering_str,
'p': p,
'max_pages': max_pages,
'films': films,
})
def user_comments(request, id, name_slug):
selected_user = get_object_or_404(models.KTUser, pk=id)
number_of_votes, number_of_comments, number... | |
+ w * 1j * t_values[39]))
+ (R_values[40] / (1 + w * 1j * t_values[40]))
+ (R_values[41] / (1 + w * 1j * t_values[41]))
+ (R_values[42] / (1 + w * 1j * t_values[42]))
+ (R_values[43] / (1 + w * 1j * t_values[43]))
+ (R_values[44] / (1 + w * 1j * t_values[44]))
+ (R_values[45] / (1 + w * 1j * t_values[45]))
+ (R_... | |
to test that treats integers as the latest minor within the major."""
return request.param
@pytest.fixture(params=[
(iati.resources.create_codelist_path, iati.resources.FILE_CODELIST_EXTENSION, iati.resources.PATH_CODELISTS),
(iati.resources.create_ruleset_path, iati.resources.FILE_RULESET_EXTENSION, iati.resource... | |
from sklearn.linear_model import LinearRegression
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
from required_modules.amplitude_encoding import *
from required_modules import gaussian_decoding as gd
import tqdm
def standardize_data(X):
'''
This function standardize an array, its su... | |
# File: tensor.py
# Creation: Wednesday August 19th 2020
# Author: <NAME>
# Contact: <EMAIL>
# <EMAIL>
# --------
# Copyright (c) 2020 <NAME>
"""
Defines tensors for deep learning application. A tensor is a multi-dimensional array, similar to ``numpy`` arrays.
"""
# Basic imports
import numpy as np
try:
import cupy... | |
<gh_stars>1-10
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive", "http_jar")
load("@bazel_tools//tools/build_defs/repo:jvm.bzl", "jvm_maven_import_external")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@bazelrio//:deps_utils.bzl", "cc_library_headers", "cc_library_shared", "c... | |
default=0.0)
def process(self, timestream):
"""Apply threshold to `weight` dataset.
Parameters
----------
timestream : `.core.container` with `weight` attribute
Returns
-------
timestream : same as input timestream
The input container with modified weights.
"""
timestream.redistribute(["prod", "stack"])
... | |
# -*- coding: utf-8 -*-
"""
RPC
~~~
:author: <NAME> <<EMAIL>>
:copyright: (c) <NAME>, 2014
:license: This software makes use of the MIT Open Source License.
A copy of this license is included as ``LICENSE.md`` in
the root of the project.
"""
# stdlib
import abc
import copy
# canteen
from canteen import cor... | |
<gh_stars>0
# -*- coding: utf-8 -*-
"""Control the execution of several Processors. In some cases it is necessary
to run several Processors in a loop. When there is a large number of tiles and
a few subsets of these tiles need to be processed with different settings,
you might want to maximize the resource use of the ... | |
('alcohol', FloatTensorType(shape=[None, 1])),
('quality', FloatTensorType(shape=[None, 1])),
('color', StringTensorType(shape=[None, 1]))
]
pipe.fit(X_train)
model_onnx = convert_sklearn(
pipe, initial_types=init_types, target_opset=TARGET_OPSET)
oinf = InferenceSession(model_onnx.SerializeToString())
pred =... | |
# -*- coding: utf-8 -*-
#
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# Using this computer program means that you agree to the terms
# in the LICENSE file included with this software distribution.
# Any use not explicitly grant... | |
"""
Python script for compute lower and upper bounds for the
mnll and jsd metrics
License:
MIT License
Copyright (c) 2020 Kundaje Lab
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 ... | |
<filename>tests/test_document.py
# coding: utf-8
import unittest
import json
import os
from xylose.scielodocument import Article, Citation, Journal, html_decode
from xylose import tools
class ToolsTests(unittest.TestCase):
def test_get_language_without_iso_format(self):
language = tools.get_language(u'xx', None)... | |
# -*- coding: utf-8 -*-
__author__ = 'Chenjun'
from gensim.models import Word2Vec
import numpy as np
import cPickle as pickle
from gensim.models.keyedvectors import KeyedVectors
from sklearn.utils import shuffle
def get_w2v_from_model(model_path,emb_path):
"""
get w2v embeddings from w2v-model.
:param model_path: ... | |
has state_dict lets get it
if hasattr(module, "state_dict") and hasattr(
local_module, "load_state_dict"
):
info("loading remote state dict")
sd_ptr = module.state_dict()
# get a blocking copy of the state_dict
info(f" Downloading remote layer: {layer_name}")
state_dict = sd_ptr.get(
request_block=request_bloc... | |
from tech import drc
import debug
import design
from math import log
from math import sqrt
import math
import contact
from pnand2 import pnand2
from pnand3 import pnand3
from pinv import pinv
from hierarchical_predecode2x4 import hierarchical_predecode2x4 as pre2x4
from hierarchical_predecode3x8 import hierarchical_... | |
<reponame>encryptogroup/RAID-PIR<gh_stars>10-100
"""
<Author>
<NAME>
(inspired from upPIR by <NAME> et al.)
(inspired from a previous version by <NAME>)
<Date>
December 2014
<Description>
Lots of helper code for RAID-PIR. Much of this code will be used multiple
places, but some many not. Anything that is at lea... | |
if made > 0:
# Open the post list
plist += '\n[color=#333333][size=small][font=Arial]The posts that were included in this count are:\n[list]\n'
# Build a list of posts that were included in this count
for row in cursor:
# Generate the post URL
url = g_PostURL.format(tid=int(row[1]), pid=int(row[0]))
# Generate t... | |
<gh_stars>1-10
#!/usr/bin/env python3
import importlib
import json
import logging
import os
import sys
import requests
import traceback
from os import listdir
from os.path import isdir
from os.path import isfile
from os.path import join
from future.backports.urllib.parse import parse_qs, urlparse
from mako.lookup im... | |
_deploy_cluster(zone):
if not xmlobject.has_element(zone, "clusters.cluster"):
return
if zone.duplication__ == None:
zone_duplication = 1
else:
zone_duplication = int(zone.duplication__)
for zone_ref in range(zone_duplication):
for cluster in xmlobject.safe_list(zone.clusters.cluster):
if cluster_... | |
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.
"""
local_var_params = locals()
all_params = [
'id'
]
all_params.extend(
[
'... | |
import numpy as np
import scipy.sparse as sparse
import scipy.sparse.linalg as linalg
from landlab import Component
# Things to add: 1. Explicit stability check.
# 2. Implicit handling of scenarios where kappa*dt exceeds critical step -
# subdivide dt automatically.
class PerronNLDiffuse(Component):
"""Nonlinear ... | |
Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api(resource_path, 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1StorageClass',
auth_settings=auth_settings,
callback=params.get('ca... | |
from collections import namedtuple
import argparse
import pdb
import traceback
import sys
import os
from qca_hex_analyzer import WmiCtrlAnalyzer, HtcCtrlAnalyzer, HttAnalyzer, AllAnalyzer
import hexfilter
description = \
"Tool used to analyze hexdumps produced by a qca wireless kernel " \
"driver (such as ath6kl, a... | |
data
self.logger.info('TextViewController: saveRig Signal received.')
self.rigs['defaultRig'] = self._componentData
@Slot()
def buildRig(self):
# If the model is not built, build it, otherwise remove it
# Send update button signal on view
error = False
for id, com in self._componentData.iteritems():
if le... | |
"squeamishness",
"squeegee",
"squeezable",
"squeeze",
"squeezer",
"squelch",
"squelchy",
"squib",
"squid",
"squiggle",
"squiggly",
"squint",
"squire",
"squirm",
"squirmy",
"squirrel",
"squirt",
"squish",
"squishy",
"stabber",
"stabbing",
"stability",
"stabilization",
"stabilize",
"stabilizer",
... | |
Document Password Verifier Derivation */
function crypto_CreatePasswordVerifier_Method1(Password) {
var Verifier = 0x0000, PasswordArray;
var PasswordDecoded = _JS2ANSI(Password);
var len = PasswordDecoded.length + 1, i, PasswordByte;
var Intermediate1, Intermediate2, Intermediate3;
PasswordArray = new_buf(len);
... | |
0x0f) << 4) | (self.theValue[0] & 0x0f)
# flags to be done in 2nd half
return v & andMask
if self.function == SoftFunction.RLD2:
# 2nd half of the RLD operation
# A[7..4] <- A[7..4], A[3..0] <- (HL)[7..4]
# translated (HL -> TMP -> ALU2, A -> ACT - > ALU1)
# (ALU.OUT)[7..4] <- (ALU1)[7..4], (ALU.OUT)[3..0] <... | |
('30',
'Still patient or expected to return for outpatient services (i.e. still a patient)'),
('31 ... 39',
'Still patient to be defined at state level, if necessary (i.e. still a patient)'),
('40', 'Expired (i.e. died) at home'),
('41',
'Expired (i.e. died) in a medical facility; e.g., hospital, SNF, ICF, or fre... | |
size and physical extent (``boxsize`` and ``boxcenter``) that ``mesh1``.
edgesin : dict, array, list
An array of :math:`k`-edges which defines the theory :math:`k`-binning; corresponding derivatives will be computed
(see ``edgesin_type``); or a dictionary of such array for each theory projection.
Else a list of de... | |
<filename>layers/spec.py
#!/usr/bin/python -i
import sys
try:
import urllib.request as urllib2
except ImportError:
import urllib2
from bs4 import BeautifulSoup
import json
import vuid_mapping
#############################
# spec.py script
#
# Overview - this script is intended to generate validation error codes and... | |
#!/usr/bin/env python
# coding=utf-8
"""
"""
from __future__ import division
import os
import pickle
import copy
import numpy as np
import matplotlib.pylab as plt
import pycity_calc.cities.scripts.energy_network_generator as enetgen
import pycity_calc.cities.scripts.energy_sys_generator as esysgen
import pycity_calc... | |
import pandas as pd
import pathlib
import numpy as np
import sys
import os
from Se_lit_based_dictionary import se_wFGD_dictionary
# For frozen code
fileDir = pathlib.Path(__file__).parents[1]
# For Original Python Code
# fileDir = pathlib.Path(__file__).parents[2]
as_dict = { # Studies for bottom ash partitioning co... | |
# -*- coding: utf-8 -*-
__author__ = 'ooo'
__date__ = '2019/1/15 12:17'
"""
只有双层耦合的 WaveResNet, 只有 SingleCouple 模块
"""
import math, torch
import torch.nn as nn
import torch.nn.functional as F
class ViewLayer(nn.Module):
def __init__(self, dim=-1):
super(ViewLayer, self).__init__()
self.dim = dim
def forward(se... | |
<filename>VCD/vc_dynamics.py
import os
import os.path as osp
import copy
import cv2
import json
import wandb
import numpy as np
import scipy
from tqdm import tqdm
from chester import logger
import torch
import torch_geometric
from softgym.utils.visualization import save_numpy_as_gif
from VCD.models import GNN
from V... | |
the values
# in column are non-numeric. This is a known bug in
# pandas: https://github.com/pydata/pandas/issues/9589
# Therefore, we need add an additional check after this.
df_excluded['raw'] = pd.to_numeric(df_excluded['raw'], errors='coerce').astype(float)
# filter out the non-numeric machine scores from the ... | |
if the sz is odd
Otherwise shifts everything by 0.5*spacing
:param sz: just the spatial dimensions, i.e., XxYxZ
:param spacing: list with spacing information [sx,sy,sz]
:param dtype: numpy data-type ('float32', 'float64', ...)
:return: returns the identity map of dimension dimxXxYxZ
"""
dim = len(sz)
if dim ==... | |
#!/usr/bin/env python3
#
# ******************************************************************
# |docname| - Create a Docker container for the Runestone webservers
# ******************************************************************
# This script provides a user-friendly install process for creating a multi-container Do... | |
81)
pos = calculate_stats(pos, oe)
oe = Shadow.OE()
oe.DUMMY = 1.0
oe.set_empty(ALPHA=0)
oe.FWRITE = 3
oe.T_IMAGE = 0.0
oe.T_SOURCE = 28.5
beam.traceOE(oe, 82)
pos = calculate_stats(pos, oe)
oe = Shadow.OE()
oe.DUMMY = 1.0
oe.set_empty(ALPHA=0)
oe.FWRITE = 3
oe.T_IMAGE = 0.0
oe.T_SOURCE = 28.5
beam.traceOE(oe, 83)
po... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.