input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
# Copyright ClusterHQ Inc. See LICENSE file for details.
"""
Persistence of cluster configuration.
"""
from base64 import b16encode
from calendar import timegm
from datetime import datetime
from json import dumps, loads
from mmh3 import hash_bytes as mmh3_hash_bytes
from uuid import UUID
from collections import Set, ... | |
eighteenByteRipe
))
return queues.apiAddressGeneratorReturnQueue.get()
def HandleCreateChan(self, params):
if len(params) == 0:
raise APIError(0, 'I need parameters.')
elif len(params) == 1:
passphrase, = params
passphrase = self._decode(passphrase, "base64")
if len(passphrase) == 0:
raise APIError(1, 'The s... | |
"""
local_var_params = locals()
all_params = [
'owner',
'offset',
'limit',
'sort',
'query',
'bookmarks',
'pins',
'mode',
'no_page'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
... | |
#
from __future__ import division
import timeit
from sklearn import preprocessing
import numpy as np
import pandas as pd
import multiprocessing
import matplotlib.pyplot as plt
from IOHMM import UnSupervisedIOHMM
from IOHMM import OLS, DiscreteMNL, CrossEntropyMNL
from IOHMM import forward_backward
from scipy.special... | |
math.square([-2., 0., 3.])
<Tensor: shape=(3,), dtype=float32, numpy=array([4., 0., 9.], dtype=float32)>
Args:
x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`,
`complex64`, `complex128`.
Returns:
A `Tensor`. Has the same type as `x`.
"""
return ... | |
any nested
``Gather`` nodes
"""
ans = self.referee
while isinstance(ans, Gather):
ans = ans.referee
assert isinstance(ans, (Decl, Call))
return ans
class WorkflowSection(WorkflowNode):
"""
Base class for workflow nodes representing scatter and conditional sections
"""
body: List[WorkflowNode]
"""
:type:... | |
<reponame>abasili98/thepdgt-bot
from flask import Flask, request, jsonify, make_response, render_template
from flask import Response
import json
import requests
from os import environ
import psycopg2
from cryptography.fernet import Fernet
app = Flask(__name__)
FERNET_KEY = environ.get('FERNET_KEY')
f = Fernet(FERN... | |
# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks_dev/rolling.ipynb (unless otherwise specified).
__all__ = ['make_generic_rolling_features', 'make_generic_resampling_and_shift_features',
'create_rolling_resampled_features', 'make_generic_rolling_features',
'make_generic_resampling_and_shift_features', 'create_r... | |
2.
Tam: The scaled time between the split and the end of ancient migration.
Ts: The scaled time between the end of ancient migration and present (in units of 2*Na generations).
Q: The proportion of the genome with a reduced effective size due to selection at linked sites
n1,n2: Size of fs to generate.
pts: Number ... | |
required, but the next branch is
# implied so we exit
wc_flag, wc_pos = None, 0
else:
wc_flag, wc_pos, wc_implicit = self._check(
keys,
branch["*"],
flags=branch["*"].get("__", flags),
i=i + 1,
explicit=explicit,
l=l,
)
# if debug:
# print("")
# print("KEYS (inner)", keys[:i], "pos", i, "flags", flags, ... | |
<gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for color conversion functions.
Authors
-------
- the rgb2hsv test was written by <NAME>, 2009
- other tests written by <NAME>, 2009
:license: modified BSD
"""
from __future__ import division
import os.path
import numpy as np
from skimage._shared.t... | |
"""pipelinerunner.py unit tests."""
import logging
import pytest
from unittest.mock import call, patch
from pypyr.cache.loadercache import pypeloader_cache
from pypyr.cache.parsercache import contextparser_cache
from pypyr.cache.pipelinecache import pipeline_cache
from pypyr.context import Context
from pypyr.errors imp... | |
from abc import ABC
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
from data import denormalize, normalize
from utils import load_data
class RelationEncoder(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(RelationEncoder, self).__init__()
se... | |
:type years: int.
:param months: The number of months to add.
:type months: int.
:param weeks: The number of weeks to add.
:type weeks: int.
:param days: The number of days to add.
:type days: int.
:param hours: The number of hours to add.
:type hours: int.
:param minutes: The number of minutes to add.
:type ... | |
0].plot(tc_tout, tc_est_profile[:, 4], 'c13', linestyle='-.', label='$TC Sim$')
p[1, 0].set_title('$v_N$')
p[1, 0].set_ylabel('$(m/s)$')
p[1, 0].legend(loc='best', prop={'size': 10})
# 3.2.b For East Velocity
p[1, 1].plot(tin, true_profile[:, 5], 'c19', label='$Orig$')
p[1, 1].hold('on')
p[1, 1].plot(lc_tout, l... | |
from __future__ import print_function
from ROOT import TStyle, kWhite, kTRUE
from ROOT import gROOT, gStyle
from ROOT import kGray, kAzure, kMagenta, kOrange, kWhite
from ROOT import kRed, kBlue, kGreen, kPink, kYellow
from ROOT import TLine, TLatex, TColor
from collections import namedtuple, OrderedDict
from math imp... | |
in NIC_WHOIS.keys():
raise ASNRegistryError(
'ASN registry %r is not known.' % ret['asn_registry']
)
ret['asn'] = temp[0].strip(' \n')
ret['asn_cidr'] = temp[2].strip(' \n')
ret['asn_country_code'] = temp[3].strip(' \n').upper()
ret['asn_date'] = temp[5].strip(' \n')
return ret
except (socket.timeout, sock... | |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.1.7
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %load_ext autoreload
# %autoreload 2
# +
import subprocess
subprocess.run('[ -f setup.py ] || (... | |
# Some entries do start with a space, but it is not *all* spaces
+ b"(?P<key>[^\x1b]*[^ \x1b][^\x1b]*)")
else:
# takes care of (1) in the function doc
selected_regex = re.compile(
# This won't work when we have multi line values in key/values
# :/
highlight_string.encode('utf-8')
+ b"\x1b\[(?P<row>[0-9]+);(?P<c... | |
<gh_stars>1-10
# Type: module
# String form: <module 'WindAlpha.analysis' from '/opt/conda/lib/python3.5/site-packages/WindAlpha/analysis.py'>
# File: /opt/conda/lib/python3.5/site-packages/WindAlpha/analysis.py
# Source:
# -*- coding: utf-8 -*-
from __future__ import division
from collections import OrderedDict
from ... | |
'''
Copyright (C) 2020-2021 <NAME> <<EMAIL>>
Released under the Apache-2.0 License.
'''
import os, sys, re
import functools
import torch as th
import collections
from tqdm import tqdm
import pylab as lab
import traceback
import math
import statistics
from scipy import stats
import numpy as np
import random
from .utils ... | |
# This is the image processing module, which I used to preprocess my images, augment my dataset, and
# organize them into a structure suitable for input to a machine learning model
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import tarfile
import tensor... | |
import unittest
import saspy
from saspy.tests.util import Utilities
class TestSASstat(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.sas = saspy.SASsession()
util = Utilities(cls.sas)
procNeeded=['reg', 'mixed', 'hpsplit', 'hplogistic', 'hpreg', 'glm', 'logistic', 'tpspline',
'hplogistic', 'hpreg', ... | |
# Copyright The IETF Trust 2013-2022, All Rights Reserved
# -*- coding: utf-8 -*-
import datetime
from django.urls import reverse
import debug # pyflakes:ignore
from ietf.utils.test_utils import TestCase
from ietf.group.factories import GroupFactory, RoleFactory
from ietf.meeting.models import Session, ResourceAss... | |
transformations)
space_groups[82] = sg
space_groups['I -4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
#
# Copyright (c) 2018 <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
# ... | |
help="Level of logging. (default error)", default="error",
choices=["error", "warn", "debug", "info"])
parser.add_argument("--class_thresholds", "-ct",
help="Class specific thresholds", default=None, nargs='+')
parser.add_argument("--output_vectors_dir", "-vd", help="Output vector path", default=OUTPUT_VECTO... | |
trajectory:
b_2=np.concatenate((b_2,bCrrnt_2),axis=0) # cm
# Total log10 of two important ratios; dimensionless :
larmR_b_2=np.concatenate((larmR_b_2,larmR_bCrrnt_2),axis=0)
uPot_enrgKin_2=np.concatenate((uPot_enrgKin_2,uPot_enrgKinCrrnt_2),axis=0)
# Total values deltaPapprch_2 (g*cm/sec):
dpxApprch_2=np.con... | |
import sys
import os
import time
from json_tricks.np import dump, load
from functools import reduce
import numpy as np
import tensorflow as tf
from sklearn.linear_model import LinearRegression
# from scipy.sparse import hstack, csr_matrix, csr
import pandas as pd
import edward as ed
from edward.models import Normal
i... | |
except KeyError:
if base_mod is not None and code not in _numeric_corrected:
return base_mod._numeric[code]
else:
raise
_toupper = {
604: 42923,
609: 42924,
613: 42893,
614: 42922,
618: 42926,
620: 42925,
647: 42929,
669: 42930,
670: 42928,
1011: 895,
1319: 1318,
1321: 1320,
1323: 1322,
1325: 1324,
1327: 1326,
430... | |
the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.rotate_server_ca),
'__call__') as call:
client.rotate_server_ca()
call.assert_called()
_, args, _ = call.mock_calls[0]
assert args[0] == cloud_sql.SqlInstancesRotateServerCaRequest()
@pytest.mark.asyncio
async def test_rotate_se... | |
<filename>rspub/core/transport.py
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
:samp:`Transport resources and sitemaps to the web server`
"""
import logging
import os
import shutil
import socket
import tempfile
import urllib.parse
from enum import Enum
from glob import glob
import paramiko
from resync import C... | |
:param VideoSeek: 视频拖拽配置。
注意:此字段可能返回 null,表示取不到有效值。
:type VideoSeek: :class:`tencentcloud.cdn.v20180606.models.VideoSeek`
"""
self.Authentication = None
self.BandwidthAlert = None
self.Cache = None
self.CacheKey = None
self.Compression = None
self.DownstreamCapping = None
self.ErrorPage = None
self.FollowRedi... | |
from __future__ import print_function
from .utils import *
from .types import *
import msgpackrpc #install as admin: pip install msgpack-rpc-python
import numpy as np #pip install numpy
import msgpack
import time
import math
import logging
class VehicleClient:
def __init__(self, ip = "", port = 41451, ... | |
from elevate import elevate
elevate()
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5 import uic
from pxpowersh import PxPowershell
import hjson
import sys
import os
from collections import OrderedDict
from random import randrange
from threading imp... | |
<filename>DeepWEST/bpti_md.py
from simtk.openmm.app import *
from simtk.openmm import *
from simtk.unit import *
from sys import stdout
from math import exp
import pandas as pd
import mdtraj as md
import pickle as pk
import numpy as np
import statistics
import itertools
import fileinput
import fnmatch
import shutil
imp... | |
<reponame>piermenti-sfracellozzi/Simple-Ds<gh_stars>1-10
# Tree:
class TreeNode:
def __init__(self, data):
self.data = data
self.children = []
self.parent = None
def add_child(self, child):
child.parent = self
self.children.append(child)
def get_level(self):
level = 0
p = self.parent
while p:
level += 1... | |
(err_q or np.quaternion(1, 0, 0, 0))
light_gl_v = tools.q_times_v(err_q.conj() * SystemModel.sc2gl_q.conj(), light_v)
# new way to discretize light, consistent with real fdb inplementation
if discretize_tol:
dlv, _ = tools.discretize_v(light_gl_v, discretize_tol, lat_range=(-math.pi/2, math.radians(90 - self.min_e... | |
hmm_group_config_path = os.path.join(self.dbCAN_HMMS_DIR, 'dbCAN-categories.txt')
HMM_fam_config_dir = os.path.join(self.dbCAN_HMMS_DIR, 'dbCAN-fams')
HMM_fam_input_dir = os.path.join(self.output_dir, 'HMMs')
with open(hmm_group_config_path, 'r', 0) as hmm_group_config_handle:
for hmm_group_config_line in hmm_grou... | |
<reponame>AlainDaccache/Quantropy
from datetime import timedelta
from matilda.fundamental_analysis.supporting_metrics import *
from matilda.fundamental_analysis.financial_statements import *
'''
Profitability ratios measure a company’s ability to generate income relative to revenue, balance sheet assets, operating cos... | |
self.loc: DistributionIF = FloatConst(loc)
elif isinstance(loc, int):
self.loc = FloatConst(float(loc))
else:
self.loc = loc
if isinstance(scale, float):
self.scale: DistributionIF = FloatConst(scale)
elif isinstance(loc, int):
self.scale = FloatConst(float(scale))
else:
self.scale = scale
return
def __re... | |
import csv
import sys
import re
from collections import OrderedDict
###################### globals ##########################
DB_DIR = "./files/"
META_FILE = "./files/metadata.txt"
AGGREGATE = ["min", "max", "sum", "avg", "count", "distinct"]
###################### functions ##########################
def make_sche... | |
'observation_id': 70,
'receiver': 'B',
'sender': 'A',
'topic': 'Web Engineering'},
{'author': 'C',
'before': [70],
'message': 'Redecentralization of the Web',
'observation_id': 71,
'receiver': 'B',
'sender': 'C',
'topic': 'Web Engineering'},
{'author': 'A',
'before': [71],
'message': 'Redecentralization of... | |
<gh_stars>0
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from .adc import _adc
from .dac import _quantize_dac
from .w2g import w2g
quantize_input = _quantize_dac.apply
quantize_weight = _quantize_dac.apply
adc = _adc.apply
from .learnable_quantize import Quantizer_train, lq_weight
... | |
"target_id": "MONDO:0004979",
"attributes": {
"p_val": 0.04742451468670237
}
},
{
"type": "associated_with",
"source_id": "rxcui:901814",
"target_id": "MONDO:0004979",
"attributes": {
"p_val": 0.04742451468670237
}
},
{
"type": "associated_with",
"source_id": "rxcui:1550957",
"target_id": "MONDO:0004979... | |
import os
from libcloud.utils.py3 import PY3
from libcloud.utils.py3 import u
from libcloud.utils.py3 import httplib
from libcloud.test import MockHttp
try:
from lxml import etree as ET
except ImportError:
from xml.etree import ElementTree as ET
class FileFixtures(object):
def __init__(self):
script_dir = os.path... | |
in the DB
and un-encode it when retrieving a value
:return: Mixed
"""
default_sentinel = object()
obj = Variable.get(key, default_var=default_sentinel,
deserialize_json=deserialize_json)
if obj is default_sentinel:
if default is not None:
Variable.set(key, default, serialize_json=deserialize_json)
return defa... | |
slippage:", "{:.4%}".format(slippage))
# check how much liquidity we have staked in the frax contract
staking = Contract("0x3EF26504dbc8Dd7B7aa3E97Bc9f3813a9FC0B4B0")
locked = staking.lockedLiquidityOf(strategy)
print("\nStrategy locked liquidity:", locked)
# Display estimated APR
print(
"\nEstimated APR with ... | |
# -*- coding: utf-8 -*-
"""AND, OR, NOR gate implementation using ANN.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/github/shyammarjit/Deep-Learning/blob/main/AND%2C_OR%2C_NOR_gate_implementation_using_ANN.ipynb
#Implementation of Artificial Neural Netw... | |
# Copyright 2015 datawire. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | |
# -*- coding: iso-8859-1 -*-
"""
Create files (from Rugheimer metadata) that give the atmospheric profile, i.e. mixing ratio, temperature and pressure as a function of altitude.
Since the Rugheimer T/P and mixing ratio files are generated from different codes, they have different abscissa, and so different files are ge... | |
<reponame>sariths/stadicViewer
"""This module enables the GUI, buttons and control logic for Room-based plots."""
# coding=utf-8
from __future__ import print_function
import bisect
import numbers
import sys
import numpy as np
from PyQt4 import QtCore,QtGui
from dataStructures.timeSeries import TimeArray
from readSta... | |
# from x2paddle import torch2paddle
from copy import deepcopy
import argparse
import math
import os
import pickle
import json
import logging
import time
import paddle
import numpy as np
import random
from collections import Counter
from paddle.nn import functional as F
from model.meta import Meta
from utils.metrics imp... | |
decimal point. if it's still not working error message and return
try:
tdia = float(self.ui.tools_table.item(row, 1).text().replace(',', '.'))
except ValueError:
self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
continue
sorted_tools.append(float('%.*f' % (self.decimals, td... | |
<gh_stars>0
# Copyright 2015 Fortinet 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 agreed to in... | |
found, a 0 is stored in the
corresponding output value.
See also `tf.batch_gather` and `tf.gather_nd`.
Args:
params: A `Tensor`.
The tensor from which to gather values. Must be at least rank
`axis + 1`.
indices: A `Tensor`. Must be one of the following types: `int32`, `int64`.
Index tensor. Must be in range `... | |
<gh_stars>100-1000
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
########################################################################################################
### LICENSE
########################################################################################################
#
# findmyhash.py - v 1.1.2
#
#... | |
"""
MIT License
Copyright (c) 2019-present <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... | |
import torch
import torch.nn as nn
from torchvision.utils import save_image
import math
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
def elbo_loss(CV_loss, mu_latent, logvar_latent):
"""
This function will add the reconstruction loss (cross entropy as difference between two probability ... | |
case of gRPC transcoding
@property
def field_headers(self) -> Sequence[str]:
"""Return the field headers defined for this method."""
http = self.options.Extensions[annotations_pb2.http]
pattern = re.compile(r'\{([a-z][\w\d_.]+)=')
potential_verbs = [
http.get,
http.put,
http.post,
http.delete,
http.patch,
... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
# ----------------
# Test Functions
# ----------------
from six.moves import zip, range
# from wbia.plottool import draw_func2 as df2
# from wbia.plottool.viz_keypoints import show_keypoints
import utool as ... | |
to plane-stress conditions, the transformed in-plane stress and strain systems of equations can be derived by substituting the plane-stress conditioned stiffness and compliance matrices (Eqn. [23], [24]) into Eqns. [31] and [32]:
#
# $$ [\mathbf{\bar{Q}}] = [\mathbf{\hat{T}_{\sigma}}][\mathbf{Q}][\mathbf{\hat{T}_{\var... | |
<reponame>asrlabncku/RAP
from chainer import cuda
from chainer import function
from chainer.utils import type_check
from chainer.utils import conv
from ctypes import *
from six import moves
import numpy as np
import cupy
import time
import os
dllpath = '/home/monica/Documents/chainer-1.17.0-RAP/chainer/functions/cnet/l... | |
"""
sets
~~~~~
The `sets` module contains a standard collection, :class:`Set`, which is based
on Python's built-in set type.
Its elements are stored in a Redis `set <http://redis.io/commands#set>`_
structure.
"""
import collections.abc as collections_abc
from functools import reduce
import operator
from redis.client... | |
0],
optical_axis_OHB[t, 1],
optical_axis_OHB[t, 2],
Time_OHB[t],
)
optical_axis_OHB_ECEF[t, :] = optical_axis_OHB_ECEF[t, :] / norm(
optical_axis_OHB_ECEF[t, :]
)
(
r_MATS_OHB_ECEF[t, 0],
r_MATS_OHB_ECEF[t, 1],
r_MATS_OHB_ECEF[t, 2],
) = MATS_coordinates.eci2ecef(
r_MATS_OHB[t, 0], r_MATS_OHB[t, 1], r_MA... | |
<reponame>andyharney/pySignare
# Copyright 2014 <NAME> (2014)
#
# 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 ... | |
add_file_with_options_async(
self,
space_id: str,
request: dingtalkdrive__1__0_models.AddFileRequest,
headers: dingtalkdrive__1__0_models.AddFileHeaders,
runtime: util_models.RuntimeOptions,
) -> dingtalkdrive__1__0_models.AddFileResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset... | |
the unicode
get,par = c_rsf.sf_histfloat(self.file,nm.encode('utf-8'))
if get:
return par
else:
return None
else:
try:
return float(self.vd[nm])
except:
return None
def close(self):
# kls
#if not self.copy:
# c_rsf.sf_fileclose(self.f)
_File.close(self)
class Output(_File):
def __init__(self,tag='out'... | |
# *****************************************************************************
#
# Copyright (c) 2019, the Perspective Authors.
#
# This file is part of the Perspective library, distributed under the terms of
# the Apache License 2.0. The full license can be found in the LICENSE file.
#
import os
import time
import py... | |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... | |
pulumi.set(__self__, "iops", iops)
@property
@pulumi.getter(name="sizeInGB")
def size_in_gb(self) -> int:
return pulumi.get(self, "size_in_gb")
@property
@pulumi.getter(name="volumeType")
def volume_type(self) -> str:
return pulumi.get(self, "volume_type")
@property
@pulumi.getter
def iops(self) -> Option... | |
<reponame>Special-K-s-Flightsim-Bots/DCSServerBot<filename>plugins/admin/commands.py
# commands.py
import asyncio
import discord
import os
import platform
import psycopg2
import psycopg2.extras
import re
import subprocess
from contextlib import closing
from core import utils, DCSServerBot, Plugin
from discord.ext impor... | |
<reponame>Imperas/riscv-dv
"""
Copyright 2019 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to ... | |
4767 9.550395119310684851200738257147825E-2871 4.775197559655342425600369128573913E-2871
4768 2.387598779827671212800184564286957E-2871 1.193799389913835606400092282143478E-2871
4769 5.96899694956917803200046141071739E-2872 2.984498474784589016000230705358695E-2872
4770 1.492249237392294508000115352679348E-2872 7... | |
>> /etc/rc.conf"' %
(r'ifconfig_' + interface + r'=\"' + test_ip + r' netmask 255.255.255.0' + media_settings + r'\"'),
shell_escape=False)
if test_subnet == subnet1 :
route1 = r'static_routes=\"internalnet2\"'
route2 = r'route_internalnet2=\"-net ' + subnet2 + r'.0/24 ' + subnet1 + r'.1\"'
else:
route1 = r'st... | |
<reponame>Stratoscale/zadarapy
# Copyright 2019 Zadara Storage, Inc.
# Originally authored by <NAME> - https://github.com/jwbrown77
#
# 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:/... | |
`x`. The shapes of `x` and `y` satisfy:
`y.shape[i] == x.shape[perm[i]] for i in [0, 1, ..., rank(x) - 1]`
Args:
x: A `Tensor`.
perm: A `Tensor`. Must be one of the following types: `int32`, `int64`.
name: A name for the operation (optional).
Returns:
A `Tensor`. Has the same type as `x`.
"""
_ctx = _context... | |
# Implementation of all commands the Machinekit workbench registers with FreeCAD.
#
# Special attention should be given to MachinekitCommandCenter. Integrating MK with FC
# turned out to be a bit arkward because the existence and communication with MK is entirely
# outside FC's control, which is not what the FC inf... | |
warning as this issue will be caught in _Reqs() initialization.
if not line and len(splited) < 1:
warn_msg = "[Warning] Empty line detected while filtering lines."
logging.warning(warn_msg)
self.warning_msg.append(warn_msg)
# In general, first line in requirement definition will include `[`
# in the confi... | |
distance <= radius from n
name : str, optional
calculated attribute name
distance : str, optional
Use specified edge data key as distance.
For example, setting ``distance=’weight’`` will use the edge ``weight`` to
measure the distance from the node n during ego_graph generation.
weight : str, optional
Use the s... | |
= out_grid_vector.CreateLayer(
'grid', spat_ref, ogr.wkbPolygon)
grid_layer_defn = grid_layer.GetLayerDefn()
extent = vector_layer.GetExtent() # minx maxx miny maxy
if grid_type == 'hexagon':
# calculate the inner dimensions of the hexagons
grid_width = extent[1] - extent[0]
grid_height = extent[3] - extent[2]
... | |
SPENLocalFactor=myParams.myDict['SPENLocalFactor']
F=GT.ExpandWithCopiesOn2(F,DataH,SPENLocalFactor)
feature=tf.concat([tf.real(F),tf.imag(F)],axis=2)
features, labels = tf.train.batch([feature, label],batch_size=batch_size,num_threads=4,capacity = capacity_factor*batch_size,name='labels_and_features')
tf.train... | |
"")
te.pushval("a")
te.pushval("b")
te.pushval("c")
te.swap()
self.assertEqual(te.state(), TES_IDLE)
self.assertIsNone(te.match())
self.assertEqual(te.nvals(), 3)
self.assertEqual(te.last_error_detail(), "")
self.assertEqual(te.popval(), "b")
self.assertEqual(te.state(), TES_IDLE)
self.assertIsNone(te.match(... | |
import random, time
from testcases.testcases_base import TestcasesBase
import unittest
class TestGatewayAPICreation(TestcasesBase):
def setUp(self):
super().setUp()
self.core0_client.create_ovs_container()
self.core0_client.timeout = 30
self.flist = 'https://hub.gig.tech/gig-official-apps/ubuntu1604.flist'
self.... | |
workspace:
gs_styles = [x for x in cat.get_styles(names=[f"{settings.DEFAULT_WORKSPACE}_{resource_name}"])]
styles = styles + gs_styles
cat.delete(lyr)
for s in styles:
if s is not None and s.name not in _default_style_names:
try:
logger.debug(f"Trying to delete Style [{s.name}]")
cat.delete(s, purge='true')
e... | |
in leaks:
if type(obj) in ignore_types:
break
else:
real_leaks.append(obj)
leaks = real_leaks
else:
return leaks or None
logger.warn('{} {}s leaked. {}', (len(leaks)), type_name, ('' if _trace_all_leaks else 'Enable _trace_all_leaks in zone.py for potential callstacks. '), owner='mduke')
for item in leaks:
l... | |
= self.layer1(out)
out = self.layer2(out)
out = self.layer3(out)
out = self.avg_pool(out)
out = out.view(out.size(0), -1)
out = self.fc(out)
out = self.drop2(out)
out = self.relu1(out)
out = self.fc2(out)
out = torch.sigmoid(out)
return out
def predict_proba(self, x):
if type(x) is np.ndarray:
x = torch.... | |
# anvil_mods.py
import pandas as pd
import numpy as np
import shapely
import geopandas as gpd
import quandl
from fred import Fred
# demo api key
quandl.ApiConfig.api_key = "<KEY>"
def formatIndicatorLikeQuandl(indicator, **kwargs):
"""
Uses the FRED module to access data not included
in QUANDL's dataset. Limit... | |
not in ['_BPM', 'OEMK'] and (Comp.Offset & 0xFFF > 0):
raise Exception("Component '%s' %x is not aligned at 4KB boundary, " \
"please adjust padding size for IPAD/OPAD in BoardConfig.py and rebuild !" % (CompBpdtDict[Desc.Sig], Comp.Offset))
Desc.Offset = Comp.Offset - Bp0.Offset
# Last 4k in bios region is reserv... | |
<gh_stars>0
from rpython.rlib.objectmodel import we_are_translated
from rpython.rlib.rarithmetic import r_uint
from rpython.rtyper.lltypesystem import rffi, lltype
from rpython.rtyper import rclass
from rpython.jit.metainterp.history import (AbstractFailDescr, ConstInt,
INT, FLOAT, REF, VOID)
from rpython.jit.backend... | |
an instance of datastore_query.Cursor.')
self._cursor = value
cursor = property(fget=_GetCursor, fset=_SetCursor)
def _GetLimit(self):
"""Getter to be used for public limit property on query info."""
return self._limit
def _SetLimit(self, value):
"""Setter to be used for public limit property on query info.
... | |
# Wait until process is complete and return stdout/stderr
self.stdout_, self.stderr_ = self.process_.communicate() # Use this .communicate instead of .wait to avoid zombie process that hangs due to defunct. Removed timeout b/c it's not available in Python 2
# Set stdout and stderr to the contents of the file object ... | |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use... | |
import time
from .settings import *
# Selecionando o algoritmo para exibir na tela
def draw_lines(grid, algorithm, posX1, posY1, posX2, posY2, color, rows, pixel_size, line):
# Como posições são sempre floats, arredondarei para int
posX1, posX2, posY1, posY2 = int(posX1), int(posX2), int(posY1), int(posY2)
# Não ... | |
comparison
def plot_image_from_latent(z_sample):
with torch.no_grad():
sample = _p.sample({"z": z_sample})["x"].view(-1, 1, 28, 28).cpu() # TODO: it should be sample_mean
return sample
# In[12]:
# writer = SummaryWriter()
z_sample = 0.5 * torch.randn(64, z_dim).to(device)
_x, _ = iter(test_loader).next()
_... | |
"m.relates_to" in event['content']:
# это ответ на сообщение:
reply_to_id=event['content']['m.relates_to']['m.in_reply_to']['event_id']
formatted_body=None
format_type=None
if "formatted_body" in event['content'] and "format" in event['content']:
formatted_body=event['content']['formatted_body']
format_type=even... | |
-> fib(3) + fib(2)
self.assertIsInstance(fib_expr.left.left, Add) # fib(3) -> fib(2) + fib(1)
self.assertIsInstance(fib_expr.left.left.left, Number) # fib(2) -> 2
self.assertEqual(fib_expr.left.left.left.evaluate(), 2)
self.assertIsInstance(fib_expr.left.left.right, Number) # fib(1) -> 1
self.assertEqual(fib_expr.... | |
if features[0] > 0.0020365312229841948
if features[3] <= 0.022401843452826142:
return 0
else: # if features[3] > 0.022401843452826142
return 1
else: # if features[2] > 0.018328781006857753
if features[3] <= 0.06313246791251004:
if features[15] <= 0.0040730624459683895:
return 1
else: # if features[15] > 0.0040... | |
`+edit trophyboard sort loss`
**Required Permissions**
:warning: Manage Server
"""
if sort_by not in ['trophies', 'gain', 'loss']:
return await ctx.send("Oops, that didn't look right! Try `trophies`, `gain` or `loss` instead.")
query = "UPDATE boards SET sort_by = $1 WHERE channel_id = $2"
await ctx.db.execute... | |
# Generated by Django 1.11.24 on 2019-09-10 10:28
import django.core.validators
import django.db.models.deletion
import django.utils.timezone
import django_fsm
import model_utils.fields
from django.db import migrations, models
import waldur_core.core.fields
import waldur_core.core.models
import waldur_core.core.shims
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.