input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020, the cclib development team
#
# This file is part of cclib (http://cclib.github.io) and is distributed under
# the terms of the BSD 3-Clause License.
"""Calculation of DDEC charges based on data parsed by cclib."""
import copy
import random
import numpy
import logging
imp... | |
York",
},
{
"city": "Arcadia",
"growth_from_2000_to_2013": "8.3%",
"latitude": 34.1397292,
"longitude": -118.0353449,
"population": "57639",
"rank": "626",
"state": "California",
},
{
"city": "Redmond",
"growth_from_2000_to_2013": "26.0%",
"latitude": 47.6739881,
"longitude": -122.121512,
"population": ... | |
void a(){
}
void foo(){
a();
}
void main(){
}
"""
expect = "Unreachable Function: foo"
self.assertTrue(TestChecker.test(input,expect,441))
def test_unreachable_func_nested_block(self):
input = """
void a(){
}
void b(){}
void foo(){
{
a();
}
}
void main(){
{
{
foo();
}
}
}
"""
... | |
outer_radius, angle_range):
"""
arguments:
angle_range (tuple): (start_angle, stop_angle) in deg from [0,360)
"""
super(Post_sector_mask, self).__init__(nn)
self.masktype = 'Sector mask'
self.centre = centre
self.r_i = inner_radius
self.r_o = outer_radius
self.tmin, self.tmax = np.deg2rad(angle_range)
self... | |
<filename>megatron/optimizers.py
import torch
from torch.optim import Optimizer
def _compute_sparse_update(beta, acc, grad_values, grad_indices):
# In the sparse case, a single accumulator is used.
update_values = torch.gather(acc, 0, grad_indices[0])
if beta > 0.:
update_values.mul_(beta)
update_values.addcmul_... | |
endpoint,
get_params,
json={'data': {}}
)
response.json.assert_called_once()
_request.reset_mock()
response.json.reset_mock()
action = utils.CREATE
kwargs = {
'data': {'serialized_id': 98},
'headers': {'Accept': 'text/plain'},
'other_param_for_requests_lib': True
}
result = utils.request(action, endpoint,... | |
"""This file contains code used in "Think Bayes",
by <NAME>, available from greenteapress.com
Copyright 2012 <NAME>
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function
import matplotlib.pyplot as pyplot
import thinkplot
import numpy
import csv
import random
import shelv... | |
#<NAME>
#<EMAIL>
#201507225
import time
import sys
import random
import copy
import statistics
import math
import interfaceUtils
import mapUtils
from worldLoader import WorldSlice
# x position, z position, x size, z size
area = (0, 0, 128, 128)
buildArea = interfaceUtils.requestBuildArea()
if buildArea != -1:
x1 = ... | |
<filename>ietf/ydk/models/ietf/ietf_yang_library.py
""" ietf_yang_library
This module contains monitoring information about the YANG
modules and submodules that are used within a YANG\-based
server.
Copyright (c) 2016 IETF Trust and the persons identified as
authors of the code. All rights reserved.
Redistribution an... | |
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth.decorators import login_required
from django_xhtml2pdf.utils import generate_pdf
from django.shortcuts import render, redirect
from django.http import HttpRespons... | |
<reponame>mihadyuk/gdal
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: gdalbuildvrt testing
# Author: <NAME> <even dot rouault @ mines-paris dot org>
#
#####################################... | |
# coding: utf-8
import numpy as np
from numpy import matrix as mat
import cv2
import os
import math
def undistort(img, # image data
fx, fy, cx, cy, # camera intrinsics
k1, k2, # radial distortion parameters
p1=None, p2=None, # tagential distortion parameters
radial_ud_only=True):
"""
undistort image using dis... | |
2*m.b42*m.b139 - 2*m.b42*m.b140 -
2*m.b42*m.b143 - 2*m.b42*m.b144 - 2*m.b42*m.b146 - 2*m.b42*m.b147 + 2*m.b42*m.b149 + 2*m.b42*
m.b150 - 2*m.b42*m.b152 + 2*m.b42*m.b153 + 2*m.b42*m.b155 + 2*m.b42*m.b156 + 2*m.b42*m.b157 +
2*m.b42*m.b158 + 2*m.b42*m.b160 + 2*m.b42*m.b161 + 2*m.b42*m.b162 + 2*m.b42*m.b163 - 2*m.b42*... | |
<gh_stars>0
import pinocchio as pin
import numpy as np
import pybullet as p
import pybullet_data
import torch
from torch import tensor
from pinocchio.robot_wrapper import RobotWrapper
import os
import matplotlib.pyplot as plt
import time
from cep.utils import numpy2torch, torch2numpy
from cep.liegroups.torch import SO3... | |
1 * u.m**2/u.s),
(1 * u.m, 0 * u.m, 1 * u.m, 1 * u.m**2/u.s))
for i in passChecks:
with self.subTest(i=i):
pc.flow_hagen(*i)
def test_flow_hagen_warning(self):
"""flow_hagen should raise warnings when passed deprecated parameters"""
error_checks = (lambda: pc.flow_hagen(1 * u.m, HeadLossMajor=1 * u.m, Length=1 ... | |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... | |
<gh_stars>0
import logging
import simplejson
import string
import time
import traceback
ID="api" #this is our command identifier, so with conventional commands, this is the command name
permission=0 #Min permission required to run the command (needs to be 0 as our lowest command is 0)
MDAPI_logger = logging.getLogger(... | |
<reponame>EricCousineau-TRI/deformable-ravens<filename>load.py
#!/usr/bin/env python
"""Strictly for loading agents to inspect. Based on `main.py`."""
import datetime
import os
import time
import argparse
import cv2
import pickle
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from os.path i... | |
<filename>src/decifer/__main__.py
"""
decifer.py
author: <NAME>
date: 2020-05-21
"""
import sys, os
import warnings
import datetime
import traceback
import multiprocessing as mp
import random as rand
from collections import defaultdict
from copy import deepcopy
from multiprocessing import Lock, Value, Pool, Manager
... | |
<reponame>jblackb1/triagelib
#!/usr/bin/env python
import json
import logging
import requests
from requests import Request, Session
global triagelog
class TriageError(Exception):
"""Base exception class for all Triage related errors
Exception is explicitly raised when an unknown Triage error"""
class TriageSta... | |
<reponame>MatthiasValvekens/certomancer<filename>certomancer/integrations/animator.py
import logging
import os
from dataclasses import dataclass
from datetime import datetime
from io import BytesIO
from typing import Optional, Dict, List, Callable
import tzlocal
from asn1crypto import ocsp, tsp, pem
from werkzeug.wrap... | |
= np.zeros(vec[0].shape) + np.nan
y = np.zeros(vec[0].shape) + np.nan
x[w] = flip * vec[1][w] / vec[0][w]
y[w] = vec[2][w] / vec[0][w]
return x, y
vec2xy.__doc__ = SphericalProj.ang2xy.__doc__ % (name, name)
def xy2vec(self, x, y=None, direct=False):
flip = self._flip
if y is None:
x, y = x
x, y = np.asarra... | |
resources.html Required
"""
class ActionTypeValueValuesEnum(_messages.Enum):
"""The type of action that Robo should perform on the specified element.
Required.
Values:
ACTION_TYPE_UNSPECIFIED: DO NOT USE. For proto versioning only.
SINGLE_CLICK: Direct Robo to click on the specified element. No-op if
specifie... | |
tmp[1][:, :, :, :]
out = self._apply_array_spin123(nh1e, nh2e, nh3e, (dveca, dvecb),
(evecaa, evecab, evecba, evecbb))
estr = 'ikmojlnp,mnopxy->ijklxy'
nevecaa = numpy.einsum(estr, h4e[:norb, :norb, :norb, :norb, \
:norb, :norb, :norb, :norb], evecaa) \
+ 2.0 * numpy.einsum(estr, h4e[:norb, :norb, :norb, norb:,... | |
# MINLP written by GAMS Convert at 04/21/18 13:52:41
#
# Equation counts
# Total E G L N X C B
# 1786 418 0 1368 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc si
# Total cont binary integer sos1 sos2 scont sint
# 1569 969 600 0 0 0 0 0
# FX 0 0 0 0 0 0 0 0
#
# Nonzero counts
# Total const NL DLL
# 8090 4298 3792 0
... | |
self.budget.costo_gasto_1 == None:
# return 0
return (self.budget.veces_gasto_1 or 0) * (self.budget.costo_gasto_1 or 0)
return 0
@property
def get_gasto_2(self):
if self.has_gasto_2:
# return self_budget
# if self.budget.veces_gasto_2 == None or self.budget.costo_gasto_2 == None:
# return 0
return (self.bu... | |
user.is_researcher and user.has_study_perms(
StudyPermission.DELETE_ALL_PREVIEW_DATA, study
)
test_func = user_can_delete_preview_data
def post(self, request, *args, **kwargs):
"""
Post method on all responses view handles the 'delete all preview data' button.
"""
study = self.get_object()
# Note: delete all... | |
= True,
name: Optional[str] = None,
dropout_in_single_layer: bool = False,
skip_conn: bool = False,
projsz: Optional[int] = None,
**kwargs,
):
"""Produce a stack of LSTMs with dropout performed on all but the last layer.
:param insz: The size of the input or `None`
:param hsz: The number of hidden units per L... | |
in the comments.
//
// other parameters:
//
// h = hedron array data according to rev flag:
// yes reversed : not reversed
// 0 1 2 3 4 5 6 7 : 0 1 2 3 4 5 6 7
// len1 len3 atom1 atom3 a1 a2 a1-a2 a2-a3 len1 len3 atom1 atom3 a1 a3 a1-a2 a2-a3
//
// split: chop half of the hedron - to selectively print parts of a rotati... | |
<filename>scripts/arcrest/ags/_networkservice.py
from __future__ import absolute_import
from __future__ import print_function
from .._abstract.abstract import BaseAGSServer
import json
########################################################################
class NetworkService(BaseAGSServer):
"""
The network servic... | |
'refresh_frequency_mins': {'key': 'refreshFrequencyMins', 'type': 'float'},
'reboot_if_needed': {'key': 'rebootIfNeeded', 'type': 'bool'},
'configuration_mode_frequency_mins': {'key': 'configurationModeFrequencyMins', 'type': 'float'},
}
def __init__(
self,
*,
configuration_mode: Optional[Union[str, "Configurat... | |
# -*- coding: utf-8 -*-
"""
The :mod:`parsimony.algorithms.proximal` module contains several algorithms
that involve proximal operators.
Algorithms may not store states. I.e., if they are classes, do not keep
references to objects with state in the algorithm objects. It should be
possible to copy and share algorithms ... | |
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
if not HAS_FILE_SEARCH:
error_msg = 'Search not supported.'
return api_error(status.HTTP_404_NOT_FOUND, error_msg)
# argume... | |
from __future__ import annotations
import asyncio
import logging
import typing as t
from datetime import datetime
from random import sample
import discord
from discord.ext import commands, tasks
from griffinbot.constants import Bot, Emoji, MOD_ROLES, StaffRoles
log = logging.getLogger(__name__)
def num_to_emoji(x... | |
descriptor as a floating point numpy array
self._mKPFlavor = "NONE" # The flavor of the keypoints as a string.
See Also:
ImageClass._getRawKeypoints(self,thresh=500.00,forceReset=False,flavor="SURF",highQuality=1)
ImageClass._getFLANNMatches(self,sd,td)
ImageClass.findKeypointMatch(self,template,quality=500.00,m... | |
<filename>iFindFriendsMini.indigoPlugin/Contents/Server Plugin/plugin.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
FindFriendsMini
Authors: See (repo)
Logons on to icloud account and access friends information for creation of indigo Devices
Enormously based on FindiStuff by Chameleon and GhostXML by DaveL17... | |
from locust import HttpLocust, TaskSet, TaskSequence, between, constant
from bs4 import BeautifulSoup, SoupStrainer
from string import ascii_lowercase
import random
import gevent
import sys
import re
# TODO:
# Modify current_hunt request to only look at unsolved puzzles
# Fix no last_pk error with chat post (user and ... | |
<gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import collections
import concurrent.futures
import contextlib
import functools
import json
import math
import os
import platform
import re
import sys
import time
import warnings
import numbers
import keyword
import numpy as np
import pyarrow a... | |
#!/usr/bin/env python
####################################################################################################
# NAME
# <NAME> - contain graphical utility functions
#
# SYNOPSIS
# <NAME>
#
# AUTHOR
# Written by <NAME> (<EMAIL>).
#
# COPYRIGHT
# Copyright © 2013-2021 <NAME> <https://barras.io>.
# The MIT Lic... | |
<gh_stars>0
# ------------------------------------------------------------------------------------------------ #
# MIT License #
# #
# Copyright (c) 2020, Microsoft Corporation #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software #
# and associated documentation files (t... | |
<gh_stars>0
from skimage import measure
from skimage.segmentation import clear_border
from scipy.stats import skew
from scipy.stats import kurtosis as kurto
from scipy.stats import mode as mod
from scipy import stats
from operator import itemgetter
from bfio.bfio import BioReader
import argparse
import logging
import o... | |
<= 0)
m.c1309 = Constraint(expr= - m.x131 + m.x132 - m.x156 <= 0)
m.c1310 = Constraint(expr= - m.x131 + m.x133 - m.x157 <= 0)
m.c1311 = Constraint(expr= - m.x131 + m.x134 - m.x158 <= 0)
m.c1312 = Constraint(expr= - m.x131 + m.x135 - m.x159 <= 0)
m.c1313 = Constraint(expr= - m.x131 + m.x136 - m.x160 <= 0)
m.c1314 ... | |
<filename>syft/tensor.py<gh_stars>0
import numpy as np
import syft.controller
class BaseTensor():
def arithmetic_operation(self, x, name, inline=False):
operation_cmd = name
if (type(x) == type(self)):
operation_cmd += "_elem"
parameter = x.id
else:
operation_cmd += "_scalar"
parameter = str(x)
if (inline... | |
import re
"""lc3-2000b.py: A definition of the LC3-2200b architecture."""
__author__ = "<NAME>"
# Define the name of the architecture
__name__ = 'LC3-2200b'
# Define overall architecture widths (in bits)
BIT_WIDTH = 32
# Define opcode widths (in bits)
OPCODE_WIDTH = 4
# Define register specifier widths (in bits)
RE... | |
this gives extra space between molecules
allow_inversion: Whether or not to allow chiral molecules to be
inverted. If True, the final crystal may contain mirror images of
the original molecule. Unless the chemical properties of the mirror
image are known, it is highly recommended to keep this value False
orientati... | |
path_in, dst, excludes = []):
if not os.path.isdir(path_in):
self._abort('Zip source directory "%s" does not exist.' % path_in)
self._verbose_info('add directory "%s" to "%s"' % (path_in, dst))
savedir = os.getcwd()
# Get nice relative paths by temporarily switching directories.
os.chdir(path_in)
try:
for based... | |
"""This file contains all the classes you must complete for this project.
You can use the test cases in agent_test.py to help during development, and
augment the test suite with your own test cases to further test your code.
You must test your agent's strength against a set of agents with known
relative strength usin... | |
35954 # GL/glext.h:3252
GL_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT = 35955 # GL/glext.h:3253
# NV_transform_feedback (GL/glext.h:3256)
GL_BACK_PRIMARY_COLOR_NV = 35959 # GL/glext.h:3257
GL_BACK_SECONDARY_COLOR_NV = 35960 # GL/glext.h:3258
GL_TEXTURE_COORD_NV = 35961 # GL/glext.h:3259
GL_CLIP_DISTANCE_NV = 3596... | |
last_node = supernodes_paths[path_from_shrink[-1]]["supernode_edges"][res[-1]]
if last_node == node_pair[1]:
res.append(node_pair[1])
else:
res += supernodes_paths[path_from_shrink[-1]]["every_pair"][(last_node, node_pair[1])]
return res
source = node_pair[0]
target = node_pair[1]
source = find(supernodes, no... | |
<reponame>grassking100/optuna<gh_stars>0
import contextlib
import copy
import time
import lightgbm as lgb
import numpy as np
import tqdm
import optuna
from optuna.integration.lightgbm_tuner.alias import _handling_alias_metrics
from optuna.integration.lightgbm_tuner.alias import _handling_alias_parameters
from optuna ... | |
<gh_stars>0
#! /usr/bin/env python2.7
#
# Migrate Picasa Web Album Archive to Smugmug
#
# Requires:
# Python 2.7
# gdata 2.0 python library
#
# <NAME> <EMAIL>
#
# based on:
# https://github.com/jackpal/picasawebuploader
# https://github.com/marekrei/smuploader
# http://nathanvangheem.com/news/moving-to-picasa-update
#... | |
import random
import os
import re
import math
import sys
#
# Convert a set to set of string
#
def set2char( F ) :
F1 = []
for fs in F :
fs1 = []
for s in fs :
fs1.append( set( [ str( x ) for x in s ] ) )
F1.append( fs1 )
return F1
#
# Add " to string
#
def primecover( s ) :
return "\"" + s + "\""... | |
"""
Controls Baxter using any game pad / joystick via the logitech and Motion modules.
Designed for Logitech controllers, may work for other controllers too.
Converted by <NAME> Oct 2015 from a script written by <NAME>,
July 2015.job
SETUP:
Before running this script, you must run the system state service and the
contr... | |
plt.bar(ind[len(ScenSel_2015)+1 + len(ScenSel_2050) +1 ::], Stock_Region_2100_use_loss_a[m,ScenSel_2100], width, hatch = '//', color=MyColorCycle_10Reg[m//2,:],
label = Def_RegionsNames_agg[m//2], bottom = Stock_Region_2100_use_loss_a[0:m,ScenSel_2100].sum(axis=0), linewidth = 0.0)
else:
p1 = plt.bar(ind[len(Sce... | |
sorted.
# Also build new list with titles ordered same as in display table.
self.src_list = set() # All srcs covering canonical
titles = {} # All titles from all srcs covering canonical
self.scatter_by_src = {} # WRW 4 Apr 2022 - collecting data for scatter plot.
for row in data: # Put is dict indexed by title.
... | |
ids = data[2:]
elif thru_flag == 1:
assert len(data) == 4, data
#ids = [data[2], 'THRU', data[3]]
ids = list(range(data[2], data[3]+1))
else:
raise NotImplementedError('thru_flag=%s data=%s' % (thru_flag, data))
return cls(components, ids, comment=comment)
def cross_reference(self, model: BDF) -> None:
"""
C... | |
import json
import re
from collections import defaultdict
import opml
import structlog
from django.contrib import messages
from django.core.exceptions import ValidationError
from django.core.paginator import EmptyPage, InvalidPage, Paginator
from django.core.urlresolvers import reverse, reverse_lazy
from django.db imp... | |
<gh_stars>0
import sys, os
import math
import collections
import re
import multiprocessing
import time
import contextlib
import json
import tqdm
def ctqdm(*args, **kwargs): return contextlib.closing(tqdm.tqdm(*args, **kwargs))
import nltk
import numpy as np
import tensorflow as tf
import pandas as pd
import sentencepi... | |
from openpyxl import load_workbook
from itertools import islice
from collections import OrderedDict
import json
import uuid
import random
import jsonpickle
import copy
import os
import sys
rules_filename = "deckfight2.xlsx"
cards_filename = "cards.json"
report_folder_path="reports"
log_reports_folder_path = "log_repo... | |
from aacharts.aatool.AAColor import AAColor
from aacharts.aatool.AAGradientColor import AAGradientColor
from aacharts.aachartcreator.AASeriesElement import AASeriesElement
from aacharts.aachartcreator.AAChartModel import AAChartModel, AAChartSymbolStyleType, AAChartSymbolType, AAChartType
from aacharts.aatool.AAGradie... | |
<reponame>nooneisperfect/ReadYourMAPFile<filename>TileHandling.py
# -*- coding: utf-8 -*-
# python imports
import glob
import os
import re
import bisect
from threading import RLock
# numpy imports
import numpy as np
import numpy
import numpy.linalg as linalg
# local imports
from smlogging import *
from mapcoord import... | |
# -*- coding: utf-8; -*-
#
# @file models.py
# @brief coll-gate application models.
# @author <NAME> (INRA UMR1095)
# @date 2016-09-01
# @copyright Copyright (c) 2016 INRA/CIRAD
# @license MIT (see LICENSE file)
# @details
import logging
import re
import uuid as uuid
from django.contrib.auth.models import User
from ... | |
<gh_stars>0
#!/usr/bin/env python
#
# Natural Language Toolkit: TGrep search
#
# Copyright (C) 2001-2021 NLTK Project
# Author: <NAME> <<EMAIL>>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""
============================================
TGrep search implementation for NLTK trees
============... | |
<reponame>tjone270/Quake-Live<gh_stars>10-100
# This file is part of the Quake Live server implementation by TomTec Solutions. Do not copy or redistribute or link to this file without the emailed consent of <NAME> (<EMAIL>).
# custom_votes.py - a minqlx plugin to enable the ability to have custom vote functionality in-... | |
# encoding: utf-8
# module System.Text calls itself Text
# from mscorlib,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089,System,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089
# by generator 1.145
# no doc
# no imports
# no functions
# classes
class Encoding(object,ICloneable... | |
None
def __init__(self, TariffCode=None, Question=None, gds_collector_=None, **kwargs_):
self.gds_collector_ = gds_collector_
self.gds_elementtree_node_ = None
self.original_tagname_ = None
self.parent_object_ = kwargs_.get('parent_object_')
self.ns_prefix_ = None
self.TariffCode = TariffCode
self.TariffCode_ns... | |
"""
Generally useful mixins for view tests (integration tests) of any project.
"""
import sys
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.contrib.messages.storage.fallback import FallbackStorage
from django.contrib.sessions.middleware import SessionMiddleware
fro... | |
Metrics hdf5 file. See deepethogram.metrics """
colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
train = f['train/' + name][:]
val = f['val/' + name][:]
if name == 'time':
train *= 1000
val *= 1000
label = 'time per image (ms)'
else:
label = name
xs = np.arange(len(train))
ax.plot(xs, train, label=... | |
#!/usr/bin/python3
# Copyright 2018 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# gen_vk_internal_shaders.py:
# Code generation for internal Vulkan shaders. Should be run when an internal
# shader program is chan... | |
x
@staticmethod
def exec_np(x):
"""
Computes the absolute value of real numbers `x`, which is the "unsigned" portion of `x` and
often denoted as `|x|`. The no-data value np.nan is passed through and therefore gets propagated.
Parameters
----------
x : np.array
Numbers.
Returns
-------
np.array :
The com... | |
<filename>ps4/src/cartpole/cartpole.py
"""
CS 229 Machine Learning
Question: Reinforcement Learning - The Inverted Pendulum
"""
from __future__ import division, print_function
from env import CartPole, Physics
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import lfilter
"""
Parts of the code (ca... | |
from MedTAG_sket_dock_App.utils import *
from psycopg2.extensions import register_adapter, AsIs
def addapt_numpy_float64(numpy_float64):
return AsIs(numpy_float64)
def addapt_numpy_int64(numpy_int64):
return AsIs(numpy_int64)
register_adapter(numpy.float64, addapt_numpy_float64)
register_adapter(numpy.int64, addapt_n... | |
<filename>models/ deeplabv3_plus_xception.py<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 21 15:16:18 2021
@author: Administrator
"""
from base import BaseModel
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
import torch.utils... | |
"parent=parent/value",) in kw["metadata"]
@pytest.mark.asyncio
async def test_batch_create_tensorboard_time_series_field_headers_async():
client = TensorboardServiceAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. ... | |
mngr.remove_directory_locks()
Including data from other runs
==============================
If a field has been observed over more than one run, the manager will
need to be made aware of the pre-existing data to make combined
datacubes. Note that this is only necessary for the final data
reduction, so observers... | |
[18, 35, 87, 10],
[20, 4, 82, 47, 65],
[19, 1, 23, 75, 3, 34],
[88, 2, 77, 73, 7, 63, 67],
[99, 65, 4, 28, 06, 16, 70, 92],
[41, 41, 26, 56, 83, 40, 80, 70, 33],
[41, 48, 72, 33, 47, 32, 37, 16, 94, 29],
[53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],
[70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],
[91, 71, 5... | |
_shtools.SHVectorToCilm(self.coeffs[:, itaper])
if normalization == 'schmidt':
for l in range(self.lwin + 1):
coeffs[:, l, :l+1] *= _np.sqrt(2.0 * l + 1.0)
elif normalization == 'ortho':
coeffs *= _np.sqrt(4.0 * _np.pi)
if csphase == -1:
for m in range(self.lwin + 1):
if m % 2 == 1:
coeffs[:, :, m] = - coeff... | |
label smoothing
"""
return losses.binary_crossentropy(y_true*0.9, y_pred)
if self.discriminator_train_model is None:
if self.gpus > 1:
self.discriminator_train_model = multi_gpu_model(self.discriminator(), gpus=self.gpus)
else:
self.discriminator_train_model = self.discriminator()
# set trainable flag and r... | |
issuing the following command::
matplotlib.pyplot.style.use('default')
Raises
------
aspecd.exceptions.MissingSaverError
Raised when no saver is provided when trying to save
"""
def __init__(self):
# Name defaults always to the full class name, don't change!
self.name = aspecd.utils.full_class_name(self)
... | |
<filename>bespin_api_v2/tests_api.py<gh_stars>0
import json
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from rest_framework import status
from data.tests_api import UserLogin
from data.models import Workflow, WorkflowVersion, WorkflowConfiguration, JobStrategy, ShareGroup, J... | |
# coding: utf-8
"""
Gitea API.
This documentation describes the Gitea API. # noqa: E501
OpenAPI spec version: 1.16.7
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
fr... | |
import psycopg2
import psycopg2.extras
import requests
from osm_handler import get_outer_way
class DBHandler():
def __init__(self, dsn):
pg_host = 'localhost'
pg_port = 5432
pg_user = 'postgres'
pg_pass = '<PASSWORD>'
pg_db = 'osm_test'
# Extent of Large Building Footprints dataset
self.bbox = '25.23561, -80.... | |
import struct
import logging
SYNC1=0xb5
SYNC2=0x62
CLASS = {
"NAV" : 0x01,
"RXM" : 0x02,
"INF" : 0x04,
"ACK" : 0x05,
"CFG" : 0x06,
"UPD" : 0x09,
"MON" : 0x0a,
"AID" : 0x0b,
"TIM" : 0x0d,
"USR" : 0x40,
"ESF" : 0x10,
"MGA" : 0x13
}
CLIDPAIR = {
"ACK-ACK" : (0x05, 0x01),
"ACK-NACK" : (0x05, 0x00),
"AID-A... | |
import os
import os.path as op
from glob import glob
import tensorflow as tf
import shutil
import json
import copy
from timeit import default_timer as timer
import utils.util_funcs as uf
import utils.util_class as uc
from tfrecords.example_maker import ExampleMaker
from tfrecords.tfr_util import Serializer, inspect_pr... | |
data = self.get_data("checked_out_acs.json")
result = json.loads(data)
fulfill_data = self.api.parse_fulfill_result(result['result'])
eq_(fulfill_data[0], """http://afs.enkilibrary.org/fulfillment/URLLink.acsm?action=enterloan&ordersource=Califa&orderid=ACS4-9243146841581187248119581&resid=urn%3Auuid%3Ad5f54da9-8177... | |
# ----------------------------------------------------------------------------
# SX Tools - Maya vertex painting toolkit
# (c) 2017-2019 <NAME> / Secret Exit Ltd.
# Released under MIT license
# ----------------------------------------------------------------------------
import maya.cmds
import maya.mel as mel
... | |
import os
import numpy as np
import math
from GPy.util import datasets as dat
class vertex:
def __init__(self, name, id, parents=[], children=[], meta = {}):
self.name = name
self.id = id
self.parents = parents
self.children = children
self.meta = meta
def __str__(self):
return self.name + '(' + str(self.id) ... | |
!= 0.0]
cx = np.linspace(zmin, zmax, options['pdf']['numpart'])
cy = np.sum(np.abs([a.pdf(cx/x)/x for x in bx]) * by, 0)
return PDF(cx, cy)
def _ndiv(self, b):
if b == 0:
raise ValueError("Cannot divide a PDF by 0.")
return PDF(self.x/b, self.y)
def __rdiv__(self, b):
if self.x[0]*self.x[-1] <= 0:
raise Va... | |
is not None:
self.WebpAdapter = WebpAdapter()
self.WebpAdapter._deserialize(params.get("WebpAdapter"))
if params.get("TpgAdapter") is not None:
self.TpgAdapter = TpgAdapter()
self.TpgAdapter._deserialize(params.get("TpgAdapter"))
if params.get("GuetzliAdapter") is not None:
self.GuetzliAdapter = GuetzliAdapter()... | |
<gh_stars>0
from __future__ import print_function, division
import torch
from tqdm.autonotebook import tqdm
import copy
import os
from torch.optim.lr_scheduler import _LRScheduler
import matplotlib.pyplot as plt
class LRFinder(object):
"""
Input:
model : DNN model
optimizer : optimizer where the define... | |
4], [5, 6]])
>>> y = np.array([1, 2, 1])
>>> labels = np.array([1, 2, 3])
>>> lpl = cross_validation.LeavePLabelOut(labels, p=2)
>>> len(lpl)
3
>>> print(lpl)
sklearn.cross_validation.LeavePLabelOut(labels=[1 2 3], p=2)
>>> for train_index, test_index in lpl:
... print("TRAIN:", train_index, "TEST:", test_inde... | |
#!/bin/bash
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) 2020 Intel Corporation
"""This script runs test cases with O-DU and O-RU"""
import logging
import sys
import argparse
import os
from itertools import dropwhile
from datetime import datetime
import json
import socket
N_LTE_NUM_RBS_PER_SYM_F1 = [
# 5MHz... | |
of the given type"""
self.add_edges([edge], edgetype)
def add_edge_table(self, etab:Mapping[ET,List[int]]) -> None:
"""Takes a dictionary mapping (source,target) --> (#edges, #h-edges) specifying that
#edges regular edges must be added between source and target and $h-edges Hadamard edges.
The method selectively ... | |
# Copyright: (c) 2018, <NAME> (@jborean93) <<EMAIL>>
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
import logging
import uuid
from pypsrp.complex_objects import Color, Coordinates, ObjectMeta, Size
log = logging.getLogger(__name__)
class PSHost(object):
def __init__(self, current_culture, cu... | |
"""Define tests for the Flux LED/Magic Home config flow."""
from __future__ import annotations
from unittest.mock import patch
import pytest
from homeassistant import config_entries
from homeassistant.components import dhcp
from homeassistant.components.flux_led.const import (
CONF_CUSTOM_EFFECT_COLORS,
CONF_CUSTO... | |
self.input_ = DocumentInfo()
self.flag_ = []
if contents is not None: self.MergeFromString(contents)
def input(self): return self.input_
def mutable_input(self): self.has_input_ = 1; return self.input_
def clear_input(self):self.has_input_ = 0; self.input_.Clear()
def has_input(self): return self.has_input_
... | |
<gh_stars>0
import os
import logging
import socket
import sys
import yaml
from urllib.request import urlopen
from urllib.request import urlretrieve
from log_config import log_setup
from helper import create_dir, check_path, get_ip, get_network_device_mac, \
set_values, validate_cidr, validate_ip, \
validate_network... | |
<gh_stars>1-10
import multiprocessing
import os
from collections import Callable
from platform import system
from time import time
from socket import gethostname
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec, rcParams
from matplotlib.ticker import MaxNLocator
from matplotlib.figure ... | |
import sys
import time
import traceback
import pygame.mixer
from pygame.locals import *
import bullet
import enemyplan
import myplan
import supply
from enemyplan import *
# 初始化
pygame.init()
pygame.mixer.init()
# 帧数对象创建
clock = pygame.time.Clock()
# 设置屏幕大小
size = width, height = 512, 900
screen = pygame.display.se... | |
XPVector(
tensor, modes[0]
) # TODO: check if we can output modes as a list in _mode_aware_matmul
elif self.isVector and other.isMatrix:
tensor, modes = other.T._mode_aware_matmul(self)
return XPVector(tensor, modes[0])
else: # self.isVector and other.isVector:
return self._mode_aware_vecvec(other) # NOTE: this ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.