input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<gh_stars>0
from .header import *
from .biencoder import BERTBiEncoder
'''Cross-Attention BertRetrieval'''
class BERTRetrieval(nn.Module):
def __init__(self, model='bert-base-chinese'):
super(BERTRetrieval, self).__init__()
self.model = BertForSequenceClassification.from_pretrained(model, num_labels=2)
def forw... | |
<gh_stars>0
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2021 <NAME>, <NAME>, <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 limit... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import itertools
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pathlib import Path
import pickle
import seaborn as sns
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_select... | |
<filename>scripts/helpers.py
# helper functions
import numpy as np
def gradient_descent(y, tx, initial_w, max_iters, gamma):
"""
Gradient descent algorithm.
inputs:
y = labels
tx = feature matrix
initial_w = vector of initial weights
max_iters = number of maximum iterations on the loop
gamma : Step size o... | |
###############################################################################
##
## Copyright 2013 Tavendo GmbH
##
## 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.o... | |
import numpy as np
from scipy.ndimage import map_coordinates
from scipy.fftpack import fftn, fftshift, ifftshift
from dipy.reconst.odf import OdfModel, OdfFit, gfa
from dipy.reconst.cache import Cache
from dipy.reconst.multi_voxel import multi_voxel_fit
from dipy.reconst.recspeed import local_maxima, remove_similar_ver... | |
import copy
import os
import secrets
from collections import OrderedDict, defaultdict
from functools import cached_property, lru_cache
from typing import Any, Callable, List, Union
from bs4 import BeautifulSoup
# from pydispatch import dispatcher
from zineb.exceptions import FieldError, ModelExistsError
from zineb.htt... | |
<reponame>Vants/stampsreplacer
import enum
import numpy as np
import os
from scripts.MetaSubProcess import MetaSubProcess
from scripts.funs.PsTopofit import PsTopofit
from scripts.processes.PsEstGamma import PsEstGamma
from scripts.processes.PsFiles import PsFiles
from scripts.utils.ArrayUtils import ArrayUtils
from ... | |
)
# set up shape vars
tgt_len, bsz, embed_dim = query.shape
src_len, _, _ = key.shape
assert (
embed_dim == embed_dim_to_check
), f"was expecting embedding dimension of {embed_dim_to_check}, but got {embed_dim}"
if isinstance(embed_dim, torch.Tensor):
# embed_dim can be a tensor when JIT tracing
head_dim = em... | |
#!/usr/bin/env python
#
# Copyright (c) 2009 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of... | |
<filename>my_widgets.py
import os
from collections import OrderedDict as od
import ipywidgets as ipw
from copy import deepcopy
import pandas as pd
import traitlets
try:
from tkinter import Tk, filedialog
tkinter_available = True
except:
tkinter_available =False
import helper_funcs as helpers
from traceback import ... | |
#!/router/bin/python
from collections import OrderedDict, namedtuple
from scapy.utils import ltoa
from scapy.error import Scapy_Exception
import random
import base64
import string
import traceback
import copy
import imp
from ..common.trex_exceptions import *
from ..common.trex_types import verify_exclusive_arg, val... | |
not None else kw_retries if kw_retries is not None else 0
backoff = backoff if backoff is not None else kw_backoff if kw_backoff is not None else 0.3
intervals = intervals or kw_intervals
if intervals and len(intervals) and all(isinstance(i, (int, float)) for i in intervals):
request_delta = [0] + intervals
else:
... | |
1, 0x4225),
Register('vr2_16_4', 2, 0x4226),
Register('vr2_8_9', 1, 0x4226),
Register('vr2_8_8', 1, 0x4227),
Register('vr2_64_0', 8, 0x4228),
Register('vr2_32_1', 4, 0x4228),
Register('vr2_16_3', 2, 0x4228),
Register('vr2_8_7', 1, 0x4228),
Register('vr2_8_6', 1, 0x4229),
Register('vr2_16_2', 2, 0x422a),
Regis... | |
and outlet")
if ((self.config.pressure_change_type != PressureChangeType.fixed_per_stage)
or (self.config.mass_transfer_coefficient == MassTransferCoefficient.calculated)):
self.length = Var(
initialize=1,
bounds=(1e-8, 1e6),
domain=NonNegativeReals,
units=units_meta('length'),
doc='Effective membrane length')... | |
<reponame>ralic/gnu_pymp3frame
# Copyright (c) 2008 <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, modif... | |
the invoice, which will be shared with the payment provider.
:type provider_data: :obj:`typing.Union[typing.Dict, None]`
:param photo_url: URL of the product photo for the invoice.
:type photo_url: :obj:`typing.Union[base.String, None]`
:param photo_size: Photo size
:type photo_size: :obj:`typing.Union[base.Intege... | |
<gh_stars>0
#Last Update 09/11/2021 by AP
"""
ReadMe:
The workflow for xanes experiment is define below. This macro aims to use one flow for XANES of any given element.
This macro is designed to work with the GUI inputs as well.
To add a new element add the paramer file in the format given below
EXAMPLE OF USAGE:
... | |
LZMA is a
## stream it will uncompress some data. If no data can be decompressed
## at all, it is not a valid LZMA stream.
lzmasizeknown = False
if lzmasizebytes != '\xff\xff\xff\xff\xff\xff\xff\xff':
lzmasize = struct.unpack('<Q', lzmasizebytes)[0]
## XZ Utils rejects files with uncompressed size of 256 ... | |
# base class
import numpy as np
import warnings
class DictNpArrayMix:
""" The basic class of data structure
The member functions are initialized by provided keys in initial function
Member functions can be accessed by using the stype of either Dictonary or numpy.ndarray
"""
def __init__(self, keys, _dat=None, _o... | |
A 1 43 ? 47.059 1.900 1.866 1.00 10.97 ? 43 ARG A CB 1
ATOM 126 C CG . ARG A 1 43 ? 47.883 3.004 2.549 1.00 10.56 ? 43 ARG A CG 1
ATOM 127 C CD . ARG A 1 43 ? 47.060 4.215 3.004 1.00 12.29 ? 43 ARG A CD 1
ATOM 128 N NE . ARG A 1 43 ? 46.128 3.823 4.025 1.00 12.31 ? 43 ARG A NE 1
ATOM 129 C CZ . ARG A 1 43 ? 46.262 ... | |
<filename>micron/stagecontrol.py
#!/usr/bin/env python3
# tertiary Helper
# Unless absolutely necessary, do not use self.controller.send(...)
# Implement the method in micron.py and call that instead
# Abstraction yo
# Advanced level functions combining multiple basic functions are to be implemented here
# Methods in... | |
import itertools
from collections import defaultdict
from functools import partial
from math import ceil
from multiprocessing import Pool
from os import cpu_count
import numpy as np
from numba import njit
from pandas import DataFrame
def __set_matrix(x, phases=None, subset_genes=None, subset_samples=None, rm_zeros=T... | |
re.match('b',Wboard.w2e)and Wboard.w5h==''\
and board.s4g+board.s3f=='':
moves = '2e5h+'
kaihimore(moves)
if oute.oute == 0:
depth1.append(moves)
if re.match('b',Wboard.w2e)and Wboard.w4g==''\
and board.s3f=='':
moves = '2e4g+'
kaihimore(moves)
if oute.oute == 0:
depth1.append(moves)
if re.match('\+b', Wboa... | |
<gh_stars>1-10
"""
This module is a collection of functions to help with multi cam editing, including the multicam class.
Note:
You need scipy for sync
"""
import os
import subprocess
#from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
#from moviepy.video.VideoClip import VideoClip
from moviep... | |
<reponame>jake100/Mathics<gh_stars>1-10
# -*- coding: utf8 -*-
"""
List functions
"""
from mathics.builtin.base import (
Builtin, Test, InvalidLevelspecError,
PartError, PartDepthError, PartRangeError, SympyFunction)
from mathics.builtin.scoping import dynamic_scoping
from mathics.core.expression import Expression,... | |
from __future__ import division, print_function
from functools import partial
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import csv
import h5py
from datetime import datetime, timedelta
import logging
from numpy.random import rand
from time import time
from os.path import exists, join
import... | |
header = "\nScheduled Tasks for Workbook Acceleration"
print_table(rows, columns, header)
if len(workbook_id_without_tasks) > 0:
print("*The Workbook Acceleration views for these workbooks will be updated when they "
"are published, or when their extract is refreshed.")
def get_workbooks_from_paths(server, args):... | |
<gh_stars>1-10
### Functions for magnetic problems with polygonal prisms
import numpy as np
from fatiando import utils
from fatiando.gravmag import polyprism
from fatiando.mesher import PolygonalPrism
from fatiando.constants import CM, T2NT
from copy import deepcopy
### Functions for the foward problem using fatiando... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==============================================================================
#
# check-html-ids.py - Catch and fix id= errors. Makes life easier
# inserting new Navigation Bars without having to renumber dozens of
# existing sections below.
#
# Feb 21 2022 - Initial ve... | |
from collections import Counter
from warnings import warn
from contextlib import suppress
import numpy as np
import matplotlib.collections as mcoll
import matplotlib.lines as mlines
import matplotlib.patches as mpatches
import matplotlib.path as mpath
from ..exceptions import PlotnineWarning
from ..doctools import do... | |
<filename>restclients_core/dao.py
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
import random
import datetime
from restclients_core.util.mock import load_resource_from_path
from restclients_core.util.local_cache import (
set_cache_value, get_cache_value)
from restclients_core.... | |
None,
73741: None,
73742: None,
73743: None,
73744: None,
73745: None,
73746: None,
73747: None,
73748: None,
73750: None,
73751: None,
73752: None,
73753: None,
73754: None,
73755: None,
73756: None,
73757: None,
73758: None,
73759: None,
73760: None,
73761: None,
73762: None,
73763: None,
73764: None,
73765: None,
73... | |
<filename>test/data/ReqMgr/reqmgr2.py
#!/usr/bin/env python
"""
Request Manager service (ReqMgr) test and client script.
The script shall have no WMCore libraries dependency.
Command line interface: --help
There are mandatory command line arguments (e.g. URL of the Request Manager)
Production ConfigCache: https://... | |
# Copyright (c) 2020-2021, NVIDIA CORPORATION & AFFILIATES. 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 requ... | |
raise Exception('sessionUuid of action[RemoveRemoteCidrsFromIPsecConnectionAction] cannot be None')
evt = api.async_call(self, self.sessionUuid)
self.out = evt
return self.out
class RemoveSNSDingTalkAtPersonAction(inventory.APIRemoveSNSDingTalkAtPersonMsg):
def __init__(self):
super(RemoveSNSDingTalkAtPersonActio... | |
hosts_dictionary.keys(): # we ping ourselvels as well
hosts_fping = hosts_fping + host + " "
for srchost in hosts_dictionary.keys():
print
print("Starting ping run from " + srchost + " to all nodes")
fileurl = os.path.join(logdir, srchost + "_" + "all")
command = "ssh -o StrictHostKeyChecking=no " + srchost + \
... | |
flag == 1 and ('pron-det' in pos_tags.columns):
used_features[41] = True
features_pair.append(pos_tags['pron-det'][pair])
else:
features_pair.append(0)
if flag == 1 and ('pron-indp' in pos_tags.columns):
used_features[42] = True
features_pair.append(pos_tags['pron-indp'][pair])
else:
fe... | |
', ' '
# copy to tuples; magnitudes may be modified
major = [major[0], major[1]]
minor = [minor[0], minor[1]]
vertical = [vertical[0], vertical[1]]
if major[0] > 0 :
majordir = major[1]
majoreach = floor(major[0] / 8)
major[0] -= majoreach * 8
if minor[0] > 0 :
minordir = minor[1]
minoreach = floor(minor[0] ... | |
<filename>Desktop Application/Advanced/Python/Sketch With Sam/Sketch With Sam.py
from tkinter import *
from tkinter import messagebox,colorchooser,filedialog
from PIL import ImageTk,Image,ImageGrab
import time
class Sketch:
def __init__(self, root):
#Take window,Window title and Canvas Control
self.window = root
s... | |
single input layer.")
parent = inputs[0]
out_tensor = nn.Softmax(parent)
if set_tensors:
self.out_tensor = out_tensor
return out_tensor
class Sigmoid(Layer):
""" Compute the sigmoid of input: f(x) = sigmoid(x)
Only one input is allowed, output will have the same shape as input
"""
def __init__(self, in_laye... | |
# Copyright (c) 2010-2016 <NAME>
# Copyright (c) 2010-2016 <NAME>
# Copyright (c) 2010-2016 Stony Brook University
# Copyright (c) 2010-2016 The Research Foundation of SUNY
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Soft... | |
"""
Core implementation of :mod:`sklearndf.transformation.wrapper`
"""
import logging
from abc import ABCMeta, abstractmethod
from typing import Any, Generic, List, Optional, TypeVar, Union
import numpy as np
import pandas as pd
from sklearn.base import TransformerMixin
from sklearn.compose import ColumnTransformer
f... | |
<reponame>Class-Tooraj/mosaici<gh_stars>0
from __future__ import annotations
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #
# < IN THE NAME OF GOD > #
# ------------------------------------------ #
__AUTHOR__ = "ToorajJahangiri"
__EMAIL__ = "<EMAIL>"
# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #
# IMPORT
import os
... | |
<gh_stars>10-100
# -*- coding: utf-8 -*-
#
# test/test_runner.py
# Part of python-daemon, an implementation of PEP 3143.
#
# Copyright © 2009 <NAME> <<EMAIL>>
#
# This is free software: you may copy, modify, and/or distribute this work
# under the terms of the Python Software Foundation License, version 2 or
# later as... | |
for iz in range(1, len(col) - 1):
if col[iz] > thresh and col[iz + 1] > thresh:
return Z[iz] + (Z[iz - 1] - Z[iz]) * (col[iz] - thresh) / (
col[iz] - col[iz - 1]
)
return np.nan
def _mld_chunk(chunk, Z=None, smoothed=False, threshold=None):
if chunk.ndim > 1:
result = np.empty(chunk.shape[:-1])
for idxs in np... | |
projection_dim=50, projection_hidden=0, projection_dropout=0.2,
compare_dim=288, compare_dropout=0.2,
dense_dim=50, dense_dropout=0.2,
lr=1e-3, activation='relu'):
q1 = Input(shape=(max_sequence_length,), name='first_sentences')
q2 = Input(shape=(max_sequence_length,), name='second_sentences')
meta_features_inpu... | |
import os
import math
import tensorflow as tf
from collections import namedtuple
from .model import Model
from .builder import MODELS
from core.layers import build_normalization
PARAMS = {
# (width_coefficient, depth_coefficient, resolution, dropout_rate)
"efficientnet-b0": (1.0, 1.0, 224, 0.2),
"efficientnet-b1":... | |
from django.contrib.auth.models import Permission
from django.urls import reverse
from django.utils.http import urlencode
from django.utils.translation import gettext_lazy as _
from django.utils.translation import gettext
from draftjs_exporter.dom import DOM
import wagtail.admin.rich_text.editors.draftail.features as ... | |
if ax == None:
fig, ax = plt.subplots(1,1)
else:
fig = plt.gcf() # will this work like this? <<<
if draw_body:
for body in self.bodyList:
#body.draw(ax)
plt.plot(body.r6[0],body.r6[1],'ko',markersize=5)
j = 0
for line in self.lineList:
j = j + 1
if color==None and isinstance(line.type, str):
if 'chain'... | |
<gh_stars>100-1000
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import collections
import codecs
import functools
import glob
import importlib
import imp
import os
import os.path as pathlib
import sys
try:
from types import FileType # py2
except ImportError:
from io impor... | |
""" Profiles file for all the Profiles classes in Deequ"""
from pydeequ.scala_utils import get_or_else_none, to_scala_seq, to_scala_map, scala_map_to_dict, scala_map_to_java_map, java_list_to_python_list
from pydeequ.pandas_utils import ensure_pyspark_df
from pyspark.sql import SparkSession, DataFrame
from collections... | |
<filename>src/autotrail/workflow/default_workflow/state_machine.py
"""Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://w... | |
Raises TestFailError if the second argument is outside a tolerance
range (defined by the "fudge factor"). The default is 5% of the first
argument.
"""
if fudge is None:
fudge = arg1*0.05
if abs(arg1-arg2) > fudge:
raise TestFailError, \
msg or "%s and %s not within %s units of each other." % \
(arg1, arg2, fud... | |
IOD': ['Patient'],
'SPECTACLE PRESCIPTION REPORT IOD': ['Patient'],
'BASIC TEXT SR IOD': ['Patient'],
'NM IMAGE IOD': ['Patient'],
'BLENDING SOFTCOPY PRESENTATION STATE IOD': ['Patient'],
'LENSOMETRY MEASUREMENTS IOD': ['Patient'],
'MR SPECTROSCOPY IOD': ['Patient'],
'ENCAPSULATED PDF IOD': ['Patient'],
'X-RAY ... | |
################################################################################
# Copyright (C) 2015 Surfacingx #
# #
# This Program is free software; you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation; either version 2, or (a... | |
<reponame>samskivert/farbot<filename>farb/sysinstall.py
# sysinstall.py vi:ts=4:sw=4:expandtab:
#
# Copyright (c) 2006-2008 Three Rings Design, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are me... | |
the moves that friendly pieces can perform to save the king
calculate_white_check_moves()
else:
if all_white_moves & 1 << black_king_eightx_y > 0:
# If the king is in check, discover the type and location of the checking pieces
for move in white_move_list:
if move[1] == black_king_eightx_y:
checke... | |
<gh_stars>1-10
# -*- coding: utf-8 -*-
# @Author: yulidong
# @Date: 2018-07-17 10:44:43
# @Last Modified by: yulidong
# @Last Modified time: 2018-11-05 16:04:44
# -*- coding: utf-8 -*-
# @Author: lidong
# @Date: 2018-03-20 18:01:52
# @Last Modified by: yulidong
# @Last Modified time: 2018-07-16 22:16:14
import time
imp... | |
# list of rooted bridges
bridge_roots.append(bridge)
# iterate over the list of newly created rooted bridges
for bridge in bridge_roots:
# if the vertex is only one non-articulation
# point in the bridge
if len(bridge) == 1:
# that the singular element of the bridge
n = self.adjacencylist[bridge[0]]
# and c... | |
<gh_stars>0
#! /usr/bin/env python
# -*- coding: utf-8 -*-
FASL_GRAPH_DEF_TYPE = 1
FASL_GRAPH_REF_TYPE = 2
FASL_FALSE_TYPE = 3
FASL_TRUE_TYPE = 4
FASL_NULL_TYPE = 5
FASL_VOID_TYPE = 6
FASL_EOF_TYPE = 7
FASL_INTEGER_TYPE = 8
FASL_FLONUM_TYPE = 9
FASL_SINGLE_FLONUM_TYPE = 10
FASL_RATIONAL_TYPE = 11
FASL_COMPLEX_TYPE =... | |
[make_simple_split('split1', 3, True, False, 'off', 'user', True)]
}
split_changes[3] = {'since': 3, 'till': 3, 'splits': []}
sse_server.publish(make_split_change_event(3))
time.sleep(1)
assert factory.client().get_treatment('maldo', 'split1') == 'on'
assert not task.running()
# Validate the SSE requests
sse_r... | |
volume = db.volume_get(self.context, volume['id'])
self.assertEqual('deleting', volume['status'])
db.volume_destroy(self.context, volume['id'])
self.assertRaises(exception.NotFound,
db.volume_get,
self.context,
volume['id'])
def test_extra_capabilities(self):
# Test valid extra_capabilities.
fake_capabilitie... | |
#!/usr/bin/python3
# Copyright © 2021 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR MIT
import argparse
import os
import sys
import pathlib
import shutil
import subprocess
import prctl
import signal
import toml
import pexpect
import plumbum
import re
import errno
from time import sleep
im... | |
7 words)
assert encoded_test_sentences[0, encoder.word_to_index("is")] == approx(1/7., rel=1e-3)
# a occurs once (out of 7 words)
assert encoded_test_sentences[0, encoder.word_to_index("a")] == approx(1/7., rel=1e-3)
# programming occurs once (out of 7 words)
assert encoded_test_sentences[0, encoder.word_to_index(... | |
import gym
from gym.spaces import Discrete, MultiDiscrete, Tuple
import numpy as np
from mujoco_worldgen.util.rotation import mat2quat
from mae_envs.wrappers.util import update_obs_space
from mae_envs.util.geometry import dist_pt_to_cuboid
from copy import deepcopy
from itertools import compress
class GrabObjWrapper(... | |
on_week_days=(FRIDAY(1),),
count=10)
start = datetime(1997, 9, 5, hour=9)
expected = (
datetime(1997, 9, 5, hour=9),
datetime(1997, 10, 3, hour=9),
datetime(1997, 11, 7, hour=9),
datetime(1997, 12, 5, hour=9),
datetime(1998, 1, 2, hour=9),
datetime(1998, 2, 6, hour=9),
datetime(1998, 3, 6, hour=9),
datetime(... | |
"operator_eval", "eval"]
ops = {
"*": operator.mul,
"/": operator.truediv,
"//": operator.floordiv,
"%": operator.mod,
"bitand": operator.and_,
"bitor": operator.or_,
"bitxor": operator.xor,
}
def build(self, tokens):
self.value = tokens[0]
_eval = self._eval = self.value[0].eval
ops = self.ops
operator... | |
"""
This is an explicit DG method: we invert the mass matrix and perform
a matrix-vector multiplication to get the solution in a time step
"""
from math import *
import mpi4py
import numpy as np
from time import time
import sys
import os
import cProfile
from firedrake import *
from firedrake.petsc import PETSc
from ... | |
<gh_stars>1-10
"""Asyncio HTTP/2 client and server sessions based on the :mod:`.nghttp2` Python
wrapper around the nghttp2 API.
"""
import asyncio
import logging
import io
import collections
from urllib.parse import urlparse
from ctypes import string_at
from . import nghttp2
from .messages import Request, Response, Di... | |
by specifying the bit
position which is set in that value.
- An 'offset','extbase','extends' triplet specifies a value
as an offset to a base value defined by the specified
'extbase' extension name, which is then cast to the
typename specified by 'extends'. This requires probing
the registry database, and imbeds ... | |
TVLA.
traces_to_use = np.zeros(len(project.waves), dtype=bool)
traces_to_use[trace_start:trace_end + 1] = True
if i_step == 0:
# Keep a single trace to create the figures.
single_trace = traces[1]
if save_to_disk_trace:
log.info("Saving Traces")
np.savez('tmp/traces.npy', traces=traces, traces_to_use=traces_t... | |
# %% [markdown]
# # Image compression - part 2. - Autoencoders
# In this post I will be looking at building an autoencoder to compress the MNIST dataset.
# See part 1. [here](https://github.com/stanton119/data-analysis/blob/master/PyTorchStuff/autoencoders/pca.md).
#
# Autoencoders build a network to encode the origin... | |
to 1.1, even though the metadata of
# the profile really says 1.0. We will use this to check
# whether the upgrade step has been applied (version is 1.1)
# or the full profile has been applied (version is 1.0).
step_bar = UpgradeStep(
"Upgrade", "other:bar", '1.0', '1.1', '', dummy_upgrade, None, "1")
_registerUp... | |
<reponame>yellcorp/dupescan
import argparse
import os
import sys
import time
import traceback
from collections import defaultdict
from typing import Optional, Iterable, Iterator
from dupescan import (
console,
core,
criteria,
fs,
funcutil,
log,
report,
units,
)
from dupescan.cli._common import add_common_cli_a... | |
from urllib.parse import quote as urlquote
from discord.ext import commands
import classyjson as cj
import asyncio
import discord
import random
import typing
from util.code import format_exception
from util.misc import strip_command
ALPHABET_LOWER = "abcdefghijklmnopqrstuvwxyz"
INSULTS = {"i am stupid", "i am dumb", ... | |
of columns to highlight
headings = [row for row in ws.iter_rows()][0]
headings = [x.value for x in headings]
matching_ = dict.fromkeys(common_columns, 0)
matching = {}
for col in matching_:
matching[col] = 0
matching[col + CHECK_SUFFIX] = 0
for col in headings:
if col in matching.keys():
matching[col] = headi... | |
<filename>win/pywinauto/controls/menuwrapper.py
# GUI Application automation and testing library
# Copyright (C) 2006 <NAME>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either ... | |
if NBnegready == False:
i = numpy.argmin(REX) # Find the sample number with the minimum
Min = REX[i]
if Min < (-1*NBlevel):
NBpeaks = NBpeaks + 1 # A Noise Blanker peak
NOISEblankeractive = True # The noise blanker is active
m1 = i - S1 # The first sample that has to be made zero
if m1 < 0: # Check if in th... | |
<reponame>DerekGloudemans/3D-detector-trials
import os
import re
import pickle
import cv2
import ast
from numpy import array
#from parameters import *
def get_precomputed_checksums(abs_path=None):
path = './resources/timestamp_pixel_checksum_6.pkl'
if abs_path is not None:
path = abs_path
with open(path, 'rb')... | |
<reponame>shirubana/bifacialvf
# -*- coding: utf-8 -*-
"""
ViewFactor module - VF calculation helper files for bifacial-viewfactor
@author <NAME>
@translated to python by sayala 06/09/17
"""
# ensure python3 compatible division and printing
from __future__ import division, print_function, absolute_import
import mat... | |
U1G=-U1*spsp.psi(-1/H-G)
U2G=-U2*spsp.psi(-2/H-G)
U3G=-U3*spsp.psi(-3/H-G)
U4G=-U4*spsp.psi(-4/H-G)
U1H= RHH*(-U1G-U1*spsp.psi(-1/H+1))
U2H=2*RHH*(-U2G-U2*spsp.psi(-2/H+1))
U3H=3*RHH*(-U3G-U3*spsp.psi(-3/H+1))
U4H=4*RHH*(-U4G-U4*spsp.psi(-4/H+1))
DL2G=U1G-2*U2G
DL2H=U1H-2*U2H
DL3G=-U1G+6*U2G-6*U3G
DL3H=-U1H... | |
<gh_stars>1-10
# -*- coding: UTF-8 -*-
import os
import json
import csv
from utils import parse_conf_args, Configuration, path, mysql, log
class trans_goldinfo:
def __init__(self, context, configs):
log_conf = None if context.get("log") is None else context.get("log").get(configs.get("logId"))
# 初始化日志
self.logg... | |
kubernetes_asyncio.client.V1EnvVar(name="OPSANI_ENVOY_PROXY_SERVICE_PORT", value=str(service_port)),
kubernetes_asyncio.client.V1EnvVar(name="OPSANI_ENVOY_PROXIED_CONTAINER_PORT", value=str(container_port)),
kubernetes_asyncio.client.V1EnvVar(name="OPSANI_ENVOY_PROXY_METRICS_PORT", value="9901")
],
ports=[
kuberne... | |
# This file is automatically generated. Do not edit.
glyph2tile = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 28, 29, 30, 31, 32, 34, 35, 36, 37,
38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
62, 63, 64, 65,... | |
'include_tags': self.include_tags, 'exclude_tags': self.exclude_tags,
'C_ACC_Version': self.CC_ACC_Version, 'CPP_ACC_Version': self.CPP_ACC_Version,
'FC_ACC_Version': self.FC_ACC_Version, 'PreCompileCommands': self.PreCompileCommands,
'PostCompileCommands': self.PostCompileCommands, 'PreRunCommands': self.PreRunComm... | |
"""DistributedObjectAI module: contains the DistributedObjectAI class"""
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.distributed.DistributedObjectBase import DistributedObjectBase
from direct.showbase import PythonUtil
from pandac.PandaModules import *
#from PyDatagram import PyDatagram... | |
#!/usr/bin/env python
import json
import os
import os.path
import sys
from argparse import ArgumentParser
from pathlib import Path
import requests
import urllib3
from api.Account import Account
from api.RestApi import RestApi
from api.System import System
from api.Validation import Validation
from github.github impor... | |
num=nfft_half)
m_ns_mag[~vb_voi,:] = m_ns_mag[~vb_voi,:] * v_slope
# Merge data:--------------------------------------------------------------
cf_mag = 5000 #5000
bw_mag = 2000 #2000
cf_cmpx = cf_mag #5000
bw_cmpx = bw_mag #2000
# Alloc:
m_mag_ap = np.zeros((nfrms, nfft_half))
m_mag_det = np.zeros((nf... | |
hlp = {
# Main Menu
"Initial Setup": """
The initial setup required to proceed with the rest of the migration. This
should be configured first, before anything else. The information in this menu
allows the tool to connect to both Nexus and Artifactory, so that it can
properly configure and execute the migration.""",
... | |
import dataclasses
from abc import abstractmethod, ABC
from typing import Optional, Tuple
import torch
import falkon
from falkon.options import FalkonOptions
__all__ = ("Loss", "LogisticLoss")
class Loss(ABC):
r"""Abstract generalized self-concordant loss function class.
Such loss functions must be three times ... | |
setting
auth_settings = ['access_token']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='PortalTemplateFolder',
auth_settings=auth_settings,
callback=params.get('callback'),
_ret... | |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 17 15:52:24 2013
@author: hlampesberger
"""
from base import Result, mapping, epsilon, write_pdf, write_png
import ops
import nfa
import operator
import itertools
import collections
__all__ = ['DFA']
class DFA(object):
def __init__(self, alphabet, states,
start, acc... | |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 23 12:19:34 2020
@author: Mark
"""
import numpy as np
import json
import xlsxwriter
from model.algorithms.algorithm1 import Algorithm1
from model.algorithms.algorithm4 import Algorithm4
from model.algorithms.algorithm5 import Algorithm5
from model.algorithms.algorithm6 im... | |
<filename>sympy/stats/tests/test_rv.py
from __future__ import unicode_literals
from sympy import (
S,
Symbol,
Interval,
exp,
symbols,
Eq,
cos,
And,
Tuple,
integrate,
oo,
sin,
Sum,
Basic,
DiracDelta,
Lambda,
log,
pi,
FallingFactorial,
Rational,
)
from sympy.stats import (
Die,
Normal,
Exponential,... | |
<reponame>rinrini001/omega-miya<filename>omega_miya/utils/omega_plugin_utils/http_fetcher.py
import os
import aiohttp
import aiofiles
import nonebot
from urllib.parse import urlparse
from http.cookies import SimpleCookie as SimpleCookie_
from asyncio.exceptions import TimeoutError as TimeoutError_
from dataclasses impo... | |
1.0 - 18.0/(np.sqrt(14)*np.sqrt(27)))
def test_correlation(self):
xm = np.array([-1.0, 0, 1.0])
ym = np.array([-4.0/3, -4.0/3, 5.0-7.0/3])
for x, y in self.cases:
dist = correlation(x, y)
assert_almost_equal(dist, 1.0 - np.dot(xm, ym)/(norm(xm)*norm(ym)))
def test_mahalanobis(self):
x = np.array([1.0, 2.0, 3.... | |
optics_type; /* Optics type (code)*/
INT32 optics_dx; /* Optics param. - (size microns) */
INT32 optics_dy; /* Optics param. - (size microns) */
INT32 optics_wavelength; /* Optics param. - (size microns) */
INT32 optics_dispersion; /* Optics param. - (*10E6) */
INT32 optics_crossfire_x; /* Optics param. - (... | |
0],
help="Monkhorst-Pack kpoint grid, in format like --kpoints-mp 1 1 1 0 0 0")
gp.add_argument("--kpoints-mp-nscf", type=int, nargs=6,
default=[3, 3, 3, 0, 0, 0],
help="Monkhorst-Pack kpoint grid, in format like --kpoints-mp 3 3 3 0 0 0")
gp.add_argument("--kpath-manual", type=str, nargs="+", default=Non... | |
Parameters
----------
transforms: list of itk.TransformBaseTemplate[itk.D]
Python list of the transforms to write.
filename:
Path to the transform file (typically a .h5 file).
compression:
Use compression, if the file format supports it.
"""
import itk
writer = itk.TransformFileWriterTemplate[itk.D].New()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.