input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
# utils for working with 3d-protein structures
import os
import numpy as np
import torch
from functools import wraps
from einops import rearrange, repeat
# import torch_sparse # only needed for sparse nth_deg adj calculation
# bio
from Bio import SeqIO
import itertools
import string
# sidechainnet
from sidechainnet... | |
0:
raise exception
return newvalue
def whole(value, exception = ValueError):
"""Casts to whole (integer) if possible"""
newvalue = int(value) #The exception may get raised here by the int function if needed
if newvalue < 0:
raise exception
return newvalue
def posrealargparse(value): return posreal(v... | |
'post_id':postIdFragment}))
self.assertEqual(response.status_code, 200, f"expected 200. got: {response.status_code}")
post_likes = json.loads(response.content)["data"]
self.assertEqual(len(post_likes), 1, f"expected list of length 1. got: {len(post_likes)}")
self.assertEqual(postId, post_likes[0]["object"], "return... | |
"""
sip.py
Computes connectivity (KS-test or percentile scores) between a test similarity
gct and a background similarity gct. The default output is signed connectivity,
which means that the connectivity score is artifically made negative if the
median of the test distribution is less than the median of the background... | |
#@<OUT> mysqlx.Type
NAME
Type - Data type constants.
SYNTAX
mysqlx.Type
DESCRIPTION
The data type constants assigned to a Column object retrieved through
RowResult.get_columns().
PROPERTIES
BIGINT
A large integer.
BIT
A bit-value type.
BYTES
A binary string.
DATE
A date.
DATETIME
A date and time co... | |
<gh_stars>0
## Advent of Code 2019: Intcode Computer v5.1
## https://adventofcode.com/2019
## <NAME> | github.com/vblank182
# **Compatible with Day 11**
# Changelog (v5):
# - Added support for relative parameter mode
# - Added ARB (Adjust Relative Base) opcode
# - Modified tape handling to support reading and writing... | |
calculated at:")
for q in q_points:
print(" %s" % q)
else:
print_error_message("Q-points are not properly specified.")
if log_level:
print_error()
sys.exit(1)
phonon.run_qpoints(
q_points,
with_eigenvectors=settings.is_eigenvectors,
with_group_velocities=settings.is_group_velocity,
with_dynamical_matrices=s... | |
"""
areas = cstudy.areas
if areas:
name = ""
if "W" in areas:
name += "Water"
if "E" in areas:
name += "Energy"
if "F" in areas:
name += "Food"
return "/static/images/" + name + "Nexus.png"
else:
return "/static/images/NoNexusAreas.png" # TODO create this image
# Recover InteractiveSession
isess = deseri... | |
<filename>bin-by-sam_v7.py
#! /usr/bin/env python
import os, sys, math, time
from optparse import OptionParser
from collections import defaultdict
import gzip
#Comai Lab, Ucdavis Genome Center
#<NAME>, <NAME>, 2019
# This work is the property of UC Davis Genome Center - Comai Lab
# Use at your own risk.
# We cannot... | |
import numpy as np
import cupy as cp
from scipy.sparse import coo_matrix
from scipy.sparse import csr_matrix
from sparana.parameter_selection import get_k_biggest
from sparana.parameter_selection import get_k_smallest
from sparana.model import model
def get_MAV_module(lobo, data):
''' This will run and store the mean... | |
will be loaded into the state and can be sampled directly
start_steps = 0
epsilon = 0.1
else:
start_steps = 5000
if TESTING:
start_steps = 10
epsilon = 1
chkpt_pth = os.path.join(CHCKPT_DIR, base_name)
agent_params = all_agent_params[agent_type].copy()
agent_params['seed'] = seed
agent_params['min_sat_actio... | |
'45 Celsius',
'state': 'Normal'},
'V1: 12v': {'reading': '11835 mV',
'state': 'Normal'},
'V1: GP1': {'reading': '910 mV',
'state': 'Normal'},
'V1: GP2': {'reading': '1198 mV',
'state': 'Normal'},
'V1: VDD': {'reading': '3295 mV',
'state': 'Normal'},
'V1: VMA': {'reading': '1201 mV',
'state': 'Normal'},
'V1:... | |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# Imports =====================================================================
from collections import OrderedDict
import dhtmlparser
from dhtmlparser import HTMLElement
from . import tools
from .structures import MARCSubrecord
# ... | |
# Copyright 2017 Google 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | |
return [True, res.json()]
else:
return [False, 'Not found']
def create_dashboard_from_template(self, dashboard_name, template, scope, shared=False, annotations={}):
if scope is not None:
if isinstance(scope, basestring) == False:
return [False, 'Invalid scope format: Expected a string']
#
# Clean up the dashb... | |
Reference.
def save(self, *args, **kwargs):
super(Proposal, self).save(*args,**kwargs)
if self.lodgement_number == '':
new_lodgment_id = 'P{0:06d}'.format(self.pk)
self.lodgement_number = new_lodgment_id
self.save()
@property
def fee_paid(self):
if not self.apiary_group_application_type:
return False
else:
... | |
"""
This module defines some classes to perform a calculation using BigDFT
using binding (GIBinding) or using system call (SystemCalculator).
"""
# In our case for the class SystemCalculator which uses system calls:
# * We define posinp (equivalent of Atoms)
# * We have a python dictionary for the parameter
# * We de... | |
#! /usr/bin/env python
##############################################################################
## DendroPy Phylogenetic Computing Library.
##
## Copyright 2010-2015 <NAME> and <NAME>.
## All rights reserved.
##
## See "LICENSE.rst" for terms and conditions of usage.
##
## If you use this work or any portion the... | |
"name"
dyndns_del(nameserver, name, type="ANY", ttl=10) -> result code (0=ok)
example: dyndns_del("ns1.toto.com", "dyn.toto.com")
RFC2136
"""
zone = name[name.find(".")+1:]
r=sr1(IP(dst=nameserver)/UDP()/DNS(opcode=5,
qd=[DNSQR(qname=zone, qtype="SOA")],
ns=[DNSRR(rrname=name, type=type,
rclass="ANY", ttl=0, rdat... | |
# Copyright 2017 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
#
# Unless required by applicable ... | |
!
FUNCTION FV4A1FE 298.15 +2.35; 6000 N !
FUNCTION FV5A1FE 298.15 +5; 6000 N !
FUNCTION FV6A1FE 298.15 +1; 6000 N !
FUNCTION FV7A1FE 298.15 +10; 6000 N !
FUNCTION FV8A1FE 298.15 +3; 6000 N !
$ implementation of EOS for FCC_A1 Fe
FUNCTION PA1FE 298.15 +FV1A1FE#**(-1)*P; 6000 N !
FUNCTION BVA1FE 298.15 +FV0A1FE#*... | |
#
# Copyright (C) 2019 Databricks, 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 applicable law or agreed to in wr... | |
Default: 0",
checker_function=lambda value: type(value) is int,
equate=False),
_Option(["-L", "seed_length"],
"Sets the length of the seed substrings to align during multiseed alignment. "
"Smaller values make alignment slower but more senstive. Default: the --sensitive preset is used "
"by default, which sets -L... | |
<filename>facebook_business/api.py
# Copyright 2014 Facebook, Inc.
# You are hereby granted a non-exclusive, worldwide, royalty-free license to
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.
# As with any s... | |
if self.state_update_callbacks and self.doStateUpdate:
await self.do_state_update_callbacks()
async def set_inputs_state(self, extinputs):
self._extinputs = {}
for extinput in extinputs:
self._extinputs[extinput["appId"]] = extinput
if self.state_update_callbacks and self.doStateUpdate:
await self.do_state_upd... | |
"""설정 GUI."""
import time
from configparser import ConfigParser
from copy import deepcopy
from collections import defaultdict
from functools import partial
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from tkinter.simpledialog import askstring
from pyathena import connect
from datepick... | |
>= 1:
grid = grid[0]
data = __convertSvgStringTo(grid.dendogram, request.POST['convertTo'])
if request.POST.has_key('fileName'):
data.fileName = request.POST['fileName']
else:
data.fileName = generateRandomString()
# return the file
return createFileResponse(data)
else:
if not request.POST['gridUSID']:
rais... | |
style or V2 style. In this binary
we only support V2 style (object-based) checkpoints.
input_dataset: The tf.data Dataset the model is being trained on. Needed
to get the shapes for the dummy loss computation.
unpad_groundtruth_tensors: A parameter passed to unstack_batch.
Raises:
IOError: if `checkpoint_path` d... | |
import nnef
import os, fnmatch
import argparse
import struct
from bitarray import bitarray
import numpy as np
import string
'''
Compiler for 3PXNet. Compiles a neural network stored in NNEF format to C using inference engine.
'''
'''
NOTIFICATIONS:
variablen is a dictionary, its keys are variable_# and value is a list... | |
# this is the "Job Entry Subsystem" (including the "Initiator")
# this is currently only working for simple JCL
from zPE.util import *
from zPE.util.global_config import *
import zPE.util.sysmsg as sysmsg
import zPE.util.spool as spool
import zPE.base.core.SPOOL as core_SPOOL
import zPE.base.conf
import sys
import... | |
__copyright__ = \
"""
Copyright ©right © (c) 2019 The Board of Trustees of Purdue University and the Purdue Research Foundation.
All rights reserved.
This software is covered by US patents and copyright.
This source code is to be used for academic research purposes only, and no commercial use is allowed.
For any ... | |
self.textout += ptxt
# print protocol result, optionally a cell header.
self.print_formatted_script_output(script_header)
script_header = False
self.auto_updater = True # restore function
print('\nDone')
def get_window_analysisPars(self):
"""
Retrieve the settings of the lr region windows, and some other gener... | |
<reponame>naxa-developers/mes-core<filename>onadata/apps/core/views.py
from django.views.generic import View, TemplateView, ListView, DetailView
from django.contrib.auth import views
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, a... | |
def get_positiveReference(self): return self.positiveReference
def set_positiveReference(self, positiveReference): self.positiveReference = positiveReference
def get_negativeReference(self): return self.negativeReference
def set_negativeReference(self, negativeReference): self.negativeReference = negativeReference
... | |
# Copyright 2020 - 2021 MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing... | |
MoloSurveyPage.objects.get(
slug='french-translation-of-test-survey')
translated_survey.save_revision().publish()
response = self.client.get(self.section.url)
self.assertContains(response,
'<h1 class="surveys__title">Test Survey</h1>')
self.assertNotContains(
response,
'<h1 class="surveys__title">French transl... | |
import abc
from .aes import aes
from .stats import StatCount, StatIdentity, StatBin, StatNone, StatFunction
class FigureAttribute(abc.ABC):
pass
class Geom(FigureAttribute):
def __init__(self, aes):
self.aes = aes
@abc.abstractmethod
def apply_to_fig(self, parent, agg_result, fig_so_far, precomputed):
pass... | |
= self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['LMv1'] # noqa: E501
return self.api_client.call_api(
'/device/devices/{deviceId}/devicedatasources/{hdsId}/instances/{instanceId}/alertsettings/{id}', 'GET',
path_params,
query_params,
header_... | |
__all__ = ["PrettyHelp"]
from typing import Any, List, Optional, Union
import discord
from discord.ext import commands
from discord.ext.commands.help import HelpCommand
from .menu import DefaultMenu, PrettyMenu
class Paginator:
def __init__(self, color, pretty_help: "PrettyHelp"):
"""A class that cr... | |
<filename>amulet/world_interface/formats/anvil/anvil_format.py
from __future__ import annotations
import os
import struct
import zlib
import gzip
from typing import Tuple, Any, Dict, Union, Generator
import numpy
import time
import re
import amulet_nbt as nbt
from amulet.world_interface.formats import Format
from am... | |
<reponame>gdsports/NSGadget_Pi
#!/usr/bin/python3
"""
MIT License
Copyright (c) 2020 <EMAIL>
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 ... | |
<reponame>haroonf/azure-cli-extensions<filename>src/providerhub/azext_providerhub/tests/latest/example_steps.py
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root f... | |
<gh_stars>0
#####################################################################################
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
# copy of the license can be found in the License.html file at the... | |
= 'High'
col.loc[((df['loan_condition'] == 'Bad Loan'), 'loan_condition_int')] = 0
col.loc[((df['loan_condition'] == 'Good Loan'), 'loan_condition_int')] = 1
by_emp_length = df.groupby(['region', 'addr_state'], as_index=False).emp_length_int.mean().sort_values(by='addr_state')
loan_condition_bystate = pd.crosstab(d... | |
image_id):
""" Reads the JSON metadata for specified layer / image id """
for layer in self.docker.history(image_id):
layers.append(layer['Id'])
def _parse_image_name(self, image):
"""
Parses the provided image name and splits it in the
name and tag part, if possible. If no tag is provided
'latest' is used.
... | |
#!/usr/bin/python
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... | |
0, 0, 0, 0],
[983, 44.0, 0, 9999, -9999, 1.0, 100, 1, 44.0, 0.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[984, 465.0, 0, 9999, -9999, 1.0, 100, 1, 465.0, 0.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[985, 22.0, 0, 9999, -9999, 1.0, 100, 1, 22.0, 0.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[986, 11... | |
<filename>data/data-pipeline/data_pipeline/score/field_names.py
# Suffixes
PERCENTILE_FIELD_SUFFIX = " (percentile)"
PERCENTILE_URBAN_RURAL_FIELD_SUFFIX = " (percentile urban/rural)"
MIN_MAX_FIELD_SUFFIX = " (min-max normalized)"
TOP_25_PERCENTILE_SUFFIX = " (top 25th percentile)"
# Geographic field names
GEOID_TRACT_... | |
closefd: bool = True,
opener: Optional[Callable[[str, int], int]] = None,
tempdir: Optional[str] = None
) -> Iterator[IO]:
"""Save a file with a temporary name and rename it into place when ready.
This is a context manager which is meant for saving data to files.
The data is written to a temporary file, which get... | |
import json
import unittest
from datetime import datetime
from unittest.mock import MagicMock, patch
from werkzeug.datastructures import MultiDict
from alerta.app import create_app, db, qb
# service, tags (=, !=, =~, !=~)
# attributes (=, !=, =~, !=~)
# everything else (=, !=, =~, !=~)
class SearchTestCase(unittes... | |
in conjugation with 2Q RB results, see :func:`calculate_2q_epg`.
Note:
This function presupposes the basis gate consists
of ``u1``, ``u2`` and ``u3``.
Args:
gate_per_cliff: dictionary of gate per Clifford. see :func:`gates_per_clifford`.
epc_1q: EPC fit from 1Q RB experiment data.
qubit: index of qubit to calc... | |
self.___NB_s___(s)[1]
NFs = self.___NF_s___(s)[1]
SBs = self.___SB_s___(s)[1]
SFs = self.___SF_s___(s)[1]
WB = self.___WB___(r)[1]
WF = self.___WF___(r)[1]
EB = self.___EB___(r)[1]
EF = self.___EF___(r)[1]
NWB = self.___N_W_B___[1]
NWF = self.___N_W_F___[1]
NEB = self.___N_E_B___[1]
NEF = self.___N_E_F___[... | |
datetime objects used to
put the data in the database, but we can check that it's
basically the same time.
:param python: A datetime from the Python part of this test.
:param postgres: A float from the Postgres part.
"""
expect = (
python - datetime.datetime.utcfromtimestamp(0)
).total_seconds()
eq_(int(expec... | |
Union[str, HospitalizationId] = None
category: Union[Union[str, NamedThingId], List[Union[str, NamedThingId]]] = None
def __post_init__(self, *_: List[str], **kwargs: Dict[str, Any]):
if self._is_empty(self.id):
self.MissingRequiredField("id")
if not isinstance(self.id, HospitalizationId):
self.id = Hospitalizat... | |
#!/usr/bin/env python
# cardinal_pythonlib/psychiatry/drugs.py
"""
===============================================================================
Original code copyright (C) 2009-2021 <NAME> (<EMAIL>).
This file is part of cardinal_pythonlib.
Licensed under the Apache License, Version 2.0 (the "License");
you ... | |
<filename>PerceptualLoss.py
import torch
import torch.nn as nn
from torchvision import models
from torch.autograd import Variable
from torch.nn.parameter import Parameter
from DeepImageDenoiser import LR_THRESHOLD, DIMENSION, LEARNING_RATE
from NeuralModels import SpectralNorm
ITERATION_LIMIT = int(1e6)
SQUEEZENET_CO... | |
{
'constant': ConstantDetModel,
'scaled': ScaledDetModel,
}
return text_to_type[spec['det_model']['type']](spec['det_model'])
class ModelInput(ABC):
def __init__(self,
spec,
composition_list,
composition_distribution,
header=None):
self.spec = deepcopy(spec)
self.compartmental_structure = spec['compartmen... | |
a DDE element to delegate
# the :py:meth:`Usage.size` and :py:meth:`Usage.create_func()` operations to this class.
#
# The :py:meth:`Usage.size` method returns the number
# of bytes used by the data element.
#
# - For usage ``DISPLAY``, the size is computed directly from the picture clause.
#
# - For usage ``COMP``,... | |
mėnesį", "12 month ago"),
param('lt', "po 2 valandų", "in 2 hour"),
# lu
param('lu', "lelu", "0 day ago"),
param('lu', "makelela", "1 day ago"),
# luo
param('luo', "nyoro", "1 day ago"),
param('luo', "kiny", "in 1 day"),
# luy
param('luy', "mgorova", "1 day ago"),
param('luy', "lero", "0 day ago"),
# lv
par... | |
self.filling_values = None
self.columns_with_null = None
if strategy not in ("mean", "median", "fix"):
raise ValueError("I don't know that type of strategy '%s' " % self.strategy)
def fit(self, X, y=None):
type_of_data = get_type(X)
self._expected_type = type_of_data
self.filling_values = {}
self.columns_wi... | |
<filename>fiftyone/utils/kitti.py
"""
Utilities for working with datasets in
`KITTI format <http://www.cvlibs.net/datasets/kitti/eval_object.php>`_.
| Copyright 2017-2021, Voxel51, Inc.
| `voxel51.com <https://voxel51.com/>`_
|
"""
import csv
import logging
import os
import eta.core.utils as etau
import eta.core.web ... | |
:param values: matrix of values if range given, if a value is None its unchanged
:param majordim: major dimension of given data
"""
if cell_list:
crange = 'A1:' + str(format_addr((self.rows, self.cols)))
# @TODO fit the minimum rectangle than whole array
values = [[None for x in range(self.cols)] for y in range... | |
If True, the regressors X are normalized
solver : {'auto', 'dense_cholesky', 'lsqr', 'sparse_cg'}
Solver to use in the computational
routines. 'dense_cholesky' will use the standard
scipy.linalg.solve function, 'sparse_cg' will use the
conjugate gradient solver as found in
scipy.sparse.linalg.cg while 'auto' wil... | |
'''
Copyright 2022 Airbus SAS
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distri... | |
638,
"Xbar": -639, "nXah": -640, "Xirv": 641, "Xnor": 642, "yXec": 643,
"hU X": -644, "yIXm": 645, "UraX": -646, "eyaX": -647, "I Xb": 648,
"jlIX": -649, "Xehl": -650, "hoXs": 651, "Xkez": 652, "Xomi": 653,
"abXe": 654, "Xdig": 655, "Xiru": 656, "diXu": 657, "GdOX": 658,
"UXir": 659, "Xico": -660, "fiSX": 661, "Xy... | |
setting -standbyMode
standbyModeMv = ixNet.getAttribute(pccInit2, '-standbyMode')
ixNet.add(standbyModeMv, 'alternate')
# Adding overlay 1 for standbyMode
ovrly = ixNet.add(standbyModeMv, 'overlay')
ixNet.setMultiAttribute(ovrly,
'-count', '1',
'-index', '2',
'-indexStep', '0',
'-valueStep', 'false',
'-... | |
# coding: utf-8
"""
EVE Swagger Interface
An OpenAPI for EVE Online # noqa: E501
OpenAPI spec version: 0.8.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from swag... | |
<reponame>empymod/frequency-design
import emg3d
import empymod
import numpy as np
import ipywidgets as widgets
import scipy.interpolate as si
import matplotlib.pyplot as plt
from IPython.display import display
from scipy.signal import find_peaks
# Define all errors we want to catch with the variable-checks and setting... | |
value:
# Update self.charset with the charset from the header
match = charset_re_match(value)
if match:
self.charset = match.group(1)
else:
# Update the header value with self.charset
if value.startswith('text/'):
value = value + '; charset=' + self.charset
name = literal and name or key
self.headers[name] =... | |
ix_, iy, iy_)
print('getCalData. gridpoint 1 position: ', xf[iy_,ix_], yf[iy_,ix_], xp1[iy_,ix_], yp1[iy_,ix_])
print('getCalData. gridpoint 2 position: ', xf[iy ,ix_], yf[iy ,ix_], xp1[iy ,ix_], yp1[iy ,ix_])
print('getCalData. gridpoint 3 position: ', xf[iy ,ix ], yf[iy ,ix ], xp1[iy ,ix ], yp1[iy ,ix ])
print('g... | |
'amount': '23.00',
'mark_canceled': False,
})
assert resp.status_code == 400
assert resp.data == {'detail': 'External error: We had trouble communicating with Stripe. Please try again and contact support if the problem persists.'}
with scopes_disabled():
r = order.refunds.last()
assert r.provider == "stripe"
as... | |
from enum import Enum
import os
from threading import Thread
from tkinter import (
Frame,
Scrollbar,
StringVar,
Canvas,
Event,
VERTICAL,
TRUE,
FALSE,
RIGHT,
Y,
NW,
LEFT,
BOTH,
Listbox,
SINGLE,
Widget,
END,
TclError,
)
from typing import Any, Optional, Union
import time
import numpy as np
import psuti... | |
#!/usr/bin/env python3
# Standard modules
import z3 # pip install z3-solver
# Local modules
from . import alloy
from .z3_wrapper import *
class Relation(dict):
"""A Relation.
This is a Relation within a relational model of the type that herd, Alloy,
or isla-axiomatic would use. Keys have type `tuple` of `str`, ... | |
import time
def print_msg_box(msg, indent=1, width=None, title=None):
"""Print message-box with optional title."""
lines = msg.split('\n')
space = " " * indent
if not width:
width = max(map(len, lines))
box = f'╔{"═" * (width + indent * 2)}╗\n' # upper_border
if title:
box += f'║{space}{title:<{width... | |
<reponame>peterpwang/abstracttemplate
#from bs4 import BeautifulSoup
import argparse
import sys
import os
import random
import re
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
import stanza
from util import read_text
# public variables
debug = 0
skip_extraction = 1
skip_upos = 1
ski... | |
interpolator.y
def pointwise(x):
# If new prob is smaller than smallest prob in function
if x < xs[0]:
return ys[0] + (x - xs[0]) * (ys[1] - ys[0]) / (xs[1] - xs[0])
# If new prob is larger than largest prob in function
elif x > xs[-1]:
return ys[-1] + (x - xs[-1]) * (ys[-1] - ys[-2]) / (xs[-1] - xs[-2])
# If ... | |
(1025*mckin**16)/mbkin**16 + (144*mckin**18)/mbkin**18)) +
(4*(-49 + (417*mckin**2)/mbkin**2 + (935*mckin**4)/mbkin**4 -
(7247*mckin**6)/mbkin**6 + (2361*mckin**8)/mbkin**8 +
(13385*mckin**10)/mbkin**10 + (16711*mckin**12)/mbkin**12 +
(4863*mckin**14)/mbkin**14 - (4600*mckin**16)/mbkin**16 -
(1018*mckin**18)/... | |
57:
return 'uvbdiff'
if table2Version == 200 and indicatorOfParameter == 56:
return 'mn2d24diff'
if table2Version == 200 and indicatorOfParameter == 55:
return 'mean2t24diff'
if table2Version == 200 and indicatorOfParameter == 54:
return 'presdiff'
if table2Version == 200 and indicatorOfParameter == 53:
re... | |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018 CERN.
#
# Asclepias Broker is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Relationshps ingestion functions."""
import uuid
from typing import Tuple
from invenio_db import db
from sql... | |
1012,
"hu": 26,
"ws": 4,
"wd": 60,
"ic": "11n"
},
{
"ts": "2017-08-31T01:00:00.000Z",
"tp": 32,
"pr": 1011,
"hu": 20,
"ws": 6,
"wd": 80,
"ic": "11n"
},
{
"ts": "2017-08-31T00:00:00.000Z",
"tp": 33,
"pr": 1011,
"hu": 16,
"ws": 3,
"wd": 120,
"ic": "11n"
},
{
"ts": "2017-08-30T23:00:00.000Z",
"tp... | |
import asyncio
import time
import typing
import logging
from aioupnp.protocols.scpd import scpd_post
from aioupnp.device import Service
from aioupnp.fault import UPnPError
from aioupnp.util import is_valid_public_ipv4
log = logging.getLogger(__name__)
def soap_optional_str(x: typing.Optional[typing.Union[str, int]])... | |
#!/usr/bin/env python
#
# $Id$
#
"""psutil is a module providing convenience functions for managing
processes in a portable way by using Python.
"""
__version__ = "0.2.1"
version_info = tuple([int(num) for num in __version__.split('.')])
__all__ = [
# exceptions
"Error", "NoSuchProcess", "AccessDenied", "TimeoutEx... | |
"""
This module serves as a Python wrapper around the nrfjprog DLL.
Note: Please look at the nrfjprogdll.h file provided with the tools for a more elaborate description of the API functions and their side effects.
"""
from __future__ import print_function
import weakref
from builtins import int
import ctypes
import... | |
= Constraint(expr= m.b296 + m.b536 <= 1)
m.c3945 = Constraint(expr= m.b297 + m.b537 <= 1)
m.c3946 = Constraint(expr= m.b298 + m.b538 <= 1)
m.c3947 = Constraint(expr= m.b299 + m.b539 <= 1)
m.c3948 = Constraint(expr= m.b300 + m.b540 <= 1)
m.c3949 = Constraint(expr= m.b301 + m.b541 <= 1)
m.c3950 = Constraint(expr= m... | |
# Copyright 2013 Devsim LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... | |
jsonFiles = glob.glob(os.path.join(self.sampleDir, "resources", "data", "json", "voa[12].txt.json"))
# Import some documents.
w.importFiles(jsonFiles, "core", document_status = "reconciled",
strip_suffix = ".txt.json")
# Build a model.
w.runFolderOperation("core", "modelbuild")
# Import some more documents.
... | |
"""
https://github.com/OpenNMT/OpenNMT-py/blob/master/onmt/translate/beam_search.py
References:
Copyright (c) 2017 <NAME>
Licensed under The MIT License, see https://choosealicense.com/licenses/mit/
@inproceedings{klein-etal-2017-opennmt,
title = "{O}pen{NMT}: Open-Source Toolkit for Neural Machine Translat... | |
in infotext)
infotext = "table%s: %s" % \
("" if single_table else "s", infotext)
if not single_table:
infotext += "; %s in total" % \
util.plural("result", result_count)
final_text = "No matches found."
if self._drop_results:
result["output"] = ""
if result_count:
final_text = "Finished searching %... | |
_get_hash(head_hash, short_hash)
txt.append(" head_hash: %s" % head_hash)
#
remh_hash = get_remote_head_hash(dir_name)
remh_hash = _get_hash(remh_hash, short_hash)
txt.append(" remh_hash: %s" % remh_hash)
#
if dir_name != ".":
subm_hash = _get_submodule_hash(dir_name)
subm_hash = _get_hash(subm_hash, short_has... | |
import rdkit
from rdkit import Chem
from optparse import OptionParser
from rdkit import RDLogger
lg = RDLogger.logger()
lg.setLevel(4)
'''
This script evaluates the quality of predictions from the rank_diff_wln model by applying the predicted
graph edits to the reactants, cleaning up the generated product, and compari... | |
<reponame>leozz37/makani<filename>avionics/servo/firmware/generate_r22_param.py
#!/usr/bin/python
# Copyright 2020 Makani Technologies 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
#
# ... | |
self.rest.send_telegram_message(chat_id, message)
else:
self.rest.send_telegram_image(chat_id, image)
def login(self):
user_id = self.configure.common_config[lybconstant.LYB_DO_BOOLEAN_SAVE_LOGIN_ACCOUNT + '_id']
user_password = li<PASSWORD>ot_license.LYBLicense().get_decrypt(
self.configure.common_config[lybcon... | |
<gh_stars>0
import sys
import pickle
import json
import os
import math
import networkx as nx
from collections import defaultdict
from net_init import load_network
from net_init import generate_random_outs_conns_with_oracle as gen_rand_outs_with_oracle
from network.sparse_table import SparseTable
from network.communica... | |
not silent:
# Ask which preset to use
print(f'Available ddrescue presets: {" / ".join(SETTING_PRESETS)}')
preset = std.choice(SETTING_PRESETS, 'Please select a preset:')
# Fix selection
for _p in SETTING_PRESETS:
if _p.startswith(preset):
preset = _p
# Add default settings
menu.add_action('Load Preset')
men... | |
einsum('ldpru,ypP->lydPru',bra[1][0],mpo[2]) # Bottom right site
Hbra[1][0].merge_inds([0,1])
Hbra[1][1] = bra[1][1].copy()
# Calculate Operator -------------------------------------
# Compute bottom environment as a boundary mpo
Hbot = update_bot_env2(0,
Hbra,
ket,
left[0],
left[1],
right[0],
right[1],
bot... | |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 29 11:49:07 2020
@author: rubenandrebarreiro
"""
# Definition of the necessary Python Libraries
# a) General Libraries:
# Import NumPy Python's Library as np
import numpy as np
# Import Math Python's Library as mathematics
import math as mathematics
# Import SciKit-L... | |
<filename>sfepy/solvers/ts_solvers.py
"""
Time stepping solvers.
"""
from __future__ import absolute_import
import numpy as nm
from sfepy.base.base import (get_default, output, assert_,
Struct, IndexedStruct)
from sfepy.base.timing import Timer
from sfepy.linalg.utils import output_array_stats
from sfepy.solvers.solv... | |
if min(self.input_resolution) <= self.win_size:
self.shift_size = 0
self.win_size = min(self.input_resolution)
assert 0 <= self.shift_size < self.win_size, "shift_size must in 0-win_size"
self.norm1 = norm_layer(dim)
self.norm_kv = norm_layer(dim)
self.cross_attn = WindowAttention(
dim, win_size=to_2tuple(self... | |
"""
Module containing routines used by 3D datacubes.
.. include common links, assuming primary doc root is up one directory
.. include:: ../include/links.rst
"""
import inspect
from astropy import wcs, units
from astropy.coordinates import AltAz, SkyCoord
from astropy.io import fits
import scipy.optimize as opt
from... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
######################################################################
# 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.
# Yo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.