content stringlengths 4 20k |
|---|
from iptest.assert_util import skiptest
from System import DateTime
from clr import StrongBox
from iptest.cominterop_util import *
com_type_name = "DlrComLibrary.Properties"
com_obj = getRCWFromProgID(com_type_name)
test_sanity_types_data = [
("pBstr", "abcd"),
("pVariant", 42),
("pVariant", "42"),
("... |
#!/usr/bin/env python
#coding=utf-8
import cyclone.auth
import cyclone.escape
import cyclone.web
import decimal
import datetime
from toughradius.manage import models
from toughradius.manage.customer import customer_forms
from toughradius.manage.customer.customer import CustomerHandler
from toughlib.permit import permi... |
#!/usr/bin/env python
"""
change file mode bits
"""
import os
import DIRAC
from COMDIRAC.Interfaces import critical
from COMDIRAC.Interfaces import DSession
from COMDIRAC.Interfaces import DCatalog
from COMDIRAC.Interfaces import pathFromArgument
from DIRAC.Core.Base import Script
from DIRAC import S_OK
class Para... |
import logging
import urllib
from edge.dateutility import DateUtility
from edge.writer.proxywriter import ProxyWriter
class Writer(ProxyWriter):
def __init__(self, configFilePath):
super(Writer, self).__init__(configFilePath)
def _generateUrl(self, requestHandler):
url = self._configuration.g... |
"""Options for the redis plugin"""
from __future__ import absolute_import, division, print_function, with_statement, unicode_literals
import oz
oz.options(
redis_cache_connections=dict(type=bool, default=True, help="Whether to cache the redis connection between requests to prevent TCP slow start"),
redis_hos... |
import unittest
import numpy
import chainer
from chainer import cuda
from chainer import functions
from chainer.functions.connection import linear
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
@testing.parameterize(*testing.prod... |
"""Example of hierarchical training using the multi-agent API.
The example env is that of a "windy maze". The agent observes the current wind
direction and can either choose to stand still, or move in that direction.
You can try out the env directly with:
$ python hierarchical_training.py --flat
A simple hierar... |
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_lazy
from ..core.config import config
from ..utils.rest_api... |
from sympy.core import S, Symbol, sympify
from sympy.utilities.source import get_class
from sympy.queries import Q, ask
from sympy.logic.boolalg import fuzzy_not
def refine(expr, assumptions=True):
"""
Simplify an expression using assumptions
Gives the form of expr that would be obtained if symbols
in... |
CABLETERMINATION = """
{% if value %}
<a href="{{ value.parent.get_absolute_url }}">{{ value.parent }}</a>
<i class="mdi mdi-chevron-right"></i>
<a href="{{ value.get_absolute_url }}">{{ value }}</a>
{% else %}
—
{% endif %}
"""
CABLE_LENGTH = """
{% if record.length %}{{ record.length }} {{ reco... |
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.base import *
from marvin.lib.utils import (validateList, cleanup_resources)
from marvin.lib.common import *
from nose.plugins.attrib import attr
from marvin.codes import PASS,FAIL
_multiprocess_shared_ = True
class Services:
def __init__(se... |
"""Collection of helper methods.
All containing methods are legacy helpers that should not be used by new
components. Instead call the service directly.
"""
from homeassistant.components.fan import (
ATTR_DIRECTION,
ATTR_OSCILLATING,
ATTR_PERCENTAGE,
ATTR_PERCENTAGE_STEP,
ATTR_PRESET_MODE,
ATTR... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
str = unicode
#===============================================================================
import os
#=============================================================... |
import base64
import hashlib
import collections
import json
import os
import signal
import shutil
import urllib2
from subprocess import check_call, call, check_output
import wget
from broot.builder import FedoraBuilder
from broot.builder import DebianBuilder
class Root:
STATE_NONE = "none"
STATE_READY = "re... |
"""
melangeadmin commandline
"""
import cmdln
import os
import shutil
import sys
def startproject(projectname, template):
"""
:param projectname: directory to copy template to
:param template: project template name
:return:
"""
if os.path.isdir(projectname):
print("directory already e... |
import os
import errno
import signal
import subprocess
import sys
import unittest
# Since we execute this script directly as part of the unit tests, we need to ensure
# that Tools/Scripts is in sys.path for the next imports to work correctly.
script_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname... |
import Adafruit_BBIO.GPIO as GPIO
import time
import thread
GPIO.setup("P8_10", GPIO.IN)
GPIO.setup("P8_12", GPIO.IN)
GPIO.setup("P8_14", GPIO.IN)
GPIO.setup("P8_18", GPIO.OUT) # Level 1
GPIO.setup("P8_20", GPIO.OUT) # Level 2
GPIO.setup("P8_22", GPIO.OUT) # Level 3
present_level = 1
old_switch_... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
from scrapy import Field, Item
from scrapy.contrib.loader import ItemLoader
from scrapy.contrib.loader.processor import TakeFirst, MapCompose, Compose
class Boredpand... |
import pytest
from api.base.settings.defaults import API_BASE
from osf_tests.factories import (
PreprintProviderFactory,
AuthUserFactory,
)
from reviews.permissions import GroupHelper
@pytest.mark.django_db
class TestPreprintProviderExists:
# Regression for https://openscience.atlassian.net/browse/OSF-76... |
"""
This is the code behind the Switching Eds blog post:
http://matthewearl.github.io/2015/07/28/switching-eds-with-python/
See the above for an explanation of the code below.
To run the script you'll need to install dlib (http://dlib.net) including its
Python bindings, and OpenCV. You'll also need to obtain the... |
from netforce.model import Model, fields, get_model
class StatementLine(Model):
_name = "account.statement.line"
_order = "date,id"
_name_field = "description"
_fields = {
"statement_id": fields.Many2One("account.statement", "Statement", required=True, on_delete="cascade"),
"state": fi... |
#!/usr/bin/env python
# given name, family name, email, phone
# a - add new person
# l - list all people
# q - quit
# f - find people (search through names + email)
# w - write info to disk
# r - read info from disk
# blog.lerner.co.il
f = open('address.csv', 'r+w')
addresses = {}
stop = False
while not stop:
com... |
import sys
import gc
import timeit
import subprocess
import compileall
from django.conf import settings
class PerformanceTest(object):
"""
Test query performance for a set of views. It will create a new database
that has the some content as a template database, test views against it and
eventually wi... |
from django.contrib.auth.decorators import login_required
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.forms import HiddenInput
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound
from django.views.decorators.csrf import csrf_protect
from djan... |
import os
from flask import current_app
from flask import Flask
from flask import g
from flask_login import LoginManager
from werkzeug.local import LocalProxy
from wiki.core import Wiki
from wiki.web.user import UserManager
class WikiError(Exception):
pass
def get_wiki():
wiki = getattr(g, '_wiki', None)
... |
__author__ = 'Nishanth'
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import time
from juliabox.cloud import JBPluginCloud
from juliabox.db import JBPluginDB
from juliabox.jbox_util import JBoxCfg
class JBoxSMTP(JBPluginCloud):
provides = [JBPluginCloud.JBP_SEND... |
#!/usr/bin/env python
"""Admin tool to clear databases"""
import sys
from optparse import OptionParser
from putil.logging import log
from pyon.datastore.datastore_common import DatastoreFactory
def main():
usage = \
"""
%prog [options] prefix
"""
description = "Use this program to clear databa... |
import argparse
import os
import yaml
import shutil
from unittest import TestCase
from nose.tools import *
from project_generator.commands import import_command
class TestImportCommand(TestCase):
"""test import command"""
def setUp(self):
if not os.path.exists('test_workspace'):
os.make... |
#!/usr/bin/env python
'''
This example shows how to display a SimpleCV image in a QT window
the code was taken from the forum post here:
http://help.simplecv.org/question/1866/any-simple-pyqt-sample-regarding-ui-or-display/
'''
import os
import sys
import signal
from PyQt4 import uic, QtGui, QtCore
from SimpleCV impor... |
#!/usr/bin/python
import random
import time
import sys
import zmq
from mpi4py import MPI
from multiprocessing import Process, Value
def sensor_reading(port, sensor):
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:" + str(port.value))
while True:
message = socket.recv()... |
from unittest import TestCase, main
from lucene import *
class BooleanOrTestCase(TestCase):
"""
Unit tests ported from Java Lucene
"""
def __init__(self, *args):
super(BooleanOrTestCase, self).__init__(*args)
self.FIELD_T = "T"
self.FIELD_C = "C"
self.t1 = TermQuery... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'johnb'
## Listing and Info about Document List
#######################################
import sqlalchemy
from mozu_image_util_functions import include_keys, log
from RESTClient import __mozu_image_table_valid_keys__
#### Initially written in ipython noteboo... |
r"""Learn RF from EIs
Run using:
ei_to_rf --logtostderr
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import tensorflow as tf
import tensorflow.contrib.slim as slim
from absl import app
import numpy as np, h5py,numpy
# for plotting st... |
import datetime
from datetime import timedelta
from django.db import models
class Metric(models.Model):
name = models.CharField(max_length=100)
description_worst = models.TextField(null=True, blank=True)
description_best = models.TextField(null=True, blank=True)
daily = models.BooleanField(default=Tr... |
# -*-coding:utf-8 -*
import os
import imaplib
from oauth2 import *
client_id="287712233618-7qua8pervof64n6g740gi8d0o7ifiu28.apps.googleusercontent.com"
client_secret="iXsCL1-rYN_D9R6RCc6mUmln"
url=GeneratePermissionUrl(client_id, scope='https://mail.google.com/')
print(url)
print("Autoriser la recherche dans vos... |
'''
Driver method to run the Altens module
'''
import sys
sys.path.append('./')
import altens
#import sassie.calculate.sascalc as sascalc
import sassie.interface.input_filter as input_filter
#import sassie.interface.sascalc_filter as sascalc_filter
import multiprocessing
svariables = {}
#### user input ####
#### u... |
"""
A simple emulation of telnetting port 80 by HTTP requests directly
to web servers.
"""
from socket import socket, gethostbyname, AF_INET, SOCK_STREAM
def http_req(server, request_uri, method, http_version):
"""Issues an HTTP request."""
# Creating a socket to connect and read from
s = socket(AF_INET, ... |
# NeoPixel library strandtest example
# Direct port of the Arduino NeoPixel library strandtest example. Showcases
# various animations on a strip of NeoPixels.
import time
from neopixel import *
# LED strip configuration:
LED_COUNT = 144 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connecte... |
from checkbox.plugin import Plugin
class ErrorPrompt(Plugin):
def register(self, manager):
super(ErrorPrompt, self).register(manager)
self._manager.reactor.call_on("prompt-error",
self.prompt_error)
def prompt_error(self, interface, text):
interface.show_error(text)
fa... |
from math import log10
from odoo.tests.common import TransactionCase
from odoo.tools import float_compare, float_is_zero, float_repr, float_round, float_split_str, pycompat
class TestFloatPrecision(TransactionCase):
""" Tests on float precision. """
def test_rounding_02(self):
""" Test rounding meth... |
#!/usr/bin/env python3
import os
from subprocess import (
check_output,
CalledProcessError,
STDOUT
)
import random
import shutil
from shutil import copyfile
from crontab import CronTab
from charmhelpers.core import unitdata
from charmhelpers.core.host import (
lsb_release,
service_running,
ser... |
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest ; pytest
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
# External impo... |
from __future__ import print_function, unicode_literals
import re
import traceback
# noinspection PyUnresolvedReferences
from requests.compat import quote
from requests.utils import dict_from_cookiejar
from sickbeard import logger, tvcache
from sickbeard.bs4_parser import BS4Parser
from sickchill.helper.common impor... |
from __future__ import unicode_literals
import binascii
from Crypto.Cipher import AES
from django.core.exceptions import ImproperlyConfigured
from django.shortcuts import redirect
from .. import BasicProvider
class SagepayProvider(BasicProvider):
'''
sagepay.com payment provider
vendor:
vendor ... |
# -*- coding: utf-8 -*-
'''
Copyright (c) 2014 Jacob Mendt
Created on Jul 2, 2015
@author: mendt
'''
import ast
import unittest
from pyramid import testing
from georeference.models.vkdb.georeferenzierungsprozess import Georeferenzierungsprozess
from georeference.models.vkdb.map import Map
from georeference.models.vk... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('premises', '0007_auto_20141020_2215'),
]
operations = [
migrations.AddField(
model_name='content... |
#!/usr/bin/python
import os
import sys
import asyncio
import tty
import termios
import fcntl
import re
import curses
class Caps:
def Caps(self):
self.has_vt102 = False
self.type = None
#write = sys.stdout.write
#
#def color_test():
# text="xYz"; # Some test text
#
# write("\n ... |
import asyncio
import arrow
from sigma.core.utils import user_avatar
async def refactor_users_node(db, usrgen):
usrs = list(usrgen)
db['UserList'].drop()
db.log.info('UserList Dropped And Starting Refactoring Process...')
start_time = arrow.utcnow().timestamp
usercount = 0
for user in usrs:
... |
from basil.HL.RegisterHardwareLayer import HardwareLayer
class weissSB22(HardwareLayer):
'''Driver for the Weiss SB 22 climate chamber.
A simple protocoll via RS 232 serial port is used with 9600/19200 baud rate and 256 modulo complement check sum.
Between the different command a delay of 5 seconds shoul... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow.compat.v1 as tf
from multidim_image_augmentation import deformation_utils
_ARRAY_COMPARE_TOLERANCE = 1e-5
class ControlGridTest(tf.test.TestCase):
def test_create_con... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from kazoo.client import KazooClient
import logging
import readline
import yaml
import yamlordereddictloader
import termbox
# import pdb, traceback, sys
# TODO add logger utility for py module
# logging.basicConfig(level=logging.DEBUG)
FORMAT = '%(asctime)s %(name)s %(l... |
from deluge.ui.client import client
from popup import SelectablePopup, Popup
from input_popup import InputPopup
import deluge.component as component
from deluge.ui.console import colors, modes
from twisted.internet import defer
import logging
log = logging.getLogger(__name__)
torrent_options = [
("max_download_s... |
import ctypes
import optparse
import os
import time
from PyQt4 import QtCore, QtGui
import qrc_qmk_resources
import pu.utils
class InputFilterError(Exception): pass
class InputFilter(pu.utils.Singleton):
def __init__(self, filter_lib = 'qmk-hook.dll'):
# void F(int arg);
self.__cbp = ctypes.CFU... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'DataSource.dataset'
db.add_column('dataset_datasource', 'dataset', self.gf('django.db.mode... |
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'such_secret_w0w'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
# Admin plugins
'flat',
# Builtins
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contr... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
FieldsCalculator.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
**********************... |
import argparse
import sys
from alfpy import bbc
from alfpy.utils import distmatrix
from alfpy.utils import seqrecords
from alfpy.utils.data.seqcontent import get_alphabet
from alfpy.version import __version__
def get_parser():
parser = argparse.ArgumentParser(
description='''Calculatee distance between ... |
# Your task is to read the input DATAFILE line by line, and for the first 10 lines (not including the header)
# split each line on "," and then for each line, create a dictionary
# where the key is the header title of the field, and the value is the value of that field in the row.
# The function parse_file should retu... |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from ciwatch import models
from ciwatch.config import cfg, get_projects
engine = create_engine(cfg.database.connection)
Session = sessionmaker()
Session.configure(bind=engine)
models.Base.metadata.create_all(engine)
session = Session()
de... |
import json
from unittest import mock
import pretend
import pytest
from pyramid.tweens import EXCVIEW, INGRESS
from warehouse import static
class TestWhiteNose:
def test_resolves_manifest_path(self, monkeypatch):
resolver = pretend.stub(
resolve=pretend.call_recorder(
lamb... |
from misc.utils import *
from misc.priority_queue import HeapElement
Node = namedtuple('Node', ['cost', 'level'])
# Record parent operator for values to even more efficiently linearize
# TODO - helpful actions
def compute_costs(state, goal, operators, op=max, unit=False, greedy=True):
variable_nodes = defaultdict(... |
"""
docker_registry.tools
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
import logging
try:
NullHandler = logging.NullHandler
except AttributeError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger(__name__).addHandler(NullHandler())
__author__ = 'Mangled Deutz'
__... |
from numpy import array
from numpy import random
import math
from shogun import CrossValidation, CrossValidationResult
from shogun import ContingencyTableEvaluation, ACCURACY
from shogun import StratifiedCrossValidationSplitting
from shogun import BinaryLabels
from shogun import RealFeatures
from shogun import Gaussia... |
import os
import subprocess
import time
from libqtile.command_client import InteractiveCommandClient
from libqtile.command_interface import IPCCommandInterface
from libqtile.ipc import Client as IPCClient
from libqtile.ipc import find_sockfile
class Client:
COLORS = [
"#44cc44", # green
"#cc44cc... |
from __future__ import print_function
import hdr_parser
import re
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from cStringIO import StringIO
_types = ["CvANN", "flann", "c"] # literally, underscore types.
namespaces = ["SimpleBlobDetector"]
empty_types = ["cvflann", "... |
from st_create_session import create_session
from xdrdef.nfs4_const import *
from environment import check, fail, create_file, open_file
from xdrdef.nfs4_type import open_owner4, openflag4, createhow4, open_claim4
import nfs_ops
op = nfs_ops.NFS4ops()
import threading
import rpc
def testDestroy(t, env):
"""
- c... |
import unittest
from collections import OrderedDict
from appassure import api
class TestAPI(unittest.TestCase):
def setUp(self):
self.api = api.AppAssureAPI(None)
self.xml = '<?xml version="1.0" encoding="utf-8"?>'
self.xmlns = 'xmlns="http://apprecovery.com/management/api/2010/05"'
... |
'''
@author: Frank
'''
import unittest
from virtualrouter import virtualrouter
from virtualrouter.plugins import dns
from zstacklib.utils import jsonobject
from zstacklib.utils import uuidhelper
from zstacklib.utils import http
import time
class Test(unittest.TestCase):
CALLBACK_URL = 'http://local... |
import os
import time
from google.cloud import errorreporting_v1beta1
from google.cloud.errorreporting_v1beta1.proto import common_pb2
from google.cloud.errorreporting_v1beta1.proto import report_errors_service_pb2
class TestSystemReportErrorsService(object):
def test_report_error_event(self):
project_id... |
import unittest
from datetime import timedelta, datetime
from ..worker.daystate import current_state, num_periods
class TestDaystateSchedule(unittest.TestCase):
def test_current_state(self):
self.assertEqual(current_state(['A', 'B'], 0, 0), 'A')
self.assertEqual(current_state(['A', 'B'], 0, 1), 'B... |
{
'name': 'Product Variant Configurator',
'summary': "Provides an abstract model for product variant configuration.",
'version': '12.0.1.0.1',
'category': 'Product Variant',
'license': 'AGPL-3',
'author': 'AvanzOSC, '
'Tecnativa, '
'ACSONE SA/NV, '
'Odoo... |
import os
try:
# Python >= 3.1
from importlib import import_module
except ImportError:
from django.utils.importlib import import_module
from statici18n.conf import settings
def get_mod_func(callback):
"""
Converts 'django.views.news.stories.story_detail' to
('django.views.news.stories', 'sto... |
import sublime
import sublime_plugin
class SurroundCommand(sublime_plugin.TextCommand):
"""
Base class to surround the selection with text.
"""
surround = ''
def run(self, edit):
for sel in self.view.sel():
len_surround = len(self.surround)
sel_str = self.view.subs... |
#!/usr/bin/env python
from __future__ import absolute_import
import datetime
import json
import os
import re
import shutil
import sqlite3
import warnings
from subprocess import Popen, PIPE
from textwrap import dedent
from unittest import TestCase, main
import scraperwiki
import six
import sys
# scraperwiki.sql._St... |
import copy
import functools
import inspect
import types
from typing import Any, Callable, Dict, Iterable, List, Optional, cast
from . import _typing
if _typing.TYPE_CHECKING:
from ._parametrize import Param
class FunctionDecorator:
def __new__(
cls, func: Callable[..., Any], *args: Any, **kwargs: A... |
import saliweb.backend
from argparse import ArgumentParser
import sys
def get_options():
parser = ArgumentParser(
description="Delete the job(s) JOBNAME in the given STATE.")
parser.add_argument("state", metavar="STATE", help="Job state to consider")
parser.add_argument(
"jobs", metavar="J... |
"""Test file manipulation functionality of Item.
"""
import shutil
import os
import stat
from os.path import join
import _common
from _common import unittest
from _common import item, touch
import beets.library
from beets import util
class MoveTest(_common.TestCase):
def setUp(self):
super(MoveTest, self)... |
# convenience wrapper for urllib2 & friends
import cookielib
import json
import urllib
import urllib2
import urlparse
from urllib import quote, quote_plus as _quote_plus
from lxml import etree, html
from bs4 import BeautifulSoup
# used in plugins that import this
from urllib2 import URLError, HTTPError
ua_cloudbot... |
from tools.SinkSnippetEmbedder.SinkUserProvider import SinkUserProvider
from tools.SinkSnippetEmbedder.SinkSnippetEmbedder import SinkSnippetEmbedder
from mlutils.clustering.NMFCluster import NMFCluster
from mlutils.anomalyDetection.anomalyCalculator import AnomalyCalculator
from tools.ClusterAnomalies.Configurations... |
from openerp.osv import osv, fields
from openerp.tools.translate import _
from datetime import datetime
class product_product(osv.Model):
_inherit = "product.product"
def copy(self, cr, uid, id, default=None, context=None):
if not default:
default = {}
product_default_code = se... |
from plplot_py_demos import *
import calendar
#--------------------------------------------------------------------------
# main
#
# Draws several plots which demonstrate the use of date / time formats for
# the axis labels.
# Time formatting is done using the system strftime routine. See the
# documentation of... |
import re
from infoblox_netmri.easy import NetMRIEasy
# This values will be provided by NetMRI before execution
defaults = {
"api_url": 'api_url',
"http_username": 'http_username',
"http_password": 'http_password',
"job_id": 'job_id',
"device_id": 'device_id',
"batch_id": 'batch_id'
}
# Create... |
#! /usr/bin/env python3
import sys
import json
import os
import math
import struct
from xor_decryptor import xor_decrypt
def parse_map_obj(path):
if os.path.isfile(path):
with open(path, 'rb') as input_file:
data = xor_decrypt(input_file.read())
if len(data) < 4:
r... |
# coding: utf-8
# In[ ]:
import datetime
def weekly_expiry():
d = datetime.date.today()
while d.weekday() != 5:
d += datetime.timedelta(1)
return d
# In[ ]:
def quarter_expiry():
ref = datetime.date.today()
if ref.month < 4:
d = datetime.date(ref.year, 3, 31)
elif ref.month... |
import unittest
from unittest.mock import patch
from pyanaconda.modules.common.constants.services import SUBSCRIPTION
from pyanaconda.modules.common.util import is_module_available
class IsModuleAvailableTestCase(unittest.TestCase):
"""Test the is_module_available() utility function."""
@patch("pyanaconda.m... |
"""Test nodes build data API with Postgres backend."""
import pytest
from falcon import testing
import uuid
import datetime
import random
import drydock_provisioner.objects as objects
from drydock_provisioner import policy
from drydock_provisioner.control.api import start_api
import falcon
class TestNodeBuildData... |
# -*- coding: utf-8 -*-
from django import forms
from django.forms import ModelForm
from models import *
from django.forms.models import inlineformset_factory
from django.forms.extras.widgets import SelectDateWidget
from django.contrib.localflavor.es.forms import *
from django.contrib.admin import widgets ... |
import json
import os
import sys
from coverage import CoveragePlugin, FileTracer
from coverage.config import DEFAULT_PARTIAL, DEFAULT_PARTIAL_ALWAYS
from coverage.misc import join_regex
from coverage.parser import PythonParser
from coverage.python import PythonFileReporter, get_python_source
# Note: This plugin will... |
"""
The :mod:`websockets.client` module defines a simple WebSocket client API.
"""
import asyncio
import collections.abc
from .exceptions import InvalidHandshake, InvalidMessage, InvalidStatusCode
from .handshake import build_request, check_response
from .http import USER_AGENT, build_headers, read_response
from .pr... |
from optparse import OptionParser
from setuptools import find_packages
from pprint import pprint
from .pgdoc import get_all_info
from ..core.registrar import default_library
from ..core.import_magic import REQUIRES_PARSED
def main():
parser = OptionParser()
parser.add_option("--output", default='procgraph_p... |
# -*- coding: utf-8 -*-
"""
pygments.formatters._mapping
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Formatter mapping defintions. This file is generated by itself. Everytime
you change something on a builtin formatter defintion, run this script from
the formatters folder to update it.
Do not alter the FORMA... |
from nova.compute import api as compute_api
from nova import exception
from nova.network import api as network_api
from nova.tests import fake_network_cache_model
from nova.tests.integrated.v3 import test_servers
class AttachInterfacesSampleJsonTest(test_servers.ServersSampleBase):
extension_name = 'os-attach-int... |
# -*- coding: utf8 -*-
import datetime
import os
from django.conf import settings
from django.core.mail import EmailMessage
from django.core.management.base import BaseCommand
from mailrobot.models import Mail
from django_apogee.models import InsAdmEtp
from duck_examen.models import EtapeExamenModel, Etape, EtapeSettin... |
# -*- coding:Utf-8 -*-
import numpy as np
import scipy as sp
import matplotlib.pylab as plt
import scipy.linalg as la
def dist_nonvectorized(A,B,C,D,alpha,beta):
"""
Parameters
----------
A
B
C
D
alpha
beta
Return
------
distance f ( =g <= comuted from another way... |
import sys, os, re, argparse
from pkg_resources import resource_string
from math import ceil, floor
from string import split
from utils import get_terminal_size
class Lexitron:
def __init__(self):
# The wordlist files
self.wordlist_common = resource_string(__name__, 'agid-common.txt')
self.... |
#!/usr/bin/python
import os
import shutil
import tempfile
import unittest
import apt
import unattended_upgrade
class MockFetcher:
items = []
class MockAcquireItem:
def __init__(self, destfile):
self.destfile = destfile
class TestClean(unittest.TestCase):
def setUp(self):
self.tempd... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'DataInstance.valid_from'
db.add_column('postdoc_datainstance', 'valid_from',
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from pyspark.ml import Pipeline
from pyspark.ml.feature import IndexToString, StringIndexer, VectorIndexer
from pyspark.ml.feature import OneHotEncoderEstimator
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.classification import RandomForestClassifier
from py... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.decorators import ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('rh', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.