content stringlengths 4 20k |
|---|
import errno
import socket
import threading
class Scanner(threading.Thread):
timeouts = 0
errors = []
def __init__(self, address, port):
self.address = address
self.port = port
self.is_active = False
super(Scanner, self).__init__()
def run( self ):
sd = socket.s... |
#!/usr/bin/env python
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from glob import glob
execfile('rootpy/info.py')
setup(name='rootpy',
version=__VERSION__,
description='The way PyROOT should be, and more!',
long_description=open('README... |
import os
import stat
import errno
import base64
import hashlib
import magic
import logging
import selinux
import exception as ge
from functools import wraps
from . import makePublic
from . import safeWrite
_glusterHooksPath = '/var/lib/glusterd/hooks/1'
_mimeType = None
log = logging.getLogger("Gluster")
class Hook... |
import os
import aiomysql
import tornado.testing
from run_service import make_app, connect_mysql
from service.mysql.initialize import destroy, initialize
from tests.handlers.handler_test_case import HandlerTestCase
class TestLisasHandler(HandlerTestCase):
def tearDown(self):
self.io_loop.run_sync(lambda... |
'''
sprites.py is a simple sprites library for managing graphics objects,
'sprites', on a Gtk.DrawingArea. It manages multiple sprites with
methods such as move, hide, set_layer, etc.
There are two classes:
class Sprites maintains a collection of sprites
class Sprite manages individual sprites within the collection.... |
# this script computes a coverage graph for each sample
import numpy,sys,subprocess,pickle,os
import matplotlib
import matplotlib.pyplot
import multiprocessing
import multiprocessing.pool
def coverageComputer(tube):
'''
this function computes the coverage over all chromosomes in a bam file
'''
... |
"""Provides the :class:`~sqlalchemy.engine.url.URL` class which encapsulates
information about a database connection specification.
The URL object is created automatically when
:func:`~sqlalchemy.engine.create_engine` is called with a string
argument; alternatively, the URL is a public-facing construct which can
be us... |
from bambou import NURESTFetcher
class NUIKESubnetsFetcher(NURESTFetcher):
""" Represents a NUIKESubnets fetcher
Notes:
This fetcher enables to fetch NUIKESubnet objects.
See:
bambou.NURESTFetcher
"""
@classmethod
def managed_class(cls):
""" Return NU... |
"""Render the category pages and feeds."""
import os
from nikola.plugin_categories import Taxonomy
from nikola import utils, hierarchy_utils
class ClassifyCategories(Taxonomy):
"""Classify the posts by categories."""
name = "classify_categories"
classification_name = "category"
overview_page_varia... |
from functools import wraps
from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext as _
from pootle_app.models.permissions import (check_permission,
get_matching_permissions)
from .mod... |
# -*- coding: utf-8 -*-
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
from django.contrib import admin
from django.shortcuts import render, get_object_or_404
from django.conf.urls import patterns,url
from django.core.urlresolvers import reverse
from django.http import... |
__author__ = 'rohansroy'
import unittest
class AutoOrganizeTest(unittest.TestCase):
def test_media_factory(self):
from autoorganize import media_factory,TVDaily, TVEpisode, TVBoxset, Movie
self.assertIsInstance(media_factory("Real.Time.with.Bill.Maher.2014.03.23.HDTV.x264-BATV", "/"), TVDaily)
... |
import pytest
from pycket.expand import expand, expand_string
from pycket.pycket_json import loads
from pycket.interpreter import *
from pycket.values import *
from pycket.prims import *
from pycket.test.testhelper import run_file
def test_puzzle():
run_file("puzzle.rkt", ("1048575", "460"), ("50", "1"))
def tes... |
import os, re
import urllib.request
import rb
from gi.repository import Gtk, Gio, GObject, Peas
from gi.repository import RB
import LyricsParse
from LyricsConfigureDialog import LyricsConfigureDialog
import gettext
gettext.install('rhythmbox', RB.locale_dir())
LYRIC_TITLE_STRIP=["\(live[^\)]*\)", "\(acoustic[^\)]*... |
from odoo import api, fields, models
class SaleOrder(models.Model):
_inherit = "sale.order"
invoice_policy = fields.Selection(
[('order', 'Ordered quantities'),
('delivery', 'Delivered quantities')],
readonly=True,
states={
'draft': [('readonly', False)],
... |
import doctest
import pytest
from insights.parsers import lspci, SkipException
from insights.parsers.lspci import LsPci, LsPciVmmkn
from insights.tests import context_wrap
LSPCI_0 = """
00:00.0 Host bridge: Intel Corporation 2nd Generation Core Processor Family DRAM Controller (rev 09)
00:02.0 VGA compatible control... |
from builtins import range
from django.test import TestCase
from spotseeker_server.models import (
Spot,
SpotExtendedInfo,
Item,
ItemExtendedInfo,
)
import simplejson as json
from django.test.utils import override_settings
@override_settings(
SPOTSEEKER_AUTH_MODULE="spotseeker_server.auth.all_ok"... |
import math
from math import pi
import numpy
from .. import config, utilities
from ..math import VecNorm
def show_reciprocal_space_plane(
mat, exp, ttmax=None, maxqout=0.01, scalef=100, ax=None, color=None,
show_Laue=True, show_legend=True, projection='perpendicular',
label=None):
"""
... |
class Py3status:
status = 'total'
def on_click(self, json, i3status_config, event):
"""
Handles click events.
"""
if self.status == 'total':
self.status = 'split'
else:
self.status = 'total'
def btcd_conncount(self, json, i3status_config):... |
#coding:utf8
from binance.exceptions import BinanceAPIException
from binance.client import Client
import random
import time
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
INTERVAL=3.5
CURRENY_A = "bnb"
CURRENY_B = "btc"
SYMBOL = "BNBBTC"
MAGIC_BALANCE = float(open("/root/binance/magic.balance").read())
MINVOL ... |
"""
Created on Jan 25, 2012
@author: Trung Dong Huynh
"""
import unittest
import logging
import os
from prov.model import ProvDocument, ProvBundle, ProvException, first, Literal
from prov.tests import examples
from prov.tests.attributes import TestAttributesBase
from prov.tests.qnames import TestQualifiedNamesBase
fr... |
import math
from collections import defaultdict, Counter
import pre_process as pp
'''
Basic VSM IR
not effective
Try BM25
in probabilistic_ir.py
'''
vsm_inverted_index = defaultdict(list)
# Collect term frequencies for each sentence in document
def extract_term_freqs(sentence):
# bag-of-words representation
... |
"""
Framework methods for the LookUpTables datatype.
.. moduleauthor:: Paula Sanz Leon <<EMAIL>>
"""
import tvb.datatypes.lookup_tables_data as lookup_tables_data
class LookUpTableFramework(lookup_tables_data.LookUpTableData):
"""
This class exists to add framework methods and attributes to LookUpTables
... |
#-------------------------------------------------------------------------------
#
# This file shows how to simulate a conveyor and a stack of pebbles
#
#
# REMARK: this is part of Chrono::Solidworks add-in
# - it assumes that you exported the .asm in this directory using the add-in
# - PyChrono must be install... |
"""A class for storing the history of what the user has entered into the
client.
"""
from collections import deque
class CommandHistory(object):
"""The history of what the user's entered."""
def __init__(self, size):
self.size = size
self.commands = deque()
self.ind = -1
def add... |
import os, argparse
import subprocess, multiprocessing
def run_cmd((cmd, log_file)):
process = subprocess.Popen(cmd, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, bufsize=1)
with open(log_file, "w", 0) as wfile:
wfile.write("-" *80 + "\n")... |
#! /usr/bin/python3
import pygame
from coordenades import *
from pygame.locals import *
from tecles import *
from objectes import *
def inicia():
global p
p = Pong()
pygame.init()
def esdeveniments():
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
elif event.type == K... |
import os
import duplicity.backend
from duplicity import log
from duplicity import util
from duplicity.errors import BackendException
class SwiftBackend(duplicity.backend.Backend):
"""
Backend for Swift
"""
def __init__(self, parsed_url):
try:
from swiftclient import Connection
... |
import numpy as np
import pandas as pd
import json
import tl_alg
from sklearn.cluster import KMeans
from sklearn.metrics.pairwise import euclidean_distances
class ClusterThenLabel(tl_alg.Base_Transfer):
"""
This transfer learning algorithm clusters the data using k means
and then labels using the provided... |
from msrest.serialization import Model
class ApplicationGatewayBackendHealthHttpSettings(Model):
"""Application gateway BackendHealthHttp settings.
:param backend_http_settings: Reference of an
ApplicationGatewayBackendHttpSettings resource.
:type backend_http_settings:
~azure.mgmt.network.v201... |
import pecan.deploy
from oslo_config import cfg
from oslo_log import log as logging
from designate.api.v2 import patches # flake8: noqa
LOG = logging.getLogger(__name__)
OPTS = [
cfg.ListOpt('enabled-extensions-v2', default=[],
help='Enabled API Extensions for the V2 API'),
cfg.IntOpt('defa... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MenuBar
The menu bar used for hierarchical navigation of commotion extensions.
Key componenets handled within:
*
"""
#Standard Library Imports
import logging
from functools import partial
#PyQt imports
from PyQt4 import QtCore
from PyQt4 import QtGui
#Commoti... |
import re
import pytest
from tabipy import Table
@pytest.fixture
def t():
"Returns the table used in the col_span tests"
t = Table((1,2,3),
(4,5,6),
(7,8,9))
cell = t.cell(0,0)
cell.row_span = 2
return t
def test_row_span_html():
"This test col_span works in html"
... |
import calendar
import json
from datetime import datetime
from datapoller.download import download
from datapoller.settings import *
from messaging.Messaging import sendMessage
from messaging.settings import RABBIT_NOTIFY_QUEUE
from sessioncontroller.utils import is_level_interesting_for_kp
__author__ = 'arik'
shared... |
'''
Created on Apr 17, 2011
@author: zavlab1
'''
from gi.repository import Gtk
from foobnix.fc.fc import FC
from foobnix.helpers.image import ImageBase
from foobnix.helpers.textarea import TextArea
from foobnix.util.const import ICON_BLANK_DISK
class CoverLyricsPanel(Gtk.Frame):
def __init__(self, controls):
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
import os
import fileinput
from PIL import Image
"""
Requires:
A folder structure according to Paradox's own: [cwd]\history\provinces\
Files:
terrain.bmp - an image painted with correct terrain RGB values
provinces.bmp - an image that defines p... |
"""
Various analytics-related logic for video.
Process raw database tracking entries related to the video player,
and construct watching segments based on the entries.
"""
import math
from datetime import datetime, timedelta
from collections import Counter
from itertools import chain
from xml.etree.ElementT... |
from kivy.app import App
from kivy.factory import Factory
from kivy.lang import Builder
Factory.register('QRScanner', module='electrum_gui.kivy.qr_scanner')
class QrScannerDialog(Factory.AnimatedPopup):
__events__ = ('on_complete', )
def on_symbols(self, instance, value):
instance.stop()
sel... |
from __future__ import absolute_import, print_function
import urlparse
import requests
import requests.exceptions
from . import exceptions, log, mesos_file, util
from .cfg import CURRENT as CFG
class MesosSlave(object):
def __init__(self, items):
self.__items = items
def __getitem__(self, name):
... |
# -*- 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):
# Deleting model 'Terms'
db.delete_table(u'cadastros_terms')
# A... |
import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v8.enums",
marshal="google.ads.googleads.v8",
manifest={"JobPlaceholderFieldEnum",},
)
class JobPlaceholderFieldEnum(proto.Message):
r"""Values for Job placeholder fields.
For more information about dynamic r... |
"""Test the Mythic Beasts DNS component."""
import logging
from unittest.mock import patch
from homeassistant.components import mythicbeastsdns
from homeassistant.setup import async_setup_component
_LOGGER = logging.getLogger(__name__)
async def mbddns_update_mock(domain, password, host, ttl=60, session=None):
... |
#!/usr/bin/python
import argparse
import logging
import time
import sys
import os
from custom_exceptions import GeneralPogoException
from api import PokeAuthSession
from location import Location
from pokedex import pokedex
def setupLogger():
logger = logging.getLogger()
logger.setLevel(logging... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@file cadytsIterate.py
@author Yun-Pang Wang
@author Daniel Krajzewicz
@author Michael Behrisch
@date 2010-09-15
@version $Id: cadytsIterate.py 11671 2012-01-07 20:14:30Z behrisch $
Run cadyts to calibrate the simulation with given routes and traffic measureme... |
# Python
# Django
from datetime import date
from django.conf import settings
from django.core.cache import cache
from django.db.models import Q
from django.template import Library
# Third party
from subscription.models import UserSubscription
register = Library()
@register.inclusion_tag('astrobin_apps_donations/i... |
from __future__ import print_function
import os, sys
import numpy as np
print ("OpenARK SMPL Model Converter Utility v0.2, created by Alex Yu 2018-19")
print ("This utility converts SMPL pickled model files (.pkl) to PCL point cloud files (.pcd) + an easy-to-parse skeleton information file.\n")
if len(sys.argv) < 2:
... |
import socket,os,struct,sys
import argparse
import datetime, time
import AcraNetwork.iNetX as inetx
import AcraNetwork.Pcap as pcap
import AcraNetwork.SimpleEthernet as SimpleEthernet
import AcraNetwork.ParserAligned as ParserAligned
def main():
try:
pcapfile = pcap.Pcap("SSR_ABM_102_... |
import mock
import testtools
from rackspace.monitoring.v1 import alarm
FAKE = {
"values": [
dict(),
dict()
]
}
EXAMPLE = {
"active_suppressions": [],
"check_id": "chAAAA",
"created_at": 1234567890,
"criteria": ("if (metric[\"duration\"] >= 2) { return new AlarmStatus(OK);"
... |
####
# Le parser permet d'aller chercher les éléments qui nous interessent dans la page web
####
from bs4 import BeautifulSoup
class Parse():
def __init__(self, page):
assert type(page)==str, "La page doit être de type string"
self.page = page
self.soup = BeautifulSoup(self.page, 'html... |
import pandas as pd
def combine(street):
return "_".join(street.split(" "))
def main():
return
# Returns a list of street names of road_usages data which contain at least two words
def joint_street_names():
unique_road_usages_streets = df_road_usages.nimi.unique()
print(unique_road_usages_streets)
... |
from django.core import serializers
from questionnaire.models import Questionnaire, Section, SubSection, Question, QuestionGroup, QuestionOption, QuestionGroupOrder
questionnaire = Questionnaire.objects.get(name="JRF 2013 Core English", description="From dropbox as given by Rouslan")
section_1 = Section.objects.creat... |
import unittest
from willow.image import Image as WillowImage
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.test.utils import override_settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, Permission
from django.core.files.upl... |
# -*- coding: utf-8 -*-
import nose.tools as ns
from relshell.batch import Batch
from relshell.recorddef import RecordDef
from relshell.record import Record
from relshell.timestamp import Timestamp
from shellstreaming.core.batch_queue import BatchQueue
from shellstreaming.operator.external_time_window import ExternalTi... |
import os
from datetime import timedelta
import logging
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3 import Retry
from crashsimilarity import utils
class Downloader(object):
def __init__(self, cache=None):
self._cache = cache
@staticmethod
def _json_o... |
# -*- coding: utf-8 -*-
# Geocluster - A simple and naive geo cluster
# (c) Régis FLORET 2014 and later
#
from .geoconvertion import *
from .geoboundbase import GeoBoundBase
from .geobound import GeoBound
from .geopoint import GeoPoint
class GeoCluster(GeoBoundBase):
def __init__(self):
super(GeoCluster,... |
""" FloatValidator.py
This file...
"""
from signetsim.json import JsonRequest
class FloatValidator(JsonRequest):
def __init__(self):
JsonRequest.__init__(self)
def post(self, request, *args, **kwargs):
field = str(request.POST['value'])
required = not ("required" in request.POST.keys() and str(request.P... |
import xbmc, xbmcgui, xbmcaddon, time, datetime, threading
from resources.zattooDB import ZattooDB
from resources.guiactions import *
__addon__ = xbmcaddon.Addon()
__addonId__=__addon__.getAddonInfo('id')
class ChannelsPreview(xbmcgui.WindowXML): #needs to be WindowXML or onInit won't fire
#print('FAV:'+s... |
from oslo_log import log as logging
from neutron._i18n import _
from neutron.api import extensions
from neutron.api.v2 import base
from neutron_lib.api import converters as lib_converters
from neutron_lib.api import extensions as api_extensions
from neutron_lib.api import validators as lib_validators
from neutron_lib ... |
from __future__ import unicode_literals
import sys,os.path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import json
import sh
from rdio import Rdio
from rdio_consumer_credentials import RDIO_CREDENTIALS, RDIO_TOKEN, GIT_REPO_PATH
try:
from urllib.error import HTTPError
except I... |
"""
=============
TAP plus
=============
@author: Juan Carlos Segovia
@contact: <EMAIL>
European Space Astronomy Centre (ESAC)
European Space Agency (ESA)
Created on 30 jun. 2016
"""
import os
from astropy.table import Table as APTable
from astropy import units as u
def check_file_exists(file_name):
if file_... |
import imath
import IECore
import Gaffer
import GafferUI
import GafferImage
def colorSpacePresetNames( plug ) :
return IECore.StringVectorData( [ "None" ] + sorted( map( lambda x: "Roles/{0}".format( x.replace( "_", " ").title() ), GafferImage.OpenColorIOTransform.availableRoles() ) ) + sorted( GafferImage.OpenCol... |
"""Gradients for operators defined in array_ops.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_util
from t... |
"""Handler for Atom PFIF 1.2 person and note feeds."""
__author__ = '<EMAIL> (Ka-Ping Yee)'
import atom
import datetime
import model
import pfif
import utils
HARD_MAX_RESULTS = 200 # Clients can ask for more, but won't get more.
MAX_SKIP = 800 # App Engine imposes a limit of 1000 on max_results + skip.
def get_l... |
# coding=utf-8
"""
Magnolia street.
Connects with Rose Street on the Crossing.
magnolia st. 1, pharmacy
magnolia st. 2, magnolia st. 3, factory
"""
from __future__ import absolute_import, print_function, division, unicode_literals
from tale.base import Location, Exit, Door
from zones import houses
def init(driver):... |
import copy
from urllib.parse import urlparse, unquote
from core.colors import good, green, end
from core.requester import requester
from core.utils import getUrl, getParams
from core.log import setup_logger
logger = setup_logger(__name__)
def bruteforcer(target, paramData, payloadList, encoding, headers, delay, ti... |
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.contrib.auth import get_user_model
User = get_user_model()
from core.forms import LoginForm
USERNAME = 'test'
PASSWORD = 'test'
EMAIL = '<EMAIL>'
class FormTests(TestCase):
"""
Test the login form.
"""
def setUp(self):
self... |
"""
Request Body validating middleware.
"""
import functools
import re
from nova.api.openstack import api_version_request as api_version
from nova.api.validation import validators
from nova import exception
from nova.i18n import _
def _schema_validation_helper(schema, target, min_version, max_version,
... |
import asyncio
import logging
import os
import signal
import subprocess
import sys
import time
import unittest
from tornado.httpclient import HTTPClient, HTTPError
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.log import gen_log
from tornado.process import fork_processes, tas... |
try:
from core import update_servers
except:
logger.info("streamondemand.library_service Error en update_servers")
# ----------------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os
import sys
import xbmc,time
from core import scrapertools
from core import con... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
# Standard imports
from future import standard_library
standard_library.install_aliases()
from builtins import *
import unittest
import logging
import json
import datetime... |
"""ctypes library of mxnet and helper functions."""
from __future__ import absolute_import
import os
import sys
import ctypes
import atexit
import warnings
import inspect
import numpy as np
from . import libinfo
warnings.filterwarnings('default', category=DeprecationWarning)
__all__ = ['MXNetError']
#----------------... |
"""Deprecations of policy elements.
Initial thinking around the deprecation is identifying changes in filters and
actions. These are likely to be the most common aspects:
* renaming a field
* making an optional field required
* removing a field
Examples:
- renaming a filter itself
c7n_azure/resources/key_vault
@K... |
import os
# Comment this if you have already set it
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
# Comment this if you have already set it
STATIC_URL = "/static/"
# Comment this if you have already set it
STATIC_ROOT = os.path.join(PROJECT_ROOT, STATIC_URL.strip("/"))
# Comment this if you have already... |
# -*- coding: utf-8 -*-
"""
Test suite for the unistring module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
import unittest
import random
from pygments import unistring as uni
from pygment... |
#!/usr/bin/env python
"""
dcm_convert.py
By: Michael Durnhofer (<EMAIL>)
11/5/2009
Searches for all DICOM files in a selected path and allows converion to NIfTI,
Compressed NIfTI, or Analyze formats. See options for help.
========= Change Log (mm.dd.yyyy) =========
========= Format: mm.dd.yyyy - Author =========... |
import functools
from django import http
from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404
import commonware.log
from mkt.webapps.models import Webapp
log = commonware.log.getLogger('mkt.purchase')
def has_purchased(f):
"""
If the addon is premium, require... |
import adult_wen
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
class alg_accuracy_change:
def __... |
"""The tests for the persistent notification component."""
from homeassistant.setup import setup_component
import homeassistant.components.persistent_notification as pn
from tests.common import get_test_home_assistant
class TestPersistentNotification:
"""Test persistent notification component."""
def setup_... |
from nose import tools as nt
from tests.base import AdminTestCase
from tests.factories import AuthUserFactory
from tests.test_conferences import ConferenceFactory
from admin.meetings.forms import MeetingForm, MultiEmailField
data = dict(
edit='False',
endpoint='short',
name='Much longer',
info_url='... |
from umongo.fields import ListField, EmbeddedField
from umongo.document import DocumentImplementation
from umongo.embedded_document import EmbeddedDocumentImplementation
def map_entry(entry, fields):
"""
Retrieve the entry from the given fields and replace it if it should
have a different name within the ... |
"""Script to normalize test single cell RNA sequencing dataset
and output common subset genes as in the final training set.
"""
import pandas as pd
import sklearn
from sklearn.preprocessing import StandardScaler
info = {'GSE57982': {'filename': 'GSE57982_primaryFpkmMatrix.txt',
'idcol': 'geneSym... |
"""This module is deprecated. Please use `airflow.providers.apache.hive.operators.mysql_to_hive`."""
import warnings
from airflow.providers.apache.hive.operators.mysql_to_hive import MySqlToHiveTransferOperator
warnings.warn(
"This module is deprecated. Please use `airflow.providers.apache.hive.operators.mysql_t... |
import inspect
import six
from webob.util import status_reasons
from nova import context
from nova import exception
from nova import test
class FakeNotifier(object):
"""Acts like messaging.Notifier."""
def __init__(self):
self.provided_context = None
self.provided_event = None
self.... |
start = list(map(int, input().split()))
def inArray(x, y, array):
return x > 0 and x < len( array[0] ) and y > 0 and y < len( array )
def fill( x, y ):
m=[
[0,0,1,0,0,1,0,0,0,0],
[0,0,1,0,0,1,0,0,0,0],
[0,0,1,1,0,1,0,0,0,1],
[0,0,1,0,0,0,1,0,1,0],
[0,0,1,0,0,0,0,1,0,0],... |
"""
Copyright (C) 2008 by Steven Wallace
<EMAIL>
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.
Thi... |
"""
Signal handlers for program enrollments
"""
import logging
from django.db.models.signals import post_save
from django.dispatch import receiver
from social_django.models import UserSocialAuth
from openedx.core.djangoapps.catalog.utils import get_programs
from openedx.core.djangoapps.user_api.accounts.signals imp... |
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from .. import Rule
#-----------------------------------------------... |
from odoo.tests import common
from openerp import fields
class SetUp(common.TransactionCase):
def _create_pos_data(self):
self.pos_inbound = self.env['pos.ar'].create({
'name': '9990'
})
self.pos_outbound = self.env['pos.ar'].create({
'name': '9999'
})
... |
"""Adds Job visibility column
Revision ID: 1c87fd8da02e
Revises: 735063d71b57
Create Date: 2017-12-13 12:18:59.551609
"""
# revision identifiers, used by Alembic.
revision = '1c87fd8da02e'
down_revision = '735063d71b57'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
from sqla... |
#!/usr/bin/env python
# -*- coding: ASCII -*-
"""
Script to retrieve from HFC the list of processed SDOSS data.
URL of the processed data are returned in a ascii file, which can
be used as an input history file for the SDOSS-HFC wrapper software.
@author: X.Bonnin (LESIA, CNRS)
"""
import os
import sys
import argpars... |
import random
import time
import mock
from mox3 import mox
from oslo_log import log as logging
from nova.compute import utils as compute_utils
from nova import context
from nova import exception
from nova.tests.unit.virt.xenapi import stubs
from nova.virt.xenapi import driver as xenapi_conn
from nova.virt.xenapi impo... |
'''
Created on 03.09.2013
@author: Walter
You are given the following information, but you may prefer to do some research
for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, ra... |
# -*- coding: utf-8 -*-
'''
The MIT License (MIT)
Copyright (c) 2014 kzczencode
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use,... |
from __future__ import absolute_import
import logging
from typing import Any, Set, Tuple, Optional
from six import text_type
from django.contrib.auth.backends import RemoteUserBackend
from django.conf import settings
from django.http import HttpResponse
import django.contrib.auth
from django_auth_ldap.backend import... |
#!/usr/bin/env python
from xml.dom import minidom, Node
import openpyxl
import sys
import tkFileDialog
def xml2xlsx(xml_filename):
wb = openpyxl.Workbook()
ws = wb.create_sheet(0, "mapping from xml")
xmldoc = minidom.parse(xml_filename)
for field in xmldoc.getElementsByTagName("field"):
de... |
import os
import zipfile
import pytest
from webtest.forms import Upload
from mock import MagicMock
from django.core.urlresolvers import reverse
from django.core.files.base import ContentFile
from ..backup import Backup
from .test_backup import BACKUPS_ROOT, DATA_ROOT
pytestmark = pytest.mark.django_db
class FakeP... |
# stdlib
from collections import defaultdict
import threading
import time
from Queue import Queue, Empty
# project
from config import _is_affirmative
from checks import AgentCheck
# 3rd party
from checks.libs.thread_pool import Pool
TIMEOUT = 180
DEFAULT_SIZE_POOL = 6
MAX_LOOP_ITERATIONS = 1000
FAILURE = "FAILURE"
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './GraphicsScene/exportDialogTemplate.ui'
#
# by: pyside-uic 0.2.13 running on PySide 1.1.1
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_Form(object):
def setupUi(self, Form):
... |
import threading
from binascii import hexlify, unhexlify
from electrum.util import bfh, bh2u
from electrum.bitcoin import (b58_address_to_hash160, xpub_from_pubkey,
TYPE_ADDRESS, TYPE_SCRIPT, NetworkConstants,
is_segwit_address)
from electrum.i18n import _
f... |
import unittest
from linkedlist import LinkedList
from linkedlist import Node
def delete_node(l, node):
"""
:param l: LinkedList contained the node to be deleted
:type l: LinkedList
:param node: Node to be deleted
:type node: Node
:return: Original LinkedList with the node deleted
:rtype:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.