input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
a namespace
# Apply namespace from nsmap
colonoffset=attrname.find(':')
namespaceuri=namespaces[attrname[:colonoffset]]
tag.attrib["{%s}%s" % (namespaceuri,attrname[(colonoffset+1):])]=value
pass
else :
tag.attrib[attrname]=value
pass
self.modified=True;
# if self.autoflush:
# self.flush()
# pass
pa... | |
"""Accounts forms module."""
from math import floor
from django import forms
from django.db.models import Q
from django.contrib.auth import forms as auth_forms
from django.contrib.auth import password_validation
from django.contrib.sites.shortcuts import get_current_site
from django.conf import settings
from django.cor... | |
# Copyright 2004-2008 <NAME>.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
"""
This file contains indexing suite v2 code
"""
file_name = "indexing_suite/algorithms.hpp"
code = """// Header file algorithms.hpp
... | |
is not fed.
shape: A `tf.TensorShape` or list of `ints`.
The (possibly partial) shape of the tensor.
name: A name for the operation (optional).
Returns:
A `Tensor`. Has the same type as `input`.
"""
_ctx = _context._context or _context.context()
tld = _ctx._thread_local_data
if tld.is_eager:
try:
_result = ... | |
<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
A Gherkin parser written using pyparsing.
"""
import os
from collections import OrderedDict
from copy import copy
from gherkin.dialect import Dialect
from gherkin.errors import ParserError
from gherkin.parser import Parser
from gherkin.token_matcher import TokenMatcher
from... | |
# coding: utf-8
"""
Prisma Cloud Compute API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: 21.04.439
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re ... | |
<gh_stars>0
# Copyright 2021 <NAME> <<EMAIL>>. All Rights Reserved.
# Author: <NAME> <<EMAIL>>
#
# 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
#... | |
# applying mask for "apparent horizon"
#
dens = ne.evaluate("rho * w_lorentz * vol") # conserved density (?)
#
mode0 = dxyz * ne.evaluate("sum(dens)") # total mass of the BH
int_modes[0][i_it] = mode0
#
Ix = dxyz * ne.evaluate("sum(dens * x)") # computing inertia center
Iy = dxyz * ne.evaluate("sum(dens * y)")
... | |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @miemie2013
import os
import sys
import random
import torch
import torch.distributed as dist
import torch.nn as nn
from mmdet.data import *
from mmdet.exp.datasets.coco_base import COCOBaseExp
class FCOSEvalCollater():
def __init__(self, context, batch_transforms):
... | |
is useful when a series of tasks with prerequisites must be run
sequentially. The prerequisites may be finished in any order, but the
tasks may only be run when all prerequisites are complete, and the
dependent task is also complete. Tasks may only depend on one other task.
For example, you might want to download ... | |
lib in libs_found:
continue
if self.clib_compiler:
args = self.clib_compiler.find_library(lib[2:], self.env,
libpaths, libtype)
# If the project only uses a non-clib language such as D, Rust,
# C#, Python, etc, all we can do is limp along by adding the
# arguments as-is and then adding the libpaths at the end.
... | |
<gh_stars>10-100
# Generated from RuleLexerPy.g4 by ANTLR 4.7.2
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
from antlr4.Token import CommonToken
from antlr4.RuleContext import RuleContext
from antlr4.Token import Token
from RuleParserPy import RuleParserPy
def serializedATN... | |
<reponame>TomNicholas/datatree
from __future__ import annotations
import textwrap
from typing import Any, Callable, Dict, Hashable, Iterable, List, Mapping, Tuple, Union
import anytree
from xarray import DataArray, Dataset, merge
from xarray.core import dtypes, utils
from xarray.core.variable import Variable
from .m... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# MinIO Python Library for Amazon S3 Compatible Cloud Storage,
# (C) 2015, 2016, 2017, 2018 MinIO, 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 Lice... | |
# -*- coding: utf-8 -*-
from collections import OrderedDict
from gluon import current
from gluon.storage import Storage
def config(settings):
"""
Template for WA-COP + CAD Cloud Integration
"""
T = current.T
# =========================================================================
# System Settings
#
set... | |
#!/usr/bin/env python
# coding=utf-8
'''
Author: ZZ_Guo
Email: <EMAIL>
Date: 2020-09-11 23:03:00
LastEditor: ZZ_Guo
LastEditTime: 2021-05-06 17:04:38
Discription:
Environment:
'''
from pysc2.lib import actions, features, units
from pysc2.env import sc2_env, run_loop, available_actions_printer
from pysc2 import maps
i... | |
<filename>UI/ui_DatabaseEdit.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'databaseEdit.ui'
#
# Created: Tue Mar 12 10:35:03 2013
# by: pyside-uic 0.2.14 running on PySide 1.1.2
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_Datab... | |
+= len(bytes_read)
return bytestream
def send(self, bytestream: bytes) -> None:
"""Try and send the data in `bytestream` to the remote.
*Events Emitted*
- None
- Evt17: Transport connected closed.
Parameters
----------
bytestream : bytes
The data to send to the remote.
"""
self.socket = cast(socket.soc... | |
force is False).
Returns a list of CrossShardTransactionDeposit from block.
Additionally, returns a map of reward token balances for this block
Raises on any error.
"""
start_time = time.time()
start_ms = time_ms()
if skip_if_too_old:
if (
self.header_tip.height - block.header.height
> self.shard_config.max_... | |
#!/usr/bin/python
# A simple database class to handle tagging files.
#TODO: return values?
#TODO: a fix for os.path.commonprefix
import sqlite3
import os
import datetime
import tarfile
import csv
import logging
logger = logging.getLogger(__name__)
SEARCH_EXCLUSIVE = 'e'
SEARCH_INCLUSIVE = 'i'
# CSV dialect used for... | |
<filename>uamqp/client.py
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#-------------------------------------------------------------... | |
: ( 8040, 8120 ),
"MH6bCd32" : ( 8120, 8139 ),
"MH6bAnother26" : ( 8139, 8140 ),
"MH6bSpecify33" : ( 8140, 8220 ),
"MH6bCd33" : ( 8220, 8239 ),
"MH6bAnother27" : ( 8239, 8240 ),
"MH6bSpecify34" : ( 8240, 8320 ),
"MH6bCd34" : ( 8320, 8339 ),
"MH6bAnother28" : ( 8339, 8340 ),
"MH6bSpecify35" : ( 8340, 8420 ),
"... | |
<filename>src/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py
# coding=utf-8
# Copyright 2022 The Fairseq Authors 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 Licens... | |
import sys
import os
import errno
import inspect
from collections import namedtuple
from enum import Enum
from pathlib import Path
def DEBUG(*x):
if 'DEBUG' in os.environ:
print('@DEBUG', *x)
# ParsingExpression
class ParsingExpression(object):
def __iter__(self): pass
def __len__(self): return 0
# operator ov... | |
read binary mat
"""
fd = open_or_fd(file_or_fd)
try:
if not read_binary:
binary = fd.read(2)
if binary == b"\0B":
mat = _read_mat_binary(fd)
else:
assert binary == b" ["
mat = _read_mat_ascii(fd)
else:
mat = _read_mat_binary(fd)
finally:
if fd is not file_or_fd:
fd.close()
return mat
def _read_mat_bin... | |
5395, 5396, 5402, 5401)
model.createElement(3760, 5636, 5637, 5643, 5642, 5396, 5397, 5403, 5402)
model.createElement(3761, 5637, 5638, 5644, 5643, 5397, 5398, 5404, 5403)
model.createElement(3762, 5638, 3083, 3084, 5644, 5398, 3043, 3044, 5404)
model.createElement(3763, 2397, 5639, 5645, 2396, 2357, 5399, 5405, 2356)
... | |
import numpy as np
import torch
import torch.nn as nn
from utils.nn import RoundStraightThrough
class IDF(nn.Module):
def __init__(self, nett, num_flows, D=2):
super(IDF, self).__init__()
print('IDF by JT.')
self.t = torch.nn.ModuleList([nett() for _ in range(num_flows)])
self.num_flows = num_flows
self.rou... | |
: panose = r'{\*\panose %s}' % font.Panose
if font.Alternate : alternate = r'{\*\falt %s}' % font.Alternate.Name
self._write( r'{\f%s\f%s%s\fcharset%s%s %s%s;}',
offset,
font.Family,
pitch,
font.CharacterSet,
panose,
font.Name,
alternate )
self._font_map[ font ] = offset
offset += 1
self._write( "}\n" )
... | |
<gh_stars>0
import matplotlib.pyplot as plt
import numpy as np
import heapq
import os
import copy
from itertools import cycle
from itertools import combinations
#%% Functions header
#------------------------------------
#----------- Functions --------------
#------------------------------------
#%% get_indexes_max_n_... | |
import atexit
import inspect
import os.path
import shutil
import tempfile
from dectate import Action
from webassets import Bundle, Environment
class Asset:
"""Represents a registered asset which points to one or more files or
child-assets.
"""
__slots__ = ("name", "assets", "filters")
def __init__(self, name... | |
<filename>src/cosmicats/popgen.py
"""A collection of methods to generating astrophysical populations"""
import numpy as np
import pandas as pd
import astropy.coordinates as coord
from astropy.coordinates import SkyCoord
from astropy.table import Table
from astropy import units as u
from cosmic.evolve import Evolve
fro... | |
<filename>tutorials/autotvm/tune_simple_template.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 Lic... | |
b, e) for (t, b, e) in sglQuotedString.scanString(escapedQuoteTest)
]
print(sglStrings)
self.assertTrue(
len(sglStrings) == 1
and (sglStrings[0][1] == 17 and sglStrings[0][2] == 66),
"single quoted string escaped quote failure (%s)" % str(sglStrings[0]),
)
dblStrings = [
(t[0], b, e) for (t, b, e) in dblQuote... | |
from collections import namedtuple
from PySide2 import QtCore, QtGui, QtWidgets
from guis.g_need import GNeed
from guis.g_panel import GPanel
from guis.g_price_bar_chart import GPriceBarChart
from my_qt.buttons import CheckableMenuButton
from my_qt.charts import PriceBarChart
from my_qt.combo_boxes import SearchCombo... | |
== '4,5,6,7':
gem5_cluster = 'bigCluster'
elif core_mask == '0,1,2,3':
gem5_cluster = 'littleCluster'
else:
raise ValueError("Unrecognised core mask!")
'''
gem5_per_cluster = make_gem5_cols_per_cluster(temp_df, gem5_cluster)
temp_df = temp_df[[x for x in temp_df.columns.values if x.find('gem5 stat') == -1]]
te... | |
<reponame>Robbybp/IDAES-CLC
"""
Base for IDAES process model objects.
"""
from __future__ import division # No integer division
from __future__ import print_function # Python 3 style print
from pyomo.environ import *
from pyomo.dae import *
from pyomo.core.base.block import SimpleBlock, IndexedBlock, _BlockData
from p... | |
<reponame>kat-mulberries/cjaas-sdk
# coding: utf-8
"""
Azure Functions OpenAPI Extension
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __fu... | |
{neighbor} routes',
]
def cli(self, neighbor, address_family='', vrf='', output=None):
if output is None:
# Build command
if address_family and neighbor and vrf:
cmd = self.cli_command[0].format(address_family=address_family,
neighbor=neighbor,
vrf=vrf)
elif address_family and neighbor:
cmd = self.cli_comma... | |
lines. Default is False.
bathymetry: bool, optional
Creates a bathymetry map of the seabed based on an input file. Default is False.
Returns
-------
fig : figure object
To hold the axes of the plot
ax: axis object
To hold the points and drawing of the plot
'''
hidebox = kwargs.get('hidebox' , False ) # ... | |
"**Error** `I do not have 'Kick Users' Permission.`")
return
except discord.HTTPException:
await ctx.send_message(message.channel, "**Error* `Kicking failed.`")
return
async def ban(ctx, message):
"""
Ban a member
:param ctx:
:param message:
:return:
"""
if not message.mentions:
await ctx.send_message(mess... | |
<filename>osc/osc.py<gh_stars>1-10
#!/usr/bin/env python3
import vpython as vp
import numpy as np
from vpython import *
from time import sleep
AMP = 10.0
RADIUS = 0.2
class Universe:
def __init__(self):
self.viewScene()
def viewScene(self):
""" Canvas Scene """
scene = vp.canvas(
title = "Oscillations",
x... | |
##############################################
# User Defined Functions for Phrase Learning
##############################################
import pandas as pd
import numpy as np
import re, nltk, time, gc, math
from azureml.logging import get_azureml_logger
run_logger = get_azureml_logger()
run_logger.log('amlrealworl... | |
res["record"], res["data"]
# index is the row number of the scan in the set of scans
index = scan - 1 # FITS scans are 1-based
if scan in self.scans:
pass
else:
self.scans.append(scan)
if record == 1:
# these data are constant for the scan
self.source = self.info["point"]["current_source"]
if self.source:
se... | |
@classmethod
def language_version(cls, version_flags=None, **kwargs):
r"""Determine the version of this language.
Args:
**kwargs: Keyword arguments are passed to cls.run_executable.
Returns:
str: Version of compiler/interpreter for this language.
"""
if version_flags is None:
version_flags = cls.version_fla... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import zulip
import requests
import re
import pprint
import os
from database import VotingTopics
import parsley
class VotingBot():
"""bot takes a zulip username and api key, a word or phrase to respond to,
a search string for gi... | |
<filename>ui/file_manager/base/tools/modules.py
#!/usr/bin/env python
#
# Copyright (c) 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import re
import sys
import subprocess
def get_file_lines(file_path):... | |
uirevision=None,
usrc=None,
v=None,
visible=None,
vsrc=None,
w=None,
wsrc=None,
x=None,
xsrc=None,
y=None,
ysrc=None,
z=None,
zsrc=None,
row=None,
col=None,
**kwargs
):
"""
Add a new Cone trace
Use cone traces to visualize vector fields. Specify a vector
field using 6 1D arrays, 3 position arrays ... | |
<gh_stars>10-100
import xarray as xr
import numpy as np
import pandas as pd
def distrib_run_build_beam_pointing_vector(dat: list):
"""
Convenience function for mapping build_beam_pointing_vectors across cluster. Assumes that you are mapping this
function with a list of data.
distrib functions also return a proce... | |
<reponame>x22x22/python-ceph-cfg
# Import Python Libs
from __future__ import absolute_import
# Python imports
import os
import os.path
import platform
import logging
import shlex
import tempfile
try:
import ConfigParser
except:
import configparser as ConfigParser
# local modules
from . import constants
from . impor... | |
x == t[i+0][0] and y == t[i+2][0]) \
or (cmd == "wdand2tagbfr" and x == t[i-2][1] and y == t[i+0][0]) \
or (cmd == "wdand2tagaft" and x == t[i+0][0] and y == t[i+2][1]) \
or (cmd == "lbigram" and x == t[i-1][0] and y == t[i+0][0]) \
or (cmd == "rbigram" and x == t[i+0][0] and y == t[i+1][0]) \
or (cmd == "prevbigr... | |
one!'
])
def handle_bid_for_job(cmd_object, dlg_context, service_registry, **kwargs):
if not cmd_object.job_tag:
return 'Bid for a job by texting the job tag, space, and "bid".'
if not is_valid_job_tag(cmd_object.job_tag):
return REPLY_INVALID_TAG_TPL % cmd_object.job_tag
db_svc = service_registry.lookup('pos... | |
its associated value indicating the destination
:type node: dict, None
:param node_id: The ID of the node in which the message will be published
:type node_id: str, None
:param node_url: The URL of the node in which the message will be published
.. note:: This argument is necessary in the absence of the ``node`` ... | |
-4, -5): None,
(0, 34, -4, -4): None,
(0, 34, -4, -3): None,
(0, 34, -4, -2): None,
(0, 34, -4, -1): None,
(0, 34, -4, 0): None,
(0, 34, -4, 1): None,
(0, 34, -4, 2): None,
(0, 34, -4, 3): None,
(0, 34, -4, 4): None,
(0, 34, -4, 5): None,
(0, 34, -3, -5): None,
(0, 34, -3, -4): None,
(0, 34, -3, -3): None,... | |
from numpy.testing import assert_array_equal
import numpy as np
import tempfile
import secrets
import h5py
from hdf5zarr import HDF5Zarr
import pytest
import itertools
class HDF5ZarrBase(object):
##########################################
# basic tests #
##########################################
@pytest.mark.p... | |
#! /usr/bin/env python
"""Generate C code from an ASDL description."""
import os, sys
import asdl
TABSIZE = 4
MAX_COL = 80
def get_c_type(name):
"""Return a string for the C name of the type.
This function special cases the default types provided by asdl.
"""
if name in asdl.builtin_types:
return name
else:
... | |
<filename>selfdrive/controls/lib/adaptivecruise.py
import math
import numpy as np
from common.numpy_fast import clip, interp
import selfdrive.messaging as messaging
# lookup tables VS speed to determine min and max accels in cruise
_A_CRUISE_MIN_V = [-1.0, -.8, -.67, -.5, -.30]
_A_CRUISE_MIN_BP = [ 0., 5., 10., 20., 4... | |
import os, sys
import numpy as np
from numpy.linalg import inv
import random
#from scipy.optimize import least_squares
from scipy import optimize
from scipy.optimize import least_squares
import helperFunctions
from helperFunctions import genEulerZXZMatrix, genEulerAngles, minimizeReprojection, points3DwrtT0, minimizeR... | |
= '> '
debug = False
echo = False
editor = os.environ.get('EDITOR')
if not editor:
if sys.platform[:3] == 'win':
editor = 'notepad'
else:
# Favor command-line editors first so we don't leave the terminal to edit
for editor in ['vim', 'vi', 'emacs', 'nano', 'pico', 'gedit', 'kate', 'subl', 'geany', 'atom']:
if... | |
minVal = -Globals.Gameplay.ToonVelMax['turning']
maxVal = Globals.Gameplay.ToonVelMax['turning']
if not leftPressed and not rightPressed or self.controlVelocity[0] > maxVal or self.controlVelocity[0] < minVal:
x = self.dampenVelocityVal(self.controlVelocity[0], 'turning', 'turning', minVal, maxVal, dt)
self.control... | |
specific elements of XML files.
# Please note that this is for READ/WRITE/EXTERNALLY UPDATED access to
# XML files. If all you need is read-only access, see xmlcontroller in paramdb2.py
class synced(object):
# This class represents a paramdb2 entry that is sync'd with an element within one or more xmldoc's
# it ... | |
preferences.
:param 'TransportPreferencesResponseArgs' transport_preferences: Preferences related to the shipment logistics of the order.
"""
if notification_preferences is not None:
pulumi.set(__self__, "notification_preferences", notification_preferences)
if transport_preferences is not None:
pulumi.set(__self_... | |
import sys
from os import path
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from compound import Compound
import re
import csv
from time import strftime
from time import time
#from profilehooks import profile
#function for auto-py-to-exe
def resource_path(relative_path):
""" Get absolute path to reso... | |
<reponame>Huang-Shijie-SDUWH/Deep_MVS_Tutorial<filename>PatchmatchNet/models/patchmatch.py
"""
PatchmatchNet uses the following main steps:
1. Initialization: generate random hypotheses;
2. Propagation: propagate hypotheses to neighbors;
3. Evaluation: compute the matching costs for all the hypotheses and choose best ... | |
<filename>skills_taxonomy_v2/analysis/skills_taxonomy_application/Application - Geography.py
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# cell_metadata_filter: -all
# comment_magics: true
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.11.4
# kernel... | |
):
listener.exitVariable(self)
def variable(self):
localctx = GraphQLParser.VariableContext(self, self._ctx, self.state)
self.enterRule(localctx, 52, self.RULE_variable)
try:
self.enterOuterAlt(localctx, 1)
self.state = 289
self.match(GraphQLParser.T__16)
self.state = 290
self.name()
except RecognitionE... | |
# Train a GANformer model (pytorch version)
import os
import re
import json
import tempfile
# import torch
from training import misc
import dnnlib
from dnnlib import EasyDict
import argparse
import glob
import sys
import loader
# Conditional set: if property is not None, then assign d[name] := prop
# for every d i... | |
and zero timer and loss.
checkpoint_path = os.path.join(FLAGS.model_dir, "equilid.ckpt")
model.saver.save(sess, checkpoint_path, global_step=model.global_step)
step_time, loss = 0.0, 0.0
# Run evals on development set and print their perplexity.
for bucket_id in xrange(len(_buckets)):
if len(dev_set[bucket_id]) ... | |
= T("Role deleted"),
msg_list_empty = T("No Roles currently defined"))
s3mgr.configure(tablename, main="role")
return s3_rest_controller(prefix, resourcename)
# -----------------------------------------------------------------------------
@auth.s3_requires_membership(1)
def membership():
"""
RESTful CRUD contro... | |
import os
import numpy as np
from scipy import ndimage
from scipy.signal import fftconvolve, convolve2d
from astropy.modeling import models, fitting
def positional_shift(R,T):
Rc = R[10:-10,10:-10]
Tc = T[10:-10,10:-10]
c = fftconvolve(Rc, Tc[::-1, ::-1])
cind = np.where(c == np.max(c))
print cind
csmall = c[ci... | |
import os
import numpy as np
import tensorflow as tf
from tensorflow.python.training import queue_runner
def load_dataset(model, num_gpus, batch_size, output_dims, input_dims, seq_length, size, base_data_path, dataset, istraining, clip_length, video_offset, clip_offset, num_clips, clip_stride, video_step, preproc_de... | |
import os
import abc
import struct
import logging
import time
from collections import OrderedDict, namedtuple
from datetime import datetime
from typing import List, Dict, Optional, Any, Type, TypeVar
from .audit_event import AUDIT_EVENT, get_audit_events
from .bsm_h import *
from .bsm_errors import BSM_ERRORS
from .a... | |
x2_type_ids], dim=0).unsqueeze(0).expand(bsz, -1)
indices = x1_indices + [x_len]
x_forwards = []
x_backwards = []
for i in range(len(indices)):
if i == 0:
j = 0
k = indices[0]
sd = th.zeros((bsz, k), dtype=th.long, device=x.device)
td = th.ones((bsz, k), dtype=th.long, device=x.device)
else:
if i == 1:
j =... | |
null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
('verification_metadata', models.ForeignKey(blank... | |
= A()
self.assertEqual(emails, [])
self.worker.add(a)
self.assertTrue(emails[0].find("Luigi: %s failed scheduling" % (a,)) != -1)
self.worker.run()
self.assertTrue(emails[0].find("Luigi: %s failed scheduling" % (a,)) != -1)
self.assertFalse(a.has_run)
@with_config({'batch_email': {'email_interval': '0'}, 'worke... | |
anim[0] in HeadAnimDict[key]:
if (base.localAvatar.style.head == key):
base.localAvatar.unloadAnims([anim[0]], "head", None)
def compileGlobalAnimList():
"""
Munge the anim names and file paths into big dictionaries for the
leg, torso, and head parts. These are used for loading the anims.
"""
# Nowadays we want... | |
xoff = log_grid(xpsf, xmax) if xlog_spacing else lin_grid(xpsf, -xmax, xmax)
else:
xoff = xoff_vals
if yoff_vals is None:
ymax = np.abs([yoff_min,yoff_max]).max()
yoff = log_grid(ypsf, ymax) if ylog_spacing else lin_grid(ypsf, -ymax, ymax)
else:
yoff = yoff_vals
# Mask Offset grid positions in arcsec
xgrid_of... | |
If smaller than necessary, data elements will be dropped from the
output matrix.
Returns:
mat_out : BCOO array with sorted indices and no duplicate indices.
"""
data, indices = _bcoo_sum_duplicates(mat.data, mat.indices, spinfo=mat._info, nse=nse)
return BCOO((data, indices), shape=mat.shape)
def _bcoo_sum_dupl... | |
from django.contrib.auth.models import User
from django.db.models import Q
from rest_framework import serializers, ISO_8601
from rest_framework.validators import UniqueValidator, UniqueTogetherValidator
from driver.models import Driver, DriverAppUser, GPSLogNew, OTP, GPSDevice, GPSDeviceLog, TracknovateGPSDevice, \
T... | |
color=(0, 255, 0) if phase == 'final' else (0, 0, 125), thickness=2)
cv2.imwrite(join(save_dir, in_ + '_t22_4.png'), res_4)
np.save(join(line_save_dir, in_ + '_line_4.npy'), np.array( lines_1 + lines_4))
## Modify t22_3:
## for all the cuts, only take the first.
###################################### t22_4 #####... | |
#!/bin/python3
import os
import subprocess
import types
import copy
import re
import json
import datetime
import asyncio
import discord
def findmatchlist(pattern, string):
matches = []
results = re.finditer(pattern, string)
for result in results:
matches.append(result)
return matches
def deleteallmatches(patt... | |
% self.layer_number)
print("Num Trans: ", num_trans, ", Num Replay Goals: ", num_replay_goals)
# For each selected transition, update the goal dimension of the selected transition and all prior transitions by using the next state of the selected transition as the new goal. Given new goal, update the reward and fini... | |
#
# This file just serves to give a better intuition of how we conducted batch experiments
# It is not strictly a part of the DBH infrastructure, just an automation layer one level above it
#
import os
import copy
import dbh
shared = {
'csv': 'dataset.csv',
'label': 'BUG',
'clean': False,
'seed': 1337,
'output... | |
<gh_stars>1-10
from sklearn.cluster import DBSCAN
import pandas as pd
from pandas.core.indexes.base import InvalidIndexError
import numpy as np
import logging
import os
from clubcpg.ParseBam import BamFileReadParser
from clubcpg.OutputComparisonResults import OutputIndividualMatrixData
from clubcpg.Imputation import Im... | |
return {'copy_file_path': fq_path}
@patch.object(DataFileUtil, "download_staging_file",
side_effect=mock_download_staging_file)
def test_upload_fail_bad_fastq_file_staging(self, download_staging_file):
self.fail_upload_reads(
{'sequencing_tech': 'tech',
'wsname': self.ws_info[1],
'fwd_staging_file_name': 'Sampl... | |
0,
"iopsvalue": "(0/101)",
"throughputvalue": "(0/404)",
"iops": "101",
"iopscontrol": "true",
"throughput": "404",
"tpcontrol": "true",
"blocksize": "4k",
"latency": "15",
"graceallowed": true,
"type": "1",
"revisionnumber": 2,
"managedstate": "Available",
"configurationstate": "sync",
"status": "Online"... | |
not sum(1 for tid in scc if not in_flight[tid].dcommit):
errlog('\n!!! Database wedged !!!')
errlog('Transactions: %s\n!!! !!!\n', ' '.join(map(str, sorted(scc))))
raise DBWedged
tid_watched = set(tid_watch or [0])
def tx_create(pid):
if not (pid % 300):
fail_if_wedged()
if not tid_watched:
yield from sys_... | |
32.926, 15.639, 34.545,
VERTEX, 32.941, 15.667, 34.572,
VERTEX, 33.067, 15.780, 34.542,
VERTEX, 33.193, 15.892, 34.513,
VERTEX, 33.319, 16.005, 34.485,
VERTEX, 33.387, 16.055, 34.446,
VERTEX, 33.535, 16.164, 34.363,
VERTEX, 33.683, 16.273, 34.280,
VERTEX, 33.831, 16.382, 34.199,
VERTEX, 33.979, 16.492, 34.119,
VERTEX, ... | |
<reponame>dgursoy/tomopy
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# #########################################################################
# Copyright (c) 2016-17, UChicago Argonne, LLC. All rights reserved. #
# #
# Copyright 2017-17. UChicago Argonne, LLC. This software was produced #
# under U.S. Gove... | |
# -*- coding: utf-8 -*-
# @Date : 2022/4/30 15:52
# @Author : WangYihao
# @File : trainer.py
import os
import platform
import random
import time
from decimal import Decimal
import numpy as np
from loguru import logger
from prettytable import PrettyTable
from tqdm import tqdm
from fairscale.optim.oss import OSS
import ... | |
import functools
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.transforms as transforms
import matplotlib.pyplot as plt
import scipy.interpolate as interp
import scipy.optimize as opt
from .stats import poisson_interval
__all__ = [
"cms_label", "legend_data_mc", "data_mc", "data", ... | |
variance
weights = [data_parser.sample_regression_weight(xi, yi,
p=model.sample_weight_scaling_factor)
for xi, yi in zip(seqs, outputs)]
if norm_factor is not None:
weights = [w / norm_factor for w in weights]
return weights
all_true = []
all_predictions = []
for seqs, outputs in test_ds:
sample_weight = det... | |
# Copyright (C) 2019 <NAME>.L.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. R... | |
<gh_stars>100-1000
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from libtbx import easy_run
import iotbx.cif
from libtbx.test_utils import approx_equal, show_diff
from six.moves import cStringIO as StringIO
import iotbx.mtz
import os
sf_5r82 = """\
data_r5r82sf
#
_audit.rev... | |
None,
'CUNEIFORM SIGN EN OPPOSING EN': None,
'CUNEIFORM SIGN EN SQUARED': None,
'CUNEIFORM SIGN EN TIMES GAN2': None,
'CUNEIFORM SIGN EN TIMES GAN2 TENU': None,
'CUNEIFORM SIGN EN TIMES ME': None,
'CUNEIFORM SIGN EREN': None,
'CUNEIFORM SIGN ERIN2': None,
'CUNEIFORM SIGN ESH2': None,
'CUNEIFORM SIGN EZEN': None,
'CUNEI... | |
per non-poly CGNS zone/solution
2. Use the Zone Number for the blockID
Examples:
7 kLow bcwallviscous wing
4 jHigh bcsymmetryplane sym
5 khigh bcoutflowsubsonic turb_inlet BCDataSet_1 BCInFlowSubsonic Dirichlet PressureStagnation 1234.0 TemperatureStagnation 4556.0
"""
p_sub.add_argument(
"bcFile",
help="File c... | |
#!/usr/bin/env python
## EPlusInterface (EPI) - An interface for EnergyPlus
## Copyright (C) 2004 <NAME>
# =======================================================================
# Distributed under the MIT License.
# (See accompanying file LICENSE or copy at
# http://opensource.org/licenses/MIT)
# ===================... | |
be specified with four bytes:
gateway_bytes = 4
# Pattern build up holding lists:
dot_subnet = []
dot_gateway = []
# This list will be returned by the function
routes = []
# Parse the byte stream one byte at a time:
for byte in byte_stream:
# Convert the bytes to decimal
byte = int(byte, 16)
# If the sub... | |
# This is a simulator for monopoly
import logging
import csv
from enum import IntEnum
from math import ceil
from random import randrange, shuffle
from monopoly_ai_sim.board import MonopolyBoardPosition, RentIdx
from monopoly_ai_sim.cards import MonopolyDeck, MonopolyCard
from monopoly_ai_sim.auction import MonopolyAuc... | |
<gh_stars>1-10
#!/usr/bin/env python3
# Copyright (c) 2019 Bitcoin Association
# Distributed under the Open BSV software license, see the accompanying file LICENSE.
'''
Check different scenarios on how reorg affects contents of mempool and journal.
# chain reorg as a set operation on the chains of blocks containing ... | |
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
import os
import re
import shlex
import subprocess
import signal
import csv
import logging
import json
import time
from datetime import datetime as dt
from requests.exceptions import RequestException
import glob
import traceback
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.