content string |
|---|
from qingcloud.iaas import constants as const
from qingcloud.misc.utils import filter_out_none
class KeypairAction(object):
def __init__(self, conn):
self.conn = conn
def describe_key_pairs(self, keypairs=None,
encrypt_method=None,
search_word=No... |
'''StackContext allows applications to maintain threadlocal-like state
that follows execution as it moves to other execution contexts.
The motivating examples are to eliminate the need for explicit
async_callback wrappers (as in tornado.web.RequestHandler), and to
allow some additional context to be kept for logging.
... |
from zope.interface.adapter import BaseAdapterRegistry
from zope.interface.adapter import AdapterLookupBase
from zope.interface import providedBy
from transaction._transaction import Status
from transaction._transaction import Transaction
from transaction import interfaces
from transaction._compat import reraise
impo... |
"""Plot a the distribution of one or more data sets in one or two dimensions.
This tool generates an SVG plot of the 1D or 2D distribution of one or more
data sets. Each data set is specified as a comma- or tab-separated data file.
If one data column is specified, then the 1-dimensional marginal distribution
of each d... |
from raptiformica.actions.mesh import get_consul_password
from tests.testcase import TestCase
class TestGetConsulPassword(TestCase):
def setUp(self):
self.mapping = {
"raptiformica/meshnet/cjdns/password": "a_secret",
"raptiformica/meshnet/consul/password": "a_different_secret",
... |
"""
This module provides code to work with html files from NDB.
http://ndbserver.rutgers.edu/NDB/structure-finder/ndb/index.html
Classes:
Record Holds NDB sequence data.
NdbParser Parses NDB sequence data into a Record object.
The algorithm is based on a state machine because the record has mult... |
# -*- coding: ascii -*-
u"""
:Copyright:
Copyright 2014 - 2021
Andr\xe9 Malo or his licensors, as applicable
:License:
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.... |
import pandas as pd, numpy as np
import sys, time, random, string, os
from synthicity.utils import misc
import spotproforma
import baydataset
# TODO better way of doing this?
def get_possible_rents_by_use(dset):
parcels = dset.parcels
# need a prevailing rent for each parcel
nodeavgrents = pd.read_csv('avenodep... |
import os
import sys
import unittest
import bufr
test_dir = os.path.dirname(os.path.abspath(__file__))
class TestBUFRFile(unittest.TestCase):
def setUp(self):
os.environ['BUFR_TABLES'] = test_dir + "/bufrtables/"
os.environ['PRINT_TABLE_NAMES'] = "false"
def test_bufr_read(self):
"... |
# Usage: `python local_testing_tool.py test_number`, where the argument
# test_number is either 0 (Test Set 1), 1 (Test Set 2) or 2 (Test Set 3).
from __future__ import print_function
import itertools
import random
import sys
# Use raw_input in Python2.
try:
input = raw_input
except NameError:
pass
MAX_QUERIES... |
#!/usr/bin/env python
"""
Tool to aid with learning IR commands
"""
from ir_deluxe import IRInterface
from irinterpreter import recognize
import json
import sys
import base64
import logging
import argparse
""" Parse it! """
parser = argparse.ArgumentParser(description="IR Deluxe^2 Learn Tool", formatter_class=argparse... |
import ROOT
from copy import deepcopy
from PyAnalysisTools.base import _logger
from PyAnalysisTools.AnalysisTools.RegionBuilder import RegionBuilder
from PyAnalysisTools.PlottingUtils.PlotConfig import PlotConfig
from PyAnalysisTools.PlottingUtils.BasePlotter import BasePlotter
class RegionSummaryModule(object):
... |
#! /usr/bin/env python
from __future__ import print_function
from openturns import *
TESTPREAMBLE()
RandomGenerator.SetSeed(0)
def cleanScalar(inScalar):
if (abs(inScalar) < 1.e-6):
return 0.0
return inScalar
try:
# Default constructor
myDefautModel = UserDefinedSpectralModel()
print(... |
# -*- coding: utf-8 -*-
import json
import requests
from . import BASE_URL, HEADERS
BASE_URL_NETWORK = BASE_URL + 'networks'
class BaseView(object):
"""
Base view class to directly access node/edge view properties.
"""
def __init__(self, network_view=None, obj_id=None, obj_type=None):
if ne... |
# coding=utf8
'''
Leecher.us direct link fetcher, uses phantomjs/selenium
version 0.2
'''
import re
from selenium.webdriver import PhantomJS
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from seleni... |
import os
import mylar
from mylar import logger
from transmissionrpc import Client
class TorrentClient(object):
def __init__(self):
self.conn = None
def connect(self, host, username, password):
if self.conn is not None:
return self.conn
if not host:
return Fal... |
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from quantum.db.models_v2 import model_base
class VlanAllocation(model_base.BASEV2):
"""Represents allocation state of vlan_id on physical network."""
__tablename__ = 'ovs_vlan_allocations'
physical_network = Column(String(64), nullable... |
from datetime import datetime
from flask import (Flask, redirect, render_template, request, make_response,
jsonify, url_for)
from flask.ext.sqlalchemy import SQLAlchemy
from temperature_client import TemperatureClient
###
# Configuration
###
# Temperature server (see pi/temp-server/server.py)
TEMP_SERVER_HOST = '1... |
import functools
from couchdbkit.ext.django import loading
from couchdbkit.ext.django.testrunner import CouchDbKitTestSuiteRunner
import datetime
from django.conf import settings
from django.utils import unittest
import settingshelper
from django.test import TransactionTestCase
from mock import patch, Mock
class HqT... |
import remotedevices_server
import fmbtandroid
import subprocess
_serialNumberPrefix = ""
class AndroidDevices(remotedevices_server.DeviceClass):
def rescan(self):
return ["%s%s" % (_serialNumberPrefix, sn)
for sn in fmbtandroid.listSerialNumbers()]
def adopt(self, deviceId):
... |
import os
import threading
from System.Core.Global import *
from System.Core.Colors import *
from System.Core.Modbus import *
from System.Lib import ipcalc
class Module:
info = {
'Name': 'Read Input Registers',
'Author': ['@enddo'],
'Description': ("Fuzzing Read Input Registers Function"),
}
option... |
# -------------------------------------------------------------------
# EdxBuilder Sequential XML Template
# -------------------------------------------------------------------
#
#
# Organization : Sciences-Po Medialab
# Dependencies
#=============
from template import XMLTemplate
from vertical import VerticalXMLTem... |
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.utils.text import slugify
from mezgrman.utils.classes import ModelFieldIteratorMixin, ModelFieldVerboseNameLookupMixin
from django.db import models
import uuid
class Location(models.Model, ModelFieldIterato... |
"""
Copyright (C) 2017 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distri... |
# coding=utf-8
from simpleai.search.utils import BoundedPriorityQueue, InverseTransformSampler
from simpleai.search.models import SearchNodeValueOrdered
import math
import random
def _all_expander(fringe, iteration, viewer):
'''
Expander that expands all nodes on the fringe.
'''
expanded_neighbors = [... |
import pmisc
from pmisc import AE, AI, RE
import pytest
# Intra-package imports
import pcsv
from tests.fixtures import write_cols_not_unique, write_file, write_file_empty
###
# Test functions
###
def test_dsort_function():
"""Test dsort function behavior."""
# Input file name has headers, separate output fil... |
import mock
from oslotest import base
from cloudferry import cfglib
from cloudferry.cloud import cloud
class TestCase(base.BaseTestCase):
"""Test case base class for all unit tests."""
def __init__(self, *args, **kwargs):
super(TestCase, self).__init__(*args, **kwargs)
self.cfg = cfglib.CON... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import tempfile
import pytest
from lib import db as database, utils
BOOKMARK_DATA = [
database.Bookmark(None, 'started', 1, 2, 3.45, None),
database.Bookmark(None, 'paused', 2, 2, 6.78, None),
database.Bookmark(None, 'started', 3, 4, 7.89, ... |
import json
from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator
from django.db import models
from django.conf import settings
from channels import Group
from django.utils import timezone
from game.round.models import Round
class Settings(models.Model):
"""
... |
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_... |
from securityhandlerhelper import securityhandlerhelper
dateTimeFormat = '%Y-%m-%d %H:%M'
import arcrest
from arcrest.agol import FeatureLayer
from arcrest.agol import FeatureService
from arcrest.hostedservice import AdminFeatureService
import datetime, time
import json
import os
import common
import gc
#-----------... |
from woob.tools.backend import Module
from woob.capabilities.housing import (CapHousing, Housing, HousingPhoto,
ADVERT_TYPES)
from woob.capabilities.base import UserError
from woob import __version__ as WOOB_VERSION
from .browser import LogicimmoBrowser
__all__ = ['LogicimmoMo... |
from touchdown.tests.aws import StubberTestCase
from touchdown.tests.stubs.aws import PasswordPolicyStubber
class TestPasswordPolicyCreation(StubberTestCase):
def test_create_password_policy(self):
goal = self.create_goal("apply")
password_policy = self.fixtures.enter_context(
Passwor... |
"""Formulae for specific earth behaviors and effects."""
from numpy import (abs, arcsin, arccos, array, clip, cos,
minimum, pi, sin, sqrt, tan, where, zeros_like)
from .constants import (AU_M, ANGVEL, DAY_S, DEG2RAD, ERAD,
IERS_2010_INVERSE_EARTH_FLATTENING, RAD2DEG, T0)
fro... |
from orbkit.detci.ci_read import psi4_detci, molpro_mcscf
from orbkit.test.tools import equal
from orbkit import options
import numpy
import os, inspect
tests_home = os.path.dirname(inspect.getfile(inspect.currentframe()))
folder = os.path.join(tests_home, 'outputs_for_testing')
options.quiet = True
#I don't know wh... |
"""Windows base service implementation.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import errno
import functools
import logging
import os
# Disable E0401: unable to import on linux
import win32security # py... |
import os
import numpy as np
import pandas as pd
from nltk.tokenize import word_tokenize
from sklearn.decomposition import PCA
from sklearn.neighbors import NearestNeighbors
probs = pd.read_csv(os.path.join('data', 'word_probs.csv'))
w2v = pd.read_table(os.path.join('data', 'w2v.csv.csv'))
w2v.columns = [0]
w2v = w2... |
"""
Download the MBGA avatar images from links in the data directory.
"""
from time import sleep
from random import randrange
import os
import sys
import glob
import argparse
def avatar_info(path='data/mbga/person/'):
info = []
for f in glob.glob(os.path.join(path, '*_img.data')):
name_parts = f.split("/")[-1]... |
from keras import backend as K
from keras.layers import initializations, InputSpec, Layer
class Maxout(Layer):
"""
Maxout dense layer tailored for W2C decoder output, following paper:
http://arxiv.org/abs/1406.1078
"""
def __init__(self, output_dim, nb_feature=4, init='glorot_uniform', bias=True, input_... |
"""Tests for wm macros"""
from taurus.external import unittest
from sardana.macroserver.macros.test import (RunMacroTestCase, testRun,
getMotors)
#get handy motor names from sardemo
_m1, _m2 = getMotors()[:2]
class WBase(RunMacroTestCase):
"""Base class for testing m... |
"""
Functions to encode strings
"""
# Copyright (C) 2015 by
# Himanshu Mishra <<EMAIL>>
# All rights reserved.
# GNU GPL v2 license.
import collections
__all__ = ['encode']
morsetab = collections.OrderedDict([
('A', '.-'),
('B', '-...'),
('C', '-.-.'),
('D', '-..'),
('E', '.'),
(... |
'''
Serialize and Deserialize Binary Tree QuestionEditorial Solution My Submissions
Total Accepted: 32879
Total Submissions: 108712
Difficulty: Hard
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across ... |
from lettuce import *
from nose.tools import assert_equal, assert_in
from webtest import TestApp
from ch5_tdd import Account
from ch5_tdd import app, BANK
@step("I create the following account:")
def i_create_the_following_account(step):
for row in step.hashes:
account = Account(row['account_number'], row... |
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.parent = None
class Bst:
def __init__(self):
self.root = None
self.size = 0
def insert(self, data):
temp = Node(data)
if self.size == 0:
... |
import os
import sys
import numpy as np
import theano
import theano.tensor as T
import lasagne
import time
from os.path import dirname
from lasagne.regularization import l2, l1
from lib.utils.data_utils import *
#------------------------------------------------------------------------------#
def predict_fn(input_va... |
""" Utility functions for implementing Winograd convolutions
[*] Fast Algorithms for Convolutional Neural Networks
Andrew Lavin, Scott Gray
https://arxiv.org/abs/1509.09308
https://github.com/andravin/wincnn
"""
from operator import mul
from functools import reduce
import numpy as np
from t... |
#
# Test for NozzleGeometryDOE.py
#
import os
import shutil
import unittest
from openmdao.examples.nozzle_geometry_doe.test.nozzle_geometry_doe \
import NozzleGeometryDOE
from openmdao.main.api import set_as_top
class NozzleGeometryDOETestCase(unittest.TestCase):
""" NozzleGeometryDOE test case """
def... |
"""TcEx Framework Inputs module"""
# standard library
import json
import os
import sys
from argparse import Namespace
from ..utils import Utils
from .argument_parser import TcArgumentParser
class Inputs:
"""Module for handling inputs passed to App from CLI, Config, SecureParams, and AOT
Args:
tcex (... |
from odoo import fields, models
#in this file, we mostly add the tag translate=True on existing fields that we now want to be translated
class AccountAccountTag(models.Model):
_inherit = 'account.account.tag'
name = fields.Char(translate=True)
class AccountAccountTemplate(models.Model):
_inherit = 'acco... |
import sys
import logging
from ..utils import make_good_url
##-------------------------------------------------------------------------
class ConnectorJSONRPC():
"""Welcome to the grand ConnectorJSONRPC. It loves to talk to Kvasir
JSONRPC instances to send it commands and gobble its responses. That's all!
To use... |
import pyopenms
import numpy as np
import os.path
import copy
from collections import defaultdict
import warnings
def deprecation(message):
warnings.warn(message, UserWarning, stacklevel=2)
class Spectrum(object):
"""
MS Spectrum Type
"""
def __init__(self, peaks, rt, msLevel, polarity, pr... |
# -*- coding: utf-8 -*-
import os
import nipype.interfaces.base as nib
import nipype.pipeline.engine as pe
class InputSpec(nib.TraitedSpec):
input1 = nib.traits.Int(desc='a random int')
input2 = nib.traits.Int(desc='a random int')
class OutputSpec(nib.TraitedSpec):
output1 = nib.traits.List(nib.traits.... |
#! /usr/bin/env python
import tensorflow as tf
import numpy as np
import os
import time
import datetime
import data_helpers
from text_cnn import TextCNN
from tensorflow.contrib import learn
# Parameters
# ==================================================
# Data loading params
tf.flags.DEFINE_float("dev_sample_perce... |
import os
from tempfile import NamedTemporaryFile
from typing import Optional, Union
import numpy as np
import pandas as pd
from airflow.exceptions import AirflowException
from airflow.models import BaseOperator
from airflow.providers.amazon.aws.hooks.s3 import S3Hook
from airflow.providers.mysql.hooks.mysql import M... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import social.apps.django_app.default.fields
from django.conf import settings
import social.storage.django_orm
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(... |
import pytest
from olypy.oid import to_oid, to_int, allocate_oid, to_int_safely
oid_to_int = {
'1': 1,
'6940': 6940,
'aa01': 10001,
'ab01': 10101,
'ba01': 12001,
'za99': 48099,
'zz99': 49999,
'nn1': 53511,
'b01': 56861,
'w65': 58525,
'c000': 61000,
'z999': 78999,
'99... |
"""Tools and calculations for assigning values to a grid."""
from __future__ import division
import numpy as np
from scipy.interpolate import griddata, Rbf
from scipy.spatial.distance import cdist
from . import interpolation, points
from ..package_tools import Exporter
exporter = Exporter(globals())
def calc_kapp... |
import os
import importlib.util
import re
class Page(object):
"""
The Page object is used to generate an html page for each branch.py file
"""
def __init__(self, settings_path):
self.settings_path = settings_path
self.page_directory = os.path.dirname(os.path.realpath(self.settings_path... |
'''
Copyright 2018 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, software
di... |
from msrest.serialization import Model
class GrantAccessData(Model):
"""Data used for requesting a SAS.
All required parameters must be populated in order to send to Azure.
:param access: Required. Possible values include: 'None', 'Read'
:type access: str or ~azure.mgmt.compute.v2018_04_01.models.Ac... |
"""Initial_schema
Revision ID: 722b06c8ce2e
Revises:
Create Date: 2017-04-18 00:01:34.407801
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '722b06c8ce2e'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
op.create_table('users... |
# classfile for the Luminaire class
from multiprocessing import Queue
import thread
class Luminaire:
'''defines a luminaire, its position, and attributes'''
def __init__(self, x, y, name):
'''constructs an instance of Luminaire'''
self.name = name
self.position = (x, y)
self.... |
from d51.django.apps.twitter import utils
from d51.django.apps.twitter.tests.test import TestCase
from django.conf import settings
from dolt.apis import twitter as dolt
import oauth2
import random
class TestOfGetTwitterFunction(TestCase):
def setUp(self):
self.orig_settings = settings
self.orig_set... |
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from .. import models
class GeoBackupPoliciesOperations(object):
"""GeoBackupPoliciesOperations operations.
:param client: Client for service requests.
:param config: Configuration of service cl... |
#!/usr/local/bin/python
# A simple script to get the number of files in the mandc db for a given obsid
import psycopg2
import sys
from optparse import OptionParser
import socket
import mwaconfig
import base64
def main():
usage="Usage: %prog [options]\n"
usage+="\tFinds the number of files associated with an o... |
print("You enter a dark room with towo doors. Do you go through door #1 or door #2?")
door = input(">")
if door is "1":
print("There's a giant bear here eating a cheese cake. What do you do?")
print("1. Take the cake.")
print("2. Scream at the bear.")
bear = input(">")
if bear is "1":
pr... |
#coding=utf-8
from uliweb import expose
from menu import bind_menu
from uliweb.utils.common import log
from uliweb.utils.common import pkg, is_pyfile_exist
@expose('/develop')
def develop_index():
return {}
@expose('/develop/appsinfo')
def develop_appsinfo():
return {'apps':application.apps}
@e... |
import torch
from torch.autograd import Variable
# Constants
CONTEXT_SIZE = 2
EMBEDDING_DIMENSIONS = 4
CORPUS_PATH = "Count of Monte Cristo"
EPOCHS = 100
LEARNING_RATE = 3e-2
# Open Count of Monte Cristo
try:
corpus = open(CORPUS_PATH, "r")
except FileNotFoundError:
print("A Text corpus with the name {} was n... |
"""
Graph based SLAM example
author: Atsushi Sakai (@Atsushi_twi)
Ref
[A Tutorial on Graph-Based SLAM]
(http://www2.informatik.uni-freiburg.de/~stachnis/pdf/grisetti10titsmag.pdf)
"""
import copy
import itertools
import math
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial.transform import R... |
"""
Polygon in 2 dimension.
"""
__all__ = [
"Location",
"Polygon",
]
from enum import Enum, auto
import line2d
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial.distance import pdist
class Location(Enum):
"""
Enumeration class that describe the location relationship between a ... |
from m5.SimObject import SimObject
from m5.params import *
class BranchPredictor(SimObject):
type = 'BranchPredictor'
cxx_class = 'BPredUnit'
cxx_header = "cpu/pred/bpred_unit.hh"
abstract = True
numThreads = Param.Unsigned(1, "Number of threads")
BTBEntries = Param.Unsigned(4096, "Number of B... |
from ....const import LOCALE as glocale
_ = glocale.translation.sgettext
#-------------------------------------------------------------------------
#
# Gprime modules
#
#-------------------------------------------------------------------------
from .._matchessourceconfidencebase import MatchesSourceConfidenceBase
#--... |
import re
# A reference to an atom
# "le théorème plop":applique:245 by id
# "link desc":verb:ref
reference_re_s = r'''"(?P<desc>[^"]*)":(?P<verb>\w+):(?P<ref>[$_\w]+)'''
reference_re = re.compile(reference_re_s)
def extract_references(value):
l = []
for match in re.finditer(reference_re, value):
# de... |
import crypto.ciphers as ciphers
from crypto.alphabets import EnglishAlphabet
def create_parsers(parser):
cipher_parser = parser.add_parser('ciphers', help='Access ciphers for encryption and decryption')
cipher_parser.add_argument('-d', dest='decrypt', help='Decrypt', action='store_true')
subparsers = cip... |
#!/usr/bin/env python
import rospy
from tf.transformations import *
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Quaternion, PoseStamped, Pose, Point
from nav_msgs.msg import Odometry
import math
import numpy as np
# LA NODE NE MARCHE PAS COMPLETEMENT. Le dev a ete arrete parce que ca causait ... |
# -*- coding: utf-8 -*-
import qi
import argparse
import sys
import time
import threading
import random
import action_base
from action_base import *
actionName = "greet"
def greet(lang):
if (lang=="Japanese"):
return "こんにちは"
elif (lang=="French"):
return "Salut"
elif (lang=="Spanish"):
... |
from django.core.mail import send_mail, mail_admins
from django.core.urlresolvers import reverse
from django.conf import settings
from django.template import loader, Context
def build_policy():
"""Builds the policy as a string from the settings."""
policy = ['allow %s' % (' '.join(settings.CSP_ALLOW) if
... |
"""
Unittests!
"""
from decimal import Decimal
from django.test import TestCase
from core import db
from core import models
class DBTestCase(TestCase):
fixtures = ['testing/base.json']
def test_get_balance(self):
balance = db.get_balance(7, 10, 3)
self.assertEqual(balance.value, 62)
self.assertEqual(
s... |
import pytest
from udata.models import MembershipRequest, Member
from udata.core.user.factories import UserFactory
from udata.core.organization.factories import OrganizationFactory
from udata.core.organization.notifications import (
membership_request_notifications
)
from udata.tests.helpers import assert_equal_... |
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('horizon.dashboards.syspanel.tenants.views',
url(r'^$', 'index', name='index'),
url(r'^create$', 'create', name='create'),
url(r'^(?P<tenant_id>[^/]+)/update/$', 'update', name='update'),
url(r'^(?P<tenant_id>[^/]+)/users/$', '... |
"""
Copyright (C) 2017, 申瑞珉 (Ruimin Shen)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed i... |
"""
Generalized Polygon Computations
Authors/Modifications:
----------------------
* Tom Trainor (<EMAIL>)
Todo:
-----
* Make sure this handles polygons with centers off the
origin, ie correclty handle arbitrary origin shifts
* Add some more polygon calcs
- compute center
- determine type (simple, complex etc)... |
"""Standard DDPG Objective."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import logging
import gin
import tensorflow.compat.v1 as tf
from dql_grasping.q_graph import DQNTarget
@gin.configurable
def ddpg_graph(a_func,
q_func,... |
from django.db import models
from django.template.defaultfilters import slugify
# Create your models here.
class Dispositivo(models.Model):
"""Modelado basico de un disposito.
"""
nombre_dispositivo = models.CharField(max_length=200)
fabricante = models.CharField(max_length=200)
caracteristicas = models.CharFiel... |
import pprint
import sys
import itertools
import simpy
import random
from operator import itemgetter
## local imports
from libMappingAndScheduling.MappingPolicy import MappingPolicy
from libBuffer.Buffer import Buffer
from libProcessingElement.CPUNode_ClosedLoop_wIBuffering import CPUNode_ClosedLoop_wIBuffering
from l... |
import os
import sys
class Presentation:
def __init__(self, name, lines, covered):
self.name = name
self.lines = lines
self.covered = covered
if self.covered == 0:
self.percent = 0
else:
self.percent = 100 * self.covered / float(self.lines)
def ... |
"""
tools for dealing with frozen atoms. Especially in relation to neighbor lists
.. currentmodule:: pele.utils.frozen_atoms
.. autosummary::
:toctree: generated/
FreezePot
makeBLJNeighborListPotFreeze
"""
import numpy as np
import pele.potentials.ljpshift as ljpshift
from pele.potentials.pote... |
# Includes the lib path
import sys
import tos
import datetime
import time
import logging
from SharedLibs.tools import raw_to_celcius, raw_to_volts_iris, raw_to_volts_micaz
from Shared import *
import pika # component to access Event Manager
sys.path.insert(0,'/opt/tinyos-2.1.2/support/sdk/python')
sys.path.insert(1,'... |
"""Schedule for pooling operators"""
import tvm
from .. import tag
from .. import generic
from ..util import traverse_inline
@generic.schedule_adaptive_pool.register(["cuda", "gpu"])
def schedule_adaptive_pool(outs):
"""Schedule for adaptive_pool.
Parameters
----------
outs: Array of Tensor
... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""Client-server application for syncing local folders with remote server.
"""
import sys
import argparse
from client.dirsync_client import Client
from server.dirsync_server import Server
from app.dir_sync_utils.util_funcs import setting_validate
__author__ = "Peter Boba... |
import json
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
import requests
from accurate_bg_check.exception import ValidationException
from requests.auth import HTTPBasicAuth
class BgCheck(object):
base_url = 'https://api.accuratebackground.com/v3/'
client_i... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import apps
from django.contrib.auth import get_permission_codename
from .settings import settings
from django.core.urlresolvers import reverse, NoReverseMatch
from django.shortcuts import resolve_url
def admin_sidebar_content(request)... |
import time, subprocess, json, urllib2
# dashboard central server host
dashboardServer = 'MY-SERVER-HERE.com'
def sendHTTPPOST(readingValue, readingNumber):
''' for given reading integer value and which number to persist it as HTTP Post it to central hub '''
req = urllib2.Request('http://'+dashboardServer+'/r... |
from contextlib import contextmanager
from dateutil.relativedelta import relativedelta
from psycopg2 import OperationalError
from odoo import api, fields, models
class HrWorkEntry(models.Model):
_name = 'hr.work.entry'
_description = 'HR Work Entry'
_order = 'conflict desc,state,date_start'
name = f... |
from sklearn.multiclass import OneVsRestClassifier
from sklearn import ensemble
from src.multi_class import input_preproc
from src.multi_class import calculate_metrics
def runClassifier(X_train, X_test, y_train, y_test):
# print y_train
cls = ensemble.RandomForestClassifier(n_estimators=100,
... |
from scipy import misc
import numpy as np
import matplotlib.pyplot as plt
import time
from scipy.ndimage.filters import gaussian_filter1d, gaussian_filter
class Gaussianfilter2D():
'''
2D gaussian filter on Black and White images
The filter image satisfies the relation
$$ C_{i,j} = \sum_{m=0}^{2 l_w} \sum_{n=0}... |
#!/usr/bin/env python
import time
from apps.webdriver_testing.pages import Page
class UnisubsMenu(Page):
#LANGUAGE DISPLAY OPTIONS
_MENU = 'span.unisubs-tabTextchoose'
_SUBTITLES_OFF = 'div.unisubs-languageList li'
_LANG_LIST = 'div.unisubs-languageList'
_LANG_TITLE = '.unisubs-languageTitle'
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import logging
import re
import datetime
from website.identifiers.clients.base import AbstractIdentifierClient
from website import settings
from datacite import DataCiteMDSClient, schema40
logger = logging.getLogger(__name__)
class DataCiteClient(Abstr... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys
GLOBAL_CONST = 'global constant'
# classes
class old:
def old_f1():
pass
def old_f2(self):
pass
class new(object):
def new_f1():
pass
def new_f2(self):
pass
# functions
def func():
pass
def nested_func():
... |
import pickle
from nose.tools import eq_
from .. import ukrainian
from ...datasources import revision_oriented
from ...dependencies import solve
from .util import compare_extraction
BAD = [
"довбойоб", "сучий", "ебать", "пісяти", "серун", "бздюха", "бздюх",
"матюгальники", "їбе", "вйоб", "дристало", "серуха"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.