input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<reponame>misads/torch_template
# encoding=utf-8
"""Misc PyTorch utils
Usage:
>>> from torch_template import torch_utils
>>> torch_utils.func_name() # to call functions in this file
"""
from datetime import datetime
import math
import os
import torch
import torch.nn as nn
from tensorboardX import SummaryWriter
imp... | |
self.add(dict(s=s, sub=sub, count=count))
class SortNumbers(Problem):
"""
Sort numbers based on strings
Sample input
---
"six one four"
Sample output
---
"one four six"
Inspired by [HumanEval](https://github.com/openai/human-eval)/19
"""
@staticmethod
def sat(ans: str, s="six one four"):
nums = 'zero... | |
# Copyright 2015 <NAME>
# 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
# d... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import subprocess
import json
import logging
import argparse
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# apps = ["PinLock", "Camera_To_USBDisk", "FatFs_RAMDisk", "... | |
<gh_stars>0
from __future__ import absolute_import
from __future__ import unicode_literals
import django
from django.test import TestCase
from django.utils.timezone import now
from mock import MagicMock
import job.test.utils as job_test_utils
import queue.test.utils as queue_test_utils
from job.execution.job_exe impo... | |
<filename>openstack_dashboard/dashboards/project/instances/tests.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under... | |
to which this particular claim pertains - eg Property/Casualy insurer
claim # or Workers Compensation case # .
"""
__name__ = 'ExplanationOfBenefit_Related'
def __init__(self, dict_values=None):
self.claim = None
# reference to Reference: identifier
self.relationship = None
# reference to CodeableConcept
s... | |
GenerateDSNamespaceDefs_.get('ArrayOfCountry')
if imported_ns_def_ is not None:
namespacedef_ = imported_ns_def_
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.original_tagname_ is not None and name_ == 'ArrayOfCountry':
name_ = self.original_tagname_
if UseCapturedNS_ and self.ns_prefix_:
namespacepref... | |
zer is M.scalar_field_algebra().zero()
True
By definition, a scalar field acts on the manifold's points, sending
them to elements of the manifold's base field (real numbers in the
present case)::
sage: N = M.point((0,0), chart=c_uv) # the North pole
sage: S = M.point((0,0), chart=c_xy) # the South pole
sage: E... | |
tuple contains (the cost value, target output - calculated output)
"""
difference = target_output - self.output
ann_error = 0.5 * difference * difference
# is_categoric = True if self.parent_layer == 2 else False
# if self.is_categoric:
# #logistic cost function
# ann_error = -target_output * math.log(sel... | |
<a href="/items/96">
<img class="media-object item img-responsive"
src="https://images-na.ssl-images-amazon.com/images/I/51evtEktP1L._SL160_.jpg"
alt="Image of Under the Volcano " style="max-width: 100px;">
</a>
<div>
<a href="https://www.amazon.com/Under-Volcano-Novel-Malcolm-Lowry/dp/0061120154?SubscriptionId=1... | |
<filename>prediction/saambe/Mutation_pred.py
def usage():
print("Available command-line options:\n -i PDBfile\n -c Chain of mutation\n -r Resid of the mutation\n -w One letter of wild amino acid\n -m One letter of mutatant amino acid\n -f Input file\n -o Output file\n -h Display this command-line summary")
def net_vol... | |
dict()
self._pdescr = dict()
self._ptype = dict() #stores the type of the parameter
self._prange = dict() # stores the min-max range of the parameter in a tuple
self._localp = dict()
self.addlocalparameter("_ports_", dict(), "Ports calculated by geom")
self._x0 = 0
self._y0 = 0
self._hv = True
self._bf = True
... | |
#!/usr/bin/env python
#
# Copyright 2007 Google 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 ag... | |
"""
Code borrowed from PLCAPI.
URL: http://svn.planet-lab.org/svn/PLCAPI/trunk/PLC/Table.py
Modifications by <NAME>
"""
from types import StringTypes, IntType, LongType
import time
import calendar
from SMDS.timestamp import Timestamp
from SMDS.faults import *
from SMDS.parameter import Parameter
class Row(dict):
... | |
for i, ann_line in enumerate(ann_list):
if len(ann_line['boxes']) == 0:
continue
width = ann_line['width']
height = ann_line['height']
bboxes = np.array(ann_line['boxes'])
bboxes[:, 0::2] = np.clip(bboxes[:, 0::2], 1, width - 1)
bboxes[:, 1::2] = np.clip(bboxes[:, 1::2], 1, height - 1)
labels = ann_line['clas... | |
def is_library(self):
return self.get_fbconfig_rule_type() == 'cpp_library'
def is_extension(self):
return self.get_fbconfig_rule_type() in (
'cpp_python_extension',
'cpp_java_extension',
'cpp_lua_extension')
def get_fbconfig_rule_type(self):
return self._rule_type
def get_buck_rule_type(self):
rule_type =... | |
in tblines)
self.assertTrue("raise NonserializableError((\"xantippe" in tblines)
finally:
Pyro4.config.SERIALIZER = "serpent"
def testBatchProxy(self):
with Pyro4.core.Proxy(self.objectUri) as p:
batch = Pyro4.batch(p)
self.assertIsNone(batch.multiply(7, 6))
self.assertIsNone(batch.divide(999, 3))
s... | |
<filename>pysaint/api.py
"""
End User를 위한 간단한 api
"""
from .constants import Line
from .saint import Saint
import copy
from tqdm import tqdm
from datetime import datetime
def get(course_type, year_range, semesters, line=Line.FIVE_HUNDRED, **kwargs):
"""
THIS IS THE END POINT OF pysaint API
USAGE::
>>> import ... | |
<reponame>Sehgal-Arjun/DataSorter
#copyright ReportLab Europe Limited. 2000-2016
#see license.txt for license details
__version__='3.3.0'
__all__= (
'BarcodeI2of5',
'BarcodeCode128',
'BarcodeStandard93',
'BarcodeExtended93',
'BarcodeStandard39',
'BarcodeExtended39',
'BarcodeMSI',
'BarcodeCodabar',
'BarcodeCode... | |
maybe.",
"And on that terrible night, that night it happened, did anything particularly important happen at the dinner? No, not that I recall.",
"Honestly, I thought I was going to find you and Peter around the next corner, playing some trick on me.",
"My mother.",
"Your father.",
"More than the shock, the sinfulness, ... | |
loopingcall.LoopingCallDone()
if utils.check_timeout(start_time, _LDEV_STATUS_WAITTIME):
raise loopingcall.LoopingCallDone(False)
loop = loopingcall.FixedIntervalLoopingCall(
_wait_for_ldev_status, timeutils.utcnow(), ldev, *args)
if not loop.start(interval=_LDEV_CHECK_INTERVAL).wait():
msg = utils.output_log(ms... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import importlib
import json
import logging
import os
import re
import collections
import copy
import shutil
import datetime
import time
import uuid
import imp
import sys
from oic.oauth2.message import REQUIRED_LIST_OF_SP_SEP_STRINGS
from oic.oauth2.message import OPTIONAL... | |
genesis block
logger.error("epoch seed is None for the genesis block!!!!!")
self.epoch_seed = sha256(b'INVALID_EPOCH_SEED')
# Prepare Metadata inputs
if block.block_number == 0 or self._chain.height + 1 == block.block_number:
prev_prev_sv_tracker = copy.deepcopy(self._chain.pstate.prev_stake_validators_tr... | |
<reponame>troglodyne/ccs-twistedextensions
# -*- test-case-name: twext.internet.test.test_sendfdport -*-
##
# Copyright (c) 2010-2017 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 ... | |
import math
import sys
#PIL
from PIL import ImageDraw
#scipy
import numpy
from scipy import optimize, ndimage
#appion
from appionlib import apImage
from appionlib import apDisplay
from appionlib import apDog
#pyami
from pyami import peakfinder
from pyami import correlator
#================================
#==========... | |
"""
x86 Encoding recipes.
"""
from __future__ import absolute_import
from cdsl.isa import EncRecipe
from cdsl.predicates import IsSignedInt, IsEqual, Or
from cdsl.predicates import IsZero32BitFloat, IsZero64BitFloat
from cdsl.registers import RegClass
from base.formats import Unary, UnaryIeee32, UnaryIeee64, UnaryImm, ... | |
import collections
import copy
import logging
import os.path
import os
import re
import json
import time
from functools import lru_cache
from typing import List, Dict, Optional, Deque
import urllib.parse
from botocore.exceptions import ClientError, EndpointConnectionError
from botocore.config import Config
from drago... | |
math.degrees(number)
def rand(minint, maxint):
return random.randint(minint, maxint)
def sin(arg):
return math.sin(arg)
def sinh(arg):
return math.sinh(arg)
def sqrt(arg):
return math.sqrt(arg)
def srand(seed=None):
if seed is None:
return random.seed()
return random.seed(seed)
def tan(arg):
return ... | |
extra == "yeah":
msg = "You are so fucked, {0}, so fucking fucked! Yeah, yeah, yeah!".format(
target)
else:
msg = "You are so fucked, {0}, so fucking fucked!".format(target)
return msg
def utard(self):
if lt == 0:
msg = "You fucktard!"
else:
msg = "{0}, you fucktard!".format(target)
return msg
def valley(... | |
import shutil, tempfile
from enthought.traits.api \
import HasTraits, Instance, Button, Int, Bool, on_trait_change
from enthought.traits.ui.api \
import View, Item, Group, HGroup, spring
from enthought.traits.ui.editors.range_editor import RangeEditor
from enthought.tvtk.pyface.scene_editor import SceneEditor
from e... | |
lost a hand.
#The HandResult class contains three non static (instance) values:
#self.CardCount; An integer value which represents the number of cards which were in the Hand class object that this HandResult class instance represents when it finished.
#self.Value; An integer value which represents the point va... | |
for norisk ageing flow age5to15 to age15to25
if '_norisk' in to_label:
add_unique_tuple_to_list(self.flows_by_type['fixed_transfer'],
(from_label, to_label,
self.params[param_label] * (1. - relevant_prop_ageing)))
elif '_norisk' in from_label and '_age15to25' in from_label:
# for diabetes_age_min
if '_diabetes' ... | |
counter + 1
if hasnameset and renamename != None:
mvname = os.path.basename(renamename)
if not os.path.exists(os.path.join(tmpdir, mvname)):
try:
shutil.move(tmpfile[1], os.path.join(tmpdir, mvname))
except Exception, e:
## if there is an exception don't rename
pass
if offset == 0 and (... | |
"%s: %s" % (prefix, self.name()))
else:
_gdb_write(indent, "%s:" % (prefix, self.name()))
for (key, value) in self.values():
_gdb_write(indent+1, "%s: %s" % (key, str(value)))
class GdbGstEvent:
def __init__(self, val):
self.val = val.cast(gdb.lookup_type("GstEventImpl").pointer())
@save_memory_access("<inacc... | |
resource.
# aggregation won't have resource files when copying a resource
if aggr.files.all().count() > 0:
parent_aggr = aggr.get_parent()
if parent_aggr is not None:
parent_aggr.update_coverage()
return element
def update_element(self, element_model_name, element_id, **kwargs):
resource = self.logical_file.re... | |
<reponame>jongiddy/dcos-e2e
import re
import subprocess
from . import constants
from .error import *
# functions that don't fall into the VM class
# basic utility function to execute some arguments and return the result
def execute (args):
try:
result = subprocess.check_output(args)
except subprocess.CalledProces... | |
0x09, 0x00, 0x00,
0x80, 0x04, 0x00, 0x00, 0x00, 0x82, 0x80, 0x08,
0x80, 0x08, 0x4a, 0x02, 0x00, 0x60, 0x12, 0x00,
0x42, 0x20, 0x0c, 0x18, 0x42, 0x20, 0x08, 0x00,
0x20, 0x01, 0x80, 0x28, 0x08, 0x82, 0x42, 0x20,
0x08, 0x00, 0x00, 0x00, 0x00, 0xbf, 0xda, 0x09,
0x82, 0x00, 0x00, 0x00, 0x00, 0x80, 0x08, 0x18,
0x00, 0... | |
('rhr_rh_user6', c_float) )
plist.append( ('rhr_rh_user7', c_float) )
plist.append( ('rhr_rh_user8', c_float) )
plist.append( ('rhr_rh_user9', c_float) )
plist.append( ('rhr_rh_user10', c_float) )
plist.append( ('rhr_rh_user11', c_float) )
plist.append( ('rhr_rh_user12', c_float) )
plist.append( ('rhr_rh_user13'... | |
the operation.
# We can disable this by passing "datetime.min" when we start tracking revisions.
doc.start_track_revisions("<NAME>", datetime.min)
builder.write("Hello again! ")
self.assertEqual(2, doc.revisions.count)
self.assertEqual("<NAME>", doc.revisions[1].author)
self.assertEqual(datetime.min, doc.revisio... | |
Connect an expression expr via connection variable cv
# Works for both read and write targets
# s:
# pos: starting index of the expression
# cv: connection variable
# expr: original expression
def connect_dp(s, pos, cv, expr):
repl = "(*(&(" + expr + ") + " + cv + "))"
s = replace_ln(s, pos, expr, repl)
return s
##... | |
#!/usr/bin/env python
"""
############################################################
Integrated Circuit Package Component Specific Work Book View
############################################################
"""
# -*- coding: utf-8 -*-
#
# rtk.hardware.gui.gtk.IntegratedCircuit.py is part of The RTK Project
#
# All r... | |
<reponame>srcarter3/awips2<gh_stars>0
##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restr... | |
+ B_i)
C_t^ = update_nl(W3x_t + U3h_{t-1} + B_c)
o_t = gate_nl(W4x_t + U4h_{t-1} + B_o)
C_t = f_t*C_{t-1} + i_t*C_t^
h_t = o_t*update_nl(C_t)
Wi and Ui can further parameterised into low rank version by
Wi = matmul(W, W_i) and Ui = matmul(U, U_i)
'''
def __init__(self, input_size, hidden_size, gate_non_linear... | |
fields ):
clone_strs = [ 'return self.__class__(' ]
for name, type_ in fields.items():
clone_strs.append( " " + _gen_list_clone_strs( type_, f'self.{name}' ) + "," )
return _create_fn(
'__deepcopy__',
[ 'self', 'memo' ],
clone_strs + [ ')' ],
)
#---------------------------------------------------------------... | |
area
analysisList = [
("InundationMax", self.moderatedMax),
("InundationTiming", self.moderatedMax, [6]),
]
return analysisList
def _extraRainfallAnalysisList(self):
analysisList = [
("QPF", self.accumSum),
]
return analysisList
###############################################################
### High ... | |
_ in range(2):
sync_mode.tick(timeout=self.timeout)
# Loop until all vehicles have reached their goal or we've exceeded self.max_iters.
for _ in range(self.max_iters):
snap, img = sync_mode.tick(timeout=self.timeout)
# Handle predictions.
self.agent_history.update(snap, self.world)
pred_dict = self._make_predi... | |
(self.dim_model, ), dtype = dtype
)
#self.flag_continue = True
self.cnt_total_event = numpy.int32(len(self.one_seq))
#
#
def soft_relu(self, x):
return numpy.log(numpy.float32(1.0)+numpy.exp(x))
#
def hard_relu(self, x):
return numpy.float32(0.5) * (x + numpy.abs(x) )
#
#
def save_model(self, file_save):
... | |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
""" Subsampled honest forest extension to scikit-learn's forest methods.
"""
import numpy as np
import scipy.sparse
import threading
import sparse as sp
import itertools
from sklearn.utils import check_array, check_X_y, issp... | |
<reponame>pursuitofepic/lookit-api<gh_stars>0
import csv
import datetime
import io
import json
import re
from django.test import Client, TestCase, override_settings
from django.urls import reverse
from django.utils.http import urlencode
from django_dynamic_fixture import G
from accounts.backends import TWO_FACTOR_AUT... | |
<reponame>evlog/SysPy<filename>SysPy_ver/Python_script/testbml2/_txt2BRAM.py
from pdb import *
def txt2BRAM_func0(txtFile_name, M_reactions, N_species, num_proc):
"""
FUNCTION: txt2BRAM_func0(a str, b int, c int)
a: text file name string
b: integer number of Spieces
c: integer number of Reactions
d: integer numb... | |
# -*- coding: utf-8 -*-
# Copyright (c) 2016-2018 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
import pytest
import numpy as np
import pandapower as pp
from pandapower.test.toolbox import add_grid_connection
from pandapower.... | |
+
"(task (plan user_speech) (action_type handover_object) (params ) (step ))",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
{"params": ["Action_take", "Person", "Object", "Place_second"],
"Action_take": [["bring" , "give"], [], [], []],
"Person": [["me"], [], [], []],
"O... | |
options(joinedload_all('instances')).\
first()
if not result:
raise exception.SecurityGroupNotFound(
security_group_id=security_group_id)
return result
@require_context
def security_group_get_by_name(context, project_id, group_name):
session = get_session()
result = session.query(models.SecurityGroup).\
filte... | |
import functools
from pathlib import Path
from typing import Sequence, Tuple, Union
import PIL
import numpy
import six
import tensorflow
from PIL import Image, ImageColor, ImageDraw, ImageFont
from attr import dataclass
from matplotlib import pyplot
from typing import Sequence, Tuple, Union
from warg.mixins.dict_mix... | |
query': '没有暂挂查询匹配的注册',
'No person record found for current user.': '没有人找到记录的当前用户。',
'No problem group defined yet': '没有问题组尚未定义',
'No records matching the query': '没有查询匹配的记录',
'No reports available.': '无可用的报告。',
'No reports currently available': '目前没有报告可用',
'No requests found': '未找到请求',
'No resources currently re... | |
<reponame>afrokyss/DIT-ILLUMNI-WAGTAIL-APP
from __future__ import unicode_literals
from django.forms import ValidationError
from django.core.exceptions import NON_FIELD_ERRORS
from django.forms.formsets import TOTAL_FORM_COUNT
from django.forms.models import (
BaseModelFormSet, modelformset_factory,
ModelForm, _get_... | |
aggregate: function applied across data going into each cell
of the table <http://www.sqlite.org/lang_aggfunc.html>_
where: list of tuples or list of strings for filtering data
method:
'valid': only returns rows or columns with valid entries.
'full': return full factorial combinations of the
conditions speci... | |
hdu = GLOBALutils.update_header(hdu,'HIERARCH DEC',h[0].header['DEC'])
hdu = GLOBALutils.update_header(hdu,'HIERARCH RA BARY',ra)
hdu = GLOBALutils.update_header(hdu,'HIERARCH DEC BARY',dec)
hdu = GLOBALutils.update_header(hdu,'HIERARCH EQUINOX',h[0].header['HIERARCH ESO TEL TARG EQUINOX'])
hdu = GLOBALutils.update... | |
725756740,
725641311,
-1,
-54461,
725712036,
10079,
-1,
725756157,
10080,
725953351,
725691838,
-1,
-54458,
725896748,
129052,
-1,
725954655,
129048,
-54456,
725893681,
128627,
-1,
726079292,
128327,
726281041,
725618449,
-1,
726346576,
726235036,
-1,
726412111,
726295300,
129180,
72653... | |
coefficients for r to the order of -4, -6, -8, and -10, respectively.
"""
new_multipole_terms = np.zeros(4)
new_multipole_terms[0] = np.sum(multipole_terms[:1])
new_multipole_terms[1] = np.sum(multipole_terms[2:6])
new_multipole_terms[2] = np.sum(multipole_terms[6:8])
new_multipole_terms[3] = np.sum(multipole_t... | |
download_url_container=report_table.quarter_download_url.to_list() # container to store the download urls of quarter statements
# Designate a directory to store downloaded statements (begin statement piling)
statement_pile_path=os.path.join(root_path,'statement_pile')
company_pile_path=os.path.join(statement_p... | |
if source in graph:
graph[source].append(sink)
else:
graph[source] = [sink]
return graph
# 59-5
def find_contigs(graph, node, indegree, outdegree):
contigs = []
for next in graph[node]:
new_path = [node, next]
ins, outs = indegree[next], outdegree[next]
while ins == 1 and outs == 1:
node = next
next = graph... | |
+ du, v + dv
smell = orangeSmell
if not 0 <= r < self.rows or not 0 <= c < self.cols:
return 'Blocked'
cellColor = self.layout[ r ][ c ]
# Red tiles are impassable.
if cellColor == self.redTile:
return 'Blocked'
elif cellColor == self.pinkTile:
pass
elif cellColor ==... | |
= os.path.join(
intermediate_dir, 'clipped_lulc%s.tif' % file_suffix)
eto_path = os.path.join(intermediate_dir, 'eto%s.tif' % file_suffix)
precip_path = os.path.join(intermediate_dir, 'precip%s.tif' % file_suffix)
depth_to_root_rest_layer_path = os.path.join(
intermediate_dir, 'depth_to_root_rest_layer%s.tif' % fi... | |
body in list:
# Style may place the ':' on the next line.
comment = get_comment(data, name + ' :')
if len(comment) == 0:
comment = get_comment(data, name + "\n")
validate_comment(filename, name, comment)
self.classes.append(
obj_class(self, filename, attrib, name, parent_name, body, comment,
includes, forward_d... | |
# -------------------------------------------------------------------------------------------------
# system
from time import sleep
from math import sqrt
import csv
# -------------------------------------------------------------------------------------------------
# PyQuantum.TC
from PyQuantum.TC.Unitary import *
# ---... | |
<reponame>ClearCalcs/pydyf
"""
A low-level PDF generator.
"""
import re
import zlib
from codecs import BOM_UTF16_BE
VERSION = __version__ = '0.1.2'
def _to_bytes(item):
"""Convert item to bytes."""
if isinstance(item, bytes):
return item
elif isinstance(item, Object):
return item.data
elif isinstance(item, f... | |
<reponame>yesArjan/Playing-Go-with-RNNs
from tensorflow.python.ops import nn_ops
from tensorflow.python.keras import activations
import tensorflow as tf
import numpy as np
class ConvRNNCell(tf.nn.rnn_cell.RNNCell):
"""A RNN cell with convolutions instead of multiplications."""
def __init__(self, input_shape, outpu... | |
0, -1, -1, 3, -1, -1, 9, -1, -1, -1, 47, -1, -1, 50,
-1, 10, -1, -1, -1, 46, -1, -1, 49, -1],
[-1, 46, -1, -1, 49, -1, -1, 52, -1, -1, 45, -1, -1, 48, -1, -1, 51,
-1, 38, -1, -1, 41, -1, -1, 44, -1, -1],
[-1, 47, -1, -1, 50, -1, -1, 53, -1, -1, 46, -1, -1, 49, -1, -1, 52,
-1, -1, 45, -1, -1, 48, -1, -1, 51, -1],
... | |
def __call__(self, obj_agent):
# self._current_agent_id = obj_agent._id2env
return self
class fx(object):
legs = {}
online = True
config_file = 'twap.conf'
now_val = 0
pending_callbacks = {}
symbols_callbacks = {}
time_callbacks = {}
initial_time = 0
trade_callback_used = {}
@staticmethod
def now(b_str... | |
<reponame>MarkusShepherd/flamme-rouge
# -*- coding: utf-8 -*-
""" tracks """
import logging
import re
from collections import deque
from typing import (
TYPE_CHECKING,
Any,
Deque,
Generator,
Iterable,
Iterator,
Optional,
Tuple,
Type,
Union,
cast,
overload,
)
from .cards import Card
from .utils import cl... | |
env, 3. file
secret_env = os.environ.get(env_name)
if not secret and secret_env:
secret_from = 'env'
self.log.info("Loading %s from env[%s]", trait_name, env_name)
secret = binascii.a2b_hex(secret_env)
if not secret and os.path.exists(secret_file):
secret_from = 'file'
self.log.info("Loading %s from %s", trait_... | |
of the argument to be deleted"
)
add_args(del_config_parser, config_path)
add_args(del_config_parser, shipped_configs)
del_config_parser.add_argument(
'-a', '--all',
action='store_true',
default=False,
help='delete all configs (asks the user to confirm before deleting) [default: False]'
)
del_config_parser.add_argu... | |
<gh_stars>100-1000
# 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
# distr... | |
<gh_stars>1-10
#!/usr/bin/python
# -*- coding: utf-8 -*-
# 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
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This progra... | |
decl, '}'))
else:
decl = ''
if name == '' and decl == '':
res = ''
else:
res = ' '.join([l for l in [stype, decl, name] if l])
return res
@property
def text(self):
"""
Text to construct this instance.
"""
return self.text_formatted(indent=0, linebreak=False)
class Dataset(Struct):
"""
Class for *Datas... | |
<filename>venv/lib/python3.6/site-packages/madmom/audio/stft.py
# encoding: utf-8
# pylint: disable=no-member
# pylint: disable=invalid-name
# pylint: disable=too-many-arguments
"""
This module contains Short-Time Fourier Transform (STFT) related functionality.
"""
from __future__ import absolute_import, division, pr... | |
def concat(lib, df1, df2, join, sort, ignore_index):
return lib.concat(
[df1, df2], join=join, sort=sort, ignore_index=ignore_index
)
run_and_compare(
concat,
data=self.data,
data2=self.data2,
join=join,
sort=sort,
ignore_index=ignore_index,
)
def test_concat_with_same_df(self):
def concat(df, **kwargs):... | |
10.1115/1.2900803.
[5] <NAME> and <NAME> (2015): Mechanical vibrations. Theory and application to structural dynamics.
ISBN 978-1-118-90020-8.
"""
super().__init__()
# Set function handles for calling in residual and jacobian
self.M = M
self.f_int = f_int
self.f_ext = f_ext
self.K = K
self.D = D
# Set time... | |
#!/usr/bin/env python
# The contents of this file are subject to the Python Software Foundation
# License Version 2.3 (the License). You may not copy or use this file, in
# either source code or executable form, except in compliance with the License.
# You may obtain a copy of the License at http://www.python.org/lice... | |
from bitcoin_tools.analysis.plots import get_cdf
from bitcoin_tools.analysis.status.data_dump import transaction_dump, utxo_dump
from bitcoin_tools.analysis.status.utils import parse_ldb, aggregate_dust_np
from .data_processing import get_samples, get_filtered_samples
from bitcoin_tools.analysis.status.plots import plo... | |
"""Defining domain generalization algorithms"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.autograd as autograd
import matplotlib.pyplot as plt
OBJECTIVES = [
'ERM',
'GroupDRO',
'IRM',
'VREx',
'SD',
# 'ANDMask', # Requires update
# 'IGA', # Requires update
# 'Fish', # R... | |
11: I11i / OOooOOo . o0oOOo0O0Ooo - O0 * OoooooooOO % iII111i
if 7 - 7: OoOoOO00 . IiII + OoooooooOO - I1Ii111 / oO0o
def lisp_process_api ( process , lisp_socket , data_structure ) :
IiI1I1 , III11I1 = data_structure . split ( "%" )
if 48 - 48: i11iIiiIii * o0oOOo0O0Ooo
lprint ( "Process API request '{}', paramete... | |
from __future__ import annotations
import pathlib
import tkinter as tk
import typing
from math import pi
from tkinter import ttk
from interface import general_functions
from interface.material_and_measures import Distance, Force, WireMaterial
class Note:
""" A single note in an instrument, contains functions and d... | |
<filename>assembler/cas.py
#!/bin/python3
from typing import List, TextIO, Tuple
import os, re, sys
class ParseException(Exception):
pass
class SourceLine:
'''
A class that represent a single line in the source file
'''
def __init__(self, line: str, num: int):
self.line = line
self.num = num
def __str__(s... | |
#!/usr/bin/env python
###################### INFORMATION ##############################
# Extract the table of content (TOC) from Reichanzeiger
#Program: **crop**
#Info: **Python3**
#Author: **<NAME>**
#Date: **08.04.2021**
####################### IMPORT ##################################
import argparse
import copy
im... | |
<filename>gspy.py
import numpy as np
import matplotlib.pyplot as plt
from scipy import linalg
#def adj_matrix_from_coords(coords,theta,show_progress=False):
# [N,M] = coords.shape
# A = np.zeros((N,N))
# for i in np.arange(1,N):
# if show_progress:
# #print 100.0*i/N, '% of adj_matrix_from_coords process completed... | |
eul[0] = math.atan2(R[1, 2], R[0, 2])
sp = math.sin(eul[0])
cp = math.cos(eul[0])
eul[1] = math.atan2(cp * R[0, 2] + sp * R[1, 2], R[2, 2])
eul[2] = math.atan2(-sp * R[0, 0] + cp * R[1, 0], -sp * R[0, 1] + cp * R[1, 1])
if unit == "deg":
eul *= 180 / math.pi
return eul
# -------------------------------------... | |
<reponame>masterapps-au/pysaml2
#!/usr/bin/env python
#
# Generated Mon May 2 14:23:33 2011 by parse_xsd.py version 0.4.
#
# A summary of available specifications can be found at:
# https://wiki.oasis-open.org/security/FrontPage
#
# saml core specifications to be found at:
# if any question arise please query the foll... | |
<gh_stars>0
# ------------------------------------------------------------------------------
# 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
#
# U... | |
<filename>bp_to_imgV2.py
import json, time
import numpy as np
import quaternion
import cv2
#from scipy.signal import convolve2d
# block rotation directions
rot_normal = np.array([
[ 0, 0, 1], #0
[ 1, 0, 0], #1
[ 0, 0,-1], #2
[-1, 0, 0], #3
[ 0,-1, 0], #4
[ 0,-1, 0], #5
[ 0,-1, 0], #6
[ 0,-1, 0],... | |
= Var(within=Reals,bounds=(0,None),initialize=1.42857142857143)
m.x1238 = Var(within=Reals,bounds=(0,None),initialize=1.42857142857143)
m.x1239 = Var(within=Reals,bounds=(0,None),initialize=1.42857142857143)
m.x1240 = Var(within=Reals,bounds=(0,None),initialize=1.42857142857143)
m.x1241 = Var(within=Reals,bounds=(0,Non... | |
position")
self.hdf5.flush()
def close(self):
logger.debug("In close")
if self.hdf5:
self.flush()
with self._sem:
self.hdf5.close()
self.hdf5 = None
def write(self, data, index=0):
"""
Minimalistic method to limit the overhead.
:param data: array with intensities or tuple (2th,I) or (I,2th,chi)
"""
logg... | |
# -*- coding: utf-8 -*-
################################################################################
# childs.py - Teil von Kodi-Addon-ARDundZDF
# Rahmenmodul für Kinderprg div. Regionalsender von ARD und ZDF
#
# 02.11.2019 Migration Python3 Modul future
# 17.11.2019 Migration Python3 Modul kodi_six + manuelle ... | |
"""
# Event source for MAGIC calibrated data files.
# Requires uproot package (https://github.com/scikit-hep/uproot).
"""
import re
import uproot
import logging
import scipy
import scipy.interpolate
import numpy as np
from decimal import Decimal
from enum import Enum, auto
from astropy.coordinates import Angle
from as... | |
import json
from jsonargparse import ArgumentParser, ActionConfigFile
import yaml
from typing import List, Dict
import glob
import os
import pathlib
import pdb
import subprocess
import copy
from io import StringIO
from collections import defaultdict
import torch
from spacy.tokenizer import Tokenizer
from spacy.... | |
"""show_interface.py
JunOS parsers for the following show commands:
* show interfaces terse
* show interfaces terse | match <interface>
* show interfaces terse {interface}
* show interfaces {interface} terse
* show interfaces descriptions
* show interfaces queue {interface}
* show interfaces policers {interface... | |
<reponame>poornasairoyal/Laser-Simulation<filename>laser/misc.py
import numpy as np
from scipy.interpolate import interp1d, interp2d
from scipy.optimize import curve_fit
import matplotlib.image as mpimg
def get_moments(image):
"""
Compute image centroid and statistical waist from the intensity distribution.
Param... | |
<filename>src/main/python/model/filter.py<gh_stars>0
import json
import logging
from collections import defaultdict
from collections.abc import Sequence
from typing import Optional, Type, Tuple, Any, List
from uuid import uuid4
import math
import qtawesome as qta
from qtpy import QtCore
from qtpy.QtCore import QAbstra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.