input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
# Cleanup
del uproot_file
def test_histogram1D_to_from_existing_histogram(logging_mixin: Any) -> None:
""" Test passing a Histogram1D to ``from_existing_histogram``. It should return the same object. """
h_input = histogram.Histogram1D(
bin_edges=np.array([0, 1, 2]),
y=np.array([2.3, 5.4]),
errors_squared=np.ar... | |
MA'},
'1508881':{'en': 'Ashland, MA'},
'1508885':{'en': 'Spencer, MA'},
'1508886':{'en': 'Rutland, MA'},
'1508892':{'en': 'Leicester, MA'},
'1508894':{'en': 'Brockton, MA'},
'1508896':{'en': 'Brewster, MA'},
'1508897':{'en': 'Brockton, MA'},
'1508898':{'en': 'Westborough, MA'},
'1508923':{'en': 'Middleborough,... | |
text for labels, title and axes ticks
ax.set_ylabel('Scores')
ax.set_title('Min and Max grain size '+str(th)+' threads')
ax.set_xticks(ind + width / 2)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
ax.legend((rects1[0], rects2[0]), ('Min', 'Max'))
def autolabel(rects):
"""
Attach a text label above e... | |
bzImage build command: " + argv_str)
tokens = argv_str.split()
if len(tokens) < 5:
verbose("Warning: not well-formated bzImage build command", LEVEL_0)
return ''
outfile = os.path.abspath(os.path.join(pwddir, tokens[-1]))
infiles = tokens[1 : len(tokens)-1]
infiles = [os.path.abspath(os.path.join(pwddir, afile))... | |
<filename>sdk/python/pulumi_azure/media/asset.py
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** 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, O... | |
x, pars: 0]
counter = -1
for p in product(*possibles):
## Comtinations
counter += 1
## print p, counter
## Sequential parameters
types = pos_types[np.random.randint(0, len(pos_types))]
# types = 'object'
auto_excluded = pos_auto_excluded[np.random.randint(0, 3)]
if types in ['object', 'listobject']:
typeret =... | |
<gh_stars>1-10
import re
import config
import logging
import sqlite3
from time import mktime
from os.path import isfile
from importlib import reload
from markov import CorpusModel
from telethon import TelegramClient, events
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(mes... | |
= np.linalg.inv(H_body_lb3)
# Get gt files and days
gt_files = np.sort([gt_f for gt_f in listdir(join(data_path, gt_folder)) if gt_f[-4:] == '.csv'])
cov_files = np.sort([cov_f for cov_f in listdir(join(data_path, cov_folder)) if cov_f[-4:] == '.csv'])
days = [d[:-4].split('_')[1] for d in gt_files]
# Loa... | |
<reponame>bpinsard/nipy
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Utilities for extracting masks from EPI images and applying them to time
series.
"""
from __future__ import absolute_import
import math
# Major scientific libraries imports
imp... | |
not in oval] for B in BIBD]
# We relabel the points to 0,1,2,...
V = [x for x in range(73) if x not in oval]
rel = dict(zip(V,range(len(V))))
PBD = [[rel[x] for x in B] for B in PBD]
return OA_from_PBD(7,66,PBD,check=False)
def OA_7_68():
r"""
Return an OA(7,68)
Construction shared by <NAME>.
.. SEEALSO::
... | |
with_file')
try:
#remove file from binary, whether having written it to dst_fullpath or not. To prevent bloating
binary = binary[:binary_offset]
if len(binary) == 0:
if MessageFields.WITH_BINARY in transport_json:
del transport_json[MessageFields.WITH_BINARY]
except Exception:
self.logger.exception(f'{self.conn... | |
<gh_stars>0
"""
This file deals with 'model parameters' issues regarding the Cluster Class (e.g. GNFW parameteres)
"""
import astropy.units as u
import numpy as np
from ClusterModel.ClusterTools import cluster_global
from ClusterModel.ClusterTools import cluster_profile
from ClusterModel.ClusterTools import cluster_s... | |
["2003-12-24", 98],
["2003-12-25", 96],
["2003-12-26", 48],
["2003-12-27", 89],
["2003-12-28", 130],
["2003-12-29", 90],
["2003-12-30", 106],
["2003-12-31", 111],
["2004-01-01", 128],
["2004-01-02", 83],
["2004-01-03", 60],
["2004-01-04", 109],
["2004-01-05", 137],
["2004-01-06", 147],
["2004-01-07", 99],... | |
<reponame>mahakbansal/ChessAlphaZero
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of the python-chess library.
# Copyright (C) 2012-2018 <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by... | |
# Copyright 2019 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... | |
"""This module implements the TwillBrowser."""
import pickle
import re
from urllib.parse import urljoin
import requests
import requests.auth
from lxml import html
from requests.exceptions import InvalidSchema, ConnectionError
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from . import log,... | |
search(g_param['OptionsDefine.WaiterInfo']['expr'], json_obj))
time.sleep(g_param['OptionsDefine.WaiterInfo']['interval'])
FormatOutput.output("action", json_obj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
def doJoinGameServerSession(args, parsed_globals):
g_param = parse_global_arg(parsed_globa... | |
# Copyright (c) 2019 PaddlePaddle Authors. 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 ... | |
doesn’t use the cache of uncompressed blocks.
:param pulumi.Input[int] merge_tree_max_rows_to_use_cache: If ClickHouse should read more than merge_tree_max_rows_to_use_cache rows in one query, it doesn’t use the cache of uncompressed blocks.
:param pulumi.Input[int] merge_tree_min_bytes_for_concurrent_read: If the nu... | |
# -*- coding: utf-8 -*-
import copy
from typing import Union
import numpy as np
def temperature(
t: np.array,
fire_load_density_MJm2: float,
fire_hrr_density_MWm2: float,
room_length_m: float,
room_width_m: float,
fire_spread_rate_ms: float,
beam_location_height_m: float,
beam_location_length_m: Union[float,... | |
"""Database tools."""
import os
from cStringIO import StringIO
from skytools.quoting import quote_copy, quote_literal, quote_ident, quote_fqident
import skytools.installer_config
try:
import plpy
except ImportError:
pass
__all__ = [
"fq_name_parts", "fq_name", "get_table_oid", "get_table_pkeys",
"get_table_colum... | |
<filename>code/feature_encoding.py<gh_stars>0
import numpy as np
from Bio import SeqIO
import math
import pandas as pd
import csv
from keras.models import load_model
from collections import Counter
import re, os, sys
import itertools
def extract_DNAfeatures(data, c_m, nc_m, Tc_pos1, Tc_neg1, Tc_pos2, Tc_neg2, Tc_pos3... | |
be calculated
accuracy Accuracy of the autocorrelation function, typically 16
split Number of seconds of each chunk to split the data into
E.g. split=10 will divide a 60 second stream in 6 ten-second
traces and calculate G for each individual trace
========== =======================================================... | |
'86180254':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6df1\u5733\u5e02')},
'86180255':{'en': 'Shantou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5934\u5e02')},
'86180251':{'en': 'Dongguan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e1c\u839e\u5e02')},
'86180252':{'en': 'Dongguan, Guangdong', 'zh': u('\u5e7f\u... | |
and len(x) == 0:
pass
else:
if isinstance(a, np.ndarray):
aa = a[:, np.newaxis]
else:
aa = a
x[ind1] += indexed(dv2, ind2) * aa
assert np.allclose(c1.data, x)
c1.axpy(-a, c2, ind=ind1, x_ind=ind2)
assert len(c1) == len(v1)
assert np.all(almost_equal(c1, v1))
def test_axpy_self(vector_array):
v = vector_ar... | |
sample
neural_mode :
defines the input for the neural net
file :
string which points to the file with the corpus of text
sg_file :
string which points to the location with the skipgrams created with the corpus of text
optimizer :
optimizer which shall be used for the keras neural net
properties:
... | |
function with respect to the distribution
location and scale only tested on a few examples
Parameters
----------
all parameters are keyword parameters
fn : function (default: identity mapping)
Function for which integral is calculated. Takes only one argument.
args : tuple
argument (parameters) of the distrib... | |
<filename>MapGen.py
import VectorMaps, json, sys
from os import system, path
#Used instead of print() and input() for purposes of accessibility to screenreaders
def dual_print(string):
system("title "+string)
print(string + '\n')
def dual_input(string):
system("title "+string)
return input(string)
... | |
= False
status = udoc.do_import(mock_cmdp)
self.assertFalse(status)
mock_cmdp.reset_mock()
udoc = udocker.Udocker(mock_local)
mock_cmdp.get.side_effect = cmd_options
mock_chkimg.return_value = ("IMAGE", "")
mock_cmdp.missing_options.return_value = True
status = udoc.do_import(mock_cmdp)
self.assertFalse(statu... | |
crossLP.addGlobalParameter('lim', 1.0)
crossLP.setCutoffDistance(3.0)
lambdas_full = np.loadtxt(TypesTable, delimiter=',')
lambdas = np.triu(lambdas_full) + np.triu(lambdas_full, k=1).T
diff_types = len(lambdas)
print(len(lambdas))
lambdas = list(np.ravel(lambdas))
fTypes = self.mm.Discrete2DFunction(di... | |
#! /usr/env/python
r"""
Landlab's Continuous-Time Stochastic (CTS) cellular automata modeling package.
Overview
--------
A CellLab CTS model implements a particular type of cellular
automaton (CA): a continuous-time stochastic CA. The approach is based on that
of Narteau et al. (2002, 2009) and Rozier and Narteau (20... | |
np.array(coords_move[i]) + np.array(delta)
else:
new_coord = np.array(coords_move[i]) - np.array(delta)
slab_move.append(species_move[i], new_coord, coords_are_cartesian=True)
return slab_move
def Find_Broken_Molecules(slab, sg, species_intact, coords_intact, unique_bulk_subgraphs):
"""
Use molecular identifica... | |
== 0:
more_pages_to_query = False
# case where there are more dates to cover
if query_end_date < end_date:
# slide the date window forward and reset the pagination values
query_start_date = query_start_date + timedelta(days=time_delta)
query_end_date = query_start_date + timedelta(days=time_delta)
query_begin = ... | |
not found
:type fcnName: string
:param fcnName: function name for error reporting
:type pos: string or ``None``
:param pos: position from locator marks for error reporting
:rtype: an object
:return: the extracted object
"""
while len(path) > 0:
head, tail = path[0], path[1:]
try:
obj = obj[head]
except (Ke... | |
# coding: utf-8
import typing
import json
import asyncio
from collections import deque
from starlette.websockets import WebSocket
from .JsPyTextSocket import JsPyTextSocket, JsPyError
from . import JsPyBackground
__all__ = ['push_nowait', 'push', 'pop', 'shift', 'add_callback',
'clear_callback', 'is_empty', 'get_keys... | |
<filename>examples/applications/fileupload.py
import argparse
import base64
import datetime
import enum
import json
import hashlib
import logging
import os
import sys
import time
from typing import Tuple, Optional, List
import requests
from requests.auth import HTTPBasicAuth
def sha256(data_bytes) -> bytes:
return ... | |
'''
## MESSAGING CLIENT 1.0
##
## This is a simple client side app that connects to the messaging server and provides End to End Encryption
## All messages tranfered between clients is indecipherable to all except communicating parties
## Users can register for accounts with the chosen server.
## You can also tr... | |
= singleFlyDf['HeadX(pix)']
singleFlyEntranceData_TheWindSide_P01 = singleFlyDf['FromTheWindPortEnd_P01_EnterIdx_ExitIdx_EnterHeadX_ExitHeadX']
singleFlyEntranceIndexList_TheWindSide_P01 = [item[0] for item in singleFlyEntranceData_TheWindSide_P01 if item]
for index in singleFlyEntranceIndexList_TheWindSide_P01:
... | |
isinstance(inputs, s3_input):
input_dict['training'] = inputs
elif isinstance(inputs, dict):
for k, v in inputs.items():
input_dict[k] = _TrainingJob._format_s3_uri_input(v)
else:
raise ValueError('Cannot format input {}. Expecting one of str, dict or s3_input'.format(inputs))
channels = []
for channel_name, c... | |
<gh_stars>0
#!/usr/bin/env python
import json
import os
import sys
import numpy as np
import pylab as pl
from scipy.optimize import curve_fit
import tqdm
import quantities_for_comparison as qc
SHOW_IN_BROWSER=True
DEFAULT_PREFACTOR = 100
DEFAULT_wb0 = 1.0/8.0
DEFAULT_wb1 = 1.0/64.0
EXPECTED_SCRIPT_VERSION = ["0.0.3"... | |
or "--l" in content:
pass
elif "{" in content and "}" in content:
try:
to_find_list = []
for i in range(len(content)):
if content[i] == "{":
back_brace = content.find("}", i)
if not back_brace == -1:
to_find_list.append([i, back_brace])
if len(to_find_list) >= 3:
break
except IndexError:
return
if to_fin... | |
<reponame>majacQ/pyEX
# *****************************************************************************
#
# Copyright (c) 2020, the pyEX authors.
#
# This file is part of the pyEX library, distributed under the terms of
# the Apache License 2.0. The full license can be found in the LICENSE file.
#
from enum import Enum
f... | |
Mod5;2 Mk-46 Mod5;10 DICASS (85) Sonobuoy;10 LOFAR (85) Sonobuoy;30 DIFAR (85) Sonobuoy;')
unit = SM.GetDefaultUnit()
unit.className = 'Oliver Hazard Perry FFGHM'
unit.unitName = "USS Rentz"
UI = SM.GetUnitInterface('USS Carl Vinson')
leader_track = UI.GetTrackById(UI.GetPlatformId())
lon_deg = 57.296*leader_tr... | |
argument,
# 2. Specified by a subclass' _default_type attribute, or
# 3. Hinted for a subclass' components attribute.
cls = cls or self._Component
component = cls(id=id, **kwargs)
if "order" not in kwargs:
# For automatically created dimensions, give a serial value to the
# order property
try:
compo... | |
_Pg2ac = np.minimum(0, _Pg)
# Energy sums in MWH
# Electrical demand including the energy consumption of the other system components
_E['El'] = np.sum(np.abs(_Plt)) * _dt / 3.6e9
# DC output of the PV generator including curtailment
_E['Epv'] = np.sum(np.abs(_Ppv)) * _dt / 3.6e9
# DC input of the batter... | |
<reponame>dnikishov/fuel-web<filename>nailgun/nailgun/task/task.py
# -*- coding: utf-8 -*-
# Copyright 2013 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apac... | |
<filename>packages/main/tests/python/test_tables.py<gh_stars>100-1000
import os
import tempfile
from collections import namedtuple, OrderedDict
from contextlib import contextmanager
from pathlib import Path
import pytest
from RPA.Tables import Table, Tables, Dialect
RESOURCES = Path(__file__).parent / ".." / "resour... | |
when "
"requesting a CHILD object."))
read_kwargs['child_id'] = uuid
# Accept parent_type as either EntryWrapper subclass or string
if not isinstance(parent_type, str):
parent_type = parent_type.schema_type
return adapter.read(parent_type, root_id=parent_uuid,
child_type=cls.schema_type, **read_kwargs)
@classm... | |
return metrics[key]
else:
return threshold_default
def _determine_threshold(self, threshold_default: float = .5) -> float:
if type(self.model) in [TabNetClassifier, MLPClassifier]:
return self._determine_threshold_nn(threshold_default)
elif isinstance(self.model, RandomForest):
self._determine_threshold_rf(thre... | |
<filename>guangdong/workspace/tools/generate_result.py<gh_stars>0
import os
import json
import os.path as osp
from tqdm import tqdm
import torch
from mmcv import Config, DictAction
from mmcv.cnn import fuse_conv_bn
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import (get_... | |
def update_snmp_config(self, context):
"""Update the snmpd configuration"""
personalities = [constants.CONTROLLER]
config_uuid = self._config_update_hosts(context, personalities)
config_dict = {
"personalities": personalities,
"classes": ['platform::snmp::runtime',
'platform::fm::runtime'],
}
self._config_appl... | |
<reponame>landportal/data
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import json
def getUNM49code(label):
return {
'Africa': "002",
'Americas': "019",
'Asia': "142",
'Caribbean': "029",
'Central Africa': "017",
'Central America': "013",
'Central Asia': "143",
'CIS (Commonwealth of Independent States)': [], #[... | |
<gh_stars>10-100
"""
The context object for evaluating script code. Most of the implementation
of TworldPy lives in the EvalPropContext module.
"""
import re
import random
import ast
import operator
import itertools
import tornado.gen
import bson
from bson.objectid import ObjectId
import motor
import twcommon.misc
f... | |
self.format == 1 or self.format == 2:
print(" format = %d" % (self.format))
gid = 1
for r in self.Range1:
names = []
for _ in range(r.nLeft + 1):
names.append(self.glyph_names[gid])
gid += 1
print(f" ({r.first}, {r.nLeft}): {', '.join(names)}")
elif self.format == 2:
print(" format = %d" % (self.format))
gid... | |
"role":
log_data[
"message"
] = "ARN type not supported for generating resource policy changes."
log.debug(log_data)
return extended_request
resource_policy = {"Version": "2012-10-17", "Statement": []}
resource_policy_sha = sha256(
json.dumps(resource_policy, escape_forward_slashes=False).encode()
).hexdigest... | |
<filename>robotframework-ls/src/robotframework_ls/impl/keyword_argument_analysis.py
from robotframework_ls.impl.protocols import (
IKeywordArg,
IRobotToken,
)
from typing import Optional, List, Deque, Iterator, Dict, Union, Sequence
import itertools
from robocorp_ls_core.lsp import Error
from robocorp_ls_core.constan... | |
:meth:`pikepdf.Pdf.get_warnings()` to
retrieve warnings.
attempt_recovery: If True (default), attempt to recover
from PDF parsing errors.
inherit_page_attributes: If True (default), push attributes
set on a group of pages to individual pages
access_mode: If ``.default``, pikepdf will
decide how to access the fil... | |
assert class_mock is not user_mock
assert_equal("instance", user.method())
assert_equal("class", user2.method())
def test_should_call_with_class_default_attributes(self):
"""Flexmock should not allow mocking class default attributes like
__call__ on an instance.
"""
class WithCall:
def __call__(self, a):
ret... | |
<reponame>happyharrycn/vatic_fpv<filename>video_tools/pympi/Elan.py
# -*- coding: utf-8 -*-
from xml.etree import cElementTree as etree
import os
import re
import sys
import time
VERSION = '1.69'
class Eaf:
"""Read and write Elan's Eaf files.
.. note:: All times are in milliseconds and can't have decimals.
:va... | |
from __future__ import absolute_import, division, print_function
"""
Author : Lyubimov, A.Y.
Created : 10/10/2014
Last Changed: 10/31/2019
Description : IOTA I/O module. Reads PHIL input, also creates reasonable IOTA
and PHIL defaults if selected. PHILFixer can be used to ensure
backwards compatibility with older pa... | |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# =================================================================
# =================================================================
"""
IBMPowerVMBaseVIFDriver
"""
import time
import traceback
from nova import context as ctx
from nova.openstack.common import lockutil... | |
'numpy.ndarray'>
"""
data = ndarray.ravel(self._data)
if self._mask is not nomask:
data = data.compress(np.logical_not(ndarray.ravel(self._mask)))
return data
def compress(self, condition, axis=None, out=None):
"""
Return `a` where condition is ``True``.
If condition is a `MaskedArray`, missing values are c... | |
from __future__ import absolute_import
import wx
from wx.lib.pubsub import pub
import matplotlib
from matplotlib.figure import Figure
from matplotlib.widgets import AxesWidget
try:
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
except IOError:
# on some linux installations this import needs to be don... | |
<gh_stars>0
import datetime
import logging
import uuid
from dataclasses import dataclass, field
from typing import Dict, Any, Optional, Iterator, Union, List
from marshmallow import fields, post_load, Schema
from sqlalchemy import (
Table,
MetaData,
Column,
String,
ForeignKey,
Boolean,
DateTime,
select,
Integ... | |
#Mainly inteded as a private method although kept public, and
#fascilitated the transformation of the compliance matrix to another
#coordinate system.
#:Args:
#- `th (1x3 Array[float])`: The angles about which the material can be
#rotated when it is initialized. In degrees.
#:Returns:
#- `Sp`: The transforme... | |
<gh_stars>0
import os
import numpy as np
from d3m import container
from collections import OrderedDict
from d3m import container, utils
from common_primitives import utils as comUtils
from d3m.metadata import base as metadata_base
from d3m import metrics
from common_primitives.dataset_to_dataframe import DatasetToDataF... | |
if any value is such a
value.
:return: The computed sample standard deviation.
"""
return sd(data=self, ignore_nodata=ignore_nodata)
def sgn(self) -> 'ProcessBuilder':
"""
Signum
:param self: A number.
:return: The computed signum value of `x`.
"""
return sgn(x=self)
def sin(self) -> 'ProcessBuilder':
... | |
<reponame>meghasfdc/st2
# Copyright 2019 Extreme Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | |
from copy import deepcopy
import unittest
from flask import json
from flask.helpers import url_for
from flask_testing.utils import TestCase
from google.appengine.datastore import datastore_stub_util
from google.appengine.ext import testbed, ndb
from mejcrt.util import onlynumbers
from .fixtures import fixture_random... | |
(1200, 7, 1000, 1800.0),
(1250, 3, 1100, 2000.0),
(1250, 7, 1200, 2200.0),
], ["time", "id", "volume", "volume_sum"])
assert_same(new_pdf2, expected_pdf2)
def test_summarizeWindows_udf(self):
from ts.flint import udf
from ts.flint import windows
from collections import OrderedDict
from pyspark.sql.types impor... | |
<filename>opsdroid/connector/gitlab/tests/test_connector_gitlab.py<gh_stars>1-10
import logging
import asyncio
from pathlib import Path
import asynctest.mock as amock
import pytest
import opsdroid.connector.gitlab.events as gitlab_events
from opsdroid.connector.gitlab import ConnectorGitlab
from opsdroid.matchers imp... | |
from ..dojo_test_case import DojoTestCase, get_unit_tests_path
from dojo.models import Test, Engagement, Product
from dojo.tools.sonarqube.parser import SonarQubeParser
class TestSonarQubeParser(DojoTestCase):
# comment out to get full diff with big reports
# maxDiff = None
def init(self, reportFilename):
my_fi... | |
# -*- test-case-name: twistedcaldav.directory.test.test_calendar -*-
##
# Copyright (c) 2005-2015 Apple Inc. 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://ww... | |
<reponame>bhuztez/sqlite3ct
from functools import wraps
from inspect import signature, Signature
from ctypes import (
PyDLL, pythonapi, CFUNCTYPE, POINTER, Structure, cast, byref,
c_ubyte, c_int, c_uint, c_double,
c_char_p, c_void_p, string_at)
import sys
libsqlite = None
if sys.platform == 'win32':
libsqlite = P... | |
<gh_stars>1-10
# Copyright (c) 2020 PaddlePaddle Authors. 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 requir... | |
<reponame>ChristopheVdE/Bacterial-WGS-pipeline
############################################################################################################
# NAME: hybrid assembly.py
# AUTHOR: <NAME>
# FUNCTION: creates some texts files containing location variables that are used by the snakefile as input
# USAGE LINUX... | |
<filename>tests/composition/test_composition.py
import functools
import logging
from timeit import timeit
import numpy as np
import pytest
from psyneulink.components.functions.function import Linear, SimpleIntegrator
from psyneulink.components.mechanisms.processing import integratormechanism
from psyneulink.componen... | |
= self.RECURSIVE
self.NONSYSTEMATIC = RM_Field_FRC_CONVGENERATOR_NONSYSTEMATIC(self)
self.zz_fdict['NONSYSTEMATIC'] = self.NONSYSTEMATIC
self.__dict__['zz_frozen'] = True
class RM_Register_FRC_PUNCTCTRL(Base_RM_Register):
def __init__(self, rmio, label):
self.__dict__['zz_frozen'] = False
super(RM_Register_FRC_... | |
#!/usr/local/bin/python
# <NAME> | 05/29/2018
#|__This script requires Python 3.4 and modules - numpy & scipy
#|__extracts the quality string and determine the length and average quality score of each read
#|__Converts the raw values for each read set into descriptive statistics
#|__Provides descriptive stats for ... | |
"HS256",
# "kid": "018c0ae5-4d9b-471b-bfd6-eef314bc7037"
# },
# "signature": "xuLifqLGiblpv9zBpuZczWhNj1gARaLV3UxvxhJxZuk"
# }
# Figure 55: Flattened JWS JSON Serialization
# 4.8. Multiple Signatures
# This example illustrates multiple signatures applied to the same
# payload. Since this example contains more than o... | |
"""
Conversion functions between corresponding data structures.
"""
import json
import logging
from collections import Hashable, OrderedDict # pylint: disable=E0611,no-name-in-module # moved to .abc in Python 3
from copy import deepcopy
from tempfile import TemporaryDirectory
from typing import TYPE_CHECKING
from urlli... | |
# Copyright 2020 Google Research. 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 ... | |
) from None
else:
try:
a.pop(b)
except TypeError:
raise TypeError(
"{} object cannot be interpreted as an integer".format(
type(b).__name__
)
) from None
return a
def removeByIndex_(self, b):
""" Removes the value at specified index or indices in-place. """
if isinstance(b, Iterable):
try:
c = 0
for i ... | |
from __future__ import annotations
import atexit
import copy
import dataclasses
import enum
import json
import logging
import os
import sys
import time
import tkinter
from pathlib import Path
from tkinter import messagebox, ttk
from typing import Any, Callable, Iterator, List, Type, TypeVar, overload
import dacite
fr... | |
(T_max, )
# compute probs
probs = torch.exp(gaussians.log_prob(frames_idx)) # (B, L_max, T_max)
# apply mask to set probs out of sequence length to 0
probs = probs.masked_fill(mask.unsqueeze(2), 0) # (B, L_max, T_max)
# compute weights
weights = probs / (torch.sum(probs, dim=1, keepdim=True) + 1e-20) # (B, L_max,... | |
"""client.py
The client script continuously measures write performance, submitting the results to a server, as well as \
logging to client_{pid}.log. The client will run the specified run time, or defaults to a random time \
that will write at least 2 files if not provided. Writing is performed in chunks to a temporar... | |
= doc.createTextNode("%s" %filteredErrata)
paragraph.appendChild(pText)
#rowValidityCell.appendChild(paragraph)
errataCell.appendChild(paragraph)
tableRow.appendChild(errataCell)
table.appendChild(tableRow)
oTableContainer.appendChild(table)
oTableRow.appendChild(oTableContainer)
oTable.appendChild(oTab... | |
<gh_stars>0
#!/usr/bin/env python
"""CRN class."""
from collections import defaultdict
import itertools
from libsbml import writeSBMLToFile, formulaToL3String, SBMLDocument
import logging
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import connected_components
import sympy as sp
im... | |
None or self.multiple_ori_ids[track_id] <= self.FRAME_THR \
or dets_ids[ious_inds[attack_ind]] not in self.multiple_ori2att \
or track_id not in self.multiple_ori2att:
continue
if ious[attack_ind, ious_inds[attack_ind]] > self.ATTACK_IOU_THR or (
track_id in self.low_iou_ids and ious[attack_ind, ious_inds[attack_i... | |
bn_momentum: float. Batch normalization momentum.
"""
self.unit1 = BnReluConv(input_channels, n_filters, filter_size,
dropout, bias, dilation,
bn_momentum=bn_momentum)
self.unit2 = BnReluConv(n_filters, n_filters, filter_size, dropout,
bias, 1, bn_momentum=bn_momentum)
if input_channels != n_filters:
self.equ... | |
<reponame>jorgeMorfinezM/cargamos_api_test
# -*- coding: utf-8 -*-
"""
Requires Python 3.8 or later
"""
__author__ = "<NAME> (<EMAIL>)"
__copyright__ = "Copyright 2021, <NAME>"
__license__ = ""
__history__ = """ """
__version__ = "1.1.A19.1 ($Rev: 1 $)"
import json
import re
import threading
import time
import uuid
... | |
enumerate with --experimental and --since 2.42.0'
'--summary',
['enumerate', '--experimental', '--since', '2.42.0', '--summary'],
{'stdout': ['3 CIMClass(s) returned'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --experimental and --since 2.45.0.',
['enumerate', '--exp... | |
"""
The client's core Flexx engine, implemented in PScript.
"""
from pscript import this_is_js, RawJS
from pscript.stubs import window, undefined, time, console, JSON
# This module gets transpiled to JavaScript as a whole
__pscript__ = True
class Flexx:
""" JavaScript Flexx module. This provides the connection bet... | |
HARKobject
from HARK.utilities import warnings # Because of "patch" to warnings modules
from HARK.interpolation import CubicInterp, LowerEnvelope, LinearInterp
from HARK.simulation import drawDiscrete, drawBernoulli, drawLognormal, drawUniform
from HARK.utilities import approxMeanOneLognormal, addDiscreteOutcomeConstan... | |
of this function (CosmoTransitions v1.0.2 and
earlier), the start and end points of the
path were effectively held fixed during the main deformation. This was
because the line ``phi_lin = phi[:1] + ...`` was calculated *before* the
line ``phi = phi+F*stepsize``. Since the spline basis functions are
zero at the sta... | |
'Session' returns object of type '_NameSpace'
"Session": (61451, 2, (9, 0), (), "Session", '{00063002-0000-0000-C000-000000000046}'),
"Size": (3592, 2, (3, 0), (), "Size", None),
"Subject": (55, 2, (8, 0), (), "Subject", None),
"UnRead": (61468, 2, (11, 0), (), "UnRead", None),
# Method 'UserProperties' retur... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Definition of the NSDE algorithm"""
import numpy as np
try:
from openmdao.utils.concurrent import concurrent_eval
except ModuleNotFoundError:
import warnings
warnings.warn("OpenMDAO is not installed. Concurrent evaluation is not available.")
from . import sorting, ... | |
those to avoid reading in the cmds table.
# For now just get things working reliably.
loads_table_path = paths.LOADS_TABLE_PATH(scenario)
loads_rows = []
# Probably too complicated, but this bit of code generates a list of dates
# that are guaranteed to sample all the months in the lookback period with
# two we... | |
0):
for yp in [-2, -1, 0, 1, 2]:
if (y + yp < last_img.shape[1]) and (y + yp >= 0):
i_xpyp = last_img[x + xp, y + yp]
if i_xpyp > 0:
new_val = min(i_xy, i_xpyp, cur_img[x, y])
if cur_img[x, y] != new_val:
cur_img[x, y] = new_val
img_list += [cur_img]
if (cur_img == last_img).all():
print("Done")
break
else... | |
("The storage engine for the table doesn't"
" support repair"),
'Msg_type': 'note',
'Op': 'repair'
}])
self.assertEqual(ret, expected)
ret = self.run_function(
'mysql.db_optimize',
name=dbname,
connection_user=self.user,
connection_pass=self.password
)
expected = []
for tablename, engine in iter(sorted(t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.