input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
np.nonzero(ball_box)
paddle_pixels = np.nonzero(paddle_line)
nonlocal trigger_pulled
if action == 1:
trigger_pulled = True
if done:
trigger_pulled = False
if not trigger_pulled:
return 'N'
try:
# we get dim 1 of ball pixels and 0 of paddle pixels, which are both horizontal axis
ball_x_center = (np.min(ball_p... | |
<filename>submit_to_anubis.py
#!/usr/bin/env python
################################################################################
# Script for submitting samples to the ANUBIS analysis service.
#
# Last change: 19/October/2009
# Contact: <EMAIL>
#
# Usage: submit_to_anubis.py [options] ANALYSIS_SUBJECT_1 ANALYSIS_SU... | |
<gh_stars>0
# -*- encoding: utf-8 -*-
from . import FixtureTest
class CountryBoundaryTest(FixtureTest):
def test_boundary(self):
import dsl
z, x, y = (8, 0, 0)
# +---------------------+
# | |
# | aaaaaaa*cccccccc |
# | a b c |
# | a b c |
# | a b c |
# | *bbbbbbb c |
# | c c |
# | c c |
# | cccccccccc... | |

<a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=Science/ReflectionsOfLightByPlaneAndSph... | |
# ccm clusters
import os
import shutil
import time
import subprocess
import signal
import yaml
import uuid
import datetime
from six import print_
from distutils.version import LooseVersion
from ccmlib import common
from ccmlib.cluster import Cluster
from ccmlib.scylla_node import ScyllaNode
from ccmlib.node import No... | |
False
elif language == 'stick':
rhyctx.durations_stick = True
else:
raise ValueError("unknown durations behavior %s; try temporary or stick"
% language)
# Instruments
def add_sfx(self, words):
if len(words) != 4 or words[2] != 'on':
raise ValueError("must have 4 words: sfx SFXNAME on CHANNELTYPE")
_, name,... | |
Constraint(expr=m.x28*m.x2514 + m.x653*m.x2520 + m.x1278*m.x2526 + m.x1903*m.x2532 <= 8)
m.c1297 = Constraint(expr=m.x29*m.x2514 + m.x654*m.x2520 + m.x1279*m.x2526 + m.x1904*m.x2532 <= 8)
m.c1298 = Constraint(expr=m.x30*m.x2514 + m.x655*m.x2520 + m.x1280*m.x2526 + m.x1905*m.x2532 <= 8)
m.c1299 = Constraint(expr=m.x3... | |
0.1 or endBall.yPosition > maxFieldCorner + 0.1):
emit = True
else:
# Check lower left corner
if (endBall.xPosition < 0 and endBall.xPosition > -2 and endBall.yPosition > -2 and endBall.yPosition < 0):
emit = False
# Check upper left corner
elif (endBall.xPosition < 0 and endBall.xPosition > -2 and endBall.yPosi... | |
933, 899, 736, 195, 147,
366, 181, 973, 59, 873, 379],
[161, 879, 580, 471, 865, 871, 542, 206, 816,
807, 436, 387, 893, 970, 145],
[367, 686, 933, 883, 434, 565, 652, 528, 199,
346, 378, 377, 911, 746, 288],
[844, 843, 849, 486, 101, 957, 940, 223, 930,
113, 359, 782, 652, 783, 559],
[56, 652, 242, 424, 531, 1... | |
A SPECIFIC VALUE.
THIS HAS IMMEDIATE EFFECT AND DO NOT FADE THE SOUND
AFFECT ALL SOUNDS WITH OR WITHOUT PANNING EFFECT.
PANNING SOUND EFFECT WILL BE CONSERVED AFTER ADJUSTING THE VOLUME
:param volume_: float; volume value, default is 1.0
:return : None
"""
# SET THE VOLUME IN CASE OF AN INPUT ERROR
... | |
<filename>components/server/tests/data/test_datamodel.py<gh_stars>0
"""Unit tests for the data model."""
import json
import pathlib
import unittest
def setUpModule(): # pylint: disable=invalid-name
"""Read the data model once for all data model tests."""
with pathlib.Path("src/data/datamodel.json").open() as data_... | |
skip_0:
if varying_in:
shader_source += "varying " + input + "_vs_output;\n"
else:
shader_source += insert_layout_location(index_counter)
shader_source += "in " + input + "_vs_output;\n"
index_counter += 1
for instance_input in instance_inputs:
shader_source += insert_layout_location(index_counter)
shader_sour... | |
"""
This module defines a class called "balto_gui" that can be used to
create a graphical user interface (GUI) for downloading data from
OpenDAP servers from and into a Jupyter notebook. If used with Binder,
this GUI runs in a browser window and does not require the user to
install anything on their computer. However, ... | |
# -*- coding: utf-8 -*-
import logging
import itertools
import typing
import semver
import copy as py_copy
from typing import List, Set, Dict, Tuple, Optional
from enzi import config
from enzi.config import DependencyRef
from enzi.config import Config as EnziConfig
from enzi.config import DependencyVersion
from enzi.... | |
<reponame>sratgh/CarND-Capstone
#!/usr/bin/env python
import rospy
from std_msgs.msg import Int32, Bool
from geometry_msgs.msg import PoseStamped, Pose, TwistStamped
from styx_msgs.msg import TrafficLightArray, TrafficLight
from styx_msgs.msg import Lane, Waypoint
from scipy.spatial import KDTree
from sensor_msgs.msg i... | |
= []
local_var_files = {}
if 'custom_signature_id' in params:
form_params.append(('custom_signature_id', params['custom_signature_id']))
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/vnd.api+json'])
# HTTP header `Content-Type`
header... | |
{'Type': 'Digital', 'x': 1189, 'y': 1752, 'width': 1032}, # Bottom hat down
'Joy_7': {'Type': 'Digital', 'x': 1189, 'y': 1808, 'width': 1032}, # Bottom hat left
'Joy_8': {'Type': 'Digital', 'x': 1189, 'y': 1640, 'width': 1032}, # Bottom hat up
'Joy_9': {'Type': 'Digital', 'x': 1198, 'y': 1275, 'width': 832}, # Rear ... | |
{}
self.point_db = {}
self.gs = None
self._ref_gs = GeometrySearch(GEO_FILL_LENGTH, use_dist=True, perform_self_testing=perform_self_testing)
self._ref_way_db = {}
self._way_db_iter = None
self._way_db_sub_iter = None
self._perform_self_testing = perform_self_testing
# Expected properties of 'reference_geometr... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016 Pluralsight, 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 ... | |
<reponame>jaxsbin/shangmi<gh_stars>1-10
# -*- coding: utf-8 -*-
from django.conf import settings
from itsdangerous import URLSafeTimedSerializer as utsr
from django.db import connection
from django.utils import timezone
from django.http import HttpResponse, QueryDict
import base64
import requests
import six
import mode... | |
<reponame>TeMU-BSC/PharmaCoNER-Tagger<gh_stars>1-10
import sklearn.preprocessing
import utils
import collections
import codecs
import utils_nlp
import re
import time
import token
import os
import pickle
import random
class Dataset(object):
"""A class for handling data sets."""
def __init__(self, name='', verbose=F... | |
1)
)
res = self.post_agreement_update(agreement_id, {
'countersignedAgreementPath': 'countersigned/file.jpg'
})
assert res.status_code == 200
data = json.loads(res.get_data(as_text=True))
expected_agreement_json = {
'id': agreement_id,
'supplierId': supplier_framework['supplierId'],
'frameworkSlug': supplie... | |
== 3:
dw = [[], [], [], []]
ew = [[], [], [], []]
dw[0] = [dList[4][0], dList[4][1] - window, dList[4][2] - window]
dw[1] = [dList[1][0], dList[1][1] - window, dList[1][2] + window]
dw[2] = [dList[2][0], dList[2][1] + window, dList[2][2] + window]
dw[3] = [dList[5][0], dList[5][1] + window, dList[5][2] - window]... | |
<filename>chemics/biomass_composition.py<gh_stars>10-100
"""
Use the `biocomp()` function to calculate biomass composition. Use the
`plot_biocomp()` function to create a Matplotlib figure of the biomass
composition results.
"""
import numpy as np
def biocomp(yc, yh, yo=None, yh2o=0, yash=0, alpha=0.6, beta=0.8, gamm... | |
'''
author: bg
goal:
type: modelz - sklearn for workflow management + PyTorch/keras for transfer learning components + pytorch for nn modules
how: wrapper class for workflow management (pytorch opt&loss + sklearn pipe&metrics) + ArchitectureMixin and implementation for custom architectures.
ref:
refactors:
'''
fr... | |
import serial.serialutil
import pygame, math, sys, uart, serial, threading, time, numpy
from scipy.optimize import curve_fit
from statistics import pstdev
# Constants
BLUE = (25, 25, 200)
PURPLE = (150, 25, 200)
BLACK = (23, 23, 23)
GREY = (56, 56, 56)
WHITE = (254, 254, 254)
RED = (200, 25, 25)
GREEN = (25, 200, 25)
... | |
NT 5.1; .NET CLR 1.1.4322)')
uagent.append('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; {1C69E7AA-C14E-200E-5A77-8EAB2D667A07})')
uagent.append('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; acc=baadshah; acc=none; freenet DSL 1.1; (none))')
uagent.append('Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)')... | |
if not name and not rule_id:
raise SDKException(
'OperationWindow',
'102',
'Either Name or Rule Id is needed')
if name and not isinstance(name, str) or rule_id and not isinstance(rule_id, int):
raise SDKException('OperationWindow', '106')
if name:
rule_id = self.get(name=name).rule_id
flag, response = self.... | |
<filename>kamodo/readers/tiegcm.py
import numpy as np
from kamodo import Kamodo, kamodofy, gridify
import time
from scipy.interpolate import RegularGridInterpolator, interp1d
from datetime import datetime,timedelta
# pip install pytiegcm
from tiegcm.tiegcm import TIEGCM
# 'UN', 'VN', 'O1', 'NO', 'N4S', 'HE', 'NE', '... | |
when the browse mode element is not found.
prevError=_("no previous embedded object"))
qn("annotation", key="a",
# Translators: Input help message for a quick navigation command in browse mode.
nextDoc=_("moves to the next annotation"),
# Translators: Message presented when the browse mode element is not found... | |
#!/usr/bin/env python3
"""
Compute the embeddings for every task and store to disk.
Since many tasks might be too large to store in GPU memory (or even
CPU memory), and because Wavenet-like models will be expensive at
inference time, we cache all embeddings to disk.
One benefit of this approach is that since all embe... | |
<filename>resources/mgltools_x86_64Linux2_1.5.6/MGLToolsPckgs/Pmv/hostappInterface/comput_util.py
## Automatically adapted for numpy.oldnumeric Apr 10, 2008 by
##
## Copyright (C) The Scripps Research Institute 2006
##
## Authors: <NAME> <<EMAIL>>
##
## $Header: /opt/cvs/python/packages/share1.5/Pmv/hostappInterface/co... | |
<filename>ea_transformer.py
import math
from functools import partial
from collections import OrderedDict
from copy import deepcopy
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from hilbert import decode, encode
from pyzorder import ZOrderIndexer
from timm.data import IMAGEN... | |
``day_of_month='1-7,15-21'`` (for the first and
third weeks of the month).
.. attribute:: month_of_year
- A (list of) integers from 1-12 that represents the months of
the year during which execution can occur.
- A string representing a Crontab pattern. This may get pretty
advanced, such as ``month_of_year='*/3'... | |
Parameters:
- path
"""
self.send_listStatus(path)
return self.recv_listStatus()
def send_listStatus(self, path):
self._oprot.writeMessageBegin('listStatus', TMessageType.CALL, self._seqid)
args = listStatus_args()
args.path = path
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush... | |
<reponame>hatemhosny/jupytext
"""ContentsManager that allows to open Rmd, py, R and ipynb files as notebooks
"""
import os
from datetime import timedelta
import nbformat
import mock
from tornado.web import HTTPError
from traitlets import Unicode, Float, Bool, Enum
from traitlets.config import Configurable
# import not... | |
for files. On Windows a merely adapter to os.utime
"""
os.utime(filepath, (time.time(), mtime))
else:
def lmtime(filepath, mtime):
"""Set mtime for files, while not de-referencing symlinks.
To overcome absence of os.lutime
Works only on linux and OSX ATM
"""
from .cmd import Runner
# convert mtime to format ... | |
]
optimizer_cls = AdamW
optimizer_kwargs = {
"betas": (args.adam_beta1, args.adam_beta2),
"eps": args.adam_epsilon,
}
optimizer_kwargs["lr"] = args.learning_rate
return optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs)
def convert_example_to_features(example, tokenizer, max_seq_length, doc_stride... | |
= None
''' '''
preset_menu = None
''' '''
preset_subdir = None
''' '''
preset_values = None
''' '''
def as_filename(self, name):
'''
'''
pass
def as_keywords(self, ignore):
'''
'''
pass
def as_pointer(self):
'''
'''
pass
def bl_rna_get_subclass(self):
'''
'''
pass
def bl_rna_get_... | |
arg_default
# If a relative path has been provided either in the environmental
# var or as the default that path needs to be appended to the
# module path. Since all full paths begin with a path delimiter
# this is a valid test
if my_tmp[0] != "/":
my_tmp = (
PathUtils.include_trailing_path_delimiter(self.module... | |
as shaded regions.
Parameters
----------
data : dict
The Python data dictionary generated from running main.py
type_ : str
Which type of data to plot, one of "eval" or "train"
ind : iter of int
The list of hyperparameter settings indices to plot
smooth_over : int
The number of previous data points to smooth ... | |
"""Test suite for faceted module"""
from collections import OrderedDict
from itertools import product
import matplotlib.axes
import matplotlib.figure
import matplotlib.pyplot as plt
import numpy as np
import pytest
from ..faceted import (
_DEFAULT_ASPECT,
_DEFAULT_WIDTH,
faceted,
faceted_ax,
_infer_constraints,
... | |
#!/usr/bin/env python
from __future__ import print_function
import cx_Oracle
import datetime
import calendar
import sys
import logging
import CondCore.Utilities.conddb_serialization_metadata as sm
import CondCore.Utilities.credentials as auth
import CondCore.Utilities.conddb_time as conddb_time
import os
authPathEnvV... | |
value/colors supported for now
if (def_val_dim == 1 or def_val_dim == 4) and default_value.count(None) < def_val_dim:
sampler_name = prefix + action.name + "_mat_node_anim"
if getIndex(samplers, sampler_name) == -1:
sampler = {}
interpolation = animateGetInterpolation(exportSettings, default_value)
sampler['in... | |
from .geometry import near, isnear, orient2d, inrng, slide
import numpy as np
import math
class vec3:
@classmethod
def O(cls):
return cls(0, 0, 0)
@classmethod
def U(cls, r=1):
return cls(r, r, r)
@classmethod
def X(cls, r=1):
return cls(r, 0, 0)
@classmethod
def Y(cls, r=1):
return cls(0, r, 0)
@cl... | |
<filename>azsmart/defaults.py
"""
Contains default configuration. To override this just
set orca definitions in the calling notebook or script.
Defines data model for running azsmart simulation
w/ orca and urbansim.
Note: the actually loading of dating tables from
h5 sources will be done via TableLoad template/confi... | |
crest.Influence), "The entity created an influence for the pulled up port")
self.assertEqual(testentity.port_in_connect.source, testentity.port_in, "The connection's source is the pulled up port")
self.assertEqual(testentity.port_in_connect.target, testentity.sub1.port_in, "The connection's target is the subentity's ... | |
<gh_stars>1-10
import gpflow
import numpy as np
import pandas as pd
import os
import sys
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_probability as tfp
import gpflow
from gpflow.utilities import ops, print_summary
from gpflow.config import set_default_float, default_float, set_default_... | |
modulus 7^20
sage: Zp(7, 20, 'capped-abs')
7-adic Ring with capped absolute precision 20
We create a capped relative ring with each print mode::
sage: k = Zp(7, 8, print_mode='series'); k
7-adic Ring with capped relative precision 8
sage: k(7*(19))
5*7 + 2*7^2 + O(7^9)
sage: k(7*(-19))
2*7 + 4*7^2 + 6*7^3 + ... | |
= None
if ctx.aliasExpr:
kwargs['alias'] = self.visit(ctx.aliasExpr)
name = self.visit(ctx.name)
workarea = self.visit(ctx.workArea)
if isinstance(workarea, float):
workarea = int(workarea)
return make_func_code('DB.use', name, workarea, opentype, **kwargs)
def visitLocate(self, ctx):
kwargs = OrderedDict()
... | |
<gh_stars>0
# Copyright 2019 <NAME>. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | |
<gh_stars>0
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import matplotlib.pyplot as plt
# In[2]:
d08=pd.read_csv("1902HackDATA/IPL2008CSV.csv")
#***Basic/General/Normal Information
d08.head()
d08.dtypes
d08.info()
d08.describe()
# In[3]:
d08
# In[4]:
d08['Strike Rate1']=None
d08['... | |
<filename>django/docs/topics/testing/overview.txt.py
XXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXX XXX XXXXXXX XXXXX
XXXXXXXXXXXXXXXXXXXXXXXXX
XX XXXXXXXX XXXXXXXXXXX
XXXXXXXXXX XXXXXXX XXXXX XXX XXXXXX XXXXXXXXXXXXX
XX XXXXXXXXX
XXX XXXXXXXXXXXXX XXXXXXXX XXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXXXX XXXXX
XXXXXXXXX XXXXXXXXXXXXX... | |
where:
callCount = the number of calls made
timeTakenCPU = the CPU time spent in microseconds
timeTakenWall = the actual time ( wall time ) spent in microseconds
"""
raise NotImplementedError("This function is not written yet. Please put in an issue on the github page.")
def pixelAspect(self):
"""
self.pixelAs... | |
"""
Each stat kind is populated from one or more stat sections (which are described
in the containers module).
Ns_Kind_CompositeIndex -> composite-indexes
Kind_CompositeIndex -> composite-indexes
Ns_Kind_IsRootEntity -> entities + builtin-indexes
Ns_Kind_NotRootEntity -> entities + builtin-indexes
Kind_IsRootEntity -> ... | |
``px``, etc.
hx : list, optional
list of normalized field heights along x axis, of length ``numRays``;
if ``None``, a list of 0.0s for ``hx`` is created.
hy : list, optional
list of normalized field heights along y axis, of length ``numRays``;
if ``None``, a list of 0.0s for ``hy`` is created
px : list, optional... | |
<filename>tests/plugins/test_accounts.py
import bcrypt
import unittest
import uuid
from unittest import mock
from kinto.core import utils
from kinto.core.events import ACTIONS, ResourceChanged
from kinto.core.testing import get_user_headers, DummyRequest
from pyramid.exceptions import ConfigurationError
from pyramid_m... | |
hasattr(self.callbacks,'logger'):
return tcgSupport.fail(self.callbacks.logger,self.callbacks.devname,StatusCode,op=currentFuncName(1), msg=msg, status=status)
def getRange(self, rangeNo, auth, authAs=None):
'''
Reads a band from the drive.
Parameters:
rangeNo - the band to read
auth - Default auth in case if ... | |
lambda t: (time2str(t,cad='%Y-%m-%d_%H:%M:%S')
+('%0.3f'%(t%1)).lstrip('0')) #taurustrend timestamp format
ml = min(len(v) for v in table.values())
for i in range(ml): #len(table.values()[0])):
csv+=sep.join([time_to_text(table.values()[0][i][0]),
str(table.values()[0][i][0])]
+[value_to_text(table[k][i][1]) fo... | |
idx):
input = self.tensor[idx]
target = self.classes[idx]
return input, target
def __len__(self):
return len(self.tensor)
class MultiTransformDataset(data.Dataset):
def __init__(self, dataset, t):
self.dataset = dataset
self.transform = transforms.Compose(
[transforms.ToPILImage()] +
t)
def __getitem__(s... | |
actions for a set of members.
These ACL classes can then be bundled and attached to a base base using
the ``ACLSet`` class.
======== ================
Type Description
======== ================
Scope The scope specifies where the ACL is valid for, e.g. ONE-level, all SUB-levels or RESET previous ACLs
Members A l... | |
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00248228,
'Renaming Unit/Peak Dynamic': 3.58947,
'Renaming Unit/Runtime Dynamic': 0.263641,
'Renaming Unit/Subthreshold Leakage': 0.0552466,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0276461,
'Runtime Dynamic': 3.77863,
'S... | |
raise TypeError( # pragma: no cover
"Unexpected type %r." % type(op))
def mark_last_node(self):
"""
Marks the last node as the final output.
"""
if self.last_added_op is None:
raise RuntimeError("last_added_op is None.") # pragma: no cover
self.mark(-1, self.last_added_op)
def mark(self, i, op):
"""
Marks ... | |
<filename>gymV02/qcore/utils/handle_data.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Implement the classes required to handle orders and the access to information
related to books and candles subscribed by an agent
@author: ucaiado
Created on 07/05/2018
'''
import os
import yaml
from collections import namedtup... | |
<reponame>charlienew/GANCS<gh_stars>10-100
import numpy as np
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
class Model:
"""A neural network model.
Currently only supports a feedforward architecture."""
def __init__(self, name, features):
self.name = name
self.outputs = [features]
def _get_layer_str(s... | |
<gh_stars>0
'''
Plot a variable (XYZ coord, ZTD, residuals) vs. time with TRACE file as input
Input:
trace_file - .TRACE file location from pea - str
output_dir - output_directory for plots - str
Plotting Options
-PPP - Plot XYZ Coords in PPP mode - str
-SPP - Plot XYZ Coords in SPP mode - str
-ZTD - Plot ZTD Estimat... | |
<reponame>MinervaVilchez/tytus<filename>parser/team25/code/astFunciones.py
from astExpresion import Expresion, ExpresionCadena, ExpresionID, ExpresionNumero, TIPO_DE_DATO
from reporteErrores.errorReport import ErrorReport # EN EL AMBITO MAS EXTERIOR SE INGRESAN A LA LISTA , EN ESTAS SUB CLASES SOLO SE SUBE EL ERROR
imp... | |
# -*- coding: utf-8 -*-
import os
import json
import requests
import configparser
from easydict import EasyDict as edict
from datetime import datetime
from archives_tools.dacs import iso2DACS
import uuid
#funtions for debugging
def pp(output):
try:
print (json.dumps(output, indent=2))
except:
import ast
print ... | |
<reponame>duserzym/BiCEP_GUI<gh_stars>1-10
import pandas as pd
import pandas as pd
from importlib import reload # allows reloading of modules
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
import ipywidgets as widgets
from IPython.display import display, clear_output
from impor... | |
= N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1]... | |
* s * iv(k,
b * s) * kv(
(-1) + k, s) + (
-3) * b * k * s * iv(k, b * s) * kv(
(-1) + k, s) + (-8) * b * k ** 2 * iv(
k,
b * s) * kv(
k, s) + 2 * iv((-1) + k,
b * s) * (
((-1) + k) * s * kv((-2) + k, s) + (
(-1) + 3 * k ** 2) * kv((-1) + k,
s) + (
-1) * ((-1) + k) * s * kv(k, s)) + (
-4) * b * s * iv(
k, ... | |
# Copyright (c) 2018, Science and Technology Facilities Council
# This software is distributed under a BSD licence. See LICENSE.txt.
"""
load_functions
--------------
Module for top-level functions that open MRC files and form the main API of
the package.
"""
# Import Python 3 features for future-proofing
from __fu... | |
*= stem.segL
# Get the end point position
end_co = stem.p.co.copy()
stem.spline.bezier_points.add()
newPoint = stem.spline.bezier_points[-1]
(newPoint.co,newPoint.handle_left_type,newPoint.handle_right_type) = (end_co + dirVec,hType,hType)
newPoint.radius = stem.radS*(1 - (stem.seg + 1)/stem.segMax) + stem.radE... | |
<reponame>Xarthisius/yt
import abc
from functools import wraps
import numpy as np
from yt.config import ytcfg
from yt.data_objects.image_array import ImageArray
from yt.funcs import ensure_numpy_array, is_sequence, mylog
from yt.geometry.grid_geometry_handler import GridIndex
from yt.geometry.oct_geometry_handler imp... | |
import numpy as np
from matplotlib.patches import Ellipse
import matplotlib.pyplot as plt
def make_fisher_matrix(params_dict, fisher_params, hpeak=0.0, obs='GS',
sigma=None, sigma_mod_frac=0.,
k_min=None, k_max=None,
z_min=None, z_max=None,
axis_PS=None, cosmo_key='CDM',
add_sigma_poisson=False):
"""
Make Fish... | |
# Copyright 2015 IBM Corp.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | |
UrlMapDefaultRouteActionRetryPolicyPerTryTimeout.to_proto(
resource.per_try_timeout
)
)
else:
res.ClearField("per_try_timeout")
return res
@classmethod
def from_proto(self, resource):
if not resource:
return None
return UrlMapDefaultRouteActionRetryPolicy(
retry_condition=Primitive.from_proto(resource.ret... | |
import numpy as np
import os
from numba import jit
fit_arg,blr,ns=False,0.1,'all'
log_path=os.path.join('./logs/avion/vol1/log_real_processed.csv')
# les booleans qui déterminent plusieurs comportements, voir coms
fit_on_v=fit_arg #est ce qu'on fit sur la vitesse prédite ou sur l'acc
used_logged_v_in_model=not... | |
<reponame>mightqxc/panda-atm<filename>pandaatm/atmbody/slow_task_analyzer.py
import os
import time
import datetime
import copy
import json
from pandacommon.pandalogger import logger_utils
from pandaatm.atmconfig import atm_config
from pandaatm.atmcore import core_utils
from pandaatm.atmbody.agent_base import AgentBas... | |
# -*- coding: utf-8 -*-
#
# Parse a RSD log file.
#
# This class is used by KanataConverter.
#
# There are several IDs in this script:
#
# iid: An unique id for each instruction in a RSD log file.
# This is outputted from SystemVerilog code.
# mid: The index of a micro op in an instruction.
# This is outputted from S... | |
ord(".")
a[2] = ord("?")
assert p[2] == b"?"
def test_from_buffer_more_cases():
try:
from _cffi_backend import _testbuff
except ImportError:
py.test.skip("not for pypy")
BChar = new_primitive_type("char")
BCharP = new_pointer_type(BChar)
BCharA = new_array_type(BCharP, None)
#
def check1(bufobj, expected):
... | |
<reponame>wjsi/aliyun-odps-python-sdk<filename>docs/source/conf.py
# -*- coding: utf-8 -*-
#
# PyOdps documentation build configuration file, created by
# sphinx-quickstart on Wed Nov 18 09:47:14 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible co... | |
import re
from typing import Any, Callable, Dict, Iterator, List, Mapping, OrderedDict, Union
import asdf
from asdf import ValidationError
from asdf.schema import _type_to_tag
from asdf.tagged import TaggedDict
from weldx.asdf.extension import WxSyntaxError
from weldx.asdf.tags.weldx.time.datetimeindex import Datetim... | |
#! /usr/bin/python
"""Code to combine different slabs into a single high resolution slab
# This code was developed by <NAME> at the ARAMIS lab.
# Maintainer: <NAME> (2019)
#
# For any use of this code, the following paper must be cited:
#
# <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>,
# <NAME>, <NAME>, <NAME>, <... | |
by one SciELO Collection.
`editor_address` references the institution who operates the
process.
`publisher_address` references the institution who is responsible
for the Journal.
"""
#Custom manager
objects = JournalCustomManager()
nocacheobjects = models.Manager()
userobjects = modelmanagers.JournalManager(... | |
is computed.
Returns
-------
corr: float
Interquartile range of 1-dimensional sequence.
"""
#ny.percentile(sig, 75) - ny.percentile(sig, 25)
return np.percentile(sig, 75) - np.percentile(sig, 25)
# Kurtosis
def calc_kurtosis(sig):
"""Compute kurtosis along the specified axes.
Parameters
----------
input:... | |
= OrderedDict([
('peer_address', YLeaf(YType.str, 'peer-address')),
('plsp_id', YLeaf(YType.int32, 'plsp-id')),
('tunnel_name', YLeaf(YType.str, 'tunnel-name')),
('pcc_address', YLeaf(YType.str, 'pcc-address')),
('tunnel_name_xr', YLeaf(YType.str, 'tunnel-name-xr')),
])
self.peer_address = None
self.plsp_id = N... | |
from collections import defaultdict
from typing import Iterable, List
import torch
from ppq.core import (COMPELING_OP_TYPES, LINEAR_ACTIVATIONS,
ORT_OOS_FUSE_START_OPS, PPLCUDA_ACTIVATIONS,
QuantizationProperty, QuantizationStates, RoundingPolicy,
TargetPlatform, TensorQuantizationConfig,
empty_ppq_cache)
from ppq... | |
SETermsRef.append([ind1, ind2, -1, -1])
ind1 = ResolvedVarNames.index('Vij')
ind2 = ResolvedVarNames.index('Vimmjm')
SETermsRef.append([ind1, ind2, -1, -1])
ind1 = ResolvedVarNames.index('Vij')
ind2 = ResolvedVarNames.index('Uimjpp')
SETermsRef.append([ind1, ind2, -1, -1])
ind1 = ResolvedVarNames.index('Vij')
i... | |
of the sound
device, and not the format you gave to `Mix_OpenAudio`, although they
may in reality be the same. This is an unfortunate but necessary speed
concern. Use `Mix_QuerySpec` to determine if you can handle the data
before you register your effect, and take appropriate actions.
You may also specify a callb... | |
command (%s for help, %s to quit): ' % (cyan('h'),
cyan('q'))
if num is not None:
choice = num
else:
choice = get_input(msg)
if isinstance(choice, int):
if 0 <= choice <= len(entries):
break
else:
if num is not None:
exit("Invalid number {}: must be between 0 and {}"
.format(num, len(entries) - 1))
else:
... | |
# encoding: utf-8
"""
@author: liaoxingyu
@contact: <EMAIL>
"""
import copy
import torch
from torch import nn
from .backbones.resnet import ResNet, BasicBlock, Bottleneck
from .backbones.senet import SENet, SEResNetBottleneck, SEBottleneck, SEResNeXtBottleneck
from .backbones.resnet_ibn_a import resnet50_ibn_a
from .b... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by <NAME> at 2019-08-20
"""Step_refine_pipline_final.py
:description : basic check .mass balance,annotation,notes
:param :
:returns:
:rtype:
"""
import os
import pickle
import re
import cobra
import pandas as pd
from Bio import SeqIO
import My_def
os.chdir... | |
# Integer matrix multiply 8816 A/B
# load 1/2/4 submatrix
partition_contiguous_idx = lane_in_quad // factor_in_partition # 0011 0011 0011 0011
# access_strided_idx = lane_idx // warp_bfa_access_shape[1]
access_strided_idx = lane_idx // new_obj.layout.factor
access_contiguous_idx = (
(lane_in_pair * factor_in_pa... | |
# search.py
# ---------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# At... | |
<filename>tuf/scripts/repo.py
#!/usr/bin/env python
# Copyright 2018, New York University and the TUF contributors
# SPDX-License-Identifier: MIT OR Apache-2.0
"""
<Program Name>
repo.py
<Author>
<NAME> <<EMAIL>>
<Started>
January 2018.
<Copyright>
See LICENSE-MIT OR LICENSE for licensing information.
<Purpos... | |
RESUMABLE_UPLOAD_THRESHOLD=5):
with _NamedTemporaryFile() as temp:
with open(temp.name, 'wb') as file_obj:
file_obj.write(DATA)
with open(temp.name, 'rb') as file_obj:
blob.upload_from_file(file_obj, rewind=True)
rq = connection.http._requested
self.assertEqual(len(rq), 3)
# Requested[0]
headers = dict(
[(x... | |
"""
Some basic inference functions adapted from my inferno module which should be available
here soon:
https://github.com/nealegibson/inferno
Really they are just rewritten versions of https://github.com/nealegibson/Infer
But there are many other options for optimisers/MCMCs/etc, and they should (in principle)
all do m... | |
import math
import os
import sys
from ConfigParser import RawConfigParser
DEFAULT_SIZE = 400
BOARD_SIZE = 8
CHECKER_SIZE = 30
MAX_VALID_SQ = 32
MOVE = 0
JUMP = 1
OCCUPIED = 0
BLACK = 1
WHITE = 2
MAN = 4
KING = 8
FREE = 16
COLORS = BLACK | WHITE
TYPES = OCCUPIED | BLACK | WHITE | MAN | KING | FREE... | |
# Owner(s): ["module: nn"]
import inspect
import torch
from unittest import mock
from unittest.mock import MagicMock, patch
from torch.testing import floating_types
from torch.testing._internal.common_device_type import instantiate_device_type_tests, dtypes
from torch.testing._internal.common_quantization import skipI... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.