input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
psf_temp_over.shape
ysh = int(yind - ypix/2)
xsh = int(xind - xpix/2)
fov_pix_over = trim_psf * osamp
coeff = []
for im in psf_coeff:
im = fshift(im, -xsh, -ysh, interp='cubic')
im = pad_or_cut_to_size(im, (fov_pix_over,fov_pix_over))
coeff.append(im)
psf_coeff = np.array(coeff)
psf_coeff_hdr['FOVPIX'] = tri... | |
<gh_stars>1-10
#!/usr/bin/python
# -*- coding: utf-8 -*-
import wx.lib.layoutf as layoutf
import traceback, wx, os
#TODO Check to see if this is still needed. Don't think that it is now that eash func also calls
app = wx.App()
def set_icon(dlg, icon):
if not icon:
return
if type(icon) is str:
ico = ... | |
import synapse.lib.module as s_module
contracttypes = (
'nda',
'other',
'grant',
'treaty',
'purchase',
'indemnity',
'partnership',
)
class OuModule(s_module.CoreModule):
def getModelDefs(self):
modl = {
'types': (
('ou:sic', ('str', {'regex': r'^[0-9]{4}$'}), {
'doc': 'The four digit Standard Industrial C... | |
self.x
if self.X.shape[1] <= self.rc:
# we have to expand X with zero columns
#Y = np.zeros((self.X.shape[0], self.rc - self.X.shape[1] + 1))
#self.X = np.c_[self.X, Y]
dx = self.rc - self.X.shape[1] + 1
self.X = np.pad(self.X, ((0, 0), (0, dx)), "constant")
self.X[:, self.rc] = self.x
self.na = self.X.shape[1]... | |
<gh_stars>0
import unittest
from math import pi
import numpy as np
from wisdem.ccblade.Polar import Polar, blend
class TestBlend(unittest.TestCase):
def setUp(self):
alpha = [
-3.04,
-2.03,
-1.01,
0.01,
1.03,
2.05,
3.07,
4.09,
5.11,
6.13,
7.14,
8.16,
9.17,
10.18,
11.18,
12.... | |
import networkx as nx
import matplotlib.pyplot as plt
class Population:
def __init__(self, name, n, e, w):
"""
:param name:
:param n: # of neurons (estimated from density and cortical area from Markov)
:param e: # of extrinsic inputs per neuron (typical values by cortical layer)
:param w: receptive field width ... | |
each_df_dtm1, trained_svd = select_top_features_from_SVD(each_df_dtm, '', True)
ls = ['svd_dim_'+str(x) for x in range(each_df_dtm1.shape[1])]
each_df_dtm1 = pd.DataFrame(each_df_dtm1,columns=ls, index=orig_each_df_index)
else:
each_df_dtm1, _ = select_top_features_from_SVD(each_df_dtm, trained_svd, False)
ls... | |
input_size: int,
output_size: int,
hidden_size: int,
n_hidden_layers: int,
target_sizes: Union[int, List[int]] = [],
**kwargs,
):
# saves arguments in signature to `.hparams` attribute, mandatory call - do not skip this
self.save_hyperparameters()
# pass additional arguments to BaseModel.__init__, mandatory ca... | |
context['jumlah'] = jml
elif rating == '2':
c.execute("SELECT distinct on (nama) nama, link, alamat_lengkap, rating, harga_termurah, tp.id_penginapan FROM tempat_penginapan tp, foto f WHERE tp.Id_penginapan = f.Id_penginapan AND tp.rating=2 AND tp.id_penginapan LIKE 'K%'")
res = dictfetchall(c)
context['res'] = re... | |
#
# Copyright (c) 2020 <NAME> <<EMAIL>>
#
# This source code is licensed under an MIT license found in the LICENSE file in the root directory of this project.
#
import os.path as osp
from itertools import product
import matplotlib
import matplotlib.colors as colors
import matplotlib.pyplot as plt
import scipy
from sci... | |
import matplotlib
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
from deep_rl import *
FOLDER = '/home/hod/Desktop/DeepRL-Bi-Res-DDPG/img'
def plot(**kwargs):
kwargs.setdefault('average', False)
# kwargs.setdefault('color', 0)
kwargs.setdefault('top_k', 0)
# kwargs.setdefault('top_k_perf', lambda x: np.... | |
<reponame>Takishima/mindquantum
# -*- coding: utf-8 -*-
# Copyright 2021 Huawei Technologies Co., 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.org/licenses/LICENS... | |
Free)",
callback_data=callbackdata)]
)
txtKeyboard = "Please select download location:"
reply_markup = InlineKeyboardMarkup(keyboard)
self.replytext(
query,
txtKeyboard,
reply_markup,
False
)
else:
self.sendmessage(
update.effective_chat.id,
context,
update.effective_user.first_name,
f"No paths were... | |
"""
super(PerspectiveManager, self).__init__()
self.toolbarItems = {}
self.createAuiManager()
pub.subscribe(self.__onObjectAdded, 'perspectiveClicked')
pub.subscribe(self.__onUpdatePageText, 'onUpdatePageText')
self.accel_tbl = wx.AcceleratorTable([
(wx.ACCEL_CTRL, ord('N'), ID_NEW),
(wx.ACCEL_CTRL, ord... | |
import struct
import curses
from time import sleep
from threading import Timer
import pickle
from .exceptions import *
import fingerpi as fp
class RepeatingTimer(object):
def __init__(self, interval, f, *args, **kwargs):
self.interval = interval
self._f = f
self.args = args
self.kwargs = kwargs
self.timer ... | |
key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in set_... | |
ndim(x) == 5:
if data_format == 'channels_first':
if ndim(bias) == 1:
x += reshape(bias, (1, bias_shape[0], 1, 1, 1))
else:
x += reshape(bias, (1, bias_shape[3]) + bias_shape[:3])
elif data_format == 'channels_last':
if ndim(bias) == 1:
x += reshape(bias, (1, 1, 1, 1, bias_shape[0]))
else:
x += reshape(bias, ... | |
<filename>probables/blooms/bloom.py
""" BloomFilter and BloomFiter on Disk, python implementation
License: MIT
Author: <NAME> (<EMAIL>)
URL: https://github.com/barrust/bloom
"""
import math
import os
from array import array
from binascii import hexlify, unhexlify
from io import BytesIO, IOBase
from mmap import mmap
... | |
from __future__ import print_function, absolute_import, division
import KratosMultiphysics
import KratosMultiphysics.StructuralMechanicsApplication as StructuralMechanicsApplication
import KratosMultiphysics.KratosUnittest as KratosUnittest
from math import sqrt, sin, cos, pi, exp, atan
class BasePatchTestCrBeam3D2... | |
# Copyright 2021 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | |
<gh_stars>0
import sys
import os
import pyperclip
from PyQt5.QtWidgets import QAction, QLabel, QMainWindow, QMessageBox, QWidget, QLineEdit, QPushButton, QLineEdit, QApplication, QScrollArea, QVBoxLayout, QCheckBox, QMenuBar
from PyQt5.QtGui import QIcon, QPixmap, QFont, QDesktopServices
from PyQt5.QtCore import QUrl, ... | |
<gh_stars>0
import eventlet
import json
import struct
import cPickle as pickle
from eventlet import wsgi,GreenPool
from eventlet.green import socket
from bricks.flow_des import FlowDesGlobal,FlowDes
from bricks.message import InfoMessage,UpdateMessageByFlow
from scheduler.scheduler import Scheduler,PolicyUtil
from mul... | |
options={
'verbose_name': '01 SKPD Asal ATL Setwan',
'proxy': True,
'verbose_name_plural': '01 SKPD Asal ATL Setwan',
},
bases=('atl.skpdasalatl',),
),
migrations.CreateModel(
name='SKPDAsalATLSosial',
fields=[
],
options={
'verbose_name': '09 SKPD Asal ATL Sosial',
'proxy': True,
'verbose_name_plural': '... | |
+ m.b263 - m.b298 <= 0)
m.c4515 = Constraint(expr= - m.b262 + m.b264 - m.b299 <= 0)
m.c4516 = Constraint(expr= - m.b263 + m.b264 - m.b300 <= 0)
m.c4517 = Constraint(expr= - m.b265 + m.b266 - m.b273 <= 0)
m.c4518 = Constraint(expr= - m.b265 + m.b267 - m.b274 <= 0)
m.c4519 = Constraint(expr= - m.b265 + m.b268 - m.b2... | |
params["R26"]
R27 = params["R27"]
R28 = params["R28"]
R29 = params["R29"]
R30 = params["R30"]
R31 = params["R31"]
R32 = params["R32"]
R33 = params["R33"]
R34 = params["R34"]
R35 = params["R35"]
R36 = params["R36"]
R37 = params["R37"]
R38 = params["R38"]
R39 = params["R39"]
R40 = params["R40"]
R41 = param... | |
"",
"reddit": "",
"slack": "",
"telegram": "",
"twitter": "",
"youtube": ""
}
},
"eGAS": {
"symbol": "eGAS",
"address": "0xb53A96bcBdD9CF78dfF20BAB6C2be7bAec8f00f8",
"decimals": 8,
"name": "<NAME>",
"ens_address": "",
"website": "http://www.ethgas.stream",
"logo": {
"src": "",
"width": "",
"height": "... | |
<filename>DelibeRating/DelibeRating/app/views.py
"""
Definition of views.
"""
import operator
import random
from random import shuffle
import datetime
from django.shortcuts import render, redirect
from django.http import HttpRequest, Http404, HttpResponse
from django.template import RequestContext
from datetime import... | |
#! /usr/bin/env python3
# Copyright(c) 2017-2018 Intel Corporation.
# License: MIT See LICENSE file in root directory.
GREEN = '\033[1;32m'
RED = '\033[1;31m'
NOCOLOR = '\033[0m'
YELLOW = '\033[1;33m'
try:
from openvino.inference_engine import IENetwork, ExecutableNetwork, IECore
import openvino.inference_engine.i... | |
<reponame>Kolkir/superpoint<filename>python/src/homographies.py
# The code is based on https://github.com/rpautrat/SuperPoint/ that is licensed as:
# MIT License
#
# Copyright (c) 2018 <NAME> & <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated docu... | |
<gh_stars>0
from numpy import array, ceil
from models import LoadSampler
def case75(flex_level = 'MEDIUM'):
case = {"version": "ANM"}
## system MVA base
case["baseMVA"] = 1.0
## Bus data
case["bus"] = array([
[1000, 3, 0.0, 0.0, 0, 0, 1, 1, 0, 33, 1, 1.1, 0.9],
[1100, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05,... | |
'{}' detected".format(
self.argname
)
else:
msg = "fixture '{}' not found".format(self.argname)
msg += "\n available fixtures: {}".format(", ".join(sorted(available)))
msg += "\n use 'pytest --fixtures [testpath]' for help on them."
return FixtureLookupErrorRepr(fspath, lineno, tblines, msg, self.argname)
cla... | |
)
os.unlink( dir_w+"/foo5" )
if os.path.exists( myldir ):
shutil.rmtree( myldir )
if os.path.exists( mysdir ):
shutil.rmtree( mysdir )
def test_mcoll_from_devtest(self):
# build expected variables with similar devtest names
progname = __file__
myssize = str(os.stat(progname).st_size)
... | |
#remove outliers
col_rm_outlier=remove_outlier(col)
#adjust max_bin for improving performance
if pd.unique(col_rm_outlier).size<max_bin:
max_bin_adj=pd.unique(col_rm_outlier).size
else:
max_bin_adj=max_bin
#R pretty bins:cut points looks better but will lose iv or ks gain
cuts_remain=R_pretty(np.nanmin... | |
# coding: utf-8
# # Execute this notebook first, after execute the notebook track_improved
# In[1]:
from utils.definitions import ROOT_DIR
filepath = ROOT_DIR+'/data/original/'
# file path
artist_csv = "artists.csv"
track_csv = "tracks.csv"
artist_improved_intermediate= "tracks_improved_intermediate.csv" # generated... | |
# BSD 3-Clause License
#
# Copyright (c) 2020, IPASC
# All rights reserved.
#
# 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 co... | |
<reponame>ansao-aci/group-based-policy
# 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 writi... | |
<filename>TooManyStalkers/bot.py
import sys
import sc2
from sc2.ids.ability_id import AbilityId
from sc2.ids.unit_typeid import UnitTypeId
from sc2.ids.upgrade_id import UpgradeId
from sc2.ids.buff_id import BuffId
from sc2.unit import Unit
from sc2.units import Units
from sc2.position import Point2, Point3
from log... | |
# -*- coding: utf8 -*-
# Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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/LI... | |
import abc
import os
import yaml
import json
import pprint
import shutil
import tarfile
import tempfile
import requests
from pathlib import Path
from typing import Dict, Sequence, Union, TYPE_CHECKING
from dotenv import load_dotenv
from agentos.identifiers import (
ComponentIdentifier,
RunIdentifier,
RepoIdentifier,... | |
in the template).
"""
return pulumi.get(self, "parameters")
@parameters.setter
def parameters(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "parameters", value)
@property
@pulumi.getter
def project(self) -> Optional[pulumi.Input[str]]:
"""
The project in which the resource belong... | |
<reponame>rubik/pyg
import re
import os
import sys
import copy
import glob
import shutil
import atexit
import tarfile
import zipfile
import urllib2
import urlparse
import functools
import ConfigParser
import pkg_resources
import multiprocessing
from pkgtools.pypi import PyPIJson
from pkgtools.pkg import SDist, Develop... | |
<filename>code/main.py
# import basic libs
import os,sys
import six
import math
import time
import shutil
import random
import datetime
import warnings
import argparse
import numpy as np
import matplotlib.pyplot as plt
import hiddenlayer as hl
from collections import OrderedDict
# import pytorch libs
import torch
i... | |
stop:0.567164 rgba(78, 59, 58, 30));\n"
"")
self.CryptoDragDrop.setObjectName("CryptoDragDrop")
self.verticalLayout_16 = QtWidgets.QVBoxLayout(self.CryptoDragDrop)
self.verticalLayout_16.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_16.setSpacing(0)
self.verticalLayout_16.setObjectName("verticalLayout_16")
s... | |
<reponame>Murabei-OpenSource-Codes/pumpwood-djangoviews
"""Create views using Pumpwood pattern."""
import os
import pandas as pd
import simplejson as json
from io import BytesIO
from django.conf import settings
from django.http import HttpResponse
from rest_framework.parsers import JSONParser
from rest_framework import... | |
init_inputs(self):
for name in self._inputs:
if name not in self._consts:
self.add_placeholder_op(name)
def inference_shapes(self):
_LOG.info("Inference shapes")
self.init_input_shape()
for node in self._nodes:
node.inference_shape(self._batch,
self._shapes,
self._nodes_by_name)
def fuse_dynamic_lstm(self,... | |
= bi_connector
__props__.__dict__["bi_connector_config"] = bi_connector_config
__props__.__dict__["cloud_backup"] = cloud_backup
__props__.__dict__["cluster_type"] = cluster_type
__props__.__dict__["disk_size_gb"] = disk_size_gb
__props__.__dict__["encryption_at_rest_provider"] = encryption_at_rest_provider
__pro... | |
<reponame>mwawrzos/logging<filename>log_parsers/parse_mlperf.py
# Copyright 2018 The MLPerf Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache... | |
become 0-dim arrays
>>> price = close = np.random.uniform(1, 10, size=target_shape)
>>> size_type = np.asarray(SizeType.TargetPercent)
>>> direction = np.asarray(Direction.LongOnly)
>>> fees = np.asarray(0.001)
>>> fixed_fees = np.asarray(1.)
>>> slippage = np.asarray(0.001)
>>> order_records, log_records = fle... | |
<filename>swarmops/MetaOptimize.py
########################################################################
# SwarmOps - Heuristic optimization for Python.
# Copyright (C) 2003-2016 <NAME>.
# See the file README.md for instructions.
# See the file LICENSE.txt for license details.
# SwarmOps on the internet: http://www.... | |
total, totalsum):
b += 1
best = min(best, getsum(a, b, total, totalsum))
best = total - best
return b
def func_47d3b72343c94709985a4ec5a9754219(p, N, q, s, r):
A = [((i * p + q) % r + s) for i in xrange(N)]
total = sum(A)
totalsum = [a for a in A]
for i in xrange(1, N):
totalsum[i] += totalsum[i - 1]
best =... | |
-offSize
file.write(binOffset)
for item in self.items:
if hasattr(item, "toFile"):
item.toFile(file)
else:
data = tobytes(item, encoding="latin1")
file.write(data)
class IndexedStringsCompiler(IndexCompiler):
def getItems(self, items, strings):
return items.strings
class TopDictInd... | |
"""This module provides ``docutils.nodes.GenericNodeVisitor`` subclasses,
which generates JSONable, 'database friendly', information about the document.
This can be used for fast-lookup of the position of elements in the document,
and to reference/target mappings.
The visitor should be run via the ``LSPTransform`` cla... | |
16)
CalculatedFrameList = int('00081162', 16)
TimeRange = int('00081163', 16)
FrameExtractionSequence = int('00081164', 16)
MultiframeSourceSOPInstanceUID = int('00081167', 16)
RetrieveURL = int('00081190', 16)
TransactionUID = int('00081195', 16)
WarningReason = int('00081196', 16)
FailureReason = int('0008119... | |
<gh_stars>1-10
# -*- coding: utf-8 -*-
from escher.quick_server import serve_and_open
from escher import urls
import os
from os.path import dirname, abspath, join, isfile, isdir
from warnings import warn
from urllib2 import urlopen, HTTPError, URLError
import json
import shutil
import appdirs
import re
from jinja2 im... | |
# encoding: utf-8
"""
.. codeauthor:: <NAME> <<EMAIL>>
"""
from __future__ import unicode_literals
from copy import deepcopy
from datetime import date, datetime, timedelta
import pytest
import pytz
from datetimerange import DateTimeRange
from dateutil.parser import parse
from dateutil.relativedelta import relatived... | |
in X.residues[res2]:
if X.dist(atom,atom2)<6.0:
if not res2 in excludes[tg]:
excludes[tg].append(res2)
break
for tg in sorted(excludes.keys()):
print tg
print excludes[tg]
print '-------'
return excludes
#
# --------
#
def calculate_average(self,data):
"""Calculate the average ghost observed and the s... | |
the barge in a way that is consistent with the
# DOE database by allocating the barge as a non-oil cargo barge
# that will pose a fuel-oil spill risk only.
if not oil_type:
fuel_spill = True
oil_type = None
# *** END ERROR CATCH ***
elif (
destination in US_origin_destination
and destination not in WA_in_noin... | |
<reponame>TranslatorIIPrototypes/robo-commons
import collections
import json
import logging
import requests
import traceback
import re
import os
import sys
import yaml
import unittest
from jinja2 import Template
from collections import defaultdict
from collections import namedtuple
from greent.concept import Concept
fr... | |
= Match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
if (matched and
not Match(r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//',
matched.group(1))):
delimiter = ')' + matched.group(2) + '"'
end = matched.group(3).find(delimiter)
if end >= 0:
# Raw string ended on same line
line = (matched.group(1) + ... | |
,
u'皔' : [u'h'] ,
u'辚' : [u'l'] ,
u'缥' : [u'p'] ,
u'庤' : [u'z'] ,
u'蠫' : [u'l'] ,
u'鞪' : [u'm'] ,
u'涮' : [u's'] ,
u'䜵' : [u'c', u's'] ,
u'逻' : [u'l'] ,
u'疾' : [u'j'] ,
u'軄' : [u'z'] ,
u'繏' : [u'x'] ,
u'巎' : [u'n'] ,
u'雔' : [u'c'] ,
u'泘' : [u'h'] ,
u'䙟' : [u'd', u'w'] ,
u'㯢' : [u'z'] ,
u'齥' : [u'x'] ,
u'瓨' : [u'h', u'j'... | |
it is already initialised, this does nothing.
if not self._lookup_dict:
self._lookup_dict = {
"is_descendant_of": {},
"mutually_exclusive_of": {}
}
def _store_calculation(self, name, key, value):
# Put a calculation into a named lookup dictionary.
# This method will always store calculation data in the root ex... | |
<gh_stars>0
from contextlib import contextmanager
import sys
from tempfile import NamedTemporaryFile
try:
from unittest import mock
except ImportError:
import mock
import pytest
import pipdeptree as p
# Tests for DAG classes
def mock_pkgs(simple_graph):
for node, children in simple_graph.items():
nk, nv = node... | |
"""
Script to create word2vec models, given a set of mapped POIs.
"""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
import argparse
import os
import math
import errno
import pandas as pd
import geopandas as gpd
from geopandas import GeoDataFrame
from shapely.geometry import Point
import sys
sys.path.append("../GeoL"... | |
<reponame>richardingham/octopus-editor-server<gh_stars>1-10
# Twisted Imports
from twisted.internet import reactor, defer, task
from twisted.python import log
# Octopus Imports
from octopus.runtime.sequence.util import Runnable, Pausable, Cancellable, BaseStep
from octopus.runtime.sequence.error import NotRunning, Alr... | |
= pyvips.Image.new_from_file(TIF_FILE)
x = x.copy()
x.set("orientation", 2)
x.write_to_file(filename)
x = pyvips.Image.new_from_file(filename)
y = x.get("orientation")
assert y == 2
x = x.copy()
x.remove("orientation")
filename = temp_filename(self.tempdir, '.tif')
x.write_to_file(filename)
x = pyvips.Image... | |
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import re
from PyAstronomy.pyaC import pyaErrors as PE
import pickle
import os
import uuid
import six
import six.moves as smo
def equal(dependsOn):
return dependsOn
class Params:
"""
Manage a set of parameters.
This class provides a framew... | |
'Wound drainage'),
('WNDE', 'Wound exudate'),
('XXX', 'To be specified in another part of the message'))),
'HL70074': ('Diagnostic service section ID',
(('AU', 'Audiology'),
('BG', 'Blood Gases'),
('BLB', 'Blood Bank'),
('CH', 'Chemistry'),
('CP', 'Cytopathology'),
('CT', 'CAT Scan'),
('CTH', 'Cardiac Cathete... | |
= '\n'
else:
eol_ = ''
if self.Malware_Subject_Node_A is not None:
self.Malware_Subject_Node_A.export(write, level, 'maecPackage:', name_='Malware_Subject_Node_A', pretty_print=pretty_print)
if self.Malware_Subject_Node_B is not None:
self.Malware_Subject_Node_B.export(write, level, 'maecPackage:', name_='Malware... | |
Select appropriate response code
grpc.StatusCode.INVALID_ARGUMENT
)
# 2. Prepare response
response = trolley_pb2.TrolleyContent(
total_count=3,
total_price=57.5,
content=[
# List of gRPC messages
trolley_pb2.Item(name="Blue car",
unit_price=3.50,
count=6),
trolley_pb2.Item(name="Red car",
unit... | |
<filename>image/controllers.py
# image/controllers.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
import requests
import wevote_functions.admin
from .functions import analyze_remote_url, analyze_image_file, analyze_image_in_memory
from .models import WeVoteImageManager, WeVoteImage, \
CHOSEN_FAVICON... | |
word[4] != "P" and word[4] != "p" and word[5] != "P" and word[5] != "p" :
print("\nWrong!\n")
numberOfErrors = numberOfErrors + 1
wrongChars = wrongChars + "p" + ", "
if guessChar == "Q" or guessChar == "q" :
if word[1] == "Q" or word[1] == "q" :
toGuess = toGuess[:1] + "q" + toGuess[2:]
if word... | |
due to being an optional var when calling pass_vars.
if os.path.exists('/etc/freebsd-update.conf'):
env.update(CFLAGS='-I/usr/local/include/')
env.update(pass_vars(required=required, optional=optional))
return env
def pass_vars(required, optional): # type: (t.Collection[str], t.Collection[str]) -> t.Dict[str, s... | |
'OPTAA' and method == 'Streamed':
uframe_dataset_name = 'CE04OSBP/LJ01C/08-OPTAAC104/streamed/optaa_sample'
var_list[0].name = 'time'
var_list[0].data = np.array([])
var_list[0].units = 'seconds since 1900-01-01'
#CSPP Data below
elif platform_name == 'CE01ISSP' and node == 'PROFILER' and instrument_class == ... | |
outputdata.createVariable('Latitude', 'f4', ('south_north', 'east_west'))
longitude[:] = lons
latitude[:] = lats
latitude.units = "Degrees North"
longitude.units = "Degrees East"
else:
print("Appending to %s" % outputfile)
outputdata = Dataset(outputfile, 'r+') # open up netCDF file for appending
print("-----... | |
<reponame>hi117/pythonql
from pythonql.algebra.operator import plan_from_list
from pythonql.algebra.operators import *
from pythonql.PQTuple import PQTuple
from pythonql.helpers import flatten
from pythonql.Rewriter import rewrite
from pythonql.debug import Debug
import json
import types
def make_pql_tuple(vals,lcs):
... | |
# Copyright (c) 2001-2008 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.python.log}.
"""
import os, sys, time, logging, warnings
from cStringIO import StringIO
from twisted.trial import unittest
from twisted.python import log, failure
class FakeWarning(Warning):
"""
A unique L{... | |
and k == j + 1 and j == i + 1:
STRAIGHT_CSSHC.append({C[i], S[j], S[k], H[l], C[m]})
STRAIGHT_CSSHC.append({C[9], S[10], S[11], H[12], C[0]})
STRAIGHT_CSSHH = []
for i in range(13):
for j in range(1, 13):
for k in range(2, 13):
for l in range(3, 13):
for m in range(4, 13):
if m == l + 1 and l == k + 1 and k == j... | |
desc"
CREATED_DATE_TIME = "createdDateTime"
CREATED_DATE_TIME_DESC = "createdDateTime desc"
CONTENT = "content"
CONTENT_DESC = "content desc"
CONTENT_URL = "contentUrl"
CONTENT_URL_DESC = "contentUrl desc"
CREATED_BY_APP_ID = "createdByAppId"
CREATED_BY_APP_ID_DESC = "createdByAppId desc"
LAST_MODIFIED_DATE_TI... | |
in test_loader:
x = x.to(device)
loss = model.test({"x": x})
test_loss += loss
test_loss = test_loss * test_loader.batch_size / len(test_loader.dataset)
print('Test loss: {:.4f}'.format(test_loss))
return test_loss
# In[12]:
def plot_reconstrunction(x):
with torch.no_grad():
z = p.forward(x, compute_jacobi... | |
<reponame>mpynode/node-designer
import unittest
import tempfile
import os
import string
import cPickle
import codecs
try:
import maya.standalone
maya.standalone.initialize()
except:
pass
import maya.api.OpenMaya as om
import maya.cmds as mc
from mpylib import MNode
from mpylib.nodes import MPyNode
class TestMPy... | |
<reponame>Pyifan/testplan
"""PyTest test runner."""
import collections
import inspect
import os
import re
import traceback
import pytest
import six
from schema import Or
from testplan.testing import base as testing
from testplan.common.config import ConfigOption
from testplan.testing.base import TestResult
from testp... | |
<filename>venv/Lib/site-packages/IPython/kernel/zmq/ipkernel.py<gh_stars>0
#!/usr/bin/env python
"""An interactive kernel that talks to frontends over 0MQ."""
#-----------------------------------------------------------------------------
# Imports
#----------------------------------------------------------------------... | |
<reponame>Arent128/npc
"""
Package for command functions and their helpers
These functions handle the real work of NPC. They can be called on their own
without going through the CLI.
"""
import json
from collections import Counter
from os import makedirs, rmdir, getcwd
from pathlib import Path
from shutil import move... | |
= tf.shape(padded_images)
with self.test_session() as sess:
(boxes_shape_, padded_boxes_shape_, images_shape_,
padded_images_shape_, boxes_, padded_boxes_) = sess.run(
[boxes_shape, padded_boxes_shape, images_shape,
padded_images_shape, boxes, padded_boxes])
self.assertAllEqual(boxes_shape_, padded_boxes_shape_)... | |
<gh_stars>1-10
import warnings
import torch
import torch.nn as nn
from torch.nn import functional as F
from npf.utils.helpers import (
channels_to_2nd_dim,
channels_to_last_dim,
make_depth_sep_conv,
)
from npf.utils.initialization import init_param_, weights_init
__all__ = [
"GaussianConv2d",
"ConvBlock",
"Res... | |
# 6.0001 Spring 2020
# Problem Set 3
# Written by: sylvant, muneezap, charz, anabell, nhung, wang19k, asinelni, shahul, jcsands
# Problem Set 3
# Name: <NAME>
# Collaborators: <NAME>
# Time Spent: 4:00
# Late Days Used: (only if you are using any)
import string
# - - - - - - - - - -
# Check for similari... | |
l
weights_fname = spec.pop('weights_fname', None)
if type(spec['ordinal_bins']) is not int:
spec['ordinal_bins'] = [int(i) for i in spec['ordinal_bins'].split('_')[1:][::2]]
#print(weights_fname)
assert weights_fname is not None, "Provide a valid weights filename to load model."
model = MordredStrategy(**spec)... | |
<reponame>railtoolkit/OpenLinTim
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__all__ = [
"ScenarioGenerator",
"ScenarioScheduler",
"ConfigurableScenarioGenerator",
"ScAlbertU1",
"ScAlbertU2",
"DistributionScenarioGenerator",
"PoissonDistScenarioGenerator",
"NormalDistScenarioGenerator",
"TreeOnTrackScenar... | |
in the archive. 'root_dir' and 'base_dir' both default
to the current directory. Returns the name of the archive file.
'owner' and 'group' are used when creating a tar archive. By default,
uses the current owner and group.
"""
sys.audit("shutil.make_archive", base_name, format, root_dir, base_dir)
save_cw... | |
<reponame>RobertJN64/MachineLearningLibOLD
import random
import json
import math
import warnings
def inSet(strings):
inputs = {}
for i in strings:
inputs[i] = InNode()
return inputs
def outSet(strings, activation_func="sigmoid"):
outputs = {}
for i in strings:
outputs[i] = OutNode(activation_func=activation_... | |
dims." % x.ndim)
n = len(x)
if demean:
xo = x - x.mean()
else:
xo = x
if unbiased:
xi = np.arange(1, n+1)
d = np.hstack((xi, xi[:-1][::-1]))
else:
d = n
if fft:
nobs = len(xo)
Frf = np.fft.fft(xo, n=nobs*2)
acov = np.fft.ifft(Frf*np.conjugate(Frf))[:nobs]/d
return acov.real
else:
return (np.correlate(... | |
are reachable
self.assertIn("/agroup3/anarray1", self.h5file)
self.assertIn("/agroup3/anarray2", self.h5file)
self.assertIn("/agroup3/agroup3", self.h5file)
def test01b(self):
"""Checking rename_node (over Groups with children 2)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test01b..." % sel... | |
<filename>func_moead.py
# -*- coding: utf-8 -*-
"""
Author: <NAME> <<EMAIL>>
website: http://www.cs.cityu.edu.hk/~xilin4/
github:
This code is a demo for this paper:
A Decomposition based Multiobjective Evolutionary Algorithm
with Classification
<NAME>, <NAME>, <NAME>
Proceedings of the 2016 IEEE C... | |
#!/usr/bin/env python
# encoding: utf-8
"""
@author: <NAME> 刘祥德
@license: (C) Copyright 2019-now, Node Supply Chain Manager Corporation Limited.
@contact: <EMAIL>
@software:
@file: warp.py
@time: 10/3/19 4:58 PM
@version 1.0
@desc:
"""
import logging
import os
import random
import cv2
import numpy as np
import torch
i... | |
<filename>tools/Blender Stuff/Plugins/KerraxImpExp/2.78 fix/scripts/addons/KrxImpExp/Krx3dsExp.py
from KrxImpExp.impexp import *
def FormatMsg(fmt, args):
msg = (fmt)
for i in range((0), (9)):
argtempl = ("%" + (int_to_string(i + 1)))
argpos = ((msg).find(argtempl))
if(argpos != -1):
msg = ((msg)[... | |
<filename>improver_tests/metadata/test_forecast_times.py
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2020 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modificatio... | |
<filename>src/GridCal/Engine/IO/cim_parser.py
# This file is part of GridCal.
#
# GridCal is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versio... | |
AFFINN = {
"плох": "-5",
"неблагоприятн": "-5",
"скучн": "-5",
"трудн": "-5",
"больн": "-5",
"зло": "-5",
"опасн": "-5",
"холодн": "-5",
"отвратительн": "-5",
"нелегк": "-5",
"бедн": "-5",
"одинок": "-5",
"жесток": "-5",
"грустн": "-5",
"ужасн": "-5",
"вынужден": "-5",
"негативн": "-5",
"неприятн": "-... | |
attributes
for key in args:
setattr(self, key, args[key])
def get(self, dbrow_or_id):
"""get from database for form"""
# check if id supplied, if so retrieve dbrow
if type(dbrow_or_id) in [int, str]:
dbrow = self.tablemodel.query().filter_by(id=dbrow_or_id).one()
else:
dbrow = dbrow_or_id
return self.truedi... | |
:obj:`Conclusion`: conclusions for model
"""
if '__type' in kwargs:
__type = kwargs.pop('__type')
return self.conclusions.get(__type=__type, **kwargs)
def get_references(self, __type=None, **kwargs):
""" Get all references from model and children
Args:
__type (:obj:`types.TypeType` or :obj:`tuple` of :obj:`t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.