input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
currently in the dictionary.
# - In contrast, the *defaultdict* will create an item of the type of the argument, in this case an integer with the default value of 0.
# - See [defaultdict](https://docs.python.org/3.3/library/collections.html#defaultdict-objects).
# In[13]:
# UNQ_C1 GRADED FUNCTION: create_dictionar... | |
<filename>src/ramstk/views/gtk3/requirement/panel.py
# -*- coding: utf-8 -*-
#
# ramstk.views.gtk3.requirement.panel.py is part of The RAMSTK Project
#
# All rights reserved.
# Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland <AT> reliaqual <DOT> com
"""GTK3 Requirement Panels."""
# Standard Library Impor... | |
self._response(request, status=200)
@routes.post("/order/{id}", name="order")
async def order(self, request):
"""Handler that queries the given order.
`7.1.3. Order Objects <https://tools.ietf.org/html/rfc8555#section-7.1.3>`_
:raises: :class:`aiohttp.web.HTTPNotFound` If the order does not exist.
:return: The... | |
content)
finally:
config.HOSTNAME_EXTERNAL = hostname_before
def test_s3_static_website_hosting(self):
bucket_name = 'test-%s' % short_uid()
self.s3_client.create_bucket(Bucket=bucket_name)
self.s3_client.put_object(Bucket=bucket_name, Key='test/index.html', Body='index')
self.s3_client.put_object(Bucket=buck... | |
<reponame>bobelly/torchsupport<gh_stars>10-100
import torch
import random
# import pandas as pd
from torchsupport.data.io import imread
from torch.utils.data import Dataset, DataLoader
if True:
from torch.utils.data.sampler import Sampler, SubsetRandomSampler
else:
from torch.utils.data import Sampler, SubsetRandomSa... | |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Blue Yonder Coding Task - Image downloader - 3. Simple and solid solution.
:author <NAME>:
:created 2018/04/05:
Usage: quickanddirty.py <path to input file>
"""
# standard library modules
import argparse
import logging
import os
import sys
import tempfile
import errno
fro... | |
and the remote :class:`.Graph`, pull properties
and node labels into the local copies. This operation does not
create or delete any entities.
:param subgraph: a :class:`.Node`, :class:`.Relationship` or other
:class:`.Subgraph`
"""
try:
pull = subgraph.__db_pull__
except AttributeError:
raise TypeError("No me... | |
# Option 4: ffma(a, -a, (2*a)
# Option 5: a * (2 - a)
#
# There are a lot of other possible combinations.
(('~ffma@32', ('fadd', b, ('fneg', a)), a, a), ('flrp', a, b, a), '!options->lower_flrp32'),
(('~ffma@32', a, 2.0, ('fneg', ('fmul', a, a))), ('flrp', a, 1.0, a), '!options->lower_flrp32'),
(('~ffma@32', a, 2... | |
import copy
import sys
import os
import eventlet
import socketio
import pathlib
from .player import Player
from .room import Room
from .table import Table
from .ai import AI
import time
import random
import string
import math
roomList = []
sio = socketio.Server()
app = socketio.WSGIApp(sio)
@sio.event
def connect(... | |
this link https://towardsdatascience.com/k-nearest-neighbor-classifier-from-scratch-in-python-698e3de97063
# and this link https://machinelearningmastery.com/tutorial-to-implement-k-nearest-neighbors-in-python-from-scratch/
# region
# calculate the Euclidean distance between two 1d-arrays
def distance(instance1, inst... | |
# Copyright (c) 2015-2017 Tigera, Inc. 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 la... | |
= Constraint(expr= - 9*m.b125 - 11*m.b133 - 5*m.b141 - 7*m.b149 - 6*m.b157 - 4*m.b165 - 0.0025*m.x229
- 0.002*m.x253 - 0.00222222222222222*m.x277 - m.x416 + m.x417 >= 0)
m.c138 = Constraint(expr= - 9*m.b126 - 11*m.b134 - 5*m.b142 - 7*m.b150 - 6*m.b158 - 4*m.b166 - 0.0025*m.x230
- 0.002*m.x254 - 0.00222222222222222*m... | |
# Copyright 2019 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | |
<gh_stars>0
#mv.py
import itertools
import copy
import numbers
import operator
from compiler.ast import flatten
from operator import itemgetter, mul, add
from itertools import combinations
#from numpy.linalg import matrix_rank
from sympy import Symbol, Function, S, expand, Add, Mul, Pow, Basic, \
sin, cos, sinh, cosh... | |
tapes contain WireCut operations."
)
return tape
def _cut_circuit_expand(
tape: QuantumTape,
use_opt_einsum: bool = False,
device_wires: Optional[Wires] = None,
max_depth: int = 1,
auto_cutter: Union[bool, Callable] = False,
**kwargs,
):
"""Main entry point for expanding operations until reaching a depth th... | |
<reponame>Shadybloom/amber-in-the-dark
#----
# Заметки:
# Список фабрик и заводов Российской империи (1907-1909 годы):
# http://istmat.info/node/26498
#----
# Фабрики (обмолот)
metadict_detail['_Обмолот зерновых (килограмм)'] = {
# TODO: Сначала обмолот, затем веялка.
# обмолот растений на молотилке.
# Молотилк... | |
#!/usr/bin/env python
import numpy as np
import netCDF4 as nc
import pandas as pd
import multiprocessing
import textwrap
import matplotlib.pyplot as plt
import lhsmdu
import glob
import json
import os
import ast
import shutil
import subprocess
from contextlib import contextmanager
import param_util as pu
import outp... | |
<reponame>IBM/spectrum-connect-csi<filename>controller/tests/array_action/svc/array_mediator_svc_test.py
import unittest
from mock import patch, Mock, call, PropertyMock
from munch import Munch
from pysvc import errors as svc_errors
from pysvc.unified.response import CLIFailureError, SVCResponse
import controller.arr... | |
DelaySpectrum(uv=[test_uv_1, test_uv_2])
dspec_object.calculate_delay_spectrum()
dspec_object.add_trcvr(144 * units.K)
assert (units.mK**2 * units.Mpc**3).is_equivalent(dspec_object.noise_power.unit)
def test_delay_spectrum_thermal_power_units():
"""Test the units on the output thermal power are correct."""
tes... | |
or value > 2 ** 16 - 1:
raise ValueError('<{}> 超过 <{}> 寄存器的取值范围'.format(value, key))
elif key in ('A', 'X', 'Y', 'S'):
if value < 0 or value > 2 ** 8 - 1:
raise ValueError('<{}> 超过 <{}> 寄存器的取值范围'.format(value, key))
elif key == 'status':
if not isinstance(value, _Status):
raise ValueError('<{}> 不是正确的 Status 寄存器'... | |
string != values['string']:
logging.warning((
'String mismatch for LCID: 0x{0:08x}, '
'file version: {1:s}, string identifier: {2:s}.\n'
'Found: {3:s}\nStored: {4:s}\n').format(
language_identifier, message_resource_file.file_version,
string_identifier, string, values['string']))
elif number_of_values != 0:
lo... | |
## @metapackage.py
# Object to simplify unpacking/building/cleaning of ASKAPsoft systems
# metapackages
#
# @copyright (c) 2007-2013 CSIRO
# Australia Telescope National Facility (ATNF)
# Commonwealth Scientific and Industrial Research Organisation (CSIRO)
# PO Box 76, Epping NSW 1710, Australia
# <EMAIL>
#
# This file... | |
<reponame>sparkslabs/kamaelia_orig<filename>Sketches/MH/DocGen/DocExtractor.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend ... | |
anything!”
“I’d tackle the old man first,” said Hallen; “I think, on general
principles, he’s the one to make inquiries of before you go to the
ladies. Let’s go to him now.”
“No;” proposed Burdon, “let’s send for him to come here. This is away
from the house, and we can talk more freely.”
“I’ll go for him,” offered ... | |
<gh_stars>100-1000
"""
Some parts are adapted from https://github.com/cocodataset/cocoapi :
Copyright (c) 2014, <NAME> and <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of ... | |
provided).
The model for the autoregressive process takes this convention:
s[n] = a1*s[n-1] + a2*s[n-2] + ... aP*s[n-P] + v[n]
where v[n] is a zero-mean white noise process with variance=sigma_v
Parameters
----------
s : ndarray
The sampled autoregressive random process
order : int
The order P of the AR sy... | |
<filename>Pilot1/Uno/uno_trainUQ_keras2.py
#! /usr/bin/env python
from __future__ import division, print_function
import logging
import os
import argparse
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import backend as K
from tensorflow.keras impor... | |
len(edge.Vertexes) > 1:
v1 = self.wp.getLocalCoords(edge.Vertexes[0].Point)
v2 = self.wp.getLocalCoords(edge.Vertexes[-1].Point)
return Part.LineSegment(v1, v2).toShape()
return edge
def doCut(self, cutplane, hidden, clip, clipDepth, shapes):
objectShapes = []
sections = []
faces = []
shps = []
# self.reor... | |
<reponame>AlkalineCandy79/PGE_Potential_PSPS_Scraper
#-------------------------------------------------------------------------------
# Name: PGE Power Outage Status Scraper
# Purpose: This script, while not the most elegant, scrapes the PG&E back end
# for data about specific addresses. As there are sometimes Apt#... | |
from buildingArrays import BuildingFactory
from random import randint, randrange
import utilityFunctions
import time
#inputs are taken from the user. Here I've just showing labels, as well as letting the user define
# what the main creation material for the structures is
inputs = (
("COMP4303 Final Project", "label")... | |
scan_info_strptime = datetime.datetime.strptime(scan_summary['scanDate'], '%Y-%m-%dT%H:%M:%S.%fZ')
scan_info_strptime_tuple = (
scan_info_strptime.year, scan_info_strptime.month, scan_info_strptime.day)
if scan_summary_strptime_tuple == scan_info_strptime_tuple:
print("[WARNING] Analysing an older application ({sc... | |
have gradients.
Outputs:
returns a map from the blob name in the input network to a blob
containing gradient or a GradientSlice in case of sparse gradient
Currently, this is hard-coded for float operators if there are branches
(i.e. a blob is used as input to multiple operators). This is because
the gradient ac... | |
validate_config(config):
"""Validate some important keys in config dict."""
# Validate server type
valid_hosts = list(TEMPLATES.keys())
if config['server'] not in valid_hosts:
print('[ERR] httpd.server must be \'apache22\', \'apache24\' or \'nginx\'', file=sys.stderr)
print('[ERR] Your configuration is:', config... | |
ProtocolData(self.edesign, ds, self.cache[dsname])
for dsname, ds in self.dataset.items()}
ds_to_get_circuits_from = self.dataset[list(self.dataset.keys())[0]]
else:
self._passdatas = {None: self}
ds_to_get_circuits_from = dataset
if self.edesign is None:
self.edesign = ExperimentDesign(list(ds_to_get_circuits_... | |
_DEF_IMAS_PLASMA_SIG.keys():
if plot_sig is None:
plot_sig = _DEF_IMAS_PLASMA_SIG[lids[0]]['plot_sig']
if plot_X is None:
plot_X = _DEF_IMAS_PLASMA_SIG[lids[0]]['plot_X']
if dsig is None:
lsig = (list(plot_sig) + list(plot_X)
+ _DEF_IMAS_PLASMA_SIG[lids[0]]['other'])
dsig = {lids[0]: lsig}
if plot_sig is None... | |
<filename>pytorch/libs/nnet/pooling.py
# -*- coding:utf-8 -*-
# Copyright xmuspeech (Author: Snowdar 2019-05-29 2020-06-10)
import numpy as np
import torch
import torch.nn.functional as F
from libs.support.utils import to_device
from .components import *
## Pooling ✿
class StatisticsPooling(torch.nn.Module):
"""... | |
<filename>theano/sandbox/cuda/opt.py
import logging
_logger = logging.getLogger('theano.sandbox.cuda.opt')
import sys
import theano
import numpy
from theano.scan_module import scan_utils, scan_op
from theano import scalar as scal
from theano import tensor, compile, gof
from theano.gof import (local_optimizer, Equilib... | |
row/column indices in the member's stiffness matrix
# 'm' & 'n' are corresponding row/column indices in the global stiffness matrix
for a in range(12):
# Determine if index 'a' is related to the i-node or j-node
if a < 6:
# Find the corresponding index 'm' in the global stiffness matrix
m = member.iNode.ID*6 + ... | |
self.m_textCtrl_fuse4e0, 0, wx.ALL, 5 )
self.m_textCtrl_fuse4f0 = wx.TextCtrl( self.m_panel_fuseUtil, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 75,20 ), 0 )
bSizer_fuseGroupCtrl1.Add( self.m_textCtrl_fuse4f0, 0, wx.ALL, 5 )
self.m_textCtrl_fuse500 = wx.TextCtrl( self.m_panel_fuseUtil, wx.ID_ANY, w... | |
#!/tools/net/bin/python
# Copyright (c) 1994, 1996, <NAME> All rights reserved.
# Copyright (c) 2004, <NAME> All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code... | |
# --------------------------------------------------------
# Swin Transformer
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by <NAME>
# --------------------------------------------------------
import torch
import torch.nn as nn
import math
import numpy as np
from t... | |
<filename>grr/lib/communicator_test.py
#!/usr/bin/env python
"""Test for client."""
import array
import logging
import pdb
import time
import requests
from grr import config
from grr.client import comms
from grr.client.client_actions import admin
from grr.client.client_actions import standard
from grr.lib import co... | |
<filename>codes/dataops/batchaug.py
import random
import numpy as np
import torch
from torch.nn import functional as F
class BatchAugment:
def __init__(self, train_opt):
self.mixopts = train_opt.get(
"mixopts", ["blend", "rgb", "mixup", "cutmix",
"cutmixup", "cutout"]) # , "cutblur"]
self.mixprob = train_opt.get... | |
* rank
I_minus_s2XTAcorrXL_LAMBDA_LT = np.identity(n_C) \
- np.dot(s2XTAcorrXL_LAMBDA, L.T)
# dimension: n_grid * condition * condition
# The step above may be calculated by einsum. Not sure
# which is faster.
weight_grad = result_exp / result_sum
weight_grad_over_denominator = weight_grad / denominator
# dimen... | |
<gh_stars>0
import os
import sys
import subprocess
import multiprocessing
from joblib import Parallel, delayed
import shutil
import pathlib
import pandas as pd
import math
import EUKulele
from EUKulele.tax_placement import place_taxonomy
from EUKulele.visualize_results import visualize_all_results
from scripts.mag_st... | |
= h2
size = total_area / npieces
cuts = []
needed = size
return yupper
def func_b0c6a9790ac9463c94555e61e46286c5(npieces, upper, lower):
li = ui = 0
areas = []
total_area = 0
x = 0
h1 = upper[0][1] - lower[0][1]
W = lower[-1][0]
while x < W:
lnext = lower[li + 1]
unext = upper[ui + 1]
if lnext[0] == une... | |
def test_type_list(self, command, version):
self.run_command(command, version=version)
columns_requested = ['ID', 'Name', 'visibility',
'is_default', 'required_extra_specs',
'optional_extra_specs', 'Description']
if 'columns' in command:
columns_requested = command.split('--columns ')[1].split(',')
is_default_... | |
rootNode.CREATE )
self.obj40=MT_pre__Feature(self)
self.obj40.isGraphObjectVisual = True
if(hasattr(self.obj40, '_setHierarchicalLink')):
self.obj40._setHierarchicalLink(False)
# MT_label__
self.obj40.MT_label__.setValue('4')
# MT_pivotOut__
self.obj40.MT_pivotOut__.setValue('')
self.obj40.MT_pivotOut__.se... | |
"not in [0,1)")
if (feedback_end_frac < 0):
raise ValueError(
f"feedback_end_frac = {feedback_end_frac} not > 0")
# If feedback_start_frac exceeds feedback_end_frac, then
# there's no range of the flux ramp cycle over which we're
# applying feedback.
if (feedback_end_frac < feedback_start_frac):
raise ValueErro... | |
if x.Name == 'VRFHeatCapFT'])
assert curveobj[0].Name == 'VRFHeatCapFT'
assert curveobj[0].Coefficient1_Constant == 1.014599599
assert curveobj[0].Coefficient2_x == -0.002506703
assert curveobj[0].Coefficient3_x2 == -0.000141599
assert curveobj[0].Coefficient4_y == 0.026931595
assert curveobj[0].Coefficient5_y2 =... | |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""Crossword Layout
"""
class IntRect:
"""Integer Rectangle, [left, right), [top, bottom)"""
def __init__(self, left=0, top=0, right=1, bottom=1):
self.left = left
self.top = top
self.right = right
self.bottom = bottom
@property
def width(self):
"""Return width... | |
<reponame>m1griffin/arrayfunc
#!/usr/bin/env python3
##############################################################################
# Project: arrayfunc
# Purpose: Generate the C code for math operators with one variable.
# Language: Python 3.4
# Date: 18-Mar-2018
#
#####################################################... | |
"""Simple implementation of single linked lists. """
class Node:
"""Implemetation of a list node. """
def __init__(self, data=None, next=None):
"""Init node object.
Parameters:
data (...): Data that is stored in this node
next (Node): Reference to the next node in the list
Returns:
None
Raises:
None
""... | |
self.assertIn(path, schema_changes_files)
# instantly create two, which will likely have the same timestamp
pathname = self.empty_schema_changes.make_template()
with self.assertRaisesRegex(MigratorError, "schema changes file '.+' already exists"):
self.empty_schema_changes.make_template()
os.remove(pathname)
sc... | |
of the results,
this method will return an empty list.
Optional parameter:
* `page` – request a specific page from the results set
'''
if self.total_results == '20,000+':
return {'total_results': self.total_results, 'page': None, 'number_of_results': 0, 'results': [], 'error': 'Your search returns too many resu... | |
# coding: utf-8
from __future__ import unicode_literals
import base64
import binascii
import collections
import ctypes
import email
import getpass
import io
import itertools
import optparse
import os
import platform
import re
import shlex
import shutil
import socket
import struct
import subprocess
import sys
import xm... | |
<filename>venv/lib/python3.7/site-packages/MDAnalysis/topology/guessers.py
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributo... | |
LLVM-vs2017, LLVM-vs2017_xp, v141, v141_xp, v141_clang_c2, v142,
llvm, ClangCL]
cppstd: [None, 14, 17, 20]
clang:
version: ["3.3", "3.4", "3.5", "3.6", "3.7", "3.8", "3.9", "4.0",
"5.0", "6.0", "7.0", "7.1",
"8", "9", "10"]
libcxx: [None, libstdc++, libstdc++11, libc++, c++_shared, c++_static]
cppstd: [None, 98... | |
self.is_cli)
self.print_err = partial(print_err, view = self.is_cli)
## Check paths images.
if self.paths_images and isinstance(self.paths_images, list):
self.check_output()
self.remind = {}
self.all_icocur_written = {}
groups = zip(self.paths_images, self.paths_icocur, self.names_icocur, self.formats_icocur, ... | |
<filename>infoblox_netmri/api/broker/v3_8_0/scorecard_history_broker.py<gh_stars>10-100
from ..broker import Broker
class ScorecardHistoryBroker(Broker):
controller = "scorecard_histories"
def index(self, **kwargs):
"""Lists the available scorecard histories. Any of the inputs listed may be be used to narrow the ... | |
= sketchArc1.addByThreePoints(adsk.core.Point3D.create(nutDistance+endC-L, (endLength/2), fretboardHeight), adsk.core.Point3D.create(nutDistance-L, 0, fretboardHeight),
adsk.core.Point3D.create(nutDistance+endC-L, (endLength/-2), fretboardHeight))
elif createEndCurve.value:
path1 = sketchArc1.addByThreePoints(endTop... | |
test_future_tasks_hidden(self):
self.run_test(
todo0 = ["past t:1999-12-31", "present t:2000-01-01", "future t:2000-01-02"],
edit0 = ["i:1 past t:1999-12-31", "i:2 present t:2000-01-01"]
)
def test_future_tasks_not_hidden(self):
self.run_test(
todo0 = ["past t:1999-12-31", "present t:2000-01-01", "future t:2000... | |
# -*- coding: utf-8 -*-
import unittest
import os
# prepare for test
os.environ['ANIMA_TEST_SETUP'] = ""
from anima.env import mayaEnv # to setup maya extensions
import pymel.core
from anima.edit import Sequence, Media, Video, Track, Clip, File
class SequenceManagerTestCase(unittest.TestCase):
"""tests the Sequen... | |
<reponame>sotte/tf-encrypted<filename>tests/test_convert.py
from typing import List, Tuple
import unittest
import logging
import os
import numpy as np
import tensorflow as tf
import tf_encrypted as tfe
from tf_encrypted.convert import Converter
from tf_encrypted.convert.register import register
from tensorflow.python... | |
<reponame>XueQinliang/DDB_RPQL
import sys
from typing import List
from concurrent.futures import ThreadPoolExecutor, as_completed
import grpc
import pickle
from time import time
from time import localtime
from time import asctime
#from jr.jr_execute import sql_drop_temp
#import structures
#from structures import Node
... | |
<reponame>WolfLo/OPTIMIST
import baselines.common.tf_util as U
import tensorflow as tf
import gym
from baselines.common.distributions import MultiGaussianVectorPdType
import numpy as np
from baselines.common import set_global_seeds
import scipy.stats as sts
"""References
PGPE: Sehnke, Frank, et al. "Policy gradients w... | |
r25c4 = request.POST.get('r25c4').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ')
r25c5 = request.POST.get('r25c5').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ')
r25c6 = request.POST.get('r25c6').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ')
r25c7 = request.POST.get('r25c7').replace('\... | |
<reponame>Southampton-Maritime-Robotics/Autonomous-Ship-and-Wavebuoys<filename>ASV/ASV/nodes/averager.py
#!/usr/bin/python
##############################################################################
#averager.py
#
#This code has been created by <NAME> (<EMAIL>) for
#averaging the main readings required during the Q... | |
<gh_stars>0
import logging
import pprint
import os
import sys
import math
import torch
import time
import random
from sklearn.metrics import average_precision_score, roc_auc_score
from scipy.sparse import coo_matrix
import numpy as np
import utils
import joblib # import Parallel, delayed
from torch.utils.tensorboard im... | |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource impo... | |
self.m_staticText_fuse4e0.SetLabel('0x4e0')
self.m_staticText_fuse4f0.SetLabel('0x4f0')
self.m_staticText_fuse500.SetLabel('OTPMK')
self.m_staticText_fuse510.SetLabel('OTPMK')
self.m_staticText_fuse520.SetLabel('OTPMK')
self.m_staticText_fuse530.SetLabel('OTPMK')
self.m_staticText_fuse540.SetLabel('OTPMK')
self.... | |
input sequence length {sequence_length} equals 1, when `past_buckets_states` is passed."
past_buckets = past_buckets_states[0]
past_states = past_buckets_states[1]
# get query vector
query_vectors = self.query_key(hidden_states)
query_vectors = self._split_hidden_size_dim(
query_vectors, self.num_attention_heads... | |
import numpy as np
def lanc(numwt, haf):
"""
Generates a numwt + 1 + numwt lanczos cosine low pass filter with -6dB
(1/4 power, 1/2 amplitude) point at haf
Parameters
----------
numwt : int
number of points
haf : float
frequency (in 'cpi' of -6dB point, 'cpi' is cycles per interval.
For hourly data cpi is ... | |
finally:
with self.lock:
self.valid_session = valid_session
return valid_session
def rest_tb_target_list(self, all_targets = False, target_id = None):
"""
List targets in this server
:param bool all_targets: If True, include also targets that are marked
as disabled.
:param str target_id: Only get information... | |
The syntax allow both attribute/command execution and the usage of multiple typed arguments:
ACTION(alarm:command,mach/dummy/motor/move,int(1),int(10))
ACTION(reset:attribute,mach/dummy/motor/position,int(0))
Accepted keywords are:
$ALARM : Alarm name
$DESCRIPTION : Description text
$VALUES : last values sto... | |
backup_db_file(copy_flag):
DB.session.close()
try: # generate timestamp from last-modified time of database file
time_str = datetime.fromtimestamp(os.stat(DB_FILE_NAME).st_mtime).strftime('%Y%m%d_%H%M%S')
except: # if error then use 'now' timestamp
time_str = datetime.now().strftime('%Y%m%d_%H%M%S')
try:
(dbname... | |
5.905610E+02, 5.953200E+02, 6.001026E+02, 6.049090E+02, 6.097391E+02, 6.145930E+02,
6.194709E+02, 6.243727E+02, 6.292986E+02, 6.342486E+02, 6.392228E+02, 6.442212E+02,
6.492439E+02, 6.542909E+02, 6.593625E+02, 6.644585E+02, 6.695791E+02, 6.747243E+02,
6.798943E+02, 6.850890E+02, 6.903085E+02, 6.955530E+02, 7.008224E... | |
is there ...
if isinstance(alpha, (int, float)):
pass # regular behavior
else: # dynamic alpha which can be calc'ed by _mean_
self._alpha_ = alpha
kwargs['alpha'] = 1.0
elif 'halflife' in kwargs:
# period cannot be recovered, force the user to specify it
self._pval = kwargs.pop('span') # exception if not there
... | |
os.path.join(settings.DEIS_LOG_DIR, self.id + '.log')
if not os.path.exists(path):
raise EnvironmentError('Could not locate logs')
data = subprocess.check_output(['tail', '-n', str(settings.LOG_LINES), path])
return data
def run(self, command):
"""Run a one-off command in an ephemeral app container."""
# TODO: ... | |
<reponame>mburakkalkan/thonny
from thonny.common import (
InputSubmission,
InterruptCommand,
EOFCommand,
parse_message,
ToplevelCommand,
ToplevelResponse,
InlineCommand,
InlineResponse,
UserError,
serialize_message,
BackendEvent,
ValueInfo,
execute_system_command,
)
import sys
import logging
import traceba... | |
cfg.LED_PIN_G, cfg.LED_PIN_B, cfg.LED_INVERT)
from parts import RGB_LED
led = RGB_LED(pgio, cfg.LED_PIN_R, cfg.LED_PIN_G, cfg.LED_PIN_B, cfg.LED_INVERT)
led.set_rgb(cfg.LED_R, cfg.LED_G, cfg.LED_B)
V.add(LedConditionLogic(cfg), inputs=['user/mode', 'recording', "records/alert", 'behavior/state', 'modelfile/modif... | |
# Aim is to apply a multiplier to the natural capital scores to reflect the degree of public access
# Challenge is that it is difficult to clip or intersect the complex public access layer with the large and
# detailed OSMM-based base map - it takes days to run and then fails.
# So here we extract a subset of the base ... | |
batch_text_or_text_pairs=batch_text_or_text_pairs,
add_special_tokens=add_special_tokens,
padding=padding,
truncation=truncation,
max_length=max_length,
stride=stride,
is_split_into_words=is_split_into_words,
pad_to_multiple_of=pad_to_multiple_of,
return_tensors=return_tensors,
return_token_type_ids=return_tok... | |
["title","author","notes"] : ## Specific coding !!??
if jsondata['group'] in ['sdl'] :
try:
self.logger.info('Before encoding :\t%s:%s' % (key,jsondata[key]))
jsondata[key]=jsondata[key].encode("iso-8859-1") ## encode to display e.g. 'Umlauts' correctly
self.logger.info('After encoding :\t%s:%s' % (key,jsondata[k... | |
<reponame>Hicham-Belhseine/tarp-detect
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File name: "SL_CIP.py"
Date created: 1/17/2018
Date last modified: 10/4/2018
Python Version: 3.6
A simple script for determining a region of interest based on target color
and shape that switches towards the use of the CA... | |
np.zeros([len(loc),len(brd)*len(snsr)+1,129])
cnt = 0
else:
handle_list = []
title_list = []
for bo in brd:
for se in snsr:
if not pool:
# generate individual figure
fig = plt.figure(figsize=figsize)
handle_list.append(fig)
title = 'Spectral Density: %s L1-L6 %s %s %s Board %i, Sensor %i' % \
(cols[0].Gas... | |
f"Subscription {subscription_id}"
readable_output = tableToMarkdown(title, sub, headerTransform=pascalToSpace)
outputs = {"GoogleCloudPubSubSubscriptions(val && val.name === obj.name)": sub}
return readable_output, outputs, sub
def create_subscription_command(
client: PubSubClient,
subscription_id: str,
topic_i... | |
additional key carried
result = cluster.to_dict()
result['action'] = action.id
return result
@request_context
def cluster_update(self, context, identity, name=None, profile_id=None,
parent=None, tags=None, timeout=None):
def update_cluster_properties(cluster):
changed = False
# Check out if fields other than ... | |
"ambassador cast.",
(Characters.Morgan,),
(3 * 60 + 30.0),
None,
(Roles.Ambassador,),
(None,),
TimelineCategory.Cast,
Missions.NoMission,
ActionTest.NoAT,
),
(
"spy",
"03:30.0",
"double agent cast.",
(Characters.Salmon,),
(3 * 60 + 30.0),
None,
(Roles.DoubleAgent,),
(None,),
TimelineCategory.Cast,
M... | |
""" PCBOT.
The main module which contains the Client. This is the module
that would be executed.
"""
import asyncio
import inspect
import logging
import sys
import traceback
from argparse import ArgumentParser
from copy import copy
from datetime import datetime
import discord
import plugins
from pcbot import utils,... | |
<reponame>chuckie82/ami<filename>ami/flowchart/library/Psalg.py
from pyqtgraph.Qt import QtGui, QtWidgets
from amitypes import DataSource, Detector, Array1d, Array2d
from ami.flowchart.Node import Node, NodeGraphicsItem
from ami.flowchart.Units import ureg
from ami.flowchart.library.common import CtrlNode
from ami.flow... | |
import math
import time
import numpy as np
import matplotlib.pyplot as plt
from functions import *
import multiprocessing as mp
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
hist_all_nodes = []
hist_remaining_nodes = []
# COMMIT TEST
hist_time_for_method = []
hist_time_for_tarjan = []
c... | |
if model.Meta.table_format in [TableFormat.cell, TableFormat.multiple_cells]:
continue
if model.Meta.table_format == TableFormat.row:
ws_name = model.Meta.verbose_name_plural
else:
ws_name = model.Meta.verbose_name
hyperlinks.append(Hyperlink(len(content), 0,
"internal:'!!{}'!A1".format(ws_name),
tip='Click to... | |
and the other one will be in the foreground
def merge_images(im1, im2, im_size):
background = Image.open(im1).resize([im_size, im_size])
foreground = Image.open(im2).resize([im_size, im_size])
background.paste(foreground, (0, 0), foreground)
return background
def merge_image_with_random_noise(image, im_size):
ran... | |
"cannot be compiled since it inherits from nn.Module"):
torch.jit.script(MyModule)
def test_view_write(self):
def fn(x, y):
l = []
l.append(x)
x_view = l[0]
a = x + x
x_view.add_(y)
b = x + x
return a == b
self.checkScript(fn, (torch.rand(2, 3), torch.rand(2, 3)))
def test_module_attrs(self):
class M(tor... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import namedtuple
from random import randint
from random import uniform
from random import choices
from random import seed
from multiprocessing import Process, Queue
import numpy as np
import numbers
# 'Model' controls single individuals,
# Whereas 'Treib... | |
# -*- coding: utf-8 -*-
"""
This module needs serious refactoring and testing
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import shelve
import six
import uuid
import json
import codecs
import os
#import lru
#git+https://github.com/amitdev/lru-dict
#import atexit
#import inspec... | |
mem_aval_pct = util.get_value_from_second_level_of_dict(ns_stats, ("memory_free_pct", "free-pct-memory"),
default_value=0, return_type=int)
mem_aval = util.pct_to_value(mem_size, mem_aval_pct)
cl_nodewise_mem_size = util.add_dicts(cl_nodewise_mem_size, mem_size)
cl_nodewise_mem_aval = util.add_dicts(cl_nodewise_mem... | |
<filename>Codes/CNN_More_complex_example.py
# File: CNN_More_complex_example.py
# Description: Neural Networks for computer vision in autonomous vehicles and robotics
# Environment: PyCharm and Anaconda environment
#
# MIT License
# Copyright (c) 2018 <NAME>
# github.com/sichkar-valentyn
#
# Reference to:
# <NAME>. Neu... | |
# -*- coding: utf-8 -*-
import unreal
import os
from Utilities.Utils import Singleton
from Utilities.Utils import cast
import Utilities
import QueryTools
import re
import types
import collections
from .import Utils
global _r
COLUMN_COUNT = 2
class DetailData(object):
def __init__(self):
self.filter_str = ""
self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.