input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<reponame>umairwaheed/scrapy-do
#-------------------------------------------------------------------------------
# Author: <NAME> <<EMAIL>>
# Date: 26.11.2017
#
# Licensed under the 3-Clause BSD License, see the LICENSE file for details.
#-------------------------------------------------------------------------------
... | |
<filename>ma_option_vol/VIX_calculation.py
import numpy as np
import datetime as dt
from iv_calculation import days_till_expiration
class Option_Contract_Data():
'''
Defines data for an option contract on a given date
'''
def __init__(self, option_description, exp_date, strike_price, px_last, px_bid, px_ask):
s... | |
# spicierModbus2mqtt - Modbus TCP/RTU to MQTT bridge (and vice versa)
# https://github.com/mbs38/spicierModbus2mqtt
#
# Written in 2018 by <NAME> <<EMAIL>>
#
#
# Provided under the terms of the MIT license.
# Contains a bunch of code taken from:
# modbus2mqtt - Modbus master with MQTT publishing
# Written and (C) 20... | |
############################################################################
# Copyright 2019 <NAME> #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/lice... | |
# ./econfirmation.py
# -*- coding: utf-8 -*-
# PyXB bindings for NM:ea6fc53702d74154a12297ea3787ddddc34f5684
# Generated 2015-02-11 21:35:49.977166 by PyXB version 1.2.4 using Python 2.6.9.final.0
# Namespace urn:eSENS:xsd:ElectronicConfirmationRequest
from __future__ import unicode_literals
import pyxb
import pyxb.bi... | |
getting All TV Shows:", sys.exc_info()[0])
raise
cur.close() # Close the cursor
conn.close() # Close the connection to the db
return None
#####################################################
# Get all movies
#####################################################
def get_allmovies():
"""
Get all the Movies in yo... | |
self.dt(v)
v_t0 = self.fwd_dt(v[:,:,0:3])
v_tn = self.bwd_dt(v[:,:,-3:])
v_t = torch.cat((v_t0, v_t, v_tn), dim=2)
v_t = v_t.reshape(len_d, len_h, len_w, len_b, len_c, len_t)
v_t = v_t.permute(5,3,4,0,1,2) # [t,b,c,d,h,w]
############### corresponding u & v ###################
u = output[:, :, 0:1, 2:-... | |
1.)
def _compute_unreduced_loss_impl(self, labels, logits, mask=None):
"""See `_RankingLoss`."""
if mask is None:
mask = utils.is_label_valid(labels)
def circle_loss_pairwise_op(score_i, score_j):
alpha_i = tf.stop_gradient(
tf.nn.relu(1 - score_i + self._margin), name='circle_loss_alpha_pos')
alpha_j = tf.st... | |
# Functions to do various things with compound structures
import os
import re
import pdb
import numpy as np
import molvs
from rdkit import Chem
from rdkit.Chem import AllChem, Draw, Descriptors
stdizer = molvs.standardize.Standardizer(prefer_organic=True)
uncharger = molvs.charge.Uncharger()
def get_rdkit_smiles(o... | |
import matplotlib.pyplot as plt
import os
import pandas
import numpy as np
from spinedb import SpineDB
import pandas as pd
def get_participating_technologies_in_capacity_market(db_emlab_powerplantdispatchplans, years_to_generate, years_emlab,
db_emlab_powerplants):
"""
This function returns all participating techn... | |
by `ptype` and can either be uniform, or always X, Y, or Z errors.
The dictionary returned is in the appropriate format for the
`circuit_simulator_for_tensored_independent_pauli_errors()` circuit simulator function.
Parameters
----------
pspec : QubitProcessorSpec
The QubitProcessorSpec that defines the device.... | |
cor updates automatically in pipeline
self.setCenterButton.hide()
plabel = QtGui.QLabel('Overlay Projection No:')
plabel.setAlignment(QtCore.Qt.AlignRight)
spinBox = QtGui.QSpinBox(parent=self.cor_widget)
spinBox.setRange(0, data.shape[0]-1)
slider = QtGui.QSlider(orientation=QtCore.Qt.Horizontal, parent=self.co... | |
# Copyright (C) 2022 <NAME> and <NAME>.
# Schutweg 15a
# 5145 NP Waalwijk
# The Netherlands
# http://www.hbm.com
# 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, includin... | |
self.path['LEV'][i,0,:ilev+1]), self.path['FREE'][i,0,:])
zw = np.append(np.append(self.path['TEV'][i,1,:itev+1], self.path['LEV'][i,1,:ilev+1]), self.path['FREE'][i,1,:])
W = self.airfoil_downwash(circulation, xw, zw, i)
# Compute A0, A1 coefficients
A0 = - 1/pi * np.trapz(W/Uinf , theta_panel)
A1 = 2/pi * np.tra... | |
<gh_stars>0
from keras.layers import Conv2D
from keras import backend as K
from keras.engine.topology import Layer
from keras.activations import softmax
from keras import backend as K
from keras.engine.topology import Layer
import numpy as np
from keras import backend as K
from keras.engine.topology import Layer
impo... | |
<filename>typings/bl_ui/properties_physics_dynamicpaint.py<gh_stars>1-10
import sys
import typing
import bpy_types
class PHYSICS_UL_dynapaint_surfaces(bpy_types.UIList, bpy_types._GenericUI):
bl_rna = None
''' '''
id_data = None
''' '''
def append(self, draw_func):
'''
'''
pass
def as_pointer(self):
''... | |
@type top: int
@type right: int
@type bottom: int
"""
return self._append(emr._ELLIPSE(((left, top), (right, bottom))))
def Rectangle(self, left, top, right, bottom):
"""
Draw a rectangle using the current pen.
@param left: x position of left side of ellipse bounding box.
@param top: y position of top side ... | |
+ m.x117 == 0.2)
m.c21 = Constraint(expr= m.x19 + m.x22 + m.x25 + m.x28 - m.x117 + m.x118 == 0.8)
m.c22 = Constraint(expr= - m.x3 + m.x30 + m.x33 + m.x36 + m.x39 + m.x42 - m.x45 - m.x60 - m.x75 - m.x119 + m.x120 == 0)
m.c23 = Constraint(expr= - m.x4 + m.x31 + m.x34 + m.x37 + m.x40 + m.x43 - m.x46 - m.x61 - m.x76 - m... | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
from functools import partial
import builtins
import gc
from enum import Enum
from itertools import islice
import operator
import copy
import inspect
import itertools
from types import MethodTyp... | |
:
O00oo00o000o = IIiO0Ooo . rloc
if ( rloc . is_exact_match ( O00oo00o000o ) ) : return ( IIiO0Ooo )
if 50 - 50: IiII - II111iiii
return ( None )
if 10 - 10: OoooooooOO % Ii1I * OOooOOo + IiII * oO0o
if 13 - 13: II111iiii
def get_rloc_by_interface ( self , interface ) :
for IIiO0Ooo in self . rloc_set :
if ( I... | |
<reponame>FYPYTHON/method
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/12/31 14:06
# @Author : <EMAIL>
# @File : erasecover.py
# @Software: PyCharm
from kazoo import client
class Solution:
def eraseOverlapIntervals(self, intervals):
if not intervals:
return 0
intervals.sort(key=lambda x: x[1])
co... | |
beta=0)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
cl1 = clahe.apply(cvuint8)
ret1, th1 = cv2.threshold(cl1, bglb, 255, cv2.THRESH_TOZERO)
ret1, th1 = cv2.threshold(th1, bgub, 255, cv2.THRESH_TOZERO_INV)
th1 = th1.astype('uint8')
#cv2.imwrite(saveName+"_clahe_thres128BG.png", th1)
gb = cv2.Gaus... | |
aratio1 = c/a this gives c = aratio1*a
# aratio2 = b/a this gives b = aratio2*a
# volume = 4/3 pi a*b*c for an ellipsoid
vol = 1*aratio1*aratio2
rad_cor = pow(vol,-1./3.)
v[:,2] *= aratio1*rad_cor # make oblate, adjusts z coords
v[:,1] *= aratio2*rad_cor # make elongated in xy plane , adjusts y coords
v[:,0] *= ... | |
#Copyright (c) Microchip. All rights reserved.
#Import needed python packages
import sys
import time #For delays and getting current time
import smbus
from array import array #For handling samples
import statistics #For signal filtration
import MAX30100_definitions as MAX30100 #MAX30100 registers definitions
#Python ... | |
'Wonderboom Airport', 'South Africa'],
['PRZ', 'Prineville (OR)', 'Prineville', 'USA'],
['PSA', 'Florence', 'Galileo Galilei', 'Italy'],
['PSB', 'Philipsburg (PA)', 'Mid-State', 'USA'],
['PSC', 'Pasco (WA)', 'Tri-Cities', 'USA'],
['PSD', 'Port Said', 'Port Said', 'Egypt'],
['PSE', 'Ponce', 'Mercedita', 'Puerto Ri... | |
<reponame>renefritze/mpi4py
# Author: <NAME>
# Contact: <EMAIL>
"""Pickle-based communication using protocol 5."""
import sys as _sys
import struct as _struct
from .. import MPI
from ..MPI import (
PROC_NULL,
ANY_SOURCE,
ANY_TAG,
Status,
)
from ..MPI import (
_typedict,
_comm_lock,
_commctx_inter,
memory as ... | |
<filename>tests/test_slippage.py
# Copyright 2018 QuantRocket LLC - 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
#
# Unle... | |
import os
import re
import time
import glob
import hashlib
import requests
import cv2 as cv
from .forms import *
from .models import *
import urllib.request
from PIL import Image
from django.shortcuts import render
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
from... | |
cutoff=atol,
cache=cache,
equalize_norms=equalize_norms,
**loop_simplify_opts)
elif meth == 'P':
tn.pair_simplify_(output_inds=ix_o, cutoff=atol,
cache=cache,
equalize_norms=equalize_norms,
**loop_simplify_opts)
else:
raise ValueError(f"'{meth}' is not a valid simplify type.")
old_nt, old_ni = nt, ni
nt, n... | |
import numpy as np
'''global constants'''
# Maximum supported configurations
gtrack_NUM_POINTS_MAX = 1000
gtrack_NUM_TRACKS_MAX = 250
# Target ID definitions
gtrack_ID_POINT_TOO_WEAK = 253
gtrack_ID_POINT_BEHIND_THE_WALL = 254
gtrack_ID_POINT_NOT_ASSOCIATED = 255
# Boundary boxes
gtrack_MAX_BOUNDARY_BOXES = 2
gtrac... | |
<filename>tools/json_schema_compiler/cc_generator.py<gh_stars>1-10
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from code import Code
from model import PropertyType
import any_helper
import cpp_util... | |
import logging
import os
import sys
import traceback
import threading
import asyncio
import time
import traceback
import numpy as np
import torch
import ray
from collections import namedtuple, defaultdict
from concurrent.futures import ThreadPoolExecutor
from readerwriterlock import rwlock
from torch._C import dtype
... | |
with a specific UUID.
:param userID: the users's UUID
:type userID: string
:rtype: list of dicts representing publishers
"""
# https://api.relayr.io/users/%s/publishers
url = '{0}/users/{1}/publishers'.format(self.host, userID)
_, data = self.perform_request('GET', url, headers=self.headers)
return data
def ... | |
# -*- coding:utf-8 -*-
# Copyright xmuspeech (Author: JFZhou 2019-11-18)
# Updata xmuspeech (Author: <NAME> 2020-12-31)
import scipy
import numpy as np
import math
import os
import kaldi_io
import sys
import logging
'''
Modified from the code avaliable at https://github.com/vzxxbacq/PLDA/blob/master... | |
import http.cookies
import grpc
import pytest
from google.protobuf import empty_pb2, wrappers_pb2
from sqlalchemy.sql import delete, func
from couchers import errors
from couchers.crypto import hash_password, random_hex
from couchers.db import session_scope
from couchers.models import (
ContributeOption,
Contributo... | |
<reponame>ultimateabhi719/ChIA-PIPE
#!/usr/bin/env python
"""
test_oldindex.py
Used to run tests on the test files found in /samples/old_index2/
From root, execute using `python test/test.py`
First, ensure you have fully installed the pypairix package:
`pip install pypairix --user`
OR
`sudo python setup.py install`
If... | |
#standard
import time
import unittest
import os
import sys
import xml.etree.ElementTree as ET
from copy import deepcopy
#TCA
from TCACore import logger, curdir, control_values, strategy_values
class ControlFiles():
"""
Call for reading and validating all Control Files
"""
def __init__(self, control_file = 'TCA... | |
'mount_fuji', 'mount_fuji'),
(b'\xe2\x9b\xb0', 'mountain', 'mountain_vs16'),
(b'\xf0\x9f\x9a\xb5', 'mountain_bicyclist', 'mountain_bicyclist', 'person_mountain_biking'),
(b'\xf0\x9f\x9a\xb5\xf0\x9f\x8f\xbb', 'mountain_bicyclist_tone1', 'mountain_bicyclist_tone1', 'person_mountain_biking_tone1'),
(b'\xf0\x9f\x9a\xb5... | |
<reponame>N5GEH/FiLiP
"""Vocabulary Models for Ontology Entities"""
from enum import Enum
from pydantic import BaseModel, Field
from typing import List, TYPE_CHECKING, Dict, Union, Set
from .source import DependencyStatement
if TYPE_CHECKING:
from . import \
CombinedObjectRelation, \
CombinedDataRelation, \
Comb... | |
import numpy as np
import gudhi as gd
from numpy.lib.stride_tricks import as_strided
import tensorflow as tf
from tensorflow.python.framework import ops
import timeit
def compute_dgm(f, card, hom_dim):
"""
Computes the persistence diagram of an image.
:param f: image
:param card: maximum number of bars kept
:par... | |
<filename>src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/_help.py
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for ... | |
from models.base import ImplicitSurface, NeRF, RadianceNet
from utils import rend_util, train_util
import copy
import functools
import numpy as np
from tqdm import tqdm
from typing import Optional
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
# def pdf_phi_s(x... | |
\"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is de... | |
<gh_stars>1-10
# Author: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# License: BSD Style.
import sys
import warnings
import itertools
import operator
from abc import ABCMeta, abstractmethod
import numpy as np
from scipy import sparse
from .base import LinearModel
from ..base import R... | |
<reponame>dopplerchase/GewitterGefahr
"""Unit tests for polygons.py."""
import unittest
import numpy
import shapely.geometry
from gewittergefahr.gg_utils import polygons
from gewittergefahr.gg_utils import projections
TOLERANCE = 1e-6
TOLERANCE_DECIMAL_PLACE = 6
# The following constants are used to test _get_longes... | |
# SOURCE: https://github.com/tiangolo/fastapi/issues/1800
# #2: https://github.com/encode/starlette/issues/658
from collections import defaultdict, deque
from datetime import datetime as dt
from asyncpg import create_pool
from json import dumps, loads
from copy import deepcopy
from os import environ
from re import find... | |
<gh_stars>1-10
#! /usr/bin/python3
"""
Datastreams are identified by the address that publishes them, and referenced
in transaction outputs.
For CFD leverage, 1x = 5040, 2x = 10080, etc.: 5040 is a superior highly
composite number and a colossally abundant number, and has 1-10, 12 as factors.
All wagers are in XCP.
... | |
<reponame>zepheira/versa
#versa.pipeline.other_actions
import itertools
from amara3 import iri
from versa import I, VERSA_BASEIRI, ORIGIN, RELATIONSHIP, TARGET, ATTRIBUTES, VTYPE_REL
#from versa.terms import VFPRINT_REL
#from versa import util
#from versa.util import simple_lookup
from . import context, materialize... | |
file_fastq_3,
file_fastq_4,
file_bam_1_1,
file_bam_2_1,
file_tsv_1_2,
mad_quality_metric_1_2,
chip_seq_quality_metric,
chipseq_filter_quality_metric,
analysis_step_run_bam,
analysis_step_version_bam,
analysis_step_bam,
pipeline_bam):
testapp.patch_json(chip_seq_quality_metric['@id'], {'quality_metric_of': ... | |
<filename>cogs/misc.py
import datetime
import asyncio
import strawpy
import random
import re
import requests
from PythonGists import PythonGists
from appuselfbot import bot_prefix
from discord.ext import commands
from discord import utils
from cogs.utils.checks import *
from bs4 import BeautifulSoup
from pyfiglet impor... | |
<gh_stars>1-10
# coding: utf-8
# Consider the data in the files a100.csv, b100.csv, s057.csv. Try to determine the
# underlying probability distributions of each data set.
# In[3]:
# Using pandas library for CSV reading and table manipulation
import pandas
import matplotlib.pyplot as plt
# In[293]:
# Reading a1... | |
2857: SChildCategory(b=array([24]), m=array([200]), lbl='프린터 공유기'),
2858: SChildCategory(b=array([14]), m=array([290]), lbl='암워머'),
2859: SChildCategory(b=array([54]), m=array([502]), lbl='미용실'),
2860: SChildCategory(b=array([1]), m=array([1]), lbl='보드게임용품'),
2861: SChildCategory(b=array([34]), m=array([332]), lbl=... | |
<reponame>cpressey/grin
#!/usr/bin/env python
""" grin searches text files.
"""
from __future__ import print_function
import bisect
import fnmatch
import gzip
import itertools
import os
import re
import shlex
import stat
import sys
from io import UnsupportedOperation
import argparse
if sys.version_info[0] > 2:
to_s... | |
import unittest
from cpuinfo import *
import helpers
class MockDataSource(object):
bits = '64bit'
cpu_count = 4
is_windows = False
arch_string_raw = 's390x'
uname_string_raw = ''
can_cpuid = False
@staticmethod
def has_proc_cpuinfo():
return True
@staticmethod
def has_dmesg():
return True
@staticm... | |
<reponame>tinyg/ironpython2
import sys, itertools, unittest
from test import test_support
from StringIO import StringIO
import ast
import types
def to_tuple(t):
if t is None or isinstance(t, (basestring, int, long, complex)):
return t
elif isinstance(t, list):
return [to_tuple(e) for e in t]
result = [t.__class_... | |
<reponame>dsaharov/psychojs-server
import json
from logger import log
import os
import tempfile
from werkzeug.utils import secure_filename
from import_study import import_study
import datetime
import shutil
import subprocess
from contextlib import contextmanager
from dateutil.parser import parse as parse_datestr
import... | |
self.lineEdit_predSample = QtWidgets.QLineEdit(self)
self.button_importKeys = QtWidgets.QPushButton('Import Keys', self)
self.button_predBP = QtWidgets.QPushButton('Pred-NMAG', self)
self.button_bpMatSaveDir = QtWidgets.QPushButton('NMAG-SaveDir', self)
self.lineEdit_bpMatSaveDir = QtWidgets.QLineEdit(self)
self.b... | |
ID (required)
:param DeviceDataSourceInstance body: (required)
:return: DeviceDataSourceInstance
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.add_device_datasource_instance_with_http_info(device_id, hds_id... | |
"""
Elements
========
Defines an :class:`.Atom` class for each element.
"""
from __future__ import annotations
import typing
from .atom import Atom
_T = typing.TypeVar('_T', bound='AtomImpl')
class AtomImpl(Atom):
"""
An implementation of the :class:`.Atom` interface.
"""
_atomic_number: typing.ClassVar[i... | |
point_cloud = list()
point_cloud.append((4.157333 ,5.020408 ,6.752996))
point_cloud.append((2.641909 ,5.020408 ,6.808028))
point_cloud.append((2.642918 ,4.106757 ,6.802344))
point_cloud.append((4.155944 ,4.106757 ,6.747401))
point_cloud.append((1.685477 ,5.020408 ,-0.064397))
point_cloud.append((3.157898 ,5.020408 ,-0.... | |
return x
scripted = torch.jit.script(grad_in_loop)
outer = scripted.graph_for(x, y)
loop = outer.findNode("prim::Loop")
loop_block = next(loop.blocks())
param_node = loop_block.paramNode()
x_value = list(param_node.outputs())[1]
self.assertTrue(x_value.requires_grad())
def test_tensor_grad(self):
x = torch.r... | |
def cluster_change_slider(self, value):
self.cluster_slider_val = value
self.cluster_sld_label.setText( str( value ) )
def palette_change_slider(self, value):
self.palette_slider_val = value
self.palette_sld_label.setText( str( value ) )
def blend_change_slider(self, value):
self.blend_slider_val = value
se... | |
SecondaryIpv4Address(object):
"""
A VRRP secondary IPv4 address
.. attribute:: ip_address <key>
VRRP Secondary IPv4 address
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
... | |
e
o
f
t
h
e
a
c
c
i
d
e
n
t
.
Type `CodeableConcept` (represented as `dict` in JSON). """
super(ExplanationOfBenefitAccident, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(ExplanationOfBenefitAccident, self).elementProperties()
js.extend([
("date", "dat... | |
self.obs_dim = obsDim
high = np.inf*np.ones(self.obs_dim)
low = -high
self.observation_space = spaces.Box(low, high)
#set what this skeleton's init pose should be
#only call this whenever initial base pose _actually chagnes_ (like upon loading)
def setStartingPose(self):
#initPose is base initial pose that get... | |
import random
import uuid
from copy import deepcopy
from datetime import datetime, timedelta, timezone
from queue import Empty
import requests
import pytest
import time
HOUR_MILLISEC = 1000 * 3600
def test_outcomes_processing(relay_with_processing, mini_sentry, outcomes_consumer):
"""
Tests outcomes are sent to t... | |
##########################################################################################
#
# Copyright (c) 2017 The MadGraph5_aMC@NLO Development team and Contributors
#
# This file is a part of the MadGraph5_aMC@NLO project, an application which
# automatically generates Feynman diagrams and matrix elements for arbi... | |
<filename>scale/storage/test/test_models.py
from __future__ import unicode_literals
import datetime
import os
import django
import django.contrib.gis.geos as geos
from django.db import transaction
from django.test import TestCase, TransactionTestCase
from django.utils.text import get_valid_filename
from django.utils.... | |
# This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2013 <NAME> and contributors
#
# License: Standard 3-clause BSD; see "license.txt" for full license terms
# and contributor agreement.
"""
Implements support for HDF5 compression filters via the h... | |
import torch.optim
import math
import pickle
from pathlib import Path
import utils
import time
import pkbar
from snn_backprop import *
class Trainer():
def __init__(self, config, data_loaders, logger, gpu=False, task='nmnist') :
"""
Initialize Trainer class.
Args
config : Configuration object that contains all ... | |
import numpy as np
from myutils import *
from easydict import EasyDict as edict
def dcg_at_k(r, k, method=1):
r = np.asfarray(r)[:k]
if r.size:
if method == 0:
return r[0] + np.sum(r[1:] / np.log2(np.arange(2, r.size + 1)))
elif method == 1:
return np.sum(r / np.log2(np.arange(2, r.size + 2)))
else:
raise Valu... | |
<filename>tests/test_framework/revault_network.py
import bip32
import logging
import os
import random
from ephemeral_port_reserve import reserve
from nacl.public import PrivateKey as Curve25519Private
from test_framework import serializations
from test_framework.bitcoind import BitcoindRpcProxy
from test_framework.coo... | |
# Copyright 2015 - Mirantis, Inc.
# Copyright 2015 - StackStorm, 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 app... | |
import qiskit, time
from numpy import pi
# define pi so that in string gates we can have pi as an angle.
# Because we use eval for string gates. For example, gate = "rz(pi/2, 1)".
name = "IBM"
simulators = simulator, unitary_simulator, state_simulator = (
"qasm_simulator", "unitary_simulator",
"statevecto... | |
or -n flags.', 'the -s and -n flags will be handled internally based on the alignment you input.')
except ValueError, (ErrorTitle, ErrorMessage, ErrorDescription):
self.message(str(ErrorTitle), str(ErrorMessage), str(ErrorDescription))
return
self.raxmlOperations.raxml_species_tree(self.raxmlOperations.inputFilen... | |
<gh_stars>1-10
import numpy as np
import scipy.optimize
from .c_fastpixelint import pixelintegrate
from .integrate import radintpix, azimintpix, radint_nsector
from .. import misc
from ..misc.basicfit import findpeak_asymmetric
from ..misc.errorvalue import ErrorValue
def findbeam_gravity(data, mask):
"""Find beam ... | |
datnum: int = None
# threshold: float = None
# param: str = None
# param_values: np.ndarray = None
# zscores: np.ndarray = None
# accepted_rows: np.ndarray = None
# rejected_rows: np.ndarray = None
# x: np.ndarray = None
# avg_data: np.ndarray = None
# avg_data_std: np.ndarray = None
# avg_fit: DA.FitInfo = None
# orig... | |
<gh_stars>0
""" Utility functions used in osxphotos """
import datetime
import fnmatch
import glob
import hashlib
import importlib
import inspect
import logging
import os
import os.path
import pathlib
import platform
import re
import sqlite3
import subprocess
import sys
import unicodedata
import urllib.parse
from plis... | |
<reponame>rsdeng/mlab
# -*- encoding: utf-8 -*-
#############################################################################
################## awmstools : Common functions for python ###################
##############################################################################
##
## o author: <NAME> (<EMAIL>)
## ... | |
import csv
import random
from constants import Transport
from utils import sort_by_value
def merge_dicts(base, to_merge, operation):
""" Merge to_merge dict in base dict applying and operation when keys are the same"""
for k, v in to_merge.items():
if k in base:
base[k] = operation(base[k], v)
else:
base[k] = ... | |
<gh_stars>1-10
#! /usr/bin/env python3
# -*- coding:utf-8 -*-
"""
################################################################################
PyEdit :a Python/tkinter text file editor and component.
Uses the Tk text widget, plus GuiMaker menus and toolbar buttons to
implement a full-featured text editor ... | |
from django.db import models
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.utils import timezone
from django.utils.translation i... | |
need to provide a tuple of 2 elements not ' + type(value))
pool, list_input = value
self._delitem(key)
node = ElementTree.SubElement(self.rootnode(self.instance), 'pool')
node.attrib['name'] = key
if pool and pool.uri:
node.attrib['output-uri'] = pool.uri
for inart in list_input:
sub = ElementTree.Element('inpu... | |
__all__ = [
"bump_version",
"check_version",
"get_version",
"serialize_pep440",
"serialize_pvp",
"serialize_semver",
"Style",
"Vcs",
"Version",
]
import copy
import datetime as dt
import re
import shlex
import shutil
import subprocess
from collections import OrderedDict
from enum import Enum
from functools im... | |
# Copyright 2015 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | |
'''
Copyright or © or Copr.
This software is a computer program whose purpose is to generate random
test case from a template file describing the data model.
This software is governed by the CeCILL-B license under French law and
abiding by the rules of distribution of free software. You can use,
modify and/ or redi... | |
0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j,
0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j,
0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j,
0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j,
0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j,
0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+... | |
from time import time
from random import randrange, seed
import numpy as np
#import pandas as pd
import cv2
#import sys
from sklearn.cluster import KMeans
from scipy.optimize import linear_sum_assignment
from scipy.spatial.distance import cdist
#from random import randrange, seed
class Tracktor():
def __init__(sel... | |
#!/bin/python2
from __future__ import print_function
from gensim.parsing.preprocessing import strip_non_alphanum, preprocess_string
from gensim.corpora.dictionary import Dictionary
from keras.models import load_model
import numpy as np
import os
import subprocess
try:
input = raw_input
except NameError:
pass
try:
m... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Script to update prebuilt versions of the projects."""
import argparse
import glob
import io
import json
import logging
import os
import platform
import re
import subprocess
import sys
from l2tdevtools import presets
from l2tdevtools import projects
from l2tdevtools im... | |
def part1(instructions):
regs = {}
lines = instructions.split("\n")
for line in lines:
line = line.replace('is', '_is')
row = line.split()
reg_key = row[0]
test_key = row[4]
direction = row[1]
inc = int(row[2])
test = ' '.join(row[4:])
try:
regs[reg_key]
except KeyError:
regs[reg_key] = 0
try:... | |
Distance per class per epoch on reconstructed iSEG image",
every=1,
params={
"title": "Hausdorff Distance per class per epoch on reconstructed iSEG image",
"legend": ["CSF", "GM", "WM"]}), Event.ON_TEST_EPOCH_END) \
.with_event_handler(
PlotCustomLinePlotWithLegend(visdom_logger,
"Hausdorff Distance per class pe... | |
{"1": {}, "2": {}, "3": {}, "4": {}},
"bstunGroupEntry": {"2": {}, "3": {}, "4": {}, "5": {}},
"bstunPortEntry": {"1": {}, "2": {}, "3": {}, "4": {}},
"bstunRouteEntry": {
"10": {},
"11": {},
"12": {},
"13": {},
"14": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"cAal5VccEntry"... | |
If `True`, use locking during the operation.
name: the name of the operation.
Returns:
The updated variable.
Raises:
TypeError: if `sparse_delta` is not an `IndexedSlices`.
"""
if not isinstance(sparse_delta, indexed_slices.IndexedSlices):
raise TypeError(f"Argument `sparse_delta` must be a "
f"`tf.IndexedSl... | |
+ m.x684 + m.x685 + m.x686 + m.x725 + m.x726 + m.x727 + m.x728
+ m.x729 + m.x730 + m.x731 + m.x809 + m.x810 + m.x811 + m.x812 + m.x813 + m.x814 + m.x815
<= 124)
m.c27 = Constraint(expr= m.x119 + m.x120 + m.x121 + m.x122 + m.x123 + m.x124 + m.x125 + m.x126 + m.x127 + m.x159
+ m.x160 + m.x161 + m.x162 + m.x163 + m.x1... | |
- m.b168 + 2*m.b168*m.b392 + 2*m.b168*m.b396 - 2*m.b168*m.b436
- 2*m.b168*m.b445 + 2*m.b168*m.b490 - 3*m.b490 + 2*m.b168*m.b494 - m.b494 - 2*m.b168*m.b529
- 2*m.b168*m.b547 + 2*m.b169*m.b327 - 8*m.b169 + 2*m.b169*m.b335 + 2*m.b169*m.b339 + 2*m.b169
*m.b366 + 2*m.b169*m.b374 + 2*m.b169*m.b378 - 2*m.b169*m.b433 + 2*m.... | |
<filename>sdk/machinelearning/azure-mgmt-guestconfig/azure/mgmt/guestconfig/models/_models_py3.py<gh_stars>1000+
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in th... | |
#
# * The source code in this file is based on the soure code of CuPy.
#
# # NLCPy License #
#
# Copyright (c) 2020-2021 NEC Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistr... | |
<filename>deepppl/translation/stan2ir.py
"""
Copyright 2018 IBM Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by appl... | |
import copy
from random import shuffle
import numpy as np
import json
import os
import time
import matplotlib.pyplot as plt
from sklearn.linear_model import SGDClassifier, PassiveAggressiveClassifier, Perceptron, SGDRegressor, PassiveAggressiveRegressor
from sklearn.naive_bayes import MultinomialNB, GaussianNB, Bernoul... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.