input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<filename>tests/unit/integration/github/test_utils.py
# 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... | |
<gh_stars>1-10
# Copyright (C) 2012 <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, pub... | |
the material structure are normally identified
by the sequential labels assigned by PENGEOM. For complex
geometries, however, it may be more practical to employ user
labels, i.e., the four-character strings that identify the
body in the geometry definition file. In PENMAIN (and only
in the parts of the code that f... | |
<gh_stars>1-10
import numpy
from amuse.test.amusetest import TestWithMPI
from amuse.community.seba.interface import SeBaInterface, SeBa
from amuse.units import units
from amuse.units import constants
from amuse.datamodel import Particle
from amuse.datamodel import Particles
class TestSeBaInterface(TestWithMPI):
d... | |
"""A collection of tools, tips, and tricks.
2009-07-20 22:36 IJC: Created
2010-10-28 11:53 IJMC: Updated documentation for Sphinx.
2011-06-15 09:34 IJMC: More functions have been added; cleaned documentation.
"""
import pdb
import numpy as np
def getfigs():
"""Return a list of all open matplotlib figures.
No i... | |
'last_modified_time_utc': {'readonly': True},
'traffic_manager_host_names': {'readonly': True},
'target_swap_slot': {'readonly': True},
'outbound_ip_addresses': {'readonly': True},
'possible_outbound_ip_addresses': {'readonly': True},
'suspended_till': {'readonly': True},
'max_number_of_workers': {'readonly': Tru... | |
""" This module provides the functionality to calculate ephemeris for two bodies problem
also in the case of perturbed methods. More advance pertubed methods will be handled
in other module
"""
# Standard library imports
import logging
from math import isclose
from typing import ForwardRef
# Third party imports
impo... | |
'prf': str,
'dh_group': list,
}
},
}
# =================================================
# Parser for
# Parser for 'show crypto ikev2 proposal'
# =================================================
class ShowCryptoIkev2Proposal(ShowCryptoIkev2ProposalSchema):
"""Parser for show crypto ikev2 proposal"""
cli_comman... | |
% (
T("Is this a strict hierarchy?"),
T("Select this if all specific locations need a parent at the deepest level of the location hierarchy. For example, if 'district' is the smallest division in the hierarchy, then all specific locations would be required to have a district as a parent.")))
table.location_parent_re... | |
<reponame>bopopescu/tencentcloud-cli-intl-en<gh_stars>0
# -*- coding: utf-8 -*-
DESC = "tke-2018-05-25"
INFO = {
"CreateCluster": {
"params": [
{
"name": "ClusterCIDRSettings",
"desc": "Container networking configuration information for the cluster"
},
{
"name": "ClusterType",
"desc": "Cluster type. Managed cl... | |
self.get_ax_vis()
try:
xmin = float(xmin_text)
ax.set_xbound(lower=xmin)
except ValueError:
self.update_status('xmin must be a number')
try:
xmax = float(xmax_text)
ax.set_xbound(upper=xmax)
except ValueError:
self.update_status('xmax must be a number')
self.figcanvas_vis.draw()
def ylim_a... | |
<gh_stars>1-10
# -*- coding: utf-8 -*-
# pylint: disable=C0111,C0103,R0205
__author__ = 'guotengfei'
import functools
import logging
import traceback
import pika
from pika.adapters.tornado_connection import TornadoConnection
LOGGER = logging.getLogger(__name__)
# 异常捕获
def exception_catch(func):
@functools.wraps(... | |
from functools import partial
from typing import *
import attr
import dlms_cosem.utils
from dlms_cosem import a_xdr, cosem, dlms_data
from dlms_cosem import enumerations as enums
from dlms_cosem.cosem import selective_access
from dlms_cosem.dlms_data import (
VARIABLE_LENGTH,
AbstractDlmsData,
DlmsDataFactory,
de... | |
plt.text(2.05, means[i, 1], nbd_sites[i], color='k',
fontsize=8)
plt.xlim(0.5, 2.5)
def plot_bid_vs_bim_release(df, nbd_sites, dtype='Release',
file_basename=None):
replicates = range(1, 4)
activators = ['Bid', 'Bim']
# Get the length of the timecourses
for nbd_index, nbd_site in enumerate(nbd_sites):
color_i... | |
go copy function, copying elements into this list from source list, up to min of size of each list """
mx = min(len(self), len(src))
for i in range(mx):
self[i] = src[i]
# Python type for slice []string
class Slice_string(GoClass):
""""""
def __init__(self, *args, **kwargs):
"""
handle=A Go-side object is... | |
cannot be raised
# from here because numpy catches.
raise ValueError(msg.format(func.__name__))
if is_bool_dtype(result):
return result
# the result is object dtype array of Period
# cannot pass _simple_new as it is
return PeriodIndex(result, freq=self.freq, name=self.name)
@property
def _box_func(self):
re... | |
import mock
import pytest
from hcloud.firewalls.client import BoundFirewall
from hcloud.firewalls.domain import Firewall
from hcloud.floating_ips.client import BoundFloatingIP
from hcloud.isos.client import BoundIso
from hcloud.servers.client import ServersClient, BoundServer
from hcloud.servers.domain import (
Serv... | |
<filename>astromodels/core/model.py
from builtins import zip
__author__ = "giacomov"
import collections
import os
import warnings
import numpy as np
import pandas as pd
import scipy.integrate
from astromodels.core.memoization import use_astromodels_memoization
from astromodels.core.my_yaml import my_yaml
from astro... | |
<filename>configs/topologies/CHIPS_Multicore_GTRocketN.py
# Copyright (c) 2018 Georgia Institute of Technology
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must... | |
# 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, Optional, Sequence, Union, overload
from .. import... | |
str, An inclusive lower bound for values.
upper_bound: str, An inclusive upper bound for values.
Raises:
ArgumentTypeError: If either the lower_bound or upper_bound
cannot be parsed. The returned function will also raise this
error if it cannot parse its input. This exception is also
raised if the returned funct... | |
import morepath
import pytest
import pickle
import sqlalchemy
import time
import transaction
import uuid
from datetime import datetime
from dogpile.cache.api import NO_VALUE
from onegov.core.framework import Framework
from onegov.core.orm import (
ModelBase, SessionManager, as_selectable, translation_hybrid, find_mod... | |
None,
'TAI THAM VOWEL SIGN OO': None,
'TAI THAM VOWEL SIGN OY': None,
'TAI THAM VOWEL SIGN TALL AA': None,
'TAI THAM VOWEL SIGN THAM AI': None,
'TAI THAM VOWEL SIGN U': None,
'TAI THAM VOWEL SIGN UE': None,
'TAI THAM VOWEL SIGN UU': None,
'TAI THAM VOWEL SIGN UUE': None,
'TAI VIET LETTER HIGH BO': None,
'TAI VIET LETTE... | |
<filename>scripts/frbpa_plotting.py
#!/usr/bin/env python3
import numpy as np
import pandas as pd
import json, logging
import argparse
import pandas as pd
from astropy.time import Time, TimeDelta
from astropy import units as u
import datetime
import pylab as plt
import matplotlib as mpl
from matplotlib.patches import R... | |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020, the cclib development team
#
# This file is part of cclib (http://cclib.github.io) and is distributed under
# the terms of the BSD 3-Clause License.
"""Parser for Jaguar output files"""
import re
import numpy
from cclib.parser import logfileparser
from cclib.parser i... | |
<filename>src/algorithms/cf.py<gh_stars>100-1000
import numpy as np
from src.algorithms import recommender_helpers as rechelp
from pyspark.sql.types import *
from pyspark.mllib.recommendation import ALS
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.classification import NaiveBayes
from operator i... | |
the moment so do some heuristics to find it.
parent_mapper = inspect(Parent)
for prop in parent_mapper.column_attrs:
if not prop.instrument:
break
else:
prop = parent_mapper._columntoproperty[
parent_mapper.polymorphic_on
]
# then make sure the column we will query on matches.
is_(parent_mapper.polymorphic_o... | |
<reponame>cdleong/transformers
#!/usr/bin/env python
# coding=utf-8
# Copyright The HuggingFace Team and The HuggingFace Inc. team. 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 L... | |
<filename>kickthemout.py
#!/usr/bin/env python
# -.- coding: utf-8 -.-
# kickthemout.py
# authors: k4m4 & xdavidhu
"""
Copyright (C) 2016 <NAME> (<EMAIL>) & <NAME> (<EMAIL>)
See License at nikolaskama.me (https://nikolaskama.me/kickthemoutproject)
"""
import time, os, sys, logging, math
from time import sleep
import ... | |
<reponame>entn-at/dropclass_speaker
import math
from collections import OrderedDict
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
'''
AdaCos and Ad margin loss taken from https://github.com/4uiiurz1/pytorch-adacos
'''
class DropClassBase(nn.Module):
def __init__(self, num_c... | |
<filename>tests/plugins/globals/test_globals.py
from parameterized import parameterized
from unittest import TestCase
from mock import patch, Mock
from samtranslator.plugins.globals.globals import GlobalProperties, Globals, InvalidGlobalsSectionException
class GlobalPropertiesTestCases(object):
dict_with_single_le... | |
transform function, then the attribute will
be set to the given default value
@type transforms: dict (optional)
@param filters: dict of functions by attribute name; if given, each
newly-read record will be filtered before being added to the table, with each
filter function run using the corresponding attribute; if... | |
<filename>data/cache.py
import os
import pickle
from typing import Optional, Dict
import config as cf
import numpy as np
from data.datasets import Dataset
from data.preprocessor import Preprocessor
from utils import log
from utils.singleton import Singleton
class Cache(metaclass=Singleton):
"""This singleton class ... | |
| Return self!=value.
|
| __rmul__(self, value, /)
| Return self*value.
|
| __sizeof__(...)
| T.__sizeof__() -- size of T in memory, in bytes
|
| count(...)
| T.count(value) -> integer -- return number of occurrences of value
|
| index(...)
| T.index(value, [start, [stop]]) -> integer -- return first in... | |
"""
Created on Thu Oct 24 15:06:36 2019
+++++++.I+.@author: <NAME>
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
... | |
<gh_stars>1-10
from copy import copy, deepcopy
from datetime import datetime
import itertools
import numpy as np
import pprint
import random
import time
from pma.pr_graph import *
from opentamp.policy_hooks.sample import Sample
from opentamp.policy_hooks.utils.policy_solver_utils import *
MAX_OPT_DEPTH = 30 # TODO: ... | |
<filename>cassandra/decoder.py
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (th... | |
<filename>data_pre/reg_data_pool.py
from __future__ import print_function
import progressbar as pb
from easyreg.reg_data_utils import *
from data_pre.reg_preprocess_example.oasis_longitude_reg import *
import copy
sesses = ['train', 'val', 'test', 'debug']
number_of_workers = 10
warning_once = True
class BaseRegDat... | |
# encoding: utf-8
"""
Represents a connection to the RAM service.
"""
import six
from footmark.connection import ACSQueryConnection
from footmark.ram.group import Group
from footmark.ram.loginprofile import LoginProfile
from footmark.ram.mfadevice import MfaDevice
from footmark.ram.policy import Policy
from footmark.r... | |
<gh_stars>1-10
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------... | |
if top:
if self.loadingOptions.namespaces:
r["$namespaces"] = self.loadingOptions.namespaces
if self.loadingOptions.schemas:
r["$schemas"] = self.loadingOptions.schemas
return r
attrs = frozenset(
[
"label",
"secondaryFiles",
"streamable",
"doc",
"id",
"outputBinding",
"format",
]
)
class ProcessRequ... | |
<gh_stars>1-10
import sys
from multiprocessing import Process, Pipe
import threading
import json
import queue
# import time
from datetime import datetime
from collections import deque
# import logging
from flask import Flask, request
import numpy as np
from .DeviceDriver import driver_mapping
from .Seri... | |
# Copyright (c) 2017-2019, <NAME>
# Copyright (c) 2014-2018, iocage
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted providing that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice,... | |
<reponame>nirmalya-broad/PatHCap_PL
#!/usr/bin/env python
# The Broad Institute
# SOFTWARE COPYRIGHT NOTICE AGREEMENT
# This software and its documentation are copyright 2016 by the
# Broad Institute/Massachusetts Institute of Technology. All rights are
# reserved.
# This software is supplied without any warranty or g... | |
<filename>learning-experiment/make_exps.py<gh_stars>0
"""
Code for:
Trade-offs in Large Scale Distributed Tuplewise Estimation and Learning
Author: <NAME>
"""
import os
import shutil
import json
import logging
import pickle
from scipy.io import loadmat
import numpy as np
# Avoid trouble when generating pdf's on a di... | |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# generated by wxGlade 0.6.8 on Fri Sep 2 19:08:14 2016
#
import wx
# begin wxGlade: dependencies
import gettext
# end wxGlade
# begin wxGlade: extracode
# end wxGlade
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrame.__init__
... | |
"""Plot statistis about missing values from given indicators."""
import matplotlib
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.ticker as ticker
from mpl_toolkits.axes_grid1.parasite_axes import SubplotHost
# Plot functions: each indicator has a differ... | |
stream.write(prepare_for_stream(header + line_separator + line_separator))
stream.write(prepare_for_stream(ldif_output + line_separator + line_separator))
return ldif_output
class Entry(EntryBase):
"""The Entry object contains a single LDAP entry.
Attributes can be accessed either by sequence, by assignment
or a... | |
<filename>result_handler.py<gh_stars>0
import random
import matplotlib.pyplot as plt
import json
import os
import copy
import numpy as np
from enum import Enum
from itertools import product
import play_back_tool
import action_space_builder
from ptitprince import PtitPrince as pt
from test_group import get_cem_parameter... | |
<filename>scripts/md_CE_formula.py
#
# General Electricity sector Decarbonization Model (GEDM)
# Copyright (C) 2020 <NAME>.
# Licensed under the MIT License (see LICENSE file).
#
# Module note:
# Functions to construct CE model constraints
#
import pyomo.environ as pe
##### ---- dispatchable -------------------------... | |
= Var(within=Binary,bounds=(0,1),initialize=0.03125)
m.b597 = Var(within=Binary,bounds=(0,1),initialize=0.03125)
m.b598 = Var(within=Binary,bounds=(0,1),initialize=0.03125)
m.b599 = Var(within=Binary,bounds=(0,1),initialize=0.03125)
m.b600 = Var(within=Binary,bounds=(0,1),initialize=0.03125)
m.b601 = Var(within=Binary,... | |
assert 'Setup failed: A build-magic container is already running.' in res.output
def test_cli_docker_not_found(cli, mocker):
"""Test the case where Docker isn't running or isn't installed."""
mocker.patch('docker.from_env', side_effect=DockerDaemonError)
res = cli.invoke(build_magic, ['-r', 'docker', '-e', 'alpine... | |
+ '%0' + '%s' % digits + 'i:%s \t%s'
first = True
s = ''
snip = '<SNIP>'
for i in xrange(len(items)):
if not first:
s += '\n'
first = False
objStr = fastRepr(items[i])
if len(objStr) > maxLen:
objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
s += format % (i, itype(items[i]), objStr)
return s
def getN... | |
<filename>calvin/runtime/north/control_apis/logging_api.py
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Ericsson AB
#
# 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/... | |
if j >= i
else zeros(2, 2))
expJblock = Matrix(2*n, 2*n, lambda i,j: expJblock2[i//2,j//2][i%2,j%2])
blocks.append(exprt * expJblock)
for i in range(n):
vectors.append(re(chain[i]))
vectors.append(im(chain[i]))
else:
vectors.extend(chain)
fun = lambda i,j: t**(j-i)/factorial(j-i) if j >= i else 0
expJblock =... | |
# Copyright (c) 2022 <NAME>
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import annotations
from typing import Any, Awaitable, Callable, Iterable
i... | |
<gh_stars>1-10
import ast
import builtins
import basetype
def chooseType(left, right):
# print('chooseType', left, right, left.getType(), right.getType())
return left.getType()
class TypeMatcher(ast.AstVisitor):
def __init__(self):
ast.AstVisitor.__init__(self)
self.opname = 'matchType'
self.name = 'typeMatch... | |
check_dims(X)
sample_weight = _check_sample_weight(sample_weight=sample_weight, X=X)
max_attempts = max(self.n_init, 10)
kernel_params = self._get_kernel_params()
if self.kernel == "gak":
self.sigma_gak_ = kernel_params.get("sigma", 1.)
if self.sigma_gak_ == "auto":
self.sigma_gak_ = sigma_gak(X)
else:
self.... | |
(:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape :obj:`(batch_size, num_attn_heads,
decoder_sequence_length, decoder_sequence_length)`.
Attentions weights of th... | |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import datetime
from seir.wrapper import MultiPopWrapper
from seir.utils import plot_solution
# read calibration data
actual_hospitalisations = pd.read_excel('data/calibration.xlsx', sheet_name='Hospitalisations')
actual_hospitalisations['Date'] ... | |
#!/usr/bin/env python
# encoding: utf-8
"""
The main worker daemon library.
"""
from Queue import Queue
import twisted.internet
import twisted.internet.protocol
import twisted.internet.reactor
import twisted.internet.endpoints
from twisted.protocols import basic as twisted_basic
import argparse
import colorama
impo... | |
import os
import torch
import yaml
import numpy as np
from PIL import Image
from skimage import io
import torch.nn.functional as F
def pil_loader(path):
# open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
with open(path, 'rb') as f:
img = Image.open(f)
return img.conv... | |
set([self._get_vBucket_id(key)]),
forward_map=self._parse_not_my_vbucket_error(error))
vb_error += 1
else:
raise error
except (EOFError, socket.error) as error:
if "Got empty data (remote died?)" in error.message or \
"Timeout waiting for socket" in error.message or \
"Broken pipe" in error.message or \
"Conne... | |
not getattr(self.textbox,"kill",0) and self.textbox.can_continue()
class menu(fadesprite,gui.widget):
z = 5
fail = "none"
id_name = "invest_menu"
def over(self,mp):
oy = self.getpos()[1]
for o in self.options:
p2 = self.opos[o]
w,h = self.opt.get_width()//2,self.opt.get_height()//2
if mp[0]>=p2[0] and mp[0]<... | |
= config['RAD_KEYS'][temp_SSID['name']].replace('"','').replace(' ','')
if "meraki123!" in secret:
print(f'\t\t{bc.FAIL}Using DEFAULT!!! Radius Secret [{bc.WARNING}{secret}{bc.FAIL}]')
#sys.exit(1)
if 'radiusServers' in temp_SSID:
#print(f'{bc.OKGREEN}Using Secret [{bc.WARNING}{secret}{bc.OKGREEN}]')
for rs in ... | |
>> 8) & 0xff
lo = pc & 0xff
self.mmu.set_addr(self.sp-1, hi)
self.mmu.set_addr(self.sp-2, lo)
self.sp -= 2
self._in_interrupt = True
self.pc = 0x0040 + interrupt.value*8
self.interrupt_controller.acknowledge_interrupt(interrupt)
self.op_pc = self.pc
opcode = self.fetch()
self.opcode = opcode
# decode
if op... | |
<gh_stars>1-10
#!/usr/bin/env python
import scipy as sp
import scipy.stats
import pprint
import argparse
import csv
import re
import os
import MySQLdb
try:
import xlsxwriter
import xlrd
writeXLS = True
print 'yes XLS module imported'
except:
writeXLS = False
print 'No XLS module imported'
### Note header
#[ 'Ch... | |
#! /usr/bin/env python
################################################################################
#
#
# $Author: smaruyam $
# $Date: 2012/12/14 17:02:45 $
# $Revision: 1.15 $ 18.06.2015 $
#
#
# <NAME> = <EMAIL>
# <NAME> = <EMAIL>
# <NAME> = <EMAIL>
#
#############################################################... | |
start_logits=to_list(outputs[0][i]),
end_logits=to_list(outputs[1][i]),
retrieval_logits=to_list(outputs[2][i]),
retriever_prob=retriever_probs[i])
all_results.append(result)
evalTime = timeit.default_timer() - start_time
logger.info(" Evaluation done in total %f secs (%f sec per example)",
evalTime, evalTime ... | |
<gh_stars>0
# Lint as: python3
# Copyright 2018 The TensorFlow 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
#
#... | |
<filename>pbcore/io/align/BamIO.py
# Author: <NAME>
__all__ = [ "BamReader", "IndexedBamReader" ]
try:
from pysam.calignmentfile import AlignmentFile # pylint: disable=no-name-in-module, import-error, fixme, line-too-long
except ImportError:
from pysam.libcalignmentfile import AlignmentFile # pylint: disable=no-... | |
{0}".format(output_dir))
MC_dir = "{0}/MC".format(output_dir)
os.makedirs(MC_dir)
print("Made directory {0}".format(MC_dir))
# First calculate all the properties and statistics we need.
reion_data = generate_data(rank, size, comm, reion_ini_files,
gal_ini_files, reion_plots, output_dir,
model_tags, output_form... | |
#!/usr/bin/env python3
import argparse
import array
import asyncio as aio
import base64
import itertools
import logging
import random
import statistics
from abc import ABCMeta, abstractmethod
from asyncio import DatagramTransport, Lock, StreamReader, StreamWriter, Task
from types import TracebackType
from typing import... | |
# This file provides common configuration for the different ways that
# the deployment can run. Configuration specific to the different modes
# will be read from separate files at the end of this configuration
# file.
import os
import json
import string
import yaml
import threading
import time
import requests
import ... | |
tile = col_to_tile.get(col)
# they are safe
if tile not in safe:
safe.append(tile)
# case when there are only negative coefficients on the left
if neg_onesCount > 0 and onesCount == 0:
for col in negList:
tile = col_to_tile.get(col)
# they are mines
if tile not in mines:
mines.append(tile)
# case when the to... | |
<reponame>mk-fg/pulseaudio-mixer-cli
#!/usr/bin/env python3
import itertools as it, operator as op, functools as ft
from collections import OrderedDict, defaultdict, deque, namedtuple
from contextlib import contextmanager
import os, sys, io, re, time, logging, configparser
import base64, hashlib, unicodedata, math
imp... | |
the course contains the new group configuration.
user_partitions = self.course.user_partitions
self.assertEqual(len(user_partitions), 1)
self.assertEqual(user_partitions[0].name, '<NAME>')
self.assertEqual(len(user_partitions[0].groups), 2)
self.assertEqual(user_partitions[0].groups[0].name, 'Group A')
self.asser... | |
values
self._phi = np.arctan2(self._yc, self._xc)
self._phi[self._phi < 0] += 2. * np.pi
# in some cases, it is more convenient to work with xc[z,y,x] so lets store views
self._theta_view = self._theta.view()
self._theta_view.shape = (self.moms_ngridpoints, self.moms_ngridpoints, self.moms_ngridpoints)
self._phi... | |
import copy
import warnings
from typing import List
import numpy as np
import pandas as pd
import scipy
import simdkalman
from numpy.fft import irfft, rfft, rfftfreq
from scipy.interpolate import interp1d
from scipy.ndimage import gaussian_filter1d
from tqdm import tqdm
from src.postprocess.metric import calc_haversi... | |
data=[('172.16.17.32:40945', '172.16.31.10:6881'),
('172.16.17.32:40945', '192.168.3.11:6889'),
('172.16.17.32:40945', '172.16.17.32:6881'),
('172.16.17.32:40945', '172.16.58.3:50321'),
('172.16.17.32:40945', '172.16.17.32:51913'),
('172.16.17.32:40945', '172.16.58.3:42371'),
('172.16.17.32:40945', '192.168.127.12:4029... | |
481 1 0 163
1 482 1 0 162
1 483 1 0 161
1 485 1 0 159
1 486 1 0 158
1 488 1 0 156
1 489 1 0 155
1 491 1 0 321
1 492 1 0 320
1 494 1 0 318
1 495 1 0 317
1 497 1 0 315
1 498 1 0 314
1 499 1 0 313
1 500 1 0 312
1 501 1 0 311
1 502 1 0 310
1 504 1 0 308
1 505 1 0 307
1 506 1 0 306
1 507 1 0 305
1 508 1 0 304
1 509 1 0 303
... | |
<reponame>kevinbfry/selective-inference
from __future__ import print_function
import numpy as np, pandas as pd
import regreg.api as rr
import nose.tools as nt
from numpy.testing import dec
try:
import rpy2.robjects as rpy
rpy2_available = True
import rpy2.robjects.numpy2ri as numpy2ri
except ImportError:
rpy2_ava... | |
<reponame>tothadi/Mailu
""" Mailu config storage model
"""
import os
import smtplib
import json
from datetime import date
from email.mime import text
from itertools import chain
import flask_sqlalchemy
import sqlalchemy
import passlib.context
import passlib.hash
import passlib.registry
import time
import os
import h... | |
1, 'b': 2, 'x': {'c': 3, 'd': 4}})
t2 = tree_value_clazz({'a': 11, 'b': 22, 'x': {'c': 33, 'd': 5}})
assert (t2 >> t1) == tree_value_clazz({'a': 5, 'b': 5, 'x': {'c': 4, 'd': 0}})
assert (32 >> t1) == tree_value_clazz({'a': 16, 'b': 8, 'x': {'c': 4, 'd': 2}})
original_id = id(t2._detach())
original_id_x = id(t2.x... | |
GDSII file will be the
dimensions of the objects created times the ratio
unit/precision. For example, if a circle with radius 1.5 is
created and we set `GdsLibrary.unit` to 1.0e-6 (1 um) and
`GdsLibrary.precision` to 1.0e-9` (1 nm), the radius of the
circle will be 1.5 um and the GDSII file will contain the
dimen... | |
<reponame>AlexMeinke/Provable-OOD-Detection
import torch
import torch.nn as nn
import copy
from torch.nn import functional as F
import utils.models.modules_ibp as modules_ibp
class CNN_IBP(nn.Module):
def __init__(self, dset_in_name='MNIST', size='L', width=None, last_bias=True, num_classes=None, last_layer_neg=Fa... | |
dict keyed by the nodes' literal_hash
# field instead.
# NB: This should be `TypeMap = Optional[Dict[Node, Type]]`!
# But see https://github.com/python/mypy/issues/1637
TypeMap = Dict[Node, Type]
def conditional_type_map(expr: Node,
current_type: Optional[Type],
proposed_type: Optional[Type],
*,
weak: bool = Fal... | |
+ b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a... | |
#!/usr/bin/env python
# author: d.koch
# coding: utf-8
# naming: pep-0008
# typing: pep-0484
# docstring: pep-0257
# indentation: tabulation
""" canp_test.py
Simple CAN interface tester
"""
# --- IMPORT ---
# Standard libraries (installed with python)
import asyncio
#import atexit
#import json
#import logging
impo... | |
be ‘not in’",
"title_templated": False,
"title": "When testing whether or not something is in an object use the form `x not in the_object` instead of `not x in the_object`.",
"solution": "Use the form `not x in the_object` instead of `x not in the_object`.",
"explanation": "This improves readability of your code as... | |
"""
.NET-style event system in Python
The aim of this module is to create an event system using only Python's base installation (e.g. no Anaconda, PyPy, etc.)
"""
if __name__ == "__main__":
# MAJOR +1 represents an added function.
__MAJOR = 1
# MINOR +1 represents a change in existing function(s) within the... | |
= 'mod3max'
elif self._function_name == 'MIN':
func_name = 'mod3min'
elif self._function_name == 'CONT':
func_name = 'mod3continuity'
elif self._function_name == 'NOT':
func_name = 'mod3not'
else:
raise Exception("Unknown binary relation: " + self._function_name)
return func_name + '(' + ",".join(c_exprs) + '... | |
"_a_eq")
am = getattr(m, "_" + cname + "_am_eq")
kappa = getattr(m.params, cname + "_kappa")
return (
2
* sqrt(a[p1, p2, i])
/ am[p1, p2, p3]
* sum(
m.mole_frac_phase_comp[p3, j]
* sqrt(a[p1, p2, j])
* (1 - kappa[i, j])
for j in m.components_in_phase(p3)
)
)
b.add_component(
"_" + cname + "_delta_eq",
... | |
Referencing Containers, Blobs, and
Metadata for more information.
:type metadata: str
:param tier: Optional. Indicates the tier to be set on the blob.
Possible values include: 'P4', 'P6', 'P10', 'P15', 'P20', 'P30',
'P40', 'P50', 'P60', 'P70', 'P80', 'Hot', 'Cool', 'Archive'
:type tier: str or ~azure.storage.blob... | |
= sys_ids
self.watch[_sys]['name'] = _sys
self.watch[_sys]['sec'] = round(d['security_status'],1)
self.watch[_sys]['constellation_id'] = d['constellation_id']
self.watch[_sys]['region'] = 'Unknown'
self.watch[_sys]['region_id'] = 0
for r in self.regions.values():
try:
if d['constellation_id'] in r['constellatio... | |
= None
self.DeleteFlag = None
self.CreateTime = None
self.UpdateTime = None
self.TsfRegionId = None
self.TsfRegionName = None
self.TsfZoneId = None
self.TsfZoneName = None
self.DeleteFlagReason = None
self.ClusterLimitCpu = None
self.ClusterLimitMem = None
self.RunServiceInstanceCount = None
self.SubnetId =... | |
"""dml voor probreg met sql om dezelfde data te gebruiken die de Django versie
gebruikt
vervallen omdat we nu de versie gebruiken die met het Django ORM werkt
"""
## import sys
import os
import datetime as dt
import sqlite3 as sql
from contextlib import closing
import logging
from probreg.shared import DataError, DBLO... | |
"""
return self.__name
def _set_name(self, v, load=False):
"""
Setter method for name, mapped from YANG variable /nst/netslice_vld/name (string)
If this variable is read-only (config: false) in the
source YANG file, then _set_name is considered as a private
method. Backends looking to populate this variable sh... | |
41:
return 'swval3'
if table2Version == 171 and indicatorOfParameter == 40:
return 'swval2'
if table2Version == 171 and indicatorOfParameter == 39:
return 'swval1'
if table2Version == 171 and indicatorOfParameter == 38:
return 'istal4'
if table2Version == 171 and indicatorOfParameter == 37:
return 'istal3'... | |
<reponame>amanchokshi/mwa-satellites
import numpy as np
import healpy as hp
import scipy.optimize as opt
import numpy.polynomial.polynomial as poly
def hp_slices_horizon(nside=None):
"""Healpix pix indices of NS, EW slices and above horizon"""
# theta phi values of each pixel
hp_indices = np.arange(hp.nside2npix(n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.