input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
pass
elif self.dPath.exists():
# is this a zip archive?
f = self.dPath.open("rb")
try:
if zipfile.is_zipfile(f):
name, ext = tail.splitext()
if ext.lower() == ".zip":
self.packageName = name
self.ExpandZip(f)
else:
# anything else must be a manifest file
self.dPath = head
mPath = tail
head, tail = self.dP... | |
customer_number, cif_number, notes from bank_details")
bank_data=mycur.fetchall()
bank_details=((tabulate(bank_data, headers=["Bank Name","Acc Holder Name","Acc Number","IFSC Code","Branch Name","Mobile Number","Email ID","Customer Number","CIF Number","Notes"], tablefmt="psql")))
mycur.execute("select card_pr... | |
#Programmer: <NAME>
#Purpose: Load in an ASF file for the geometry/topology of a skeleton
#And load in an AMC file with information for animating that skeleton
#http://research.cs.wisc.edu/graphics/Courses/cs-838-1999/Jeff/ASF-AMC.html
#Motion capture data can be found in the CMU MOCAP database
from OpenGL.GL import *
... | |
# alias for OSError. OSError has a winerror attribute and an
# errno attribute.
# Under Python 2, WindowsError is an OSError subclass.
# Under Python 2.5 and higher on Windows, WindowsError has a
# winerror attribute and an errno attribute.
# The winerror attribute is bound to the Windows error code while
# th... | |
<reponame>tacaswell/pyFAI<filename>pyFAI/test/test_mask.py
#!/usr/bin/env python
# coding: utf-8
#
# Project: Azimuthal integration
# https://github.com/silx-kit/pyFAI
#
# Copyright (C) 2015-2018 European Synchrotron Radiation Facility, Grenoble, France
#
# Principal author: <NAME> (<EMAIL>)
#
# Permission is hereby gr... | |
# """ Create mock boto3 clients for testing """
from datetime import datetime
import boto3
from botocore.stub import Stubber
from logger import LOG
MOCK_COGNITO_USER_POOL_ID = "eu-west-2_poolid"
def _keep_it_real():
""" Keep the native """
if not getattr(boto3, "real_client", None):
boto3.real_client = boto3.cl... | |
dadi.Spectrum.from_phi(phi, (n1,n2), (xx,xx))
# mis-oriented
fsM = dadi.Numerics.reverse_array(fsO)
### Sum the two spectra in proportion O
fs = O*fsO+(1-O)*fsM
return fs
def AMG(params, (n1,n2), pts):
nu1, nu2, b1, b2, m12, m21, Tam, Ts, O = params
"""
Model with split, ancient migration
nu1: Size of pop... | |
dim=2)
all_encoder_outputs = torch.where(mask, torch.tensor(0., device=flair.device), all_encoder_outputs)
# use token embedding as initial hidden state for decoder
if self.encoder_embeddings:
# embed sentences
self.encoder_embeddings.embed(sentences)
# create initial hidden state tensor for batch (num_layers, ... | |
# this file is copied from
# https://github.com/Hadisalman/smoothing-adversarial
# originally written by <NAME>.
from abc import ABCMeta, abstractmethod
import numpy as np
import torch
from torch.autograd import Variable
from torch.nn import CrossEntropyLoss
import torch.nn as nn
import torch.nn.functional as F
impor... | |
#!/usr/bin/env python
#
# iuwandbox.py
#
# Copyright (C) 2014-2018, <NAME>
# This software is released under the new BSD License,
# see LICENSE
#
import os
import sys
import re
import codecs
import argparse
from time import sleep
from argparse import ArgumentParser
from wandbox import Wandbox
from requests.exceptions... | |
For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values.
:type op_PolicyRulesInvalid: String
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param val_f_PolicyRulesInvalid:... | |
# -*- coding: utf-8 -*-
import re
import pytest
from django.core.urlresolvers import reverse
from django_dynamic_fixture import G
from readthedocs.builds.constants import LATEST
from readthedocs.builds.models import Version
from readthedocs.projects.models import HTMLFile, Project
from readthedocs.search.tests.utils... | |
*__17CTempPauseMessage(struct CTempPauseMessage *this)")
del_items(0x80083FBC)
SetType(0x80083FBC, "void ___14CPauseMessages(struct CPauseMessages *this, int __in_chrg)")
del_items(0x80083FF0)
SetType(0x80083FF0, "struct CPauseMessages *__14CPauseMessages(struct CPauseMessages *this)")
del_items(0x80084004)
SetType(0x8... | |
uk_36
+ 4500 * uk_37
+ 160 * uk_38
+ 25281 * uk_39
+ 8 * uk_4
+ 35775 * uk_40
+ 1272 * uk_41
+ 50625 * uk_42
+ 1800 * uk_43
+ 64 * uk_44
+ 130470415844959 * uk_45
+ 141482932855 * uk_46
+ 403869462877 * uk_47
+ 20579335688 * uk_48
+ 51448339220 * uk_49
+ 20 * uk_5
+ 409014296799 * uk_50
+ 578793816225 ... | |
= (35, 120, 10, 'buy')
self.par_boes = [(10, 250), (10, 250), (1, 100), ('buy', 'sell', 'none')]
self.par_count = 4
self.par_types = ['discr', 'discr', 'conti', 'enum']
self.opt_tag = 0
self.data_types = ['close']
self.data_freq = 'd'
self.sample_freq = 'd'
self.window_length = 270
self.assertEqual(self.stg.s... | |
from operator import add, mul
import os
from PyQt4.Qt import QPushButton, SIGNAL, QTextEdit, QScrollArea, QTabWidget, \
QLineEdit, QAbstractTableModel, QModelIndex, Qt, QVariant, QTableView, QIcon,\
QDialogButtonBox, QGridLayout, QLabel, QComboBox, QMenu, QCursor, QListWidget,\
QListWidgetItem, QMessageBox, QString... | |
(masked with %s)" % \
maskedwith
len2 = len(title)
title += "\n" + (len2 * '~')
strg += title + "\n" + str(data_masked) + "\n"
strg += self.get_data_str('refout', underline=True, underchar="-")
strg += self.get_data_str('zerodata', underline=True, underchar="-")
if hasattr(self, 'pixeldq'):
strg += self.get_... | |
CREATED_BY = "createdBy"
DISPLAY_NAME = "displayName"
LAST_MODIFIED_BY = "lastModifiedBy"
LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime"
IS_DEFAULT = "isDefault"
LINKS = "links"
PAGES_URL = "pagesUrl"
PAGES = "pages"
PARENT_NOTEBOOK = "parentNotebook"
PARENT_SECTION_GROUP = "parentSectionGroup"
class Enum60... | |
in games
for slot in slots]) + slack_minus >= c_min,
name="GA1_min_" + str(slot) + "_" + str(ind))
if lazy:
constr.Lazy = lazy
# Break constraints
if c_name == "BR1":
teams = [int(t) for t in constraint["teams"].split(';')]
slots = [int(s) for s in constraint["slots"].split(';')]
mode = constraint["mode2"]
in... | |
0 and randomCharacter == "0":
randomCharacter = aRandom.choice(characters)
chosenCharacters.append(randomCharacter)
return "".join(chosenCharacters)
def randomString(alphabet, length=None, maxLength=20):
"""Generate a random string of characters from a given up a bit.
This function generates and returns a rando... | |
<gh_stars>10-100
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License")... | |
<filename>odincal/odincal/level1b_exporter_32.py
import numpy
import copy
from odin import odin
from pg import DB
from sys import stderr, stdout, stdin, argv, exit
import os
import string
class db(DB):
def __init__(self):
passwd = os.getenv('ODINDB_PASSWD')
DB.__init__(
self,
dbname='odin',
user='odinop',
host... | |
import json
import os
import pprint
from os import listdir
from os.path import isfile, join
import cv2 as cv
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy
import seaborn as sns
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.n... | |
# -*- coding: UTF-8 -*-
"""
Model tests for Workflow
Author: <NAME>
"""
# python
import datetime
import sys
# django
from django.test.client import Client
from django.test import TestCase
from django.contrib.auth.models import User
# project
from workflow.models import *
class ModelTestCase(TestCase):
"""
Testi... | |
# Copyright 2022 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | |
traversal a subgraph may be
revisited. Complexity would be O(V*E).
Let k = number of apps with a vertex that have the in degree > 1 and
that are not leaf apps. We can bind k to be 0<=k<=10000, shall we reach
that app number.
Each node and each vertex will be visited once O(V+E) (root apps
+ vertex to leaf).
On... | |
-1.095550e-02, 5.748574e+00],
[ 4.407484e+02, 4.736099e-01, -5.086917e-01, -6.610682e-01],
[-2.458302e+00, 6.864762e+00, 2.633289e+00, -4.246873e-01],
[-1.839424e+01, -1.194455e+00, 5.659980e+02, -2.567729e+00]]])
Coordinates:
* lat (lat) int64 -90 -45 0 45
* lon (lon) int64 0 90 180 270
* level (level) int64 10... | |
<filename>diofant/core/basic.py
"""Base class for all the objects in Diofant."""
from collections import Mapping, defaultdict
from itertools import zip_longest
from .cache import cacheit
from .compatibility import iterable, ordered
from .decorators import _sympifyit
from .sympify import SympifyError, sympify
class ... | |
value starts
status = PTP_VALUE
else:
log.cl_error("invalid [%s]: key contains with illegal characters",
param)
return None
else:
assert status == PTP_VALUE
if char == "\\":
if escape:
value += "\\"
escape = True
# The escape will be handled together with next char.
continue
if char == delimiter:
if esca... | |
<reponame>JonathanCasey/asana_extensions
#!/usr/bin/env python3
"""
Move Tasks Rule functionality to implement the generic interface components
defined by the metaclass.
Module Attributes:
logger (Logger): Logger for this module.
(C) Copyright 2021 <NAME>. All Rights Reserved Worldwide.
"""
import logging
import as... | |
<reponame>baotuquan/impala<filename>tests/util/auto_scaler.py
#!/usr/bin/env impala-python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF license... | |
%num_img_channels)
sys.stderr.write("conv_size for structured_model is %i\n" %conv_size)
#theano.config.compute_test_value = 'raise'
sys.stderr.write('... building the model\n')
x = T.tensor4('x', dtype=theano.config.floatX) # the data is presented in 4D shape (#batch, #kpts, #row, #cols)
# the given input is the... | |
the :ref:`User Guide <least_angle_regression>`.
Parameters
----------
X : None or ndarray of shape (n_samples, n_features)
Input data. Note that if X is None then Gram must be specified,
i.e., cannot be None or False.
y : None or ndarray of shape (n_samples,)
Input targets.
Xy : array-like of shape (n_samples,)... | |
str. The proper command to be submitted to desi_proc to process the job defined by the prow values.
"""
cmd = 'desi_proc'
cmd += ' --batch'
cmd += ' --nosubmit'
cmd += ' --traceshift'
if queue is not None:
cmd += f' -q {queue}'
if prow['OBSTYPE'].lower() == 'science':
if prow['JOBDESC'] == 'prestdstar':
cmd +... | |
1, 2, 2, 2, 1]
energizations 1.5 1.11803 [1, 0, 3, 1, 3, 0, 1, 1, 2, 3]
energize 2.1 0.7 [2, 2, 2, 1, 3, 2, 3, 2, 3, 1]
energized 2.3 0.64031 [3, 2, 3, 3, 3, 2, 2, 2, 1, 2]
energizer 2.1 0.53852 [3, 2, 2, 2, 2, 2, 2, 3, 1, 2]
energizers 1.7 0.9 [2, 0, 2, 3, 3, 1, 1, 2, 2, 1]
energizes 2.1 0.53852 [3, 2, 3, 2, 2, 2, 2, ... | |
<reponame>securedataplane/preacher
# Testing the basic intent functionality of ONOS
class FUNCintent:
def __init__( self ):
self.default = ''
def CASE1( self, main ):
import time
import imp
import re
"""
- Construct tests variables
- GIT ( optional )
- Checkout ONOS master branch
- Pull latest ONOS code
... | |
"""
problog.forward - Forward compilation and evaluation
----------------------------------------------------
Forward compilation using TP-operator.
..
Part of the ProbLog distribution.
Copyright 2015 <NAME>, DTAI Research Group
Licensed under the Apache License, Version 2.0 (the "License");
you may not use thi... | |
import pybamm
import unittest
import numpy as np
class TestQuickPlot(unittest.TestCase):
def test_simple_ode_model(self):
model = pybamm.lithium_ion.BaseModel(name="Simple ODE Model")
whole_cell = ["negative electrode", "separator", "positive electrode"]
# Create variables: domain is explicitly empty since these... | |
internal system
raise NotImplementedError('Inventory data system not defined.')
# TODO: Complete the following function
def _load_current_forecast_data():
#Load current inventory from SAP HANA or relevant internal system
raise NotImplementedError('Inventory data system not defined.')
# extension = os.path.basename... | |
<filename>TWEET_LANGUAGE_EDITION_v2.py
import sys
import urllib
import re
from datetime import datetime
import tweepy
from twython import Twython, TwythonError
import requests
import time
from random import randint, choice, sample, randrange, shuffle
from time import sleep
from twitter import *
import os
from colorama ... | |
from bokeh.sampledata import us_states, us_counties
from bokeh.plotting import figure, show, output_notebook, output_file, save
from bokeh import palettes
from bokeh.models import ColorBar,HoverTool,LinearColorMapper,ColumnDataSource,FixedTicker, LogColorMapper
output_notebook()
import re
import numpy as np
from modeli... | |
<reponame>felixmusil/run_qe
# Taken from https://gitlab.com/ase/ase/blob/master/ase/io/espresso.py for some small modifications about units
"""Reads Quantum ESPRESSO files.
Read multiple structures and results from pw.x output files. Read
structures from pw.x input files.
Built for PWSCF v.5.3.0 but should work with ... | |
43.687 -6.651 1.00 30.00 C
ATOM 366 N1 DC X 18 -27.504 43.568 -6.588 1.00 30.00 N
ATOM 367 C2 DC X 18 -26.875 43.416 -5.345 1.00 30.00 C
ATOM 368 O2 DC X 18 -27.567 43.383 -4.323 1.00 30.00 O
ATOM 369 N3 DC X 18 -25.521 43.319 -5.296 1.00 30.00 N
ATOM 370 C4 DC X 18 -24.813 43.348 -6.434 1.00 30.00 C
ATOM 371 N4 DC X 1... | |
as domestic or international and remove Domestic
print("\tCategorizing international and domestic flights",end="")
for i,j in G.edges():
if G.nodes[i]["country"] == G.nodes[j]["country"]:
G[i][j]['international'] = False
else:
G[i][j]['international'] = True
print("\t\t[Done]")
# Calculate distance between de... | |
<reponame>aaronrmm/filesystem_spec<filename>fsspec/implementations/reference.py<gh_stars>0
import base64
import io
import itertools
import logging
import os
from functools import lru_cache
import fsspec.core
try:
import ujson as json
except ImportError:
import json
from ..asyn import AsyncFileSystem, sync
from ..c... | |
import enum
import datetime
from typing import Dict, List, Union
import pymongo.database
import iso8601
from bson.objectid import ObjectId
from bson.errors import BSONError
from layabase import ComparisonSigns, CRUDController
@enum.unique
class IndexType(enum.IntEnum):
Unique = 1
Other = 2
_operators = {
Compa... | |
o1)
b2 = bookings.add(owner, a1, o3)
bookings.accept_booking(b1)
assert b1.state == 'accepted'
assert b2.state == 'blocked'
def test_booking_limit_exemption(session, owner):
activities = ActivityCollection(session)
attendees = AttendeeCollection(session)
periods = PeriodCollection(session)
occasions = Occas... | |
FixedTarget.from_name("Rigel")
>>> keck = Observer.at_site("Keck")
>>> rigel_rise_time = keck.target_rise_time(time, target, which="next") # doctest: +SKIP
>>> print("ISO: {0.iso}, JD: {0.jd}".format(rigel_rise_time)) # doctest: +SKIP
ISO: 2001-02-04 00:51:23.330, JD: 2451944.53569
"""
return self._determine_whic... | |
# Copyright 2002-2011 <NAME>. See LICENSE for licensing information.
"""mixminion.directory.ServerList
Implements a store of serverinfos for a directory, as well as functions
to generate and sign directories.
FFFF Right now, this is about maximally slow. There are a lot of tricks
FFFF we could do to speed it up:... | |
<reponame>jjiege/odoo<gh_stars>0
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import re
from odoo import api, fields, models, tools, _
from odoo.exceptions import ValidationError
from odoo.osv import expression
from odoo.addons import decimal_preci... | |
<filename>src/win/bootDeviceWin_FDCB.py
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Oct 26 2018)
## http://www.wxformbuilder.org/
##
## PLEASE DO *NOT* EDIT THIS FILE!
##########################################... | |
= random.choices(in_nodes_list, prob_in_copy)[0]
while in_nodes_count_copy[product2] < (1 + mod_num):
product2 = random.choices(in_nodes_list, prob_in_copy)[0]
reactant = random.choice(in_nodes_list)
if [[reactant], [product1, product2]] in reaction_list2:
pick_continued += 1
continue
if [[reactant], [product... | |
pass
def setRotatePivotTranslation(*args, **kwargs):
"""
Sets the transform's rotate pivot translation.
"""
pass
def setRotation(*args, **kwargs):
"""
Sets the transform's rotation using an MEulerRotation or MQuaternion.
"""
pass
def setRotationComponents(*args, **kwargs):
"""
Sets the tr... | |
<reponame>yyht/electra_electric
"""Create input function for estimator."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import os
import collections
import numpy as np
import tensorflow as tf
tf.disable_v2_behavior()
def check_tf_version():... | |
"--async-msg", action = "store_true", dest = srv_options['asyncmsg']['des'],
default = srv_options['asyncmsg']['def'], help = srv_options['asyncmsg']['help'])
server_parser.add_argument("-V", "--loglevel", action = "store", dest = srv_options['llevel']['des'], choices = srv_options['llevel']['choi'],
default = srv_o... | |
<reponame>Myself5/build
#
# Copyright (C) 2016 The EFIDroid Project
#
# 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 appli... | |
resolution of azimuth and altitude angles for the screen transmittance map.
| A value of 0 means no transmittance map will be generated.
| Valid values for this field are 0, 1, 2, 3 and 5.
| Units: deg
Args:
value (int): value for IDD Field `Angle of Resolution for Screen Transmittance Output Map`
Raises:
Valu... | |
DIV
"""
try:
import qrcode
import qrcode.image.svg
except ImportError:
return s3_str(value)
# Generate the QR Code
qr = qrcode.QRCode(version = 2,
# L-level good enough for displaying on screen, as
# it would rarely be damaged or dirty there ;)
error_correction = qrcode.constants.ERROR_CORRECT_L,
box_size... | |
= "{0} wrt {1} | {2} | {3} | {4} | {5}"\
.format(
pad_name('<output>', 30, quotes=True),
pad_name('<variable>', 30, quotes=True),
pad_name('calc mag.'),
pad_name('check mag.'),
pad_name('a(cal-chk)'),
pad_name('r(cal-chk)'),
)
else:
max_width_of = len("'<output>'")
max_width_wrt = len("'<variable>'")
for of... | |
<gh_stars>1-10
# coot-utils.py
# adapted from coot-utils.scm
#
# Copyright 2004, 2005, 2006, 2007 by <NAME>
# Copyright 2008, 2009 by <NAME>, The University of York
# Copyright 2000 by <NAME>
# Copyright 2004, 2005, 2006, 2007 by <NAME>, The University of York
# <one line to give the program's name and a brief idea of... | |
"""
Copyright 2013 The Trustees of Princeton University
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... | |
from esahub import scihub, utils, checksum, check, main
import unittest
import contextlib
import logging
import re
import datetime as DT
import pytz
import os
import sys
import subprocess
from shapely.wkt import loads as wkt_loads
from esahub.tests import config as test_config
from esahub import config
logger = loggin... | |
k_ET + k_D
d_prob_ph_em = k_emission * δt # prob. of emission in δt
if d_prob_ph_em > α:
d_prob_ph_em = 1 - exp(-d_prob_ph_em)
p = rg.rand()
if d_prob_ph_em >= p:
break # break out of the loop when the photon is emitted
nanotime += δt
# Update R following the OU process
N = rg.randn()
R = ou_single_step_cy(R,... | |
# Princeton University licenses this file to You 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... | |
on the threshold.
For example, the actual output size of scores would be (10,) if there are 10 boxes.
"""
# Step 1: Compute box scores
box_scores = box_confidence * box_class_probs
# Step 2: Find the box_classes using the max box_scores, keep track of the corresponding score
box_classes = K.argmax(box_scores... | |
<filename>spark_fhir_schemas/stu3/complex_types/procedure.py
from typing import Union, List, Optional
from pyspark.sql.types import (
StructType,
StructField,
StringType,
ArrayType,
BooleanType,
DataType,
TimestampType,
)
# This file is auto-generated by generate_schema so do not edit manually
# noinspection ... | |
<reponame>Garyfallidis/dipy
"""Create a unit sphere by subdividing all triangles of an octahedron
recursively.
The unit sphere has a radius of 1, which also means that all points in this
sphere (assumed to have centre at [0, 0, 0]) have an absolute value (modulus)
of 1. Another feature of the unit sphere is that the u... | |
__check(sodium.crypto_stream_xchacha20_xor(c, message, mlen, nonce, key))
return c.raw
# crypto_stream_chacha20_xor_ic(unsigned char *c, const unsigned char *m, unsigned long long mlen, const unsigned char *n, uint64_t ic, const unsigned char *k)
def crypto_stream_xchacha20_xor_ic(message, nonce, initial_counter, ke... | |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator 2.3.3... | |
]
testResult = main.FALSE
installResult = main.intentFunction.installPointIntent(
main,
name="NOOPTION",
senders=senders,
recipients=recipients )
if installResult:
testResult = main.intentFunction.testPointIntent(
main,
intentId=installResult,
name="NOOPTION",
senders=senders,
recipients=recipients,
sw1=... | |
typing.Sequence[str]
gateway : str
ip_addresses : typing.Sequence[str]
is_up : bool
mac_address : str
space : str
'''
dns_nameservers_ = dns_nameservers
gateway_ = gateway
ip_addresses_ = ip_addresses
is_up_ = is_up
mac_address_ = mac_address
space_ = space
# Validate arguments against known Juju API type... | |
<reponame>vedantirb/cross3d<gh_stars>100-1000
##
# \namespace blurapi.libs.XML.xmlelement
#
# \remarks defines the XML Element wrapper instance for the blurapi system
#
# \author <EMAIL>
# \author <NAME>
# \date 04/09/10
#
import xml.dom.minidom
# Load the monkey patched version to fix a known bug http://bugs.pyth... | |
np.empty(self.shape, dtype=dtype)
itemmask = np.zeros(len(items), dtype=bool)
# By construction, all of the item should be covered by one of the
# blocks
if items.is_unique:
for block in self.blocks:
indexer = items.get_indexer(block.items)
if (indexer == -1).any():
raise AssertionError('Items must contain all... | |
supportVector_models = list()
kernel_type = get_kernel_type(model)
supportVector_models.append(pml.SupportVectorMachineModel(
modelName=model.__class__.__name__,
classificationMethod=get_classificationMethod(model),
VectorDictionary=get_vectorDictionary(model, derived_col_names, categoric_values),
SupportVectorMa... | |
#
#
# Copyright 2019 Asylo 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... | |
= {}
for _s in [ShortSensor]: __swig_getmethods__.update(getattr(_s,'__swig_getmethods__',{}))
__getattr__ = lambda self, name: _swig_getattr(self, AccelX, name)
__repr__ = _swig_repr
def value(self): return _wallaby.AccelX_value(self)
def __init__(self):
this = _wallaby.new_AccelX()
try: self.this.append(this)... | |
# -*- coding: utf-8 -*-
"""
Module: pypub.scrapers.taylorfrancis
NOTE: THIS IS FOR A DEPRECATED VERSION OF T&F!! THE HTML TAGS NEED TO BE CHANGED.
Tasks/Examples:
---------------
1) ****** Get references given a doi value *******
from pypub.scrapers import ________ as __
refs = __.get_references('000689938790372... | |
return True
def _get_rulestring(self, cr, uid, ids, name, arg, context=None):
"""
Gets Recurrence rule string according to value type RECUR of iCalendar from the values given.
@param self: The object pointer
@param cr: the current row, from the database cursor,
@param id: List of calendar event's ids.
@param co... | |
<reponame>SatisSoft/egts-debugger<gh_stars>0
import crcmod
EGTS_PROTOCOL_VERSION = b'\x01'
EGTS_PC_OK = 0
EGTS_TRANSPORT_LAYER_MIN_HEADER_LEN = 11
EGTS_SERVICE_LAYER_MIN_RECORD_HEADER_LEN = 7
EGTS_SERVICE_LAYER_MIN_SUBRECORD_LEN = 3
# polynomial are taken from EGTS documentation
# x^8 + x^5 + x^4 + 1 = 0x0131
crc8_fun... | |
for MACHINE's vote.
with GoldSegReviewer(self, "voa3", "user2") as (d, goldSeg):
for v in d._votesForSegments().get(goldSeg, []):
if v["annotator"].find("MACHINE") > -1:
v["annotator"] += ",user2"
# User1 votes, which automagically advances the doc out of reconciliation.
with GoldSegReviewer(self, "voa3", "use... | |
from scipy.stats import kurtosis, skew
from rackio_AI.utils.utils_core import Utils
import pywt
import numpy as np
import pandas as pd
from rackio_AI.decorators.wavelets import WaveletDeco
from easy_deco.progress_bar import ProgressBar
from easy_deco.del_temp_attr import set_to_methods, del_temp_attr
# @set_to_methods... | |
= indices[None, ...]
return bcoo_todense(data, indices, shape=(max(data.shape[0], indices.shape[0]), *shape)), 0
ad.defjvp(bcoo_todense_p, _bcoo_todense_jvp, None)
ad.primitive_transposes[bcoo_todense_p] = _bcoo_todense_transpose
batching.primitive_batchers[bcoo_todense_p] = _bcoo_todense_batching_rule
xla.translatio... | |
item).
We also need to allow for special words which we want to assign
specific tags (which may differ from those used in the
training/testing corpora, e.g. the decision to just tag the word "to"
with its own unique label).
>>> specials={"to":"TO", "that": "THAT"}
Make a tagger using the data in BNC/TRAINING
>>> ta... | |
# pylint: disable=W0611, W0621, C0302, R0914
import allure
from adcm_client.objects import ADCMClient
from adcm_pytest_plugin.utils import parametrize_by_data_subdirs
from .utils import prepare_cluster_and_get_config
@allure.step('Check that field is invisible if group is active or not')
def _check_that_field_is_in... | |
<filename>cora/foreground/pointsource.py
"""Simulating extra-galactic point sources."""
from os.path import join, dirname
import numpy as np
import numpy.random as rnd
# There's a very strange issue here, importing the following two lines in the
# (original) reverse order causes a segfault. It's maybe related to:
# ... | |
'/Cisco-IOS-XR-l2vpn-cfg:l2vpn/Cisco-IOS-XR-l2vpn-cfg:pw-routing/Cisco-IOS-XR-l2vpn-cfg:pw-routing-bgp'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.enable is not None:
return... | |
tokenize.transform(df)
# vectorize
vector_col = temp_col_name(with_token, output_column)
if vectorizer == VECTORIZER_HASHING:
# check for legal inputs
hashing_num_features = parse_parameter(
int, vectorizer_hashing_parameters.get("number_of_features", 262144), "number_of_features", 262144
)
vectorize = Hashing... | |
<gh_stars>1-10
"""
This module exists to do basic processing of timecourse data that is output
from kinefld simulations
Possible things TODO:
add a wildcardstructure thing like ****** when structures not yet exposed
"""
import math
import numpy as np
import pandas
# from scipy.signal import argrelextrema
from scipy... | |
<reponame>VicoWu/impala<filename>tests/authorization/test_owner_privileges.py
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# t... | |
= spark_session.createDataFrame(
data=pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]})
)
batch_identifiers = {
"pipeline_stage_name": "core_processing",
"airflow_run_id": 1234567890,
"custom_key_0": "custom_value_0",
"i_am_illegal_key": "i_am_illegal_value",
}
# Insure that keys in batch_identifiers that a... | |
#!/usr/bin/env python
# coding: utf-8
# # Spatial Solver Tutorial
# Spatialsolver is a pyne module that contains seven neutron transport equation solvers.
# The neutron transport equation is a balance statement that conserves neutrons.
# In[2]:
import pyne
import pyne.spatialsolver
import numpy as np
# In[3]:
... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__version__ = '0.5'
try:
import fcntl
import sys, os, time
from random import randint
from platform import system
import logging.handlers
from threading import Thread
from threading import Timer
from subprocess import Popen, PIPE
from signal import SIGINT,signal
... | |
1) # [batch x actions x hid]
Wy = torch.mul(u, a_oh).sum(1) + self.bias
xWy = x.bmm(Wy.unsqueeze(2)).squeeze(2)
xWy.data.masked_fill_(x_mask.data, -float('inf'))
if self.training:
# In training we output log-softmax for NLL
alpha = F.log_softmax(xWy, dim=-1)
else:
# ...Otherwise 0-1 probabilities
alpha = F.so... | |
'fmu', 'mechanics')
version: a version string (e.g. '1.0', 'dangerous') (Default value = '')
objects: the objects which belong to the submodel (None will derive
objects from the selection) (Default value = None)
Returns:
: a tuple of the submodelgroup and interfacegroup/None
"""
if not objects:
objects = bpy.... | |
<filename>rebook/mrcdi.py
import cv2
import numpy as np
from dewarp import get_AH_lines, correct_geometry, estimate_vanishing, \
arc_length_points
from geometry import Line
import lib
from lib import RED, GREEN, BLUE
def peak_points(l, AH):
x_min, x_max = l[0][1], l[-1][1] + l[-1][3]
y_min = min([y for c, x, y, w,... | |
#! /usr/bin/python
# -*- coding: utf-8 -*-
import tensorflow as tf
from tensorlayer.layers.core import Layer
from tensorlayer import logging
from tensorlayer.decorators import deprecated_alias
__all__ = [
'PoolLayer',
'MaxPool1d',
'MeanPool1d',
'MaxPool2d',
'MeanPool2d',
'MaxPool3d',
'MeanPool3d',
'GlobalM... | |
None:
fout.write("\t\t\t\t%s %s\n" % (item, str(self.params[item])))
fout.write("\t\t\t\t&END CONSTRAINT_EXPONENTS\n")
def set_params(self, params):
for item in params:
if len(item.split("-")) == 5:
self.params[item.split("-")[-1]] = params[item]
else:
pass
class cp2k_dft_qs_optimize_lri_basis:
... | |
"""
Local MRIQC Stats
-----------------
This module allows the user to compare his/her images with all
similar images collected at the same scanner and same parameters,
for purpose of Quality Control (QC).
IQM: Image Quality Metrics
"""
import json
import urllib.request
import urllib.error
from datetime import datet... | |
= re.sub('^timestmp', 'timestamp', column_type)
column_type = re.sub('^blob', 'binary', column_type)
column_type = re.sub('^real', 'float', column_type)
column_type = re.sub('^vargraph', 'varchar', column_type)
column_type = re.sub('^graphic', 'varchar', column_type)
if self.common_config.db_db2as40... | |
<reponame>bertucho/epic-movie-quotes-quiz<filename>dialogos/build/idna/idna/idnadata.py
# This file is automatically generated by build-idnadata.py
scripts = {
'Arabic': frozenset(
list(range(0x600,0x605)) +
list(range(0x606,0x60c)) +
list(range(0x60d,0x61b)) +
[0x61e] +
list(range(0x620,0x640)) +
list(range(0x... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.