input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<filename>layout/routing/grid.py
# -*- coding: utf-8 -*-
"""This module defines the RoutingGrid class.
"""
from typing import TYPE_CHECKING, Sequence, Union, Tuple, List, Optional, Dict, Any
import numpy as np
from ..util import BBox
from bag.util.search import BinaryIterator
from bag.math import lcm
if TYPE_CHECK... | |
<reponame>pulumi/pulumi-kubernetes-crds
# coding=utf-8
# *** WARNING: this file was generated by crd2pulumi. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... impor... | |
ADDR_TYPES:
create_interface_in_kernel(
tgen,
"r1",
"loopback1",
LOOPBACK_1[addr_type],
"RED_A",
)
create_interface_in_kernel(
tgen,
"r1",
"loopback2",
LOOPBACK_2[addr_type],
"BLUE_A",
)
step(
"Create a static routes in vrf RED_B on router RED_1 pointing"
" next-hop as interface's IP in vrf RED_A"
)... | |
for OFFLINE Migrations.
:param pulumi.Input[str] compartment_id: (Updatable) OCID of the compartment where the secret containing the credentials will be created.
:param pulumi.Input[pulumi.InputType['MigrationDataTransferMediumDetailsArgs']] data_transfer_medium_details: (Updatable) Data Transfer Medium details for t... | |
u('\u6d59\u6c5f\u7701\u6e56\u5dde\u5e02')},
'861385721':{'en': 'Zhoushan, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u821f\u5c71\u5e02')},
'861385720':{'en': 'Zhoushan, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u821f\u5c71\u5e02')},
'861385723':{'en': 'Zhoushan, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u821f\u5c71\u5e02')},
... | |
from touchworks.logger import Logger
import json
import uuid
import requests
import time
logger = Logger.get_logger(__name__)
class TouchWorksException(Exception):
pass
class TouchWorksErrorMessages(object):
GET_TOKEN_FAILED_ERROR = 'unable to acquire the token from web service'
MAGIC_JSON_FAILED = 'magic json ... | |
xconv7a = bn()(xconv7a)
merge0=concatenate([xup7,xconv7a])
xconv7b = Conv2D(12, (kernel_size, kernel_size), activation='relu', padding='same',
kernel_regularizer=regularizers.l2(l2_lambda) )(merge0)
xconv7b = bn()(xconv7b)
merge1=concatenate([xup7,xconv7a,xconv7b])
xconv7c = Conv2D(12, (kernel_size, kernel... | |
= 2
elif LA2 in {STATE}:
alt2 = 3
elif LA2 in {DATA}:
alt2 = 4
elif LA2 in {NID, SET}:
alt2 = 5
else:
nvae = NoViableAltException("", 2, 0, self.input)
raise nvae
if alt2 == 1:
# /home/tux/PycharmProjects/ProtoGen_public/Parser/ProtoCC.g:171:16: int_decl
pass
root_0 = self._adaptor.nil()
self._state... | |
""" Analysis of the content of BioModels
:Author: <NAME> <<EMAIL>>
:Date: 2017-05-31
:Copyright: 2017, Karr Lab
:License: MIT
"""
import bioservices
import ete3
import glob
import datanator.data_source.bio_portal
import libsbml
import os
import sqlalchemy
import sqlalchemy.ext.declarative
import sqlalchemy.orm
import... | |
# -*- coding: UTF-8 -*-
# Copyright 2009-2019 Rumma & Ko Ltd
# License: BSD (see file COPYING for details)
"""This defines the :class:`Action` class and the :func:`action`
decorator, and some of the standard actions. See :ref:`dev.actions`.
"""
import six
from builtins import str
import logging ; logger = logging.ge... | |
import re
import uuid
from urllib import urlopen
from datetime import datetime, timedelta
from flask import request, jsonify
from models import AccountDetails, TaskLog, UserProfile, UserSkill, TaskDetails, ProjectDetails, \
WorkspaceDetails, SkillData
from routes.authenticated.utils import send_invitation_email, chec... | |
source=source,
destination=destination,
send_asset=send_asset,
send_max=send_max,
dest_asset=dest_asset,
dest_amount=dest_amount,
path=path)
class ChangeTrust(Operation):
"""The :class:`ChangeTrust` object, which represents a ChangeTrust
operation on Stellar's network.
Creates, updates, or deletes a trustli... | |
import logging
import numpy as np
import pandas as pd
import scipy.stats as ss
from scipy.linalg import eig
from numba import jit
import sg_covid_impact
# from mi_scotland.utils.pandas import preview
logger = logging.getLogger(__name__)
np.seterr(all="raise") # Raise errors on floating point errors
def process_co... | |
10:30:00,54.33,3581.0,52.99
2335,10,19698.0,390,Leisure,1970-01-01 10:30:00,26.71,1781.0,26.35
2336,3,7605.0,390,Housework,1970-01-01 10:30:00,10.31,753.0,11.14
2337,11,3718.0,390,Travel and Other,1970-01-01 10:30:00,5.04,379.0,5.61
2338,4,2216.0,390,Child Care,1970-01-01 10:30:00,3.0,150.0,2.22
2339,5,447.0,390,A... | |
= self.refresh_token
return result
def from_map(self, map={}):
if map.get('headers') is not None:
self.headers = map.get('headers')
if map.get('addition_data') is not None:
self.addition_data = map.get('addition_data')
if map.get('app_id') is not None:
self.app_id = map.get('app_id')
if map.get('grant_type') ... | |
4*' ', [
'return {crc_reflect_function}({cfg_xor_in} & {cfg_mask}, {cfg_width});'.format(**sym),
]),
'} else {',
CodeGen(opt, 4*' ', [
'return {cfg_xor_in} & {cfg_mask};'.format(**sym),
]),
'}',
], [
Conditional2(opt, '', opt.algorithm == opt.reflect_in, [
'return {crc_reflect_function}({cfg_xor_in} & {cfg_ma... | |
'action': self.nodeurl
})
form['id'] = factory(
'field:label:text',
props={
'label': 'Id',
})
form['title'] = factory(
'field:label:text',
props={
'label': 'Title',
})
form['add'] = factory(
'submit',
props={
'action': 'add',
'expression': True,
'handler': self.add,
'next': self.next,
'label': 'Add',... | |
from collections import defaultdict
import unittest
import math
import sys
from validateModeller import *
from simtk.openmm.app import *
from simtk.openmm import *
from simtk.unit import *
if sys.version_info >= (3, 0):
from io import StringIO
else:
from cStringIO import StringIO
class TestModeller(unittest.TestCa... | |
raise CredentialNotVerifiable("Malformed XML: No credential tag found")
# Just take the first cred if there are more than one
cred = creds[0]
self.set_refid(cred.getAttribute("xml:id"))
self.set_expiration(utcparse(getTextNode(cred, "expires")))
# import traceback
# stack = traceback.extract_stack()
og = getTe... | |
longs]
X1 = X1.reshape(-1, X1.shape[1] * X1.shape[2])
level = var + area_name
self.logger.info('Begin PCA training for %s', level)
X1_compressed = self.PCA_transform(X1, 9, level)
self.logger.info('Successfully PCA transform for %s', level)
X2 = data[var + '_next'][:, lats, :][:, :, longs]
X2 = X2.reshape(-1, ... | |
import math
from typing import Union
import numpy as np
def rotation_matrix(axis, theta):
"""
Return the rotation matrix associated with counterclockwise rotation about
the given axis by theta radians.
"""
axis = np.asarray(axis)
axis = axis / math.sqrt(np.dot(axis, axis))
a = math.cos(theta / 2.0)
b, c, d =... | |
zinc = 4.125,
annotstart = (1234, 5678),
annotinc = (5, 2),
corners = ((1000, 1000),
(3775, 1000),
(1000, 2890),
(3775, 2890)),
**kwargs
) as writer:
expect_datarange_1 = datarange
if datatype == SampleDataType.float and zgyWriterFactory != oldzgy.ZgyWriter:
# The value is unspecified. It could be NaN if the... | |
<gh_stars>0
# -*- coding: utf-8 -*-
import copy
import datetime
import json
import os
import six
from bson.objectid import ObjectId
from .model_base import AccessControlledModel
from girder import events
from girder.constants import AccessType
from girder.exceptions import ValidationException, GirderException
from gir... | |
import copy
import glob
import json
import os
import re
from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Union
import numpy as np
import pandas as pd
import pyarrow
import pyarrow.parquet as pq
import scipy.cluster.hierarchy
CAPACITY = "mw"
MERGE = {
"sums": [CAPACITY, "area"],
"means": [
... | |
<filename>py_extrema/utils.py<gh_stars>0
from numba import njit, jit, guvectorize
from collections import OrderedDict
import numpy as np
import numexpr as ne
import attr
import pandas as pd
from itertools import product
from scipy.interpolate import RegularGridInterpolator, interpn
class FiniteDictionary(OrderedDict)... | |
'zhū',
0x7027: 'lóng,shuāng',
0x7028: 'lài',
0x7029: 'duì',
0x702A: 'fàn',
0x702B: 'hú',
0x702C: 'lài',
0x702D: 'shū',
0x702E: 'lián',
0x702F: 'yíng',
0x7030: 'mí',
0x7031: 'jì',
0x7032: 'liàn',
0x7033: 'jiàn,zùn',
0x7034: 'yīng,yǐng,yìng',
0x7035: 'fèn',
0x7036: 'lín',
0x7037: 'yì',
0x7038: 'jiān',
... | |
% element, item, re.IGNORECASE):
#if item.split(".")[0].lower() == element.lower() or item.split("_")[0].lower() == element.lower():
if re.match("(%s)(.*)(upf)" % element, item, re.IGNORECASE) or re.match("(%s)(_*)(upf)" % element, item, re.IGNORECASE):
shutil.copyfile(item, os.path.join(directory, item))
brea... | |
give them a toonup or make them suffer.
if toon.getHp() > toon.getMaxHp():
toon.takeDamage(toon.getHp() - toon.getMaxHp())
else:
toon.toonUp(toon.getMaxHp() - toon.getHp())
# Set their type and level that they specified.
types = toon.getCogTypes()
types[corpIndex] = typeIndex
toon.b_setCogTypes(types)
levels ... | |
= w@E
A = E - mu
ub = unbias_var(w, avoid_pathological=False)
C12 = sqrt(ub*w[:,None]) * A
return C12
def mask_unique_of_sorted(idx):
"NB: returns a mask which is True at [i] iff idx[i] is NOT unique."
duplicates = idx==np.roll(idx,1)
duplicates |= idx==np.roll(idx,-1)
return duplicates
def bandw(N,m):
""""
... | |
from k5test import *
# Skip this test if pkinit wasn't built.
if not os.path.exists(os.path.join(plugins, 'preauth', 'pkinit.so')):
skip_rest('PKINIT tests', 'PKINIT module not built')
# Check if soft-pkcs11.so is available.
try:
import ctypes
lib = ctypes.LibraryLoader(ctypes.CDLL).LoadLibrary('soft-pkcs11.so')
... | |
'horizon', where all elements are equal to the last element of 'series'
Parameters
----------
series : ndarray
The data to use for the naive forecast
horizon : int
The length of the forecast
Returns
-------
ndarray
A simple naive forecast (Shape: ('horizon', ))
"""
return np.array([series[-1]] * horizon)... | |
distributed around the
location given by the current state of the object, i.e., the current
parameter values. In each direction, the walker are randomly distributed
with a Gaussian distribution, whose default standard deviation is one.
The scales argument can be used to control the width of Gaussians used
to distr... | |
filelines[i][0] == '-' and i < 25:
startLine = i + 1
if startLine == 0:
logger.error('Sounding file format does not follow format standards!')
self._weatherLoaded = False
# Import data into variables
for line in filelines[startLine:]:
try:
data = line.split()
if len(data) == 11:
PRESS.append(float(data[0]))... | |
from __future__ import division, absolute_import, print_function
from rdkit import Chem, Geometry
from simtk.openmm import app, Vec3
from simtk import unit
import itertools
import pyparsing as pyp
from itertools import groupby
proteinResidues = ['ALA', 'ASN', 'CYS', 'GLU', 'HIS',
'LEU', 'MET', 'PRO', 'THR', 'TYR',
'... | |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may ch... | |
0.5*m.b557*m.b590 + 0.5*m.b557*m.b615 + 0.5*m.b557*m.b616 +
0.5*m.b557*m.b621 + 0.5*m.b557*m.b652 + 0.5*m.b557*m.b659 + 0.5*m.b557*m.b663 + 0.5*m.b557*m.b704
+ 0.5*m.b557*m.b749 + 0.5*m.b557*m.b759 + 0.5*m.b557*m.b788 + 0.5*m.b557*m.b789 + 0.5*m.b558*
m.b561 + 0.5*m.b558*m.b576 + 0.5*m.b558*m.b587 + 0.5*m.b558*m.b6... | |
import torch
from torch import nn
import gym
from gym.spaces import Box, Discrete, Space
from copy import copy, deepcopy
import numpy as np
from typing import Optional, Union, Iterable, List, Dict, Tuple, Any
from numbers import Real, Integral
from .runningstat import RunningStat
from .misc import (
fill_parameters,
... | |
import os
import datetime
import tempfile
import sys
from subprocess import call
import numpy as np
class ansyswrapper:
__matid = 0
__csid = 10
__ls_num = 1
def __init__(self, path_to_and_bin=None, ans_hi_version=250, ans_low_version=50, anslic='ane3fl',
infile='input.dat',
outfile='output.dat', projdir=tempf... | |
import time
import argparse
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from pathlib import Path
import context
from mhealth.utils.plotter_helper import save_figure
from mhealth.utils.commons import create_progress_bar
# Used if com... | |
ans
x = ad.Variable(0.3, label="x")
y = ad.sinh(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.sinh(0.3), grad(adnp.sinh)(0.3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(0.3, label="x") + 0.3
y = ad.sinh(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, s... | |
global
'http://www.openstat.ru/',
# Why: #8116 in Alexa global
'http://www.adlandpro.com/',
# Why: #8117 in Alexa global
'http://www.trivago.de/',
# Why: #8118 in Alexa global
'http://feiren.com/',
# Why: #8119 in Alexa global
'http://www.lespac.com/',
# Why: #8120 in Alexa global
'http://www.icook.tw/',
# ... | |
from django.utils import timezone
from .models import *
from .constants import *
# Reading material for double entry accounting:
# http://en.wikipedia.org/wiki/Double-entry_bookkeeping_system
# http://www.find-uk-accountant.co.uk/articles/fua/16
# http://www.accountingcoach.com/accounts-receivable-and-bad-debts-expen... | |
10*(0/5)),
(10*(1/6), 10*(0/5)),
(10*(1/6), 10*(4/5)),
(10*(-3/6), 10*(4/5))]
)
def test_crop_bounding_boxes_by_fixed_ints_without_keep_size(self):
aug = iaa.Crop((1, 0, 4, 4), keep_size=False)
bbs = [ia.BoundingBox(x1=0, y1=0, x2=10, y2=10),
ia.BoundingBox(x1=1, y1=2, x2=9, y2=10)]
bbsoi = ia.BoundingBoxesOn... | |
# -*- coding: utf-8 -*-
"""Train a CNN to detect presence of red and blue line on an RDT and also give the normalized y-axis location.
Example:
$ python train_blue_red.py --transfer_learning True
"""
import os
import numpy as np
import cv2
import imgaug as ia
import keras.backend as K
from sklearn.utils import clas... | |
one is internally converted to type two. For 2 models with four features, this looks like: [0.1,0.9] -> [[0.1,0.9],[0.1,0.9],[0.1,0.9],[0.1,0.9]]
default: uniform weights (None)
output_file: filepath of output phrase table. If it ends with .gz, file is automatically zipped.
output_lexical: If defined, also write... | |
<filename>module_particle_systems.py<gh_stars>0
from header_particle_systems import *
####################################################################################################################
# Each particle system contains the following fields:
#
# 1) Particle system id (string): Used for referencing parti... | |
Federal creditor agencies generally are required
to refer debts at no later than 120 days delinquent to the Cross-Servicing Program and TOP. Before
referring a debt to Fiscal Service for collection, federal creditor agencies must provide debtors
with notice and an opportunity to enter into a repayment agreement base... | |
<url>
Play IRC art files from web links.
"""
if not channel:
channel = msg.args[0]
if channel != msg.args[0] and not ircdb.checkCapability(msg.prefix, "admin"):
irc.errorNoCapability("admin")
return
if not irc.isChannel(channel):
channel = msg.nick
optlist = dict(optlist)
self.stopped[channel] = False
if "d... | |
from __future__ import print_function, division
from sympy.core import Add, S, sympify, oo, pi, Symbol, Dummy, expand_func
from sympy.core.compatibility import range, as_int
from sympy.core.function import Function, ArgumentIndexError
from sympy.core.numbers import Rational
from sympy.core.power import Pow
from sympy.... | |
# -- coding: utf-8 --
# MIT License
#
# Copyright (c) 2019 <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... | |
import pika.adapters
import pika
import uuid
import json
EXCHANGE = 'chatexchange'
EXCHANGE_TYPE = 'topic'
BINDING_KEY_DEFAULT = 'public.*'
PORT = 5672
# few utility print functions
def pi(msg):
print '\n[RabbitMQClient] : inside ' + msg.upper() + '()'
def pc(msg):
print '[RabbitMQClient] : Calling ' + msg.uppe... | |
0, prompt_str)
zc = screen.getstr(0, l).lower()
while zc != 'up' and zc != 'right':
screen.clear()
screen.addstr(0, 0, 'You didn\'t enter a direction that was allowed.')
screen.refresh()
wait()
screen.clear()
screen.addstr(0, 0, prompt_str)
zc = screen.getstr(0, l).lower()
break
except:
screen.clear()
scre... | |
at location: " + str(has_substring)
self._sentence = self._sentence.replace("XXX", str(int(self._log_person_investment)))
has_substring = self._sentence.find("YYY")
if(has_substring != -1):
print "[6] Found the substring 'YYY' at location: " + str(has_substring)
self._sentence = self._sentence.replace("YYY", str(i... | |
<filename>pyccel/codegen/compiling/compilers.py<gh_stars>0
#!/usr/bin/python
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------------------------#
# This file is part of Pyccel which is released under MIT License. See the LICENSE file or #
# go to https://github.com/pyccel... | |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 11 12:50:13 2018
@author: madcas
"""
import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import scipy
from PIL import Image
from scipy import ndimage
import tensorflow as tf
from tensorflow.python.framework import ops
from cn... | |
<filename>plugins/jobs/girder_jobs/models/job.py
# -*- coding: utf-8 -*-
import datetime
from bson import json_util
from girder import events
from girder.constants import AccessType, SortDir
from girder.exceptions import ValidationException
from girder.models.model_base import AccessControlledModel
from girder.models.... | |
<filename>movingpandas/trajectory.py
# -*- coding: utf-8 -*-
import os
import sys
import contextily as ctx
from shapely.affinity import translate
from shapely.geometry import Point, LineString
from fiona.crs import from_epsg
from datetime import datetime
sys.path.append(os.path.dirname(__file__))
from movingpandas... | |
'''
Some util functions
Part of the code is referenced from Kaggle
'''
import os
import cv2
import torch
import random
import numpy as np
import pandas as pd
from . import fmix
from tqdm import tqdm
from torch.utils.data import Dataset
from torch.cuda.amp import autocast
import copy
def seed_everything(seed):
'''Al... | |
<reponame>sprksh/finance-calculator
from tests.data import scheme_data, benchmark_data
benchmark_scheme_code = 'S0089095'
benchmark_scheme_name = 'Nifty Largemidcap 250 (Total Return)'
# benchmark_data = [
# ('2017-06-01', 6249.670000),
# ('2017-06-02', 6283.580000),
# ('2017-06-05', 6312.220000),
# ('2017-06-06', 62... | |
elif match_count == 4:
# remove swap location from matches and add to bonus list
bonus_list.extend(self.get_bonus_list(row, column, temp_matches, 1))
# if length of match list >= 3, add temp matches to matches
if match_count >= 3:
match_list.extend(temp_matches)
return match_list, bonus_list
def remove_row(se... | |
self._state.following.append(self.FOLLOW_else_if_clause_in_if_stmt543)
else_if_clause50 = self.else_if_clause()
self._state.following.pop()
if self._state.backtracking == 0:
self._adaptor.addChild(root_0, else_if_clause50.tree)
else:
break #loop9
# Expr.g:99:30: ( else_clause )?
alt10 = 2
LA10_0 = self.i... | |
Constraint(expr= m.b5 - m.b13 + m.b40 <= 1)
m.c94 = Constraint(expr= m.b5 - m.b15 + m.b41 <= 1)
m.c95 = Constraint(expr= m.b5 - m.b17 + m.b42 <= 1)
m.c96 = Constraint(expr= m.b5 - m.b19 + m.b43 <= 1)
m.c97 = Constraint(expr= m.b5 - m.b21 + m.b44 <= 1)
m.c98 = Constraint(expr= m.b5 - m.b23 + m.b45 <= 1)
m.c99 = Co... | |
out = _responds(RESULT_FAILURE, msg="No such cmd")
return out
class CMD_ComingEpisodes(ApiCall):
_help = {"desc": "display the coming episodes",
"optionalParameters": {"sort": {"desc": "change the sort order"},
"type": {"desc": "one or more of allowedValues separated by |"},
"paused": {"desc": "0 to exclude paus... | |
# Authors: <NAME> <<EMAIL>>
"""
Support recovery on simulated data (2D)
=======================================
This example shows the advantages of spatially relaxed inference when
dealing with high-dimensional spatial data. To do so, we compare several
statistical methods that aim at recovering the support, i.e., pr... | |
<filename>hiseq/utils/argsParser.py
# -*- coding: utf-8 -*-
"""
Parse arguments from command line
- trimmer
- align
"""
import argparse
import pathlib
def add_sheet_args():
"""
Prepare sample sheet for Demx
output:
1. sample_name,i7,i5,barcode
2. i7_name,i7,reads
3. sample_name,NULL,NULL,barcode (bc onl... | |
f = [0] + list(self._get_cpo_expr(f).value)
invf = [0] + list(self._get_cpo_expr(invf).value)
self._add_to_model(CpoFunctionCall(Oper_inverse, Type_Constraint, (build_cpo_expr(f), build_cpo_expr(invf))))
def _compile_pred_bool_clause(self, fc):
""" Implementation of bool_clause predicate
Args:
a: First array of... | |
"""
This module provides tools for creating kmz products for a SICD type element.
.. Note::
Creation of ground overlays (i.e. image overlay) requires the optional
Pillow dependency for image manipulation.
Examples
--------
Create a kmz overview for the contents of a sicd type reader.
.. code-block:: python
impor... | |
<reponame>cleary-lab/CISI<filename>decompression/autoencoding/module/ccae.py
import numpy as np
import tensorflow as tf
import glob,os,sys
from scipy.spatial import distance
from tensorflow_probability import edward2 as ed
import tensorflow_probability as tfp
tfd = tfp.distributions
from tensorflow.core.framework.summa... | |
"""The standard runtime library."""
from runtime.env import (Datatype, Value, Function, Operator,
Signature, FunctionBinding, CastException, ANY, NULL,
RuntimeException)
NUMBER = Datatype("*number", None, ANY)
def cast_integer(value):
"""Casts a value to an INTEGER."""
if isinstance(value, Value):
if value.data... | |
<filename>core/extension/android.py
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Notes:
#
# This generates makefiles suitable for inclusion into the Android build system
# via an Android.mk file. It ... | |
the conjugate
# as well
i_times = range(0, n_time_points-NFFT+1, NFFT-n_overlap)
n_slices = len(i_times)
FFT_slices = {}
FFT_conj_slices = {}
Pxx = {}
for i_channel in all_channels:
#dbg:
#print i_channel
Slices = np.zeros( (n_slices,n_freqs), dtype=np.complex)
for iSlice in xrange(n_slices):
thisSlice ... | |
5:
return 'aerddpssm'
if table2Version == 215 and indicatorOfParameter == 4:
return 'aerddpsss'
if table2Version == 215 and indicatorOfParameter == 3:
return 'aersrcssl'
if table2Version == 215 and indicatorOfParameter == 2:
return 'aersrcssm'
if table2Version == 215 and indicatorOfParameter == 1:
return '... | |
"""
Functions for processing input commands.
All global functions in this module whose name does not start with "_"
is considered an inputfunc. Each function must have the following
callsign (where inputfunc name is always lower-case, no matter what the
OOB input name looked like):
inputfunc(session, *args, **kwargs... | |
<reponame>OpenMDAO-Plugins/flops_wrapper
"""
OpenMDAO Wrapper for Flops
Automatically generated from flops.scriptWrapper with parse_phoenixwrapper.
This wrapper is based on the ModelCenter Java wrapper, version 2.00 Beta
"""
# pylint: disable-msg=E0611,F0401,E1101
from numpy import int64 as numpy_int64
from numpy imp... | |
in AGI
ymod1 = (e00200 + e00700 + e00800 + e01400 + e01700 +
invinc - invinc_agi_ec + e02100 + e02300 +
max(e00900 + e02000, -ALD_BusinessLosses_c[MARS - 1]))
if CG_nodiff:
# apply QDIV+CG exclusion if QDIV+LTCG receive no special tax treatment
qdcg_pos = max(0., e00650 + c01000)
qdcg_exclusion = (min(CG_ec, qdc... | |
(208, 192, 229),
"prim" : (240, 226, 236),
"primrose" : (237, 234, 153),
"provincial pink" : (254, 245, 241),
"prussian blue" : ( 0, 49, 83),
"puce" : (204, 136, 153),
"pueblo" : (125, 44, 20),
"puerto rico" : ( 63, 193, 170),
"pumice" : (194, 202, 196),
"pumpkin" : (255, 117, 24),
"pumpkin skin" : (177, 97, ... | |
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import (
MinValueValidator,
MaxValueValidator,
validate_ipv6_address,
validate_ipv4_address,
)
from django.forms import (
CharField,
IntegerField,
BooleanField,
NullBooleanFie... | |
<gh_stars>0
"""Logic for line following.
UPDATE:(Vijay - 9/27/15) - Follower is outdated since we won't be
line-following for IEEE Hardware Competition 2016. This file has
been left here for reference;
Please do not instantiate it until it's fixed.
"""
from time import time
from time import sleep
import numpy as np
... | |
<reponame>csssuf/pulumi-kubernetes
# coding=utf-8
# *** WARNING: this file was generated by pulumigen. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... i... | |
* 2]),
int(params[pointIndex * 2 + 1])))
expectedPoints = (self._pointCount + (self.closed() and 1 or 0))
moreToCome = len(self.points) < expectedPoints
if len(self.points) > self._pointCount:
if len(self.points) > expectedPoints:
sys.stderr.write("WARNING: read too many points?!\n")
del self.points[self._point... | |
"""
print("REFRESH")
self.download_data()
return
print("PROCESS")
self.process_data()
print("OK")
self.data_status = "current"
self.cds.selected.on_change('indices',self.on_selection_change_callback)
self.country_select.options=sorted(self.adfCountryData.keys())
self.compute_data_status()
self.country_select... | |
import sys
import requests
import os
# Used for debugging gpu errors
# os.environ['CUDA_LAUNCH_BLOCKING'] = '1'
import pandas as pd
import networkx as nx
import utils as u
import torch
import torch.distributed as dist
import numpy as np
import time
import datetime
import random
from copy import deepcopy
from datarea... | |
<reponame>pulkitag/pyphy-engine
import numpy as np
import matplotlib.pyplot as plt
import collections as co
import cairo
import math
import pdb
import copy
from collections import deque
import os
import scipy.io as sio
import scipy.misc as scm
import pickle
#Custom packages
import primitives as pm
import geometry as gm... | |
= QtGui.QBrush(QtGui.QColor(157, 255, 127, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTi... | |
root)
# (nd has only 1 sibling)
# (nd is leftmost child)
# w--x
# \\/
# nd---y w--x--y
# \\ / \\ | /
# u--v--par --> u--v--par
# \\ | / \\ | /
# z z
if debugging:
print 'del case 4a (%d)' % deleting
y = nd.rsib
w = nd.lchild
x = w
while x.rsib is not None:
x.par = nd.par
x = x.rsib
x.rsib = y
x.par =... | |
"""
hash_table.py
Python implementation of the very simple, fixed-array hash table
used for the audfprint fingerprinter.
2014-05-25 <NAME> <EMAIL>
"""
from __future__ import print_function
import numpy as np
import random
import cPickle as pickle
import os, gzip
import scipy.io
import math
# Current format version
... | |
object_info.initial_detrend_period is not None:
self.rotator_period = object_info.initial_detrend_period
elif self.auto_detrend_periodic_signals:
self.rotator_period = self.__calculate_max_significant_period(lc, periodogram)
if self.rotator_period is not None:
logging.info('========================================... | |
#!/usr/bin/python3
import threading, queue, time
import picamera.array as picamarray, numpy, pathlib
import numpy.ma as nma
import png, io
from pootlestuff import watchables as wv
class piCamCPU(wv.watchablesmart):
"""
a base class for things that want to analyse images in detail for movement detection, exposure ad... | |
refresh
trialMouse.status = STARTED
prevButtonState = [0, 0, 0] # if now button is down we will treat as 'new' click
if trialMouse.status == STARTED: # only update if started and not finished!
x, y = trialMouse.getPos()
trialMouse.x.append(x)
trialMouse.y.append(y)
buttons = trialMouse.getPressed()
tria... | |
<reponame>open-publishing/open-publishing-api
import random
import string
import datetime
import os
import mimetypes
import json
import collections
import requests
import jsonschema
import pkg_resources
from open_publishing.core.enums import DocumentStatus, Language, Country, VLBCategory
from open_publishing.core.enum... | |
#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
import unittest
import os
import tempfile
import shutil
import time
import redis
from rmtest import ModuleTestCase
if "REDIS_MODULE_PATH" not in os.environ:
os.environ["REDIS_MODULE_PATH"] = "../../target/release/libredis_sql.so"
os.environ["RUST_BACKTRACE"] = "full"
... | |
<filename>device_drivers/device_attributes.py
#!/usr/bin/python
# @file device_attributes.py
#
# Python classes to represent attributes of a Linux device
#
# @author <NAME>
# @date 2020
# @copyright 2020 Audio Logic
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BU... | |
A `torch.Tensor` object representing delayed h_state of shape (batch_size, h_size). Default is NoneT = torch.FloatTensor([-1e38]) (i.e., will not be used).
prev_c_state: Optional; A `torch.Tensor` object representing previous c_state of shape (batch_size, state_size). Default is NoneT = torch.FloatTensor([-1e38]) (i.e... | |
#============================================================================
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope th... | |
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, ... | |
overlap is ~1
def cost_function(new_tensors):
new_state = state.with_different_tensors(new_tensors)
overlap = self.evolution_pepo.matrix_element(new_state, state, **contraction_options)
res = np.abs(overlap)
return res * np.exp(self.dt * state_energy)
else:
def cost_function(new_tensors):
new_state = state.wit... | |
"""
A test suite for the different solvers.
"""
import unittest
import NTPolySwig as nt
import warnings
from scipy.sparse import csr_matrix
from scipy.io import mmread
from mpi4py import MPI
from helpers import result_file, log_file
# MPI global communicator.
comm = MPI.COMM_WORLD
warnings.filterwarnings(action="igno... | |
"//" u_expr| m_expr "/" u_expr |
m_expr "%" u_expr
a_expr ::= m_expr | a_expr "+" m_expr | a_expr "-" m_expr
The "*" (multiplication) operator yields the product of its arguments.
The arguments must either both be numbers, or one argument must be an
integer and the other must be a sequence. In the former case, the
n... | |
match):
"""Process match as piece move unless it fits better as a b-pawn move.
bx[ac][1-8] is ambiguous when case is ignored. The board state is
examined to decide if 'b' or 'B' means bishop or pawn. Sometimes
the only way to decide is by taking case into account.
"""
group = match.group
pml = group().lower()
... | |
#!/usr/bin/python3
# Author: GMFTBY
# Time: 2020.2.7
'''
Seq2Seq in Transformer, implemented by Pytorch's nn.Transformer
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
import math
import random
import numpy as np
import pickle
import ipdb
import sys
import types
im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.