code stringlengths 1 199k |
|---|
from datetime import datetime, timedelta
EMPTY_DATA = datetime(1900,1,1,0,0,0) # '1900-01-01 00:00:00'
def get_date(value, is_datetime = False):
''' Return OpenERP data format
value: MS or My SQL data format (datetime)
datetime: Select the format in date or datetime
'''
if value == EMPTY_DAT... |
from openerp import models, fields, api
from datetime import *
import time
class clv_insured_card_history(models.Model):
_name = 'clv_insured_card.history'
insured_card_id = fields.Many2one('clv_insured_card', 'Insured Card', required=True)
user_id = fields.Many2one ('res.users', 'User', required=True,
... |
def merged_initial_and_data(form):
data = {}
for name, field in form.fields.iteritems():
data[name] = field.initial
for source in (form.initial, getattr(form, "cleaned_data", {})):
for name, value in source.iteritems():
if value is not None:
data[name] = value
... |
"""Sync models and database.
Revision ID: 7d180b95fcbe
Revises: f78ca4cad5d6
Create Date: 2019-05-15 18:28:47.050549
"""
revision = '7d180b95fcbe'
down_revision = 'f78ca4cad5d6'
from alembic import op
import sqlalchemy as sa
renames = [
('assignee', 'assignee_line_item_current_key', 'assignee_line_item_id_current_k... |
import requests
from bs4 import BeautifulSoup
import os.path
from datetime import datetime, timedelta
import pkfunctions
cal_path = 'historical-catalyst-calendar'
one_hour_ago = datetime.now() - timedelta(hours=1)
if os.path.exists(cal_path):
filetime = datetime.fromtimestamp(os.path.getctime(cal_path))
if file... |
import matplotlib.pyplot as plt
import numpy as np
import math
from datetime import datetime
from matplotlib.dates import date2num, num2date
class PlotData(object):
def __init__(self):
self.left_axis_label = ''
"""
Axis which goes on the left-hand side
"""
self.right_axis_label = ''
"""
Ax... |
import sys
import pywbem
import optparse
import time
from OpenSSL import SSL
from twisted.internet import ssl, reactor
from twisted.python import log
from twisted.web import server, resource
from socket import getfqdn
_g_verbose=False
_g_options=None
class WBEMConn:
_shared_state = {}
conn = None
def __init... |
import matplotlib
matplotlib.use("Agg") |
"""autogenerated by genpy from hrl_msgs/FloatArray.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import std_msgs.msg
class FloatArray(genpy.Message):
_md5sum = "fb60495edd59d3fcf90e173153ae8a9a"
_type = "hrl_msgs/FloatArray"
_has_header = True ... |
from mock import patch, sentinel, call
from arctic.scripts.arctic_fsck import main
from ...util import run_as_main
def test_main():
with patch('arctic.scripts.arctic_fsck.Arctic') as Arctic, \
patch('arctic.scripts.arctic_fsck.get_mongodb_uri') as get_mongodb_uri, \
patch('arctic.scripts.arctic_fs... |
from unittest import TestCase
from num2words.utils import splitbyx
class TestUtils(TestCase):
def test_splitbyx(self):
self.assertEqual(list(splitbyx(str(12), 3)), [12])
self.assertEqual(list(splitbyx(str(1234), 3)), [1, 234])
self.assertEqual(list(splitbyx(str(12345678900), 3)),
... |
import sys
from paravistest import datadir, pictureext, get_picture_dir
from presentations import CreatePrsForFile, PrsTypeEnum
import pvserver as paravis
myParavis = paravis.myParavis
picturedir = get_picture_dir("IsoSurfaces/G1")
file = datadir + "maill.2.med"
print " --------------------------------- "
print "file "... |
import ocl
print ocl.version()
p0 = ocl.CLPoint(0,0,0)
p1 = ocl.CLPoint(1,2,3)
p2 = ocl.CLPoint(1.1,2.2,3.3)
clp=[]
clp.append(p0)
clp.append(p1)
clp.append(p2)
f = ocl.LineCLFilter()
f.setTolerance(0.01)
for p in clp:
f.addCLPoint(p)
f.run()
p2 = f.getCLPoints()
for p in p2:
print(p) |
from spack import *
class EcpProxyApps(BundlePackage):
"""This is a collection of packages that represents the official suite of
DOE/ECP proxy applications. This is a Spack bundle package that
installs the ECP proxy application suite.
"""
tags = ['proxy-app', 'ecp-proxy-app']
maintainers =... |
from obus import Enum
from obus import BusEventDesc
from obus.data import ObusBusEvent
class BusEventBase(ObusBusEvent):
# obus event base
Type = Enum("BusEventBase.Type", {
"CONNECTED": 0, # Connected to bus
"DISCONNECTED": 1, # Disconnected from bus
"CONNECTION_REFUSED": 2, # Connectio... |
"""
Python API for the Nitrate test case management system
This module provides a high-level python interface for the nitrate
module. Handles connection to the server automatically, allows to set
custom level of logging and data caching. Supports results coloring.
Synopsis:
Minimal config file ~/.nitrate::
... |
from __future__ import print_function
import unittest
from unittest.mock import patch
import sys
import time
import tempfile
import shutil
import teres
DEBUG = True
def debug_var(obj, fn_name, name, value):
if not DEBUG:
return
sys.stderr.write(
'%s.%s(): %s=%r\n'
% (
obj.__c... |
import os, sys, shutil, copy
from optparse import OptionParser
sys.path.append(os.environ['SU2_RUN'])
import SU2
def main():
# Command Line Options
parser=OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="read config from FILE", metavar="FILE")
parser.ad... |
from sqlalchemy import Column
from sqlalchemy import Date
from sqlalchemy import Float
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import UniqueConstraint
from sqlalchemy.dialects import mysql
from sqlalchemy.ext.declarative import declarative_base
from... |
KOI8R_CharToOrderMap = ( \
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
253,142,1... |
"""
This module contains a function load_WI_JSON_export to import WellInverter exported data into wellFARE.
load_WI_JSON_export returns a wells dictonary.
The individual well data is stored in wells[wellname][measurename]
The available measure names are stored in wells["measures"]
The group list is stored in wells["gro... |
import sys
import os
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String, Date, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import OperationalError
password = None
try:
# Construct a reliable location of the... |
import json
import guessit
from flask import url_for
from werkzeug.datastructures import MultiDict
import guessitrest
class TestVersion(object):
def test_version(self, client):
response = client.get(url_for('.guessitversion'))
assert response.status_code == 200
assert 'guessit' in response.j... |
from subprocess import call, check_output
def _parse_metadata(metadata):
""" Parses Spotify metadata (though it may apply to anything answering over DBUS.
The format should be something like:
array [
dict entry (
string "key"
variant "value... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from rest_framework import routers
from views import *
from teams.models import TeamViewSet
router = routers.DefaultRouter()
router.register(r'teams', TeamView... |
def json_loader(filename):
from json import load
with open(filename) as f:
return load(f)
def yaml_loader(filename):
from yaml import load, FullLoader
with open(filename) as f:
return load(f, Loader=FullLoader)
def configuration_loader(filename):
from collections import Mapping
f... |
"""Freeze a Python script into a binary.
usage: freeze [options...] script [module]...
Options:
-p prefix: This is the prefix used when you ran ``make install''
in the Python build directory.
(If you never ran this, freeze won't work.)
The default is whatever sys.prefix eval... |
from termcolor import colored
from xml.etree import ElementTree as ET
import subprocess
import sys
import time
CONF_FILE = "../realsibs.xml"
subprocess.call(["killall", "-9", "sib-tcp"])
subprocess.call(["killall", "-9", "redsibd"])
tree = ET.parse(CONF_FILE)
root = tree.getroot()
rsib = {}
for r in root.findall('SIB')... |
from pycp2k.inputsection import InputSection
class _each266(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Just_energy = None
self.Powell_opt = None
self.Qs_scf = None
self.Xas_scf = None
self.Md = None
self.Pint = None
self.Metady... |
from fenrirscreenreader.core import debug
class command():
def __init__(self):
pass
def initialize(self, environment):
self.env = environment
def shutdown(self):
pass
def getDescription(self):
return 'No Description found'
def run(self):
self.env['runtime']['b... |
"""General-use classes to interact with the CertificateManager service through CloudFormation.
See Also:
`AWS developer guide for CertificateManager
<https://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html>`_
"""
from .._raw import certificatemanager as _raw
from .._raw.certificatemanager import * |
from pyblish import api
from pyblish_bumpybox import inventory
class ExtractMaya(api.InstancePlugin):
""" Appending RoyalRender data to instances. """
families = ["img"]
order = inventory.get_order(__file__, "ExtractMaya")
label = "Royal Render"
hosts = ["maya"]
targets = ["process.royalrender"]... |
from lxml import etree
import sys
TAGfile = open(sys.argv[1]+"/Testing/TAG", 'r')
dirname = TAGfile.readline().strip()
xmlfile = sys.argv[1]+"/Testing/"+dirname+"/Test.xml"
xslfile = sys.argv[2]
xmldoc = etree.parse(xmlfile)
xslt_root = etree.parse(xslfile)
transform = etree.XSLT(xslt_root)
result_tree = transform(xmld... |
import os
import glob
import shutil
header0 = "#ifndef PRECICE_NO_MPI\n";
header1 = "#include \"mpi.h\"\n";
header2 = "#endif\n";
filenames = os.listdir(".")
for filename in filenames:
#print "Looking at", filename
if os.path.isdir(filename):
nestedfiles = os.listdir(filename + "/")
for i in range(len... |
PDOs={
"RPDO1": [1, ('6040', "control_word", 2), ('6060', "op_mode", 1)],
"RPDO2": [1, ('607A', "target_position", 4), ('60FF', "target_velocity", 4)],
"RPDO3": [1, ('60C1sub1', "target_interpolated_position", 4)],
"RPDO4": [1, ('60FEsub1... |
# upload.py
def init():
from sys import stderr
from os import makedirs
from shutil import rmtree
print('init:', file=stderr)
rmtree(TMP_DIR, True)
makedirs(TMP_DIR)
def upload():
from sys import stderr
from requests import get
from requests import post
from requests import delet... |
"""
This file contains the tests for the community.py for TrustChain community.
"""
import time
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks, returnValue
from twisted.internet.threads import blockingCallFromThread
from Tribler.Test.Community.Trustchain.test_trustchain_utilitie... |
'''
Remote example with registry. CLIENT 2
@author: Daniel Barcelona Pons
'''
from pyactor.context import set_context, create_host, sleep, shutdown
from s4_registry import NotFound
class Server(object):
_ask = {'add', 'wait_a_lot'}
_tell = ['substract']
def add(self, x, y):
return x + y
def subs... |
def fourthPower(x):
'''
x: int or float.
'''
return square(x) * square(x) |
from time import sleep
import bitcodin
bitcodin.api_key = 'YOUR API KEY'
input_obj = bitcodin.Input(url='http://bitbucketireland.s3.amazonaws.com/Sintel-original-short.mkv')
print("INPUT REQUEST: %s\n\n" % input_obj.to_json())
input_result = bitcodin.create_input(input_obj)
print("INPUT RESULT: %s\n\n" % input_result.t... |
import os
os.environ['DJANGO_SETTINGS_MODULE']='settings'
import webapp2 as webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
import numpy as np
import cgi
import cgitb
cgitb.enable()
class maxsusQaqcPage(webapp.RequestHandler):
def get(self):
... |
"""
Pick causal SNPs from dap_ss/torus output.
============================================================================
AUTHOR: Michael D Dacre, mike.dacre@gmail.com
ORGANIZATION: Stanford University
LICENSE: MIT License, property of Stanford, use as you wish
VERSION: 0.1
CREATED: 201... |
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
exce... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Article',
fields=[
('id', models.AutoField(auto_created=T... |
'''
A Python program for testing the regrid2d.CurvRectRegridder class "by hand"
and also serves as a coding example of using this class.
@author: Karl Smith
'''
from __future__ import print_function
import numpy
import ESMP
from esmpcontrol import ESMPControl
from regrid2d import CurvRectRegridder
def createExampleData... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import (
compat_urllib_parse_urlencode,
compat_str,
compat_xpath,
)
from ..utils import (
ExtractorError,
find_xpath_attr,
fix_xml_ampersands,
float_or_none,
HEADRequest,
sanitized_Reque... |
from os.path import dirname, join as join_path
from setuptools import setup, find_packages
def _read(file_name):
sock = open(file_name)
text = sock.read()
sock.close()
return text
setup(
name = 'pyramid_twitterauth',
version = '0.2.1',
description = 'Twitter OAuth for Pyramid.',
author =... |
import unittest
import utils
class Solution:
def isMonotonic(self, a):
"""
:type a: List[int]
:rtype: bool
"""
increasing = None
for i in range(len(a) - 1):
if a[i] < a[i + 1]:
if increasing is None:
increasing = True
... |
name_of_student = "Meghan"
print name_of_student
statement = "Hello {0}, it's nice to meet you".format(name_of_student)
print statement
color = raw_input("Whats your favorite color? ")
response = "Well {0}, {1} is a great color, nice to meet you, have a great day".format(name_of_student, color)
print response |
import sys
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
version = "{}.{}".format(sys.version_info.major, sys.version_info.minor)
message = "Hello World from Flask in a uWSGI Nginx Docker container with Python {} - testing".format(
version
)
return message
@app.route... |
from muchos.config import Ec2DeployConfig
def test_ec2_cluster():
c = Ec2DeployConfig(
"muchos",
"../conf/muchos.props.example",
"../conf/hosts/example/example_cluster",
"../conf/checksums",
"../conf/templates",
"mycluster",
)
assert c.checksum_ver("accumulo",... |
from
class Config:
"""
A configuration class to specify parameters that will be passed
to your common crawl job.
"""
def __init__(self):
pass
@classmethod
def from_yaml(cls):
pass |
from panda3d.core import ColorBlendAttrib, NodePath, Vec4
from direct.interval.IntervalGlobal import *
from EffectController import EffectController
class FlashEffect(NodePath, EffectController):
def __init__(self):
NodePath.__init__(self, 'FlashEffect')
EffectController.__init__(self)
self.... |
__author__ = 'Lynch Lee'
import logging
filename = './emchat-py.log'
class Logger(object):
@staticmethod
def get_logger(name):
# create logger
u_logger = logging.getLogger(name)
# set log file path
logging.basicConfig(filename=filename)
# set level
u_logger.setLev... |
__doc__="""
Draw centre line
"""
import GlyphsApp
Font = Glyphs.font
FontMaster = Font.selectedFontMaster
selectedLayers = Font.selectedLayers
def drawPath( myCoordinates ):
try:
myRect = GSPath()
for thisPoint in myCoordinates:
newNode = GSNode()
newNode.type = thisPoint[1]
newNode.connection = thisPoint... |
from scattertext.features.FeatsFromSpacyDocAndEmpath import FeatsFromSpacyDocAndEmpath
from collections import Counter
class FeatsFromOnlyEmpath(FeatsFromSpacyDocAndEmpath):
def get_feats(self, doc):
return Counter()
def get_doc_metadata(self, doc, prefix=''):
return FeatsFromSpacyDocAndEmpath.get_doc_metadata(se... |
"""Leaky version of a Rectified Linear Unit activation layer."""
from keras import backend
from keras.engine.base_layer import Layer
from keras.utils import tf_utils
from tensorflow.python.util.tf_export import keras_export
@keras_export('keras.layers.LeakyReLU')
class LeakyReLU(Layer):
"""Leaky version of a Rectifie... |
from django import forms
from django.conf import settings
from django.utils.timezone import now
from bambu_blog.models import Post
class PostForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(PostForm, self).__init__(*args, **kwargs)
self.fields['date'].initial = now()
self.fi... |
from ray.rllib.agents.dqn.apex import ApexTrainer
from ray.rllib.agents.dqn.dqn import DQNTrainer, SimpleQTrainer, DEFAULT_CONFIG
from ray.rllib.utils import renamed_agent
DQNAgent = renamed_agent(DQNTrainer)
ApexAgent = renamed_agent(ApexTrainer)
__all__ = [
"DQNAgent", "ApexAgent", "ApexTrainer", "DQNTrainer", "D... |
import paramiko
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy)
print '*** Connecting...'
client.connect('mininet-internal', 22, 'mininet','mininet')
(iin,out,err) = client.exec_command('ls -la');
print iin
print out.read()
print err
client.close() |
from model.group import Group
import pytest
def test_add_group_data(app, db, data_groups, check_ui):
group = data_groups
with pytest.allure.step('Given a group list'):
old_groups = db.get_group_list()
with pytest.allure.step('When I add a group %s to the list' % group):
app.group.create(grou... |
import unittest
import testing.types as _types
from testing.builders import (
ColorGroups_Builder,
Digits_Builder,
File_Builder,
HardError_Builder,
Integers_Builder,
Reserved_Builder,
ValueOrError_Builder,
easy_Builder,
numerical_Builder,
)
class BuilderTest(unittest.TestCase):
d... |
import abc
from pypika.terms import Function
from pypika.utils import format_alias_sql
class _AbstractSearchString(Function, metaclass=abc.ABCMeta):
def __init__(self, name, pattern: str, alias: str = None):
super(_AbstractSearchString, self).__init__(self.clickhouse_function(), name, alias=alias)
s... |
from thrift.Thrift import *
from ttypes import *
from thrift.Thrift import TProcessor
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol, TProtocol
try:
from thrift.protocol import fastbinary
except:
fastbinary = None
class Iface:
def get(self, serviceName):
"""
Parameters... |
import json
from email.parser import Parser
from nose.tools import *
from flanker import _email
from flanker.mime import create
from flanker.mime.message import errors
from flanker.mime.message.part import MimePart
from ... import *
def from_python_message_test():
python_message = Parser().parsestr(MULTIPART)
m... |
from django.conf import settings
from django.http import HttpResponse
from django.test import TestCase, override_settings
from django_auth_ldap.backend import _LDAPUser
from django.test.client import RequestFactory
from typing import Any, Callable, Dict, Optional
from builtins import object
from oauth2client.crypt impo... |
from flask import Flask, Response, jsonify, request
from conftest import uuids, make_tarfile
import json
import os
import time
import typing
app = Flask(__name__)
def generate_sleep_intervals(num_exceptions: int = 6) -> int:
"""Generator to return sleep times for the first num_exceptions"""
count = 0
while ... |
import mock
from pytest import raises
from paasta_tools.secret_providers.vault import SecretProvider
def test_secret_provider():
SecretProvider(
soa_dir='/nail/blah',
service_name='universe',
cluster_names=['mesosstage'],
)
def test_decrypt_environment():
with mock.patch(
'pa... |
class List(object):
def __init__(self, *elements):
self._elements = elements
def __repr__(self):
return str(list(self._elements))
def filter(self, f):
return List(*filter(f, self._elements))
def map(self, f):
return List(*map(f, self._elements))
def reduce(self, f):
return reduce(f, self._elements)
l = L... |
"""
Copyright 2010 IO Rodeo Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
di... |
from __future__ import absolute_import, division, unicode_literals
import json
from copy import deepcopy
from datetime import datetime
from flask.ext.restful import reqparse
from changes.api.base import APIView, error
from changes.api.auth import get_project_slug_from_step_id, requires_project_admin
from changes.config... |
import jinja2
import os
import webapp2
from google.appengine.api import users
from google.appengine.ext import ndb
def guestbook_key(guestbook_name='default_guestbook'):
return ndb.Key('Guestbook', guestbook_name)
jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),... |
"""django template tags for contact display logic
"""
__author__ = 'mikie@google.com (Mika Raento)'
import urllib
from django import template
from django.utils.html import escape
from common.util import create_nonce
register = template.Library()
def is_not_contact(user, view, actor):
if not user or user.nick != view.... |
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
import jsonfield.fields
from django.utils.timezone import utc
class Migration(migrations.Migration):
replaces = [(b'utils', '0001_initial'), (b'utils', '0002_emailrecipient'), (b'utils', '0003_email'), (b'utils', '0004_... |
"""Various helper functions"""
import asyncio
import base64
import binascii
import datetime
import functools
import io
import os
import re
from urllib.parse import quote, urlencode
from collections import namedtuple
from pathlib import Path
import multidict
from . import hdrs
from .errors import InvalidURL
try:
fro... |
import datetime
import dateutil.parser
import json
import mox
import time
import unittest
from aliyun.ecs.model import (
AutoSnapshotPolicy,
AutoSnapshotExecutionStatus,
AutoSnapshotPolicyStatus,
Disk,
DiskMappingError,
Image,
Instance,
InstanceStatus,
InstanceType,
SecurityGroup... |
import mysql.connector
from model.group import Group
from model.contact import Contact
class DbFixture:
def __init__(self, host, name, user, password):
self.host = host
self.name = name
self.user = user
self.password = password
self.connection = mysql.connector.connect(host=h... |
import sys, lucene, unittest
from lucene import JArray
from PyLuceneTestCase import PyLuceneTestCase
from java.io import StringReader
from org.apache.lucene.analysis import Analyzer
from org.apache.lucene.analysis.core import \
LowerCaseTokenizer, WhitespaceTokenizer
from org.apache.lucene.analysis.tokenattributes ... |
import copy
import testtools
from shaker.engine.aggregators import traffic
class TestTrafficAggregator(testtools.TestCase):
def test_agent_summary(self):
aggregator = traffic.TrafficAggregator(None)
original = {
"stderr": "", "stdout": '',
"meta": [["time", "s"], ["Ping ICMP"... |
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from ...sipmessaging import SIPHeaderField
from ...sipmessaging import classproperty
class ContentEncodingSIPHeaderField(SIPHeaderField):
# noinspection PyNestedDecorators
@classproperty
@classmethod
def canoni... |
from socket import *
import os
NPROCS = 8
def tcp_server(address, handler):
sock = socket(AF_INET, SOCK_STREAM)
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sock.bind(address)
sock.listen(5)
# fork copies of the server
for n in range(NPROCS):
if os.fork() == 0:
break
while True:
client, addr... |
import copy
import random
import netaddr
from oslo.config import cfg
from sqlalchemy import and_
from sqlalchemy import event
from sqlalchemy import orm
from sqlalchemy.orm import exc
from neutron.api.v2 import attributes
from neutron.common import constants
from neutron.common import exceptions as n_exc
from neutron.c... |
import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v8.enums",
marshal="google.ads.googleads.v8",
manifest={"LegacyAppInstallAdAppStoreEnum",},
)
class LegacyAppInstallAdAppStoreEnum(proto.Message):
r"""Container for enum describing app store type in a legacy app
... |
"""Casual Volumetric Capture datasets.
Note: Please benchmark before submitted changes to this module. It's very easy
to introduce data loading bottlenecks!
"""
import json
from typing import List, Tuple
from absl import logging
import cv2
import gin
import numpy as np
from hypernerf import camera as cam
from hypernerf... |
"""
Created on Mon Jul 24 14:16:05 2017
@author: Leonardo Venancio
"""
print "Para posições positivas em 1D\n"
R1 = float(raw_input('Posicao Satelite: '))
R2 = float(raw_input('Posicao Satelite: '))
v=3
Obs = float(raw_input('Posicao do Observador: '))
T1= abs((R1-Obs)/v)
T2= abs((R2-Obs)/v)
print
print 'T1 = ' + str... |
"""Execute operations in a loop and coordinate logging and checkpoints."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import os
import tensorflow as tf
from agents.tools import streaming_mean
_Phase = collections.namedtuple(
'Phase... |
from uw_canvas.conversations import Conversations |
"""Log Parser for RTI Connext applications.
The class parse a log generated from DDS application when the
highest log verbosity is enabled. Then it will generate an output in
human-readable format.
Classes:
+ LogParser: parse a set of logs into human-redable format.
"""
from __future__ import absolute_import
import r... |
import pytest
from flask import Flask
from flask_restful import Api
from bluepill import BluePillStateError
from bluepill.server import BackgroundServer, get_application, get_api
@pytest.fixture
def server():
"""Create an instance of BackgroundServer for testing."""
return BackgroundServer()
def test_get_applic... |
from ciscoconfparse import CiscoConfParse
cisco_config = CiscoConfParse('cisco_ipsec.txt')
crypto = cisco_config.find_objects_wo_child(parentspec=r"^crypto map CRYPTO", childspec=r"set transform-set AES")
for aes in crypto:
print aes.text
for child in aes.children:
print child.text |
import sys
import numpy as np
target = int(sys.argv[1])
print 'Generating %d GB garbage...' % target
block_size = 1*1024*1024*1024/8
bulk = []
for i in range(target):
bulk.append(np.zeros(block_size, dtype='float64'))
raw_input('done') |
import os
import sys
import importlib
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
import pkg_resources
pkg_resources.working_set.add_entry(lib_path) |
"""Tests for Model subclassing."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
import six
from tensorflow.python import keras
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.eager import context
from ... |
"""
Stores jobs in a file governed by the :mod:`shelve` module.
"""
import shelve
import pickle
import random
import logging
from raksha.apscheduler.jobstores.base import JobStore
from raksha.apscheduler.job import Job
from raksha.apscheduler.util import itervalues
logger = logging.getLogger(__name__)
class ShelveJobSt... |
from common.methods import set_progress
from azure.storage.blob import BlockBlobService, PublicAccess
import os
from servicecatalog.models import ServiceBlueprint
from resources.models import Resource, ResourceType
from accounts.models import Group
def generate_options_for_file_name(control_value=None, **kwargs):
n... |
import unittest
from pydoop.test_utils import get_module
TEST_MODULE_NAMES = [
'test_local_fs',
'test_hdfs_fs',
'test_path',
'test_hdfs',
]
def suite(path=None):
suites = []
for module in TEST_MODULE_NAMES:
suites.append(get_module(module, path).suite())
return unittest.TestSuite(sui... |
import abc
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
import packaging.version
import pkg_resources
import google.auth # type: ignore
import google.api_core # type: ignore
from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # typ... |
from __future__ import unicode_literals
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = '//phdops.kblin.org'
RELATIVE_URLS = False
FEED_ALL_ATOM = 'feeds/all.atom.xml'
CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml'
DELETE_OUTPUT_DIRECTORY = True |
import os
import sys
sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('./../src'))
from inscriptis.metadata import __copyright__, __author__, __version__
extensions = ['sphinx.ext.autodoc',
'sphinx.ext.viewcode',
'sphinx.ext.githubpages',
'sphinx.ext.napoleon',
'myst_parser']
... |
from typing import Iterable, Set, Union
from airflow.models.taskinstance import TaskInstance
from airflow.utils import timezone
from airflow.utils.log.logging_mixin import LoggingMixin
from airflow.utils.session import create_session, provide_session
from airflow.utils.state import State
XCOM_SKIPMIXIN_KEY = "skipmixin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.