content string |
|---|
def youtube_video_whitelist(iframe_tag):
"""
Given an HTML iframe element, pass it through the filters we impose on
embedded YouTube video.
Returns the HTML iframe element as a string, which can be reinserted
at the position of the element that was passed.
"""
from bs4 import BeautifulSoup
... |
class Board:
def __init__(self, x, y):
self.x = x
self.y = y
self.ships = []
self.shots = []
def drawBoard(self, player, ships):
for y in range(0, self.y+1):
row = ""
for x in range(0, self.x+1):
if x == 0:
i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import time
import struct
import marshal
import traceback
try: from cStringIO import StringIO
except: from StringIO import StringIO
def pack_int(i):
return struct.pack(">i", i)
def pack_short(i):
return struct.pack(">h", i)
def pac... |
"""
Database manipulations
Dynamically identifies the correct database to use for the current domain
"""
from pandora import box
from django.utils import simplejson as json
import UserDict
from os import path
FILE_ROOT = path.abspath(path.dirname(__file__))
HARDTREE_DB_SETTINGS_FILE = path.join(FILE_ROOT, 'dbsettin... |
from bluetooth import *
import blumote
import cPickle
import os
import sys
import time
class Blumote_Client(blumote.Services):
def __init__(self):
blumote.Services.__init__(self)
self.addr = None
def find_blumote_pods(self, pod_name = None):
if pod_name is None:
pod_name = self.service["name"]
print "... |
# This Python file uses the following encoding: utf-8
### Import Modules ###
import sqlite3 # databases
#--------------------#
#-- Initialisation --#
#--------------------#
# create the connection object that represents the database
connection = sqlite3.connect('budget.db')
# create a Cursor object and call its exec... |
"""Task state related logic."""
from cylc import LOG
from cylc.prerequisite import Prerequisite
from cylc.task_id import TaskID
from cylc.task_outputs import (
TaskOutputs,
TASK_OUTPUT_EXPIRED, TASK_OUTPUT_SUBMITTED, TASK_OUTPUT_SUBMIT_FAILED,
TASK_OUTPUT_STARTED, TASK_OUTPUT_SUCCEEDED, TASK_OUTPUT_FAILED... |
# -*- coding: utf-8 -*-
import diaper
import fauxfactory
import pytest
from wrapanapi import VmState
from . import do_scan
from cfme import test_requirements
from cfme.control.explorer.conditions import VMCondition
from cfme.control.explorer.policies import HostCompliancePolicy
from cfme.control.explorer.policies impo... |
from PyQt4 import QtSql, QtCore
from tableDeBase import TableDeBase
class TableRatios (TableDeBase):
def __init__(self):
TableDeBase.__init__(self,"Ratios")
self.setField(('Maillage','Version','RatioMax','RatioMin','Quartile1','Mediane','Quartile3','Moyenne'))
self.setTypeField(('in... |
import hashlib
import random
from app import db
class User(db.Model):
_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
user = db.Column(db.String)
email = db.Column(db.String)
password = db.Column(db.String)
apikey = db.Column(db.String)
def __init__(self, user, password, ema... |
from abc import ABCMeta, abstractmethod
from typing import Dict
from Src.BioAnalyzer.CrossCutting.DTOs.GenePrioritization.NetworkDto import NetworkDto
from Src.BioAnalyzer.CrossCutting.Filters.GenePrioritization.FeSingleNetwork import FeSingleNetwork
from Src.Core.Data.MongoRepositoryBase import MongoRepositoryBase
... |
#!/usr/bin/python
import logging
from subprocess import Popen,PIPE
import re
import pdb
from logging.handlers import SMTPHandler
from creds import USER,PASS
# logger
logger = logging.getLogger('Alert - email')
# Handler
ch = SMTPHandler( ('smtp.gmail.com',465) ,'<EMAIL>' ,'<EMAIL>', 'Alert - Email ', credentials=(U... |
bl_info = {
"name": "Manage UI translations",
"author": "Bastien Montagne",
"version": (1, 1, 2),
"blender": (2, 75, 0),
"location": "Main \"File\" menu, text editor, any UI control",
"description": "Allow to manage UI translations directly from Blender "
"(update main po files, update s... |
from math import *
# -----------------------------------------------------------------------------
# Set of helper functions
# -----------------------------------------------------------------------------
def normalize(vect, tolerance=0.00001):
mag2 = sum(n * n for n in vect)
if abs(mag2 - 1.0) > tolerance:
... |
"""
PR Watch app - PR sandbox creation management command.
"""
from urllib.parse import urlparse
from django.core.management.base import BaseCommand
from instance.models.deployment import DeploymentType
from instance.utils import create_new_deployment
from pr_watch.github import get_pr_by_number
from pr_watch.models ... |
#!/usr/bin/env python
import json
import os
import urllib2
from scriptCommon import catchPath
def upload(options):
request = urllib2.Request('http://melpon.org/wandbox/api/compile.json')
request.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(request, json.dumps(options))
re... |
from flask.ext.wtf import validators #, ValidationError
from flask.ext.wtf import Form, TextField, SelectField
THEMES = (
(u'cuidado',)*2,
(u'familia',)*2,
(u'emergencia',)*2,
(u'medicamentos',)*2,
(u'regional',)*2,
)
class ContribForm(Form):
"""Form that receives contributions from users to... |
import os
import sys
from gi.repository import GLib, GObject, Gio, ModemManager
"""
The ModemWatcher class is responsible for monitoring ModemManager
"""
class ModemWatcher:
"""
Constructor
"""
def __init__(self):
# Flag for initial logs
self.initializing = True
# Setup DBus m... |
from openerp import models, api, _
import logging
_logger = logging.getLogger(__name__)
try:
import phonenumbers
except ImportError:
_logger.debug('Cannot import phonenumbers')
class wizard_create_crm_phonecall(models.TransientModel):
_name = "wizard.create.crm.phonecall"
@api.multi
def button_... |
"""
.. _tut-visualize-evoked:
Visualizing Evoked data
=======================
This tutorial shows the different visualization methods for
`~mne.Evoked` objects.
As usual we'll start by importing the modules we need:
"""
import os
import numpy as np
import mne
#######################################################... |
# -*- coding: utf-8 -*-
import datetime
import random
import string
from lxml.html import parse
from urllib import urlencode
from urllib2 import urlopen
from urlparse import urljoin
from urlparse import urlparse
from openerp import models, fields, api, _
def VALIDATE_URL(url):
if urlparse(url).scheme not in ('h... |
from django.db import models
from djforms.core.models import GenericContact, GenericChoice
class ParkingTicketAppeal(GenericContact):
college_id = models.CharField(
"Carthage ID#", max_length=10
)
residency_status = models.ForeignKey(
GenericChoice,
related_name="parking_... |
# pylint: disable=missing-docstring,invalid-name,using-constant-test,invalid-sequence-index,undefined-variable
dictionary = dict()
key = 'key'
if 'key' in dictionary: # [consider-using-get]
variable = dictionary['key']
if 'key' in dictionary: # [consider-using-get]
variable = dictionary['key']
else:
var... |
# USAGE
# python stitch.py --first images/bryce_left_01.png --second images/bryce_right_01.png
# import the necessary packages
from follow_hot.panorama import Stitcher
import argparse
import imutils
import cv2
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-f",... |
# -*- coding: utf-8 -*-
"""
orgco
Copyright (c) 2013, 2015 Friedrich Paetzke (<EMAIL>)
All rights reserved.
"""
import os
from pygments import highlight as pyg_highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name, guess_lexer
from pygments.styles import get_style_by_n... |
#!/usr/bin/env python
"""
@package mi.dataset.parser.dosta_ln_wfp_sio_mule
@file marine-integrations/mi/dataset/parser/dosta_ln_wfp_sio_mule.py
@author Christopher Fortin
@brief Parser for the dosta_ln_wfp_sio_mule dataset driver
Release notes:
Initial Release
"""
__author__ = 'Christopher Fortin'
__license__ = 'Apa... |
# _ _ __ __
# __| |(_)__ _ _ _ __ _ ___ _ \ \ / /
# / _` || / _` | ' \/ _` / _ \_| ' \ V /
# \__,_|/ \__,_|_||_\__, \___(_)_||_\_/
# |__/ |___/
#
# INSECURE APPLICATION WARNING
#
# django.nV is a PURPOSELY INSECURE web-application
# meant to demonstrate Django se... |
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import os
path = "/Users/petermarinov/msci project/all code/50 hearts preferential/50 hearts anis 0.99 corr 0.99/50 hearts 0.333 restitution"
previous_fib = np.genfromtxt("/Users/petermarinov/msci project/all code/intermittent /par... |
import collections
import fnmatch
import itertools
import random
from oslo_config import cfg
from oslo_context import context
from oslo_log import log
import oslo_messaging
from six import moves
from six.moves.urllib import parse as urlparse
from stevedore import extension
from ceilometer.agent import plugin_base
fro... |
import ldap
import django
from django.db.backends import BaseDatabaseFeatures, BaseDatabaseOperations, BaseDatabaseWrapper
from django.db.backends.creation import BaseDatabaseCreation
class DatabaseCreation(BaseDatabaseCreation):
def create_test_db(self, verbosity=1, autoclobber=False):
"""
Create... |
"""Main Spotifyt module. Intended for argument parsing"""
import argparse
import sys
import tempfile
import os
import spotifyt.spoty_handler.playlist_parser
import spotifyt.spoty_handler.authentication
import spotifyt.media_handler.downloader
import spotifyt.banner
SYT_TMP_DIR = tempfile.gettempdir() + '/spotifyt/'
... |
from pyanaconda.ui.tui import simpleline as tui
from pyanaconda.ui.tui.tuiobject import TUIObject, YesNoDialog
from pyanaconda.ui.common import Spoke, StandaloneSpoke, NormalSpoke, collect
from pyanaconda.users import validatePassword, cryptPassword
import re
from collections import namedtuple
from pyanaconda.iutil imp... |
from autotest.client.shared import error, utils
from virttest import virsh, utils_libvirtd
from xml.dom.minidom import parseString
def run_virsh_domifstat(test, params, env):
"""
Test command: virsh domifstat.
The command can get network interface stats for a running domain.
1.Prepare test environmen... |
"""
Created on Sun Sep 17 16:36:46 2017
@author: dariocorral
"""
import pandas as pd
from tickers import Tickers
from quotes import Quotes
from candles import Candles
class Indicators(object):
"""
Trading Indicators
"""
def __init__ (self):
self.__tickers = Tickers()
sel... |
class Modifier(object):
'''
Modifier object for contextual class modification. When it comes to python, there's no guarantee
that users will always consent adults while monkey patching stuff. This can hurt later, because
we don't know how much stuff we've patched along the way.
For example, the API... |
"Utility for deleting personal information when no longer required"
import logging
from wsrc.site.usermodel.models import Player, Season, Subscription
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.INFO)
def to_initial(name):
return name[:1] + "."
# We don't remove player's names as they are stil... |
"""
defines class that describes C++ typedef declaration
"""
import declaration
import dependencies
class typedef_t( declaration.declaration_t ):
"""describes C++ typedef declaration"""
def __init__( self, name='', type=None ):
"""creates class that describes C++ typedef"""
declar... |
from odoo import fields, models, api, SUPERUSER_ID
class UtmCampaign(models.Model):
_inherit = 'utm.campaign'
_description = 'UTM Campaign'
quotation_count = fields.Integer('Quotation Count', groups='sales_team.group_sale_salesman', compute="_compute_quotation_count")
invoiced_amount = fields.Integer(... |
NSEEDS=512
MAX_SEEDS_PER_ASN=2
MIN_BLOCKS = 337600
# These are hosts that have been observed to be behaving strangely (e.g.
# aggressively connecting to every node).
SUSPICIOUS_HOSTS = {
"130.211.129.106", "178.63.107.226",
"83.81.130.26", "88.198.17.7", "148.251.238.178", "176.9.46.6",
"54.173.72.127", ... |
import os
from app import flask_app, time, datetime, parse_date, db
from flask import flash, redirect, session, Response, url_for, render_template, Blueprint, request, send_from_directory
from flask.ext.login import login_required
from flask.ext.login import current_user
# from jinja2 import Environment
import jinja2
f... |
"""NDArray configuration API."""
import ctypes
from ..base import _LIB
from ..base import c_str_array, c_handle_array
from ..base import NDArrayHandle, CachedOpHandle
from ..base import check_call
def _monitor_callback_wrapper(callback):
"""A wrapper for the user-defined handle."""
def callback_handle(name,... |
import unittest
from federatedml.util.validation_strategy import ValidationStrategy
import numpy as np
from federatedml.util import consts
from federatedml.param.evaluation_param import EvaluateParam
class TestValidationStrategy(unittest.TestCase):
def setUp(self) -> None:
self.role = 'guest'
sel... |
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import sys
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
README = read('README.rst')
class PyTest(TestCommand):
def finalize_options(se... |
# -*- coding: utf-8 -*-
import mock
import pytest
import unittest
from nose.tools import * # noqa
from tests.base import OsfTestCase, get_default_metaschema
from osf_tests.factories import ProjectFactory, UserFactory
from framework.auth import Auth
from addons.base.tests.models import (OAuthAddonNodeSettingsTestSu... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
import base64
import json
try:
import yaml
has_lib_yaml = True
except ImportError:... |
import copy
from django import forms
from django.db.models.fields import FieldDoesNotExist
from django.utils.translation import ugettext_lazy as _
from django.contrib.gis.db.models.fields import GeometryField
import floppyforms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Bu... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from DIRAC.Core.Workflow.Parameter import *
from DIRAC.Core.Workflow.Module import *
from DIRAC.Core.Workflow.Step import *
from DIRAC.Core.Workflow.Workflow import *
bodyTestApp = """class TestAppModule:
... |
# coding: utf-8
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
import sys # noqa: F401
... |
"""
This linter looks for table that were not updated recently
"""
from collections import OrderedDict
from datetime import datetime
from time import time
from indexdigest.utils import LinterEntry
from .linter_0028_data_too_old import get_time_columns, get_boundary_times
def check_data_not_updated_recently(database... |
"""
A PyrobotSimulator world. A large room with two robots and
two lights.
(c) 2005, PyroRobotics.org. Licensed under the GNU GPL.
"""
from pyrobot.simulators.pysim import TkSimulator, TkPioneer, \
PioneerFrontSonars, PioneerFrontLightSensors
def INIT():
# (width, height), (offset x, offset y), scale:
s... |
"""Tests of disco_route53"""
from unittest import TestCase
from boto.route53.record import Record
from moto import mock_route53, mock_sns
from disco_aws_automation import DiscoRoute53
TEST_DOMAIN = 'example.com.'
TEST_DOMAIN2 = 'foo.com.'
TEST_RECORD_NAME = 'subdomain.example.com.'
TEST_RECORD_NAME2 = 'subdomain.foo... |
import httplib, urllib
from threading import Thread
from datetime import datetime
from django.db import models
from django.db.models.signals import post_save
from locations.models import Location
from standards.models import Standard, WaterUseType
from reporters.models import Reporter
from wqm.models import... |
import random
import re
from datetime import datetime
import urllib
import hashlib
from sqlalchemy.ext.declarative import AbstractConcreteBase
from flaskext.mail import Message
from flask import url_for, abort, render_template, g
from btnfemcol import db, cache, mail
from btnfemcol.utils import Hasher
class Site... |
#!/usr/bin/python
from subprocess import *
from time import sleep, strftime
from datetime import datetime
import urllib
import urllib2
import json
import sys
#################
# BOX constants #
#################
boxId = 1
boxLatitude = 53.3430708
boxLongitude = -6.2747221
questionId = ""
question = ""
if len(sys.ar... |
from test_framework import DobbscoinTestFramework
from dobbscoinrpc.authproxy import AuthServiceProxy, JSONRPCException
from util import *
def get_sub_array_from_array(object_array, to_match):
'''
Finds and returns a sub array from an array of arrays.
to_match should be a unique idetifier of a sub... |
from django.db import models
from django.contrib.auth.models import User
import logging
#from django.db.models import Avg, Max, Min, Count
import random
_NAME_LENGTH=30
class Goal(models.Model):
name = models.CharField(max_length=_NAME_LENGTH, primary_key=True)
created = models.DateTimeField(auto_now_add=T... |
# coding=utf-8
"""Provider test code for Generic Provider."""
from __future__ import unicode_literals
from datetime import date, datetime, timedelta
from dateutil import tz
from medusa.providers.generic_provider import GenericProvider
import pytest
sut = GenericProvider('FakeProvider')
@pytest.mark.parametrize(... |
"""Independent identical distributed vector of random variables."""
from copy import deepcopy
import numpy
import chaospy
from ..baseclass import Distribution
from .joint import J
class Iid(J):
"""
Opaque method for creating independent identical distributed random
variables from an univariate variable.
... |
"""
Copyright 2015 Hewlett-Packard
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, softwar... |
# Save a dwarsprofiel as DXF
from dxfwrite import DXFEngine as dxf
def draw_z(drawing, line, measurement):
x = line.distance_to_midpoint(measurement.point)
y = measurement.z1 - 0.2
text = "({x:.2f}, z1={y:.2f})".format(x=x, y=measurement.z1)
drawing.add(dxf.text(
text,
inser... |
"""
websocket - WebSocket client library for Python
Copyright (C) 2010 Hiroki Ohtani(liris)
This library 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 2.1 of the License, ... |
__author__ = "Jordonbc"
import logging
import time
import os
import sys
if not os.path.exists("JDE/Logs"):
os.mkdir("JDE/Logs")
logging.basicConfig(filename='JDE/Logs/' + str(time.strftime('%d-%m-%Y-%H-%M%p') + ".log"), level=logging.DEBUG,
datefmt='%I:%M:%S %p',
format='%(... |
#!/usr/bin/python
import sys
sys.path.append("server/")
from server.ext.debugger.elt.database import db_cli
from subprocess import Popen
import code
import os
from threading import Timer
db = []
log = []
pox = []
mn = []
timer = None
debug_sample = [
"ext.debugger.elt.of_01_debug",
"--fake_debugger=0.1",
... |
import sys
import os
import time
import subprocess
from util import system
from util.log import LOG as logger
PROFILE_PATH = "config.android.profile."
class Android(object):
def __init__(self, profile="", directory=""):
if directory == "":
self.setDirectory(system.APP_TMP)
else:
... |
import numpy as np
from scipy.stats import chi
import nose.tools as nt
import numpy.testing.decorators as dec
from ...distributions import chisq
from ...tests.decorators import set_sampling_params_iftrue, set_seed_iftrue, rpy_test_safe
from ...tests.flags import SMALL_SAMPLES, SET_SEED
from .. import affine as AC
# ... |
#!/usr/bin/python
"""MobWrite Uploader
Copyright 2009 Google Inc.
http://code.google.com/p/google-mobwrite/
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... |
#!/usr/local/bin/python
from unittest import TestCase
from solver import Solver
__author__ = 'brcoulter'
class TestSolver(TestCase):
def test_simple_int_solver(self):
import random
random.seed(1)
class IntSolver(Solver):
def __init__(self, state=-10):
self._sta... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'CostCenter.account_number'
db.alter_column(u'accountin... |
import pandas as pd
import requests
class vaAPI(object):
""" Class to pull links to images from Victoria and Albert API
for more documentation, see http://www.vam.ac.uk/api/
"""
def __init__(self, before, after, limit = 45, img = 1, offset = 1):
self.base = 'http://www.vam.ac.uk/api/json/mu... |
import os
from spack import *
class Nauty(AutotoolsPackage):
"""nauty and Traces are programs for computing automorphism groups of
graphsq and digraphs"""
homepage = "http://pallini.di.uniroma1.it/index.html"
url = "http://pallini.di.uniroma1.it/nauty26r7.tar.gz"
version('2.6r7', 'b2b18e03ea... |
import numpy
import random
class MFRandom(object):
""" A class to centralise random numbers.
This is centralised so that a seed can be set in a single place in order
to make simulations repeatable. This is particularly relevant in the case
of NEURON simulations, which are saved and spawned in anothe... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
COV = None
if os.environ.get('FLASK_COVERAGE'):
import coverage
COV = coverage.coverage(branch=True, include='app/*')
COV.start()
from app import create_app, db
from app.models import Category, Item, User, Message
from flask.ext.script import Manager, Shell... |
#!/Users/edelsonc/anaconda/bin/python
"""
This script runs the SharkCubed web applications
author: edelsonc
"""
import sys
import os
import webbrowser
import pycoil
import jinja2.ext
from flask import Flask, render_template, request, redirect
# checks if the file is running as an app or in normal Python and directs f... |
"""An implementation of a binary trie for storing w bit integers
This structure is able to store elements, x, where int(x) is an unsigned
w bit integer.
"""
from utils import new_array, w, binfmt
from base import BaseSet
class BinaryTrie(BaseSet):
class Node(object):
def __init__(self):
self... |
from makeblog.post import Post
from makeblog.author import Author
from makeblog.templating import jinja, render
from makeblog.plugins import (
PluginMount,
PreRenderPlugin,
RenderPlugin,
PostRenderPlugin,
)
from datetime import datetime
from operator import attrgetter
from os import listdir, system, wal... |
from localization import Province, Country, Store
from user import User
from receipt import Receipt, Item, Category
import datetime
def populate_all_tables(session):
populate_provinces_tbl(session)
def populate_provinces_tbl(session):
canada = Country("CAN", "Canada")
ontario = Province('Ontario','ON... |
import functools
from typing import List
from test_framework import generic_test
from test_framework.random_sequence_checker import (
binomial_coefficient, check_sequence_is_uniformly_random,
compute_combination_idx, run_func_with_retries)
from test_framework.test_utils import enable_executor_hook
def random... |
# -*- coding: utf-8 -*-
import os
from sigal import utils
CURRENT_DIR = os.path.dirname(__file__)
SAMPLE_DIR = os.path.join(CURRENT_DIR, 'sample')
def test_copy(tmpdir):
filename = 'exo20101028-b-full.jpg'
src = os.path.join(SAMPLE_DIR, 'pictures', 'dir2', filename)
dst = str(tmpdir.join(filename))
... |
"""
Django settings for app1 project.
Generated by 'django-admin startproject' using Django 1.11.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# B... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from deepy.core.env import EPSILON
from deepy.core import neural_computation
import theano.tensor as T
@neural_computation
def cross_entropy(y, target_index, mask=None, after_softmax=False):
if y.ndim == 3:
return cross_entropy_3d(y, target_index, mask, afte... |
"""This example creates a product base rate.
To determine which base rates exist, run get_all_base_rates.py.
Tags: BaseRateService.createBaseRates
"""
__author__ = 'Nicholas Chen'
# Import appropriate modules from the client library.
from googleads import dfp
PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE'
RATE_CARD_ID = 'I... |
#!/usr/bin/env python
from __future__ import division, print_function, absolute_import
import datetime
import os
import sys
from os.path import join as pjoin
if sys.version_info[0] >= 3:
from io import StringIO
else:
from cStringIO import StringIO
import numpy as np
from numpy.testing import (TestCase, asse... |
from mixer.backend.sqlalchemy import mixer
from datetime import datetime
dt_now = datetime.now()
__model__ = 'carepoint.models.cph.patient.Patient'
patient_default = mixer.blend(
__model__,
pat_id=1,
cmt_id=1,
pat_status_cn=1,
pat_type_cn=1,
nh_pat_id='NhPatId',
chart_id='ChartId',
l... |
from collections import namedtuple
import unittest
import logging
from systrace import decorators
from systrace.tracing_agents import battor_trace_agent
from battor import battor_wrapper
from devil.android import battery_utils
from devil.utils import battor_device_mapping
from devil.utils import find_usb_devices
moc... |
#!/usr/bin/env python3
import warnings
import torch
from .. import settings
from .deprecation import bool_compat
from .warnings import NumericalWarning
def _default_preconditioner(x):
return x.clone()
@torch.jit.script
def _jit_linear_cg_updates(
result, alpha, residual_inner_prod, eps, beta, residual, p... |
from telemetry.core.platform import platform_backend
from telemetry.core.platform import proc_util
class CrosPlatformBackend(platform_backend.PlatformBackend):
def __init__(self, cri):
super(CrosPlatformBackend, self).__init__()
self._cri = cri
def StartRawDisplayFrameRateMeasurement(self):
raise No... |
def generateWignerMatrix(matrix_size):
matrix = np.zeros((matrix_size, matrix_size)) #Form a symmetric matrix
newSize = (matrix_size*(matrix_size+1))/2
bern = bernoulli.rvs(0.5, size=newSize) #Get the random bernoulli variates
for i in range(0, len(bern)):
if bern[i]==0:
bern[i]=-1
... |
"""
Copyright 2014-2021 Vincent Texier <<EMAIL>>
DuniterPy 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.
DuniterPy is distributed in the... |
from __future__ import absolute_import, division, print_function
from simdna.simdnautil import dinuc_shuffle, util
from simdna.synthetic.substringgen import AbstractSubstringGenerator
from simdna.synthetic.quantitygen import FixedQuantityGenerator, AbstractQuantityGenerator
from collections import OrderedDict
import ... |
from __future__ import annotations
import logging
import sys
import traceback
from typing import Any, Mapping, TYPE_CHECKING
from ai.backend.common.events import AgentErrorEvent
from ai.backend.common.logging import BraceStyleAdapter
from ai.backend.common.types import (
AgentId,
LogSeverity,
)
from ai.backen... |
import picross
import sys
import optparse
def main():
parser = optparse.OptionParser(usage=sys.argv[0]+' [options]')
parser.add_option('--req',action='store',type='int',dest='req',default=0xc0,help='request')
parser.add_option('--val',action='store',type='int',dest='val',default=0,help='value')
parser.... |
"""State module: contains State class"""
__all__ = ['State']
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.showbase.DirectObject import DirectObject
import types
class State(DirectObject):
notify = directNotify.newCategory("State")
# this 'constant' can be used to specify that... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
import chunked_uploads.models
from django.conf import settings
import django_extensions.db.fields
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependen... |
"""
Provides functionality to run a Hadoop job using a Jar
"""
import logging
import os
import random
import luigi.hadoop
import luigi.hdfs
logger = logging.getLogger('luigi-interface')
def fix_paths(job):
"""
Coerce input arguments to use temporary files when used for output.
Return a list of tempora... |
from django.shortcuts import render, redirect
from django.utils.translation import ugettext as _
from django.http import Http404
from weblate.lang.models import Language
from weblate.trans.models import Project, Dictionary, Change
from urllib import urlencode
def show_languages(request):
return render(
re... |
# backend.py - compile LaTeX to PDF, optionally open in viewer, count PDF pages
import errno
import os
import platform
import re
import subprocess
from . import tools
__all__ = ['compile', 'Npages']
PLATFORM = platform.system().lower()
OPTS = {'latexmk': ['-silent'],
'texify': ['--batch', '--verbose', '--q... |
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import TestCase, assert_array_almost_equal, dec, \
assert_equal, assert_
from common import FUNCS_TP, FLAPACK_IS_EMPTY, CLAPACK_IS_EMPTY, FUNCS_FLAPACK, \
FUNCS_CLAPACK, ... |
from collections import OrderedDict
from typing import Dict, Type
from .base import TenantServiceTransport
from .grpc import TenantServiceGrpcTransport
from .grpc_asyncio import TenantServiceGrpcAsyncIOTransport
# Compile a registry of transports.
_transport_registry = OrderedDict() # type: Dict[str, Type[TenantSer... |
import sys
import json
import itertools
import tempfile
import os
import fcntl
import time
import errno
assert len(sys.argv) > 2
def process(file, root):
try:
values = json.load(file)
keys = [x['file'] for x in values]
except:
values = []
keys = []
out = dict(i... |
"""
Decorators for views based on HTTP headers.
"""
import logging
from calendar import timegm
from functools import wraps
from django.http import HttpResponseNotAllowed
from django.middleware.http import ConditionalGetMiddleware
from django.utils.cache import get_conditional_response
from django.utils.decorators imp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.