input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
import os
import sys
import json
import sqlite3
import time
import shutil
import hashlib
from pathlib import Path
import dataset
import colored
import click
from flask import current_app, g
from flask.cli import with_appcontext
from . import AppDB
def check_file(f):
if isinstance(f, str):
f = Path(f)
return f.is... | |
IPv4Network or IPv4Address')
else:
force = rule.get('force')
if force:
if not validators.domain(value): raise ValueError('for domain key, value must be domain')
else: raise ValueError('to add domain acl, please set force=true & do at your own risk')
rule.pop('force', None)
return rule
class ACLModel(BaseModel)... | |
<gh_stars>1-10
import os
import sys
from datetime import datetime
import pickle
import abc
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions
from util import print_log, save_weights, load_weights
from util import ind_multivariate_normal_fn
from distribution_shift_g... | |
'Light World'),
('Dark Death Mountain Teleporter (West)', 'Death Mountain'),
('Dark Death Mountain Teleporter (East)', 'East Death Mountain (Top)'),
('Dark Death Mountain Teleporter (East Bottom)', 'East Death Mountain (Bottom)'),
('Mire Mirror Spot', 'Dark Desert'),
('Dark Desert Drop', 'Dark Desert'),
('Desert ... | |
Or, use below if you prefer not to switch to that group.
# # # mod1 + shift + letter of group = move focused window to group
# # Key([mod, mod3], i.name, lazy.window.togroup(i.name),
# # desc="move focused window to group {}".format(i.name)),
# ])
def notmuch_imp():
from notmuch import Query, Database
db = Database(... | |
Set up date bits and bobs
nyrs = TheEdYr - TheStYr + 1
npts = nyrs*73
# Set up empty arrays
PentadData = np.empty((npts,len(TheDataArr[0,:,0]),len(TheDataArr[0,0,:])))
# Loop through each gridbox
for ln in range(len(TheDataArr[0,0,:])):
for lt in range(len(TheDataArr[0,:,0])):
ptst = 0 # counter for pen... | |
False
return channel.states[ca.CLIENT] is ca.CONNECTED
async def wait_for_search(self, *, timeout=common.PV_DEFAULT_TIMEOUT):
"""
Wait for this PV to be found.
This does not wait for the PV's Channel to be created; it merely waits
for an address (and a VirtualCircuit) to be assigned.
Parameters
----------
t... | |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# cell_metadata_filter: collapsed,title
# formats: ipynb,py:percent
# rst2md: false
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.2'
# jupytext_version: 1.2.4
# kernelspec:
# display_name: Python 3
# language: python
# name: pyth... | |
#---------------------------------------------------------------------------
# Copyright 2018 The Open Source Electronic Health Record Agent
#
# 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
#
... | |
# Single line comments start with a number symbol.
""" Multiline strings can be written
using three "s, and are often used
as documentation.
"""
####################################################
# 1. Primitive Datatypes and Operators
####################################################
# You have numbers
from f... | |
<reponame>JuliusvR/L5NeuronSimulation
import glob
import json
import os
import re
from bmtk.simulator.bionet.pyfunction_cache import add_synapse_model
from neuron import h
import random
import numpy as np
scale = 10
#np.random.seed(3)
weight_means = {"exc": {}, "inh": {}}
generators = []
def lognormal(m, s):
mean ... | |
import sagemaker
import shortuuid
from yaspin import yaspin
from yaspin.spinners import Spinners
import time
import datetime
import tarfile
import re
import boto3
import glob
import os
import shutil
import pkg_resources
import subprocess
from sagemaker.multidatamodel import MultiDataModel
from sagemaker.model import Mo... | |
#=============================================================================#
# neksuite #
# #
# A python module for reading and writing nek5000 files #
# #
# Authors: <NAME>, <NAME> #
# Contacts: jcanton(at)mech.kth.se, nicolo(at)mech.kth.se #
# Last edit: 2015-10-19 #
#==============================================... | |
to the list of Affected Products.
Affects Version/s: ‘NIT Branch Build’. It can be updated later if need be.
Submitter Org: ‘Intel – FW Development’
Suspected Problem Area: Select according to the failure observed.
Issue Characteristic: According to the failure observed.
Scrum Team: PCIe Team
Description: T... | |
where_set_str = ['%r' % (where_value,) for where_value in where_set]
operation_fmt = """
SELECT {colnames}
FROM {tblname}
WHERE {where_colname} IN ( {where_set} )
"""
fmtdict = {
'tblname': tblname,
'colnames': ', '.join(colnames),
'where_colname': where_colname,
'where_set': ', '.join(where_set_str),
}
re... | |
B<mult=float>
Use this multiplier to compute the generator B<size>.
This directive is exclusive from B<size>.
=item B<nogen>
Do not generate data for this attribute, so it will get its default value.
=item B<null=float>
Probability of generating a null value for this attribute.
This applies to all generators.
=it... | |
<reponame>ouyang-w-19/decogo
# MINLP written by GAMS Convert at 04/21/18 13:52:25
#
# Equation counts
# Total E G L N X C B
# 1822 11 10 1801 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc si
# Total cont binary integer sos1 sos2 scont sint
# 3011 1511 1500 0 0 0 0 0
# FX 0 0 0 0 0 0 0 0
#
# Nonzero counts
# Total c... | |
"""Tests for transform logic.
The tests are split into three levels:
low level: functions operating on numpy(numba) level (located in transform.py)
mid level: function wrappers that operate on xarray objects (located in transform.py)
high level: API implementations in the grid object (located in grid.py)
"""
# TODO:
#... | |
<filename>tests/sample_data.py
import numpy as np
def _swiss_roll_sample_data():
matrix = np.array([[-0.4894, 1.5333, 7.9007],
[-2.9166, 10.143, 7.6818],
[8.3068, 3.5432, -8.3503],
[7.3161, 6.1689, -9.0958],
[0.06178, 5.7664, 7.8459],
[9.7424, 6.1378, -6.9183],
[4.1468, 19.766, 5.9403],
[6.3269, 8.... | |
0x215961: (0x8C79, 0), # East Asian ideograph
0x215962: (0x8C82, 0), # East Asian ideograph
0x225963: (0x743C, 0), # East Asian ideograph
0x215964: (0x8C89, 0), # East Asian ideograph
0x215965: (0x8C8D, 0), # East Asian ideograph
0x225966: (0x742E, 0), # East Asian ideograph
0x225967: (0x742F, 0), # East Asian id... | |
<gh_stars>10-100
# -*- coding:utf-8; python-indent:2; indent-tabs-mode:nil -*-
# Copyright 2013 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... | |
self._name = name
def _get_name(self):
if not hasattr(self, '_name'):
self._name = None
return self._name
name = property(_get_name, _set_name)
def _get_project(self):
for proj in ws.values():
if self in proj:
return proj
project = property(fget=_get_project)
@property
def network(self):
r"""
A short... | |
transform=ax1.transAxes)
else:
plt.text(0.03, 1.1, f"z", size=fontsize, transform=ax1.transAxes)
plt.title(f"$k={l+1}$", size=14)
ax1.set_xticks(ax1.get_xticks()) # just get and reset whatever you already have
ax1.set_xlim(left=0, right=len(data_a)) # set the new/modified labels
distance_d = utils.fractional_di... | |
make_SEP_catalog(root=direct['product'], threshold=thresh)
if radec == 'self':
okmag = ((cat['MAG_AUTO'] > align_mag_limits[0]) &
(cat['MAG_AUTO'] < align_mag_limits[1]))
cat['X_WORLD', 'Y_WORLD'][okmag].write('self',
format='ascii.commented_header',
overwrite=True)
#clip=30
logfile = '{0}_wcs.log'.forma... | |
"""This module holds classes related to graphs.
This module contains the `Vertex`, `VertexAttributeError`, `Graph`, and `GraphVertexError` classes. `Vertex` represents
a graph vertex. `VertexAttributeError` is an error raised by `Vertex`. `Graph` represents a directed graph.
`GraphVertexError` is an error raised by `G... | |
import bpy
import bgl
import blf
import bmesh
import math
import sys
from bpy_extras import view3d_utils
from bpy_extras.io_utils import ImportHelper
from bpy.props import StringProperty
from bmesh.types import BMVert, BMEdge, BMFace
from mathutils import Matrix, Vector, Quaternion
from mathutils.geometry import inter... | |
is TIMEOUT:
return TIMEOUT
n0 = self._recv_hex_nibble(timeout)
if n0 is TIMEOUT:
return TIMEOUT
return (n1 << 0x04) | n0
def _recv_hex_nibble(self, timeout):
char = self.getc(1, timeout)
if char is TIMEOUT:
return TIMEOUT
if isinstance(char, int):
char = bytes([char])
if char > b'9':
if char < b'a' or cha... | |
where no hashes will be determined and the potcar_spec dictionaries
will read {"symbol": ElSymbol, "hash": None}. By Default, looks in
the same directory as the vasprun.xml, with same extensions as
Vasprun.xml. If a string is provided, looks at that filepath.
occu_tol (float): Sets the minimum tol for the determina... | |
[adapted from IETF interfaces model (RFC 7223)]
Changed the counter type to counter64.
For packet-oriented interfaces, the number of inbound
packets that contained errors preventing them from being
deliverable to a higher-layer protocol. For character-
oriented or fixed-length interfaces, the number of
inbound ... | |
colNamesLoad)
app.logger.info('[%s] : [INFO] Load metrics merge complete',
datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
colNamesMemory = {'cached': 'cached_master', 'buffered': 'buffered_master',
'used': 'used_master', 'free': 'free_master'}
df_memory = self.chainMerge(lmemory, colNamesMemo... | |
<gh_stars>1-10
# encoding: utf-8
"""Integration tests for pairwise comparisons."""
import numpy as np
import pytest
from cr.cube.cube import Cube
from cr.cube.cubepart import _Slice
from ..fixtures import CR, OL, SM, NA
from ..util import load_python_expression
class Describe_Slice:
"""Integration-test suite for... | |
standing on grass and surrounded by darkness.",
"terrain": "NORMAL",
"coordinates": "(62,49)",
"elevation": 0,
"e": 832,
"w": 936
},
936: {
"title": "Darkness",
"description": "You are standing on grass and surrounded by darkness.",
"terrain": "NORMAL",
"coordinates": "(61,49)",
"elevation": 0,
"s": 988,
... | |
'''
Created on 28 Mar 2021
@author: thomasgumbricht
'''
import os
from sys import exit
import numpy as np
import gc
#from numpy import pi, log, tan, empty, float32, arctan, rad2deg, gradient
from scipy.ndimage import gaussian_gradient_magnitude
from math import sqrt
from geoimagine.gis import RasterOpenGetFirs... | |
<reponame>hung0913208/Base
from threading import Lock
from time import sleep
from .logger import Logger, DEBUG
from .utils import update_variable_safety
try:
from queue import Queue, Empty
except ImportError:
from Queue import Queue, Empty
import subprocess
import sys
import os
class Performer(object):
def __init... | |
<reponame>prayjourney/saleor<filename>saleor/dashboard/product/views.py
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import permission_required
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import get_object_or_404, ... | |
<filename>bestiary/parse/monsters.py
from django.db.models import Sum
from bestiary.models import Monster, AwakenCost, MonsterCraftCost, Skill, LeaderSkill, Elements, GameItem, Stats
from bestiary.models.monsters import AwakenBonusType
from bestiary.parse import game_data
from .util import update_bestiary_obj
import... | |
import os
from base64 import b64decode, b64encode
import pytest
from bitcoinx.coin import Bitcoin, BitcoinTestnet
from bitcoinx.keys import *
from bitcoinx.hashes import sha256, sha512, _sha256, hmac_digest, hash160, double_sha256
from bitcoinx.misc import int_to_be_bytes
from bitcoinx.signature import InvalidSignatu... | |
<filename>mars/session.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2020 Alibaba Group Holding Ltd.
#
# 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.... | |
in ltypes:
if not TypeObject.existSame(t, ["int", "float", "complex", "bytes", "Text", "bool"]):
rej_ltypes.append(t)
return [rej_ltypes], outs
def unop_float(self, left, right):
#NO MORE USED
ltypes = left.types
rej_ltypes = []
outs = TypeObject("float", 0)
for t in ltypes:
if not TypeObject.existSame(t, ["... | |
# Copyright 2013-2018 CERN for the benefit of the ATLAS collaboration.
#
# 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 ap... | |
import glob, re, datetime, platform
from openpyxl import Workbook, load_workbook
"""
TASK: merge info_set and entry
TASK: replace the select project with comma after thing, I keep screwing it up
TASK: make it so it can use a greater range of spreadsheet and music files
AMBITION: Create a method for creating new spread... | |
c++ code
('xdot', 'x'): 'w', # has generic implementation in c++ code
('w', 'w'): 'tcl', # dtcldw = 0
('w', 'x'): 'tcl', # dtcldx = 0
}
for cv in ['w', 'tcl']:
if var_in_function_signature(eq, cv) \
and cv not in self._lock_total_derivative \
and var is not cv \
and min(self.sym(cv).shape) \
and (
(eq, var) ... | |
import logging
import sys
import os.path
from uk_covid19 import Cov19API
import json
import sched
import time
from datetime import datetime
import typing
shed = sched.scheduler(time.time, time.sleep)
pending_updates = []
#start
def log()-> None:
'''
Initiates logging with the logging file log.log... | |
+ m.x947 == 0)
m.c966 = Constraint(expr=-m.x2047*m.x1791 + m.x948 == 0)
m.c967 = Constraint(expr=-m.x2048*m.x1791 + m.x949 == 0)
m.c968 = Constraint(expr=-m.x2046*m.x1792 + m.x950 == 0)
m.c969 = Constraint(expr=-m.x2047*m.x1792 + m.x951 == 0)
m.c970 = Constraint(expr=-m.x2048*m.x1792 + m.x952 == 0)
m.c971 = Const... | |
an unexpected keyword argument '%s'"
" to method get_report_group_list" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'fields' in params:
query_params.append(('fields', params['fields'])) # noqa: E501
if 'size' in params:
query_params.append((... | |
<gh_stars>0
# Copyright L.P.Klyne 2013
# Licenced under 3 clause BSD licence
# $Id: WbConfigEdit.py 2612 2008-08-11 20:08:49Z graham.klyne $
"""
Module to define a class for editing WebBrick configuration data.
"""
from WbConfigData import WbConfigData
import WbDefs
class WbConfigEdit(WbConfigData):
"""
This cl... | |
import torch
from torch.utils.tensorboard import SummaryWriter
from torch.nn.utils.clip_grad import clip_grad_norm_
from torch import distributions
from boltzmann import protein
from boltzmann.generative import transforms
from boltzmann import nn
from boltzmann import utils
from boltzmann import training
from sklearn.n... | |
<reponame>lboeman/solarforecastarbiter_dashboard<filename>sfa_dash/blueprints/form.py
import json
from json.decoder import JSONDecodeError
from requests.exceptions import HTTPError
from flask import (Blueprint, render_template, request,
abort, redirect, url_for, flash)
from sfa_dash.api_interface import (sites, obse... | |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 11 16:31:58 2021
@author: snoone
"""
import os
import glob
import pandas as pd
import numpy as np
pd.options.mode.chained_assignment = None # default='warn'
OUTDIR2= "D:/Python_CDM_conversion/daily/cdm_out/head"
OUTDIR = "D:/Python_CDM_conversion/daily/cdm... | |
converts `parameterized` to a
dictionary, then fills an INI file with the contents of this dictionary.
INI files are broken up into sections; all key-value pairs must belong to a section.
If `parameterized` is a :class:`param.parameterized.Parameterized` instance (rather
than a hierarchical dictionary of them), th... | |
<reponame>avetiso/conan<gh_stars>0
import platform
import textwrap
import time
import unittest
import pytest
from conans.model.ref import ConanFileReference
from conans.test.utils.tools import TestClient, GenConanfile
from conans.util.files import save
class CompatibleIDsTest(unittest.TestCase):
def test_compatib... | |
from __future__ import annotations
import asyncio
import contextvars
import functools
import os
import pathlib
import re
from typing import Any, Dict, List, Optional, Set, Tuple, Type, Union
import pydantic
import pydantic.json
import yaml
import servo.configuration
import servo.connector
import servo.pubsub
import ... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006, 2007, 2008 <NAME> <<EMAIL>>
# Copyright (C) 2008, 2009 <NAME> <<EMAIL>>
# Copyright (C) 2009 <NAME> <<EMAIL>>
#
# This software's license gives you freedom; you can copy, convey,
# propagate, redistribute and/or modify this program under the terms of... | |
<reponame>chenyb4/senlin
# 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
#... | |
0], dtype=np.float32),
high=np.array([0.6, 0.6, 0.3], dtype=np.float32),
default=np.array([0, 0, 0], dtype=np.float32),
),
"orientation": SimpleNamespace(
low=-np.ones(4, dtype=np.float32),
high=np.ones(4, dtype=np.float32),
default=np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float32),
),
"velocity": SimpleNamespa... | |
user.is_staff:
from . import tasks
celery_task = tasks.task_get_sequencing_faster.delay(None, api_o, json_data, user=user.pk if user else None, response_uuid=api_o["request"])
if celery_task:
api_o["tasks"].append(celery_task.id)
api_o["messages"].append("Call api.majora.task.get with the appropriate task ID later... | |
returns a dictionary of all of the letter frequencies of the letters present in the string!
# ## Restrictions:
# ---
#
# * E̯̟͈̔͝v͇e̫̜͈̱͆ͣr̨̡͓̔͂ͯy̵̹̟̓҉̠̙̈̚t̴̖͓ͯh̺͇̖͡i̱̪͊ͤņ̦ģ̺ ̆i̶̖̦ͫ̐͠s͏̖̍̕ ̪̱̣̌́ͪ͐͛̌͊̽̉f̟̣́̀̀͑ͭâͧí̸̭͘r̸͉̓̄̉̎ͫ͢ ̓g̸̲̝̝̫̘̅ͦa͓m͓̙̀̕ͅe̱̳͍̟ͤͬ̎̏̎͞.̩̣̅ͣ ̼̫̮̤̫̾̊ͦ̄̚҉D̹̀̾̋̊͘oņ͓̮̅͠'̥t̻ ̱̩̪̭̍ͤͩ͢͡e͎̿x͉ͣ̍̔p̙͖̽ͭ̀̔́... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Application core
================
An application core is a utility class to handle all "business logic" for application.
It handles communication between :func:`dcase_framework.datasets.Dataset`,
:func:`dcase_framework.features.FeatureExtractor`,
:func:`dcase_framework... | |
} -> bool"""
@property
def UseTiling(self) -> bool:"""UseTiling { get; set; } -> bool"""
@property
def XOffset(self) -> float:"""XOffset { get; set; } -> float"""
@property
def XScale(self) -> float:"""XScale { get; set; } -> float"""
@property
def YOffset(self) -> float:"""YOffset { get; set; } -> float"""
@p... | |
import os
import re
import itertools
import bs4
from bs4 import BeautifulSoup, NavigableString
from typing import List, Dict, Tuple, Optional
import copy
import latex2mathml.converter
from doc2json.grobid2json.grobid.grobid_client import GrobidClient
from doc2json.utils.grobid_util import parse_bib_entry, get_author_d... | |
1
#print('bsxh=', bsxh)
if nh > 0:
coords = np.concatenate((coords,coords2))
chgs = np.concatenate((chgs,[0]*nh))
zsa = np.concatenate((zs,[1]*nh))
nat = nheav + nh
#mols = []
ishown = T
for _bom in boms:
bom = np.zeros((nat,nat),dtype=int)
bom[:nheav,:nheav] = _bom
# append H's
for _bxh in bsxh:
_ia,_ja... | |
'latest_twitter_background_image_url': latest_twitter_background_image_url,
'latest_twitter_banner_image_url': latest_twitter_banner_image_url,
}
return results
def analyze_source_images(
twitter_id=0,
twitter_screen_name='',
facebook_user_id=0,
maplight_id=0,
vote_smart_id=0,
image_url_https="",
kind_of_im... | |
#!/usr/bin/env python3
# t_tensor.py
#------------------------------------------------------------------------------------------------#
# This software was written in 2016/17 #
# by <NAME> <<EMAIL>>/<<EMAIL>> #
# and <NAME> <<EMAIL>> ("the authors"), #
# to accompany the book "Computer Simulation of Liquids", second e... | |
timestep > number_of_stochastic_moves:
act = np.argmax(action_logits[0])
elif timestep <= number_of_stochastic_moves:
action_prob = [np.exp(single_log)/sum(np.exp(action_logits[0])) for single_log in action_logits[0]]
act = np.random.choice([0,1,2,3,4],1,p=action_prob)[0]
actions[player1] = act
_, rew, done, _ ... | |
<gh_stars>1000+
#!/usr/bin/env pytest
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test /vsiwebhdfs
# Author: <NAME> <even dot rouault at spatialys dot com>
#
###########################################################################... | |
a target data cube
:param self: A data cube.
:param target: A data cube that describes the temporal target resolution.
:param method: A resampling method to be applied, could be a reducer for downsampling or other methods
for upsampling. A reducer is a single process such as ``mean()`` or a set of processes, which... | |
should_check_jumpdest
)
if len(should_check_jumpdest_solutions) != 1:
raise EthereumError("Conditional not concretized at JMPDEST check")
should_check_jumpdest = should_check_jumpdest_solutions[0]
# If it can be solved only to False just set it False. If it can be solved
# only to True, process it and also se it... | |
Leakage': 0.00611897,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00348781,
'Renaming Unit/Peak Dynamic': 4.56169,
'Renaming Unit/Runtime Dynamic': 1.58562,
'Renaming Unit/Subthreshold Leakage': 0.070483,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0362779,
'Runtime D... | |
# -*- coding: utf-8 -*-
# Copyright 2014 Rackspace
# 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 ... | |
'value'),
State('bandwidth_dropdown', 'value'),
State('min_radius_dropdown', 'value'),
State('njobs_dropdown', 'value'),
State('select-sample1', 'selectedData'),
State('select-sample2', 'selectedData'),
State('select-sample3', 'selectedData'),
],
)
def run_projection(n_clicks_run_projection, dummy, dummy2, du... | |
<reponame>ronn4031/ccva
## Author: <NAME> (<EMAIL>)
## Written in Python 2.7 for use with ArcGIS
from __future__ import division
import arcpy
import math
import csv
import os
import sys
######
## Define functions necessary for the script
######
def calculate_estimate(inList):
"""
Sum values from the rows of a tab... | |
from app import app, db
from app.models import *
import datetime
import sys
sys.path.append('./sanitize')
from sanitize_utils import *
from trueskill import setup, Rating, quality_1vs1, rate_1vs1
from trueskill_functions import MU, SIGMA, CONS_MU, BETA, TAU, DRAW_PROBABILITY, populate_trueskills
from misc_utils impor... | |
w, h, ar = target_rect.width, target_rect.height, target_rect.ar
else:
w = kwargs.get("width", 100)
h = kwargs.get("height", 100)
ar = w / h
keep_aspect_ratio = kwargs.get("keep_aspect_ratio", False) is True
i_h, i_w = src_img.shape[:2]
if keep_aspect_ratio and (ar > 0):
i_ar = i_w / i_h
if ar > i_a... | |
<filename>tests/test_prior.py
import warnings
import numpy as np
from scipy.integrate import quad, dblquad, tplquad
import dpmm
from test_utils import timer
@timer
def test_GaussianMeanKnownVariance():
mu_0 = 0.15
sigsqr_0 = 1.2
sigsqr = 0.15
model = dpmm.GaussianMeanKnownVariance(mu_0, sigsqr_0, sigsqr)
D = n... | |
<gh_stars>0
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2013 UnitedStack 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/l... | |
<reponame>neoshanarayanan/lammps_simulations
#!/usr/bin/env python
"""
/* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
<NAME>, <EMAIL>
Copyright (2003) Sandia Corporat... | |
import random
from .grid import Grid
from .snakestuff import *
# Values to put in grid, priorities TBD
OPEN_SPACE = '.'
FOOD = 'F'
ME_HEAD = 'H'
ME_BODY = 'B'
ME_TAIL = 'T'
EATABLE_HEAD_ZONE = 'e'
VERY_EATABLE_HEAD = 'E'
OTHER_HEAD = 'h'
OTHER_BODY = 'b'
OTHER_TAIL = 't'
MAYBE_GO = '+'
#EAT_THIS_HEAD =... | |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""Ciscoのshow ip routeをパースします
2016/04/20 初版
2021/06/28 textfsmを使ってパースするクラスを追加
"""
__author__ = '<NAME>'
__version__ = '0.2'
__date__ = '2021/06/28'
#
# 標準ライブラリのインポート
#
import re
import os
import sys
from typing import Text
import typing
#
# 外部ライブラリのインポート
#
HAS_TEXTFSM = T... | |
'almaty',
1: 'bangkok',
2: 'bombay',
3: 'brasilia',
4: 'cairo',
5: 'cape_verde_is',
6: 'darwin',
7: 'eniwetok',
8: 'fiji',
9: 'hong_kong',
10: 'islamabad',
11: 'kabul',
12: 'magadan',
13: 'mid_atlantic',
14: 'moscow',
15: 'muscat',
16: 'newfoundland',
17: 'samoa',
18: 'sydney',
19: 'tehran',
20: 'to... | |
and H first, to make a correct hill formula (remember dicts in python 3.6+ are ordered)
if 6 in at_num_to_counts:
symbol_to_counts["C"] = at_num_to_counts[6]
del at_num_to_counts[6]
if 1 in at_num_to_counts:
symbol_to_counts["H"] = at_num_to_counts[1]
del at_num_to_counts[1]
# Now count instances of all elemen... | |
aerodynamic thrust at rated')
self.add_output('rated_Q', val=0.0, units='N*m', desc='rotor aerodynamic torque at rated')
self.add_discrete_output('fst_vt_out', val={})
def compute(self, inputs, outputs, discrete_inputs, discrete_outputs):
#print(impl.world_comm().rank, 'Rotor_fast','start')
fst_vt, R_out = self... | |
<filename>toyplot/data.py
# Copyright 2014, Sandia Corporation. Under the terms of Contract
# DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain
# rights in this software.
"""Classes and functions for working with raw data."""
import collections
import itertools
import numbers
import os
i... | |
<reponame>tank-overlord/diep-X
# -*- coding: utf-8 -*-
# Author: <NAME> <<EMAIL>>
#
# License: BSD 3-Clause
import pygame
from pygame import draw, Color, math, freetype
import time
import random
import math
import pathlib
import os
streamliner = False
def sin_deg(deg):
return math.sin(deg/180*math.pi)
def co... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This API client for Amazon's MWS is based on the python-amazon-mws package
# available here: https://github.com/czpython/python-amazon-mws
import hmac
import urllib
import base64
import hashlib
import logging
import xmltodict
from time import strftime, gmtime
from coll... | |
import random
import unittest
from SDWLE.agents.basic_agents import DoNothingAgent, PredictableAgent
from SDWLE.constants import MINION_TYPE
from testsSDW.agents.testing_agents import CardTestingAgent, OneCardPlayingAgent, WeaponTestingAgent, \
PlayAndAttackAgent, SelfSpellTestingAgent
from testsSDW.testing_utils imp... | |
import logging
import sys
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from itertools import repeat
from tempfile import NamedTemporaryFile
from typing import Optional, List, Type, Tuple
from typing import TypeVar, Any, Set
from urllib.parse import parse_qs, urlparse
from django import db
fro... | |
#!/usr/bin/python -u
# -*- coding: latin-1 -*-
#
# Set covering in Z3
#
# Some set covering problems. See below for descriptions.
# - Placing of firestations, from Winston 'Operations Research'
# - Minimize the number of security telephones in street corners on a campus. (Taha)
# - Senators making a committee (<NAME>)... | |
<reponame>snakeclub/labelImg
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# Copyright 2019 黎慧剑
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
扩展功能库
@module ext... | |
<reponame>fkusche/asyncdbus<gh_stars>1-10
from .validators import assert_object_path_valid, assert_bus_name_valid
from . import message_bus
from .message import Message
from .constants import MessageType, ErrorType, MessageFlag
from . import introspection as intr
from .errors import DBusError, InterfaceNotFoundError
fr... | |
"metadataonly",
("prop", "1948:180"): "metadataonly",
("prop", "1948:181"): "metadataonly",
("prop", "1948:182"): "metadataonly",
("prop", "1948:183"): "metadataonly",
("prop", "1948:185"): "metadataonly",
("prop", "1948:186"): "metadataonly",
("prop", "1948:188"): "metadataonly",
("prop", "1948:19"): "metadata... | |
import binascii
import struct
import os
import gevent
import ipaddress
import time
from gevent.lock import RLock
from gevent.event import AsyncResult
from gevent import socket
import collections
import traceback
try:
import color_logging
import logging
logger = logging
except:
import logging
logger = logging
log... | |
"18": {
"level": 18,
"exp": 220,
"member_max": 44,
"admin_max": 6,
"sign_gold": 1800
},
"19": {
"level": 19,
"exp": 230,
"member_max": 46,
"admin_max": 6,
"sign_gold": 1900
},
"20": {
"level": 20,
"exp": 240,
"member_max": 48,
"admin_max": 6,
"sign_gold": 2000
},
"21": {
"level": 21,
"exp": 250,
... | |
<gh_stars>10-100
import asyncio
from FIREX.utils import admin_cmd, edit_or_reply, sudo_cmd
from userbot import *
from userbot.cmdhelp import CmdHelp
DEFAULTUSER = str(ALIVE_NAME) if ALIVE_NAME else "ν2.ο"
@bot.on(admin_cmd(pattern="think$"))
@bot.on(sudo_cmd(pattern="think$", allow_sudo=True))
async def _(event):
... | |
Inputs:
keyword A regular expression to match the VICAR keyword(s).
Case is ignored.
value The replacement value of the keyword.
occurrence An index defining which occurrence of the keyword to
set; provided because the same keyword can occur
multiple times. Use 0 for the first occurrence; this
is the default.
... | |
<gh_stars>1-10
import requests,json,sys,re,os,time
import threading
from datetime import datetime
from VideoIDHelper import *
from collections import deque
from bs4 import BeautifulSoup
def reportPlaylistProgress():
global t
print("{} videos have been read from the playlist...".format(len(p)))
t=threading.Timer(... | |
volgeom.VolGeom(vg.shape, vg.affine, mask)
data = vg.get_masked_nifti_image(nt=1)
msk = vg.get_masked_nifti_image()
dset = fmri_dataset(data, mask=msk)
vg_dset = volgeom.from_any(dset)
# ensure that the mask is set properly and
assert_equal(vg.nvoxels, vg.nvoxels_mask * maskstep ** 3)
assert_equal(vg_dset, vg)... | |
<reponame>LukasLuehrs/scikit-activeml
"""
The :mod:`skactiveml.base` package implements the base classes for
:mod:`skactiveml`.
"""
import warnings
from abc import ABC, abstractmethod
from copy import deepcopy
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin
from sklearn.metr... | |
#! /usr/bin/env python3
import sys
import pickle
import argparse
import numpy as np
import pandas as pd
import scipy.stats as stats
def like_calc(X, y_test, unc):
"""
Given a simulated entry with uncertainty and a test entry, calculates the
likelihood that they are the same.
Parameters
----------
X : numpy a... | |
import os
import sys
import unittest
from typing import Dict
from nptyping import NDArray
import numpy as np
# TODO: Handle module imports in another way if it is possible
sys.path.append(os.path.join(os.path.dirname(__file__), '../../'))
from dea.utils.symbols import *
from dea.technical.dea_radial import DEARadia... | |
def get_relationships(self, subject_term=None, object_term=None):
"""Returns all the relationships that were added to the two
given terms.
:Parameters:
- `subject_term`: the subject term; an instance of `GOTerm`.
``None`` means all terms.
- `object_term`: the object term; an instance of `GOTerm`.
``None`` means... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.