content
stringlengths
4
20k
from django.conf import settings from django.http import HttpResponseForbidden, HttpResponseRedirect from django.core.signing import TimestampSigner, BadSignature, SignatureExpired from django.contrib.auth import get_user_model, login as django_login, REDIRECT_FIELD_NAME from django.contrib.auth.decorators import login...
''' Task Coach - Your friendly task manager Copyright (C) 2004-2010 Task Coach developers <<EMAIL>> Task Coach 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) ...
from sh import ErrorReturnCode_1 from functools import partial from test_base import TestBase from docker_host import DockerHost from utils import retry_until_success class Ipv6MultiHostMainline(TestBase): def run_ipv6_multi_host(self, default_as=None, per_node_as=None): """ Run a mainline multi-...
from distutils.spawn import find_executable import glob import os import StringIO import unittest from virtconv import VirtConverter from tests import utils base_dir = os.getcwd() + "/tests/virtconv-files/" out_dir = base_dir + "libvirt_output" conn = utils.open_kvm() class TestVirtConv(unittest.TestCase): def...
from functools import wraps from werkzeug import secure_filename, escape from flask import g, session, redirect, url_for from forms import LoginForm, SearchForm, DeleteForm, ExportForm, ImportForm def login_required(f): "view decorator that redirects nonauthenticated users to index" @wraps(f) def decorated...
from oslo_config import cfg from oslo_log import log as logging from nca47.common.i18n import _ from nca47.common.i18n import _LI from nca47.common.exception_zdns import ZdnsErrMessage from nca47.common.exception import NonExistDevices from nca47.api.controllers.v1 import tools import requests import json CONF = cfg.C...
"""Class-based request view for passing HTTP requests to Request instances""" from flask import request from flask.views import View from nidhogg.protocol.legacy import exceptions as exc from nidhogg.protocol.legacy import request as req class LegacyView(View): """Class-based view for legacy auth""" methods...
import csv import sys import traceback def excinfo(): """Retrieve exception info suitable for printing as command error.""" exc_type, exc_value, _ = sys.exc_info() return ''.join(traceback.format_exception_only(exc_type, exc_value)) # message: str | [str*] def error(output, message, exitcode=None): wr...
""" This module provides some glue code that allows the pycairo package to be used for drawing direclty on wx.DCs. In cairo terms, the DC is the drawing surface. The `CairoContextFromDC` function in this module will return an instance of the pycairo Context class that is ready for drawing, using the native cairo surf...
from msrest.serialization import Model class DdlName(Model): """A Data Lake Analytics DDL name item. :param first_part: the name of the table associated with this database and schema. :type first_part: str :param second_part: the name of the table associated with this database and schema. ...
class DesiredCapabilities(object): FIREFOX = { "browserName": "firefox", "version": "", "platform": "ANY", "javascriptEnabled": True } INTERNETEXPLORER = { "browserName": "internet explorer", "version": "", "platfo...
from nose.tools import assert_equal, assert_raises, assert_true # handle py3 and py2 cases: try: import unittest.mock as mock except ImportError: import mock patch = mock.patch import python_kemptech_api.exceptions as exceptions from python_kemptech_api.objects import VirtualService, RealServer class Test_...
from datetime import datetime from datetime import timedelta import fauxfactory import pytest from wrapanapi import VmState from cfme import test_requirements from cfme.control.explorer import alert_profiles from cfme.control.explorer import policies from cfme.control.explorer.alert_profiles import AlertProfileDetail...
from django.contrib.auth.models import User from django.shortcuts import resolve_url from django.test import TestCase from valentina.app.models import Profile, Chat, Affiliation, Message class TestCaseAPI(TestCase): """ This is basic test case for all API methods that are called within the chat page. It ...
#!/usr/bin/python # coding: utf-8 import subprocess import time import os import sys import MySQLdb from smtplib import SMTP, SMTPAuthenticationError, SMTPConnectError, SMTPSenderRefused import ConfigParser import socket import fcntl import struct import readline import random import string jms_dir = os.path.dirname(...
from spack import * class RCluster(RPackage): """Methods for Cluster analysis. Much extended the original from Peter Rousseeuw, Anja Struyf and Mia Hubert, based on Kaufman and Rousseeuw (1990) "Finding Groups in Data".""" homepage = "https://cloud.r-project.org/package=cluster" url = "https...
from collections import defaultdict, namedtuple from datetime import datetime, timedelta from random import shuffle from sqlalchemy import Boolean, Column, BigInteger, String, ForeignKey from sqlalchemy import DateTime from sqlalchemy.orm import relationship, backref from sqlalchemy.orm.session import object_session f...
#!/usr/bin/env python # coding=utf-8 """ Annotate module """ from __future__ import unicode_literals from __future__ import absolute_import __author__ = "Clare Corthell" __copyright__ = "Copyright 2015, summer.ai" __date__ = "2015-12-07" __email__ = "<EMAIL>" from nltk import pos_tag, word_tokenize, pos_tag_sents fro...
# -*- coding: utf-8 -*- """ combine.py ========== .. argparse:: :module: combine :func: create_parser :prog: combine.py .. code-block:: bash adam@work:~$ ls part.0 part.1 adam@work:~$ python combine -r ( 1/ 1) : . adam@work:~$ ls combined.pkl.gz part.0 part.1 .. moduleauthor:: ...
from keras.models import Model from keras.layers.core import Flatten, Dense, Dropout, Activation, Lambda, Reshape from keras.layers.convolutional import Conv2D, Deconv2D, ZeroPadding2D, UpSampling2D from keras.layers import Input, merge from keras.layers.advanced_activations import LeakyReLU from keras.layers.normaliza...
"""Support for Xiaomi curtain.""" import logging from homeassistant.components.cover import ATTR_POSITION, CoverDevice from . import PY_XIAOMI_GATEWAY, XiaomiDevice _LOGGER = logging.getLogger(__name__) ATTR_CURTAIN_LEVEL = "curtain_level" DATA_KEY_PROTO_V1 = "status" DATA_KEY_PROTO_V2 = "curtain_status" def set...
DETECT_SYSTEM3_RESULT = [('system', 'product', 'serial', 'Empty'), ('system', 'product', 'name', 'S2915'), ('system', 'product', 'vendor', 'Tyan Computer Corporation'), ('system', 'product', 'version', 'REFERENCE'), ...
import unittest import junit_xml import time import logging from mamba import formatters from mamba import reporter from mamba.application_factory import ApplicationFactory # UNITTEST JUNITXML class LoggerStream(object): @staticmethod def write(text): if text == '\n': text = '' ...
from touchdown.aws.common import Resource from touchdown.core import argument, serializers from touchdown.core.plan import Plan, Present from ..account import BaseAccount from .byte_match import ByteMatchSet from .ip_set import IpSet from .waf import WafApply, WafDescribe, WafDestroy class Match(Resource): """A...
import numpy as np from bokeh.objects import ColumnDataSource, DataRange1d, Plot, Glyph, LinearAxis, Grid from bokeh.widgetobjects import VBox, Tabs, Panel from bokeh.glyphs import (AnnularWedge, Annulus, Arc, Bezier, Circle, Line, MultiLine, Oval, Patch, Patches, Quad, Quadratic, Ray, Rect, Segment, Square, Wedge...
# -*- coding: utf-8 -*- NOT_DEFINED = 'X' NOT_DEFINED_NAME = 'Not Defined' NOT_DEFINED_VALUE = 1 # Exploit Code Maturity E_CODE = 'E' E_NAME = 'Exploit Code Maturity' E_UNPROVEN = 'U' E_PROOF_OF_CONCEPT = 'P' E_FUNCTIONAL = 'F' E_HIGH = 'H' E_HUMAN_READABLE = { E_UNPROVEN: 'Unproven', E_PROOF_OF_CONCEPT: 'P...
''' conf.py: common support for configurable objects ''' import string from core.api import coreapi class ConfigurableManager(object): ''' A generic class for managing Configurables. This class can register with a session to receive Config Messages for setting some parameters for itself or for the ...
import json from twisted.internet import defer from twisted.internet import threads from leap.soledad.client.events import SOLEDAD_SYNC_RECEIVE_STATUS from leap.soledad.client.events import emit_async from leap.soledad.client.http_target.support import RequestBody from leap.soledad.common.log import getLogger from lea...
__author__ = "Manuel Escriche <<EMAIL>>" import os, pickle, base64, requests from datetime import datetime from kconfig import trackersBook, trackersBookByKey from kconfig import tComponentsBook from kernel.Jira import JIRA class DataEngine: class DataObject: def __init__(self, name, storage): ...
# -*- 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 model 'Offer' db.create_table(u'hir_offer', ( (u'id', self.gf('django.db.models.fields....
import torch import torch.nn.functional as F from torch import nn from maskrcnn_benchmark.layers import ROIAlign from .utils import cat class LevelMapper(object): """Determine which FPN level each RoI in a set of RoIs should map to based on the heuristic in the FPN paper. """ def __init__(self, k_m...
#!/usr/bin/env python # -*- encoding: utf-8 """Plot view counts for YouTube playlists.""" __author__ = 'Wojciech Walczak' __email__ = 'ww(at)tosh.pl' import os import sys import pafy # see: https://github.com/np1/pafy import matplotlib.pyplot as plt def cr_results_path(): results_path = os.path.join('results', ...
""" Testing for Clustering methods """ import numpy as np from sklearn.cluster.affinity_propagation_ import AffinityPropagation from sklearn.cluster.affinity_propagation_ import affinity_propagation from sklearn.datasets.samples_generator import make_blobs from sklearn.metrics import euclidean_distances from sklearn....
"""Helper class for AsyncSamplesOptimizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import threading from six.moves import queue from ray.rllib.evaluation.metrics import get_learner_stats from ray.rllib.optimizers.aso_minibatch_buffer import Min...
import pytest from udata import search from . import response_factory, FakeSearch @pytest.mark.usefixtures('app') class SearchResultTest: def factory(self, response=None, **kwargs): ''' Build a fake SearchResult. ''' response = response or response_factory() query = searc...
# To clean html import justext from bs4 import BeautifulSoup # from boilerpipe.extract import Extractor # Boilerpipe is not currently being mantained. Removed till it comes back to live. def preprocess_html(text, preprocessor, forcePeriod): """ Options: preprocessor: justext, bs4, None con...
import os from setuptools import setup, find_packages def read_relative_file(filename): """Returns contents of the given file, which path is supposed relative to this module.""" with open(os.path.join(os.path.dirname(__file__), filename)) as f: return f.read() NAME = 'django-genericfilters-demo'...
"""Import Module Plotly To Ploting Graph""" import plotly.plotly as py import plotly.graph_objs as go """Get data""" data = open('Real_Final_database_02.csv') alldata = data.readlines() listdata = [] for i in alldata: listdata.append(i.strip().split(',')) type_z = ['Flood', 'Epidemic', 'Drought', 'Earthquake', 'S...
from __future__ import absolute_import from testutil.dott import feature, sh, testtmp # noqa: F401 # test sparse sh % "hg init myrepo" sh % "cd myrepo" ( sh % "cat" << r""" [extensions] sparse= rebase= """ >> "$HGRCPATH" ) sh % "echo a" > "index.html" sh % "echo x" > "data.py" sh % "echo z" > "readme....
import datetime import itertools import string import factory from base.models.enums import entity_type, organization_type from base.tests.factories.entity import EntityFactory def generate_acronyms(): acronyms_letters_generator = itertools.permutations(string.ascii_uppercase, r=4) for acronym_letters in ac...
from tcp import TcpServer from rpc import RPCConnection, RPCClient, load_all_handlers from protocol_manager import g_protoMgr from tornado.gen import coroutine from tornado import ioloop from os.path import dirname, abspath import logging import functools import config ...
""" !Changing this line will break Test_findfile.test_found! Non-gui unit tests for idlelib.GrepDialog methods. dummy_command calls grep_it calls findfiles. An exception raised in one method will fail callers. Otherwise, tests are mostly independent. *** Currently only test grep_it. """ import unittest from tes...
from oslo_config import cfg from magnum.i18n import _ trust_group = cfg.OptGroup(name='trust', title='Trustee options for the magnum services') trust_opts = [ cfg.BoolOpt('cluster_user_trust', default=False, help=_('This setting controls whether to assig...
input = """ % Date: Wed, 14 Oct 1998 10:22:30 -0500 (CDT) % From: Esra Erdem <<EMAIL>> % To: Gerald Pfeifer <<EMAIL>> % Message-ID: <<EMAIL>> % % This is the version for smodels, where I have replaced the compute{} statement % by a query and resolved two EDB/IDB problems by adding a rule of the form % sth :- tr...
""" Chromosome plotting functions. Notes ----- Adapted from Ryan Dale's GitHub Gist for plotting chromosome features. [#Dale]_ References ---------- .. [#Dale] Ryan Dale, GitHub Gist, https://gist.github.com/daler/c98fc410282d7570efc3#file-ideograms-py """ """ The MIT License (MIT) Copyright (c) 2016 Ryan Dale ...
# utils/serializer_utils.py # email: <EMAIL> import datetime import decimal import uuid import json from django.db.models import FieldDoesNotExist from django.db.models.fields.related import ManyToManyField from django.db.models.query import QuerySet from django.utils import six, timezone from django.utils.encoding i...
class IRCIPC(object): "explanation %(foo)s did %(bar)s" Parameters = [] # ["foo", "bar"] def __init__(self, **kwds): super(IRCIPC, self).__init__() for param in self.Parameters: optional = False if param[:1] == "?": param = param[1:] op...
from __future__ import absolute_import, unicode_literals import collections import json from django.shortcuts import render, redirect, get_object_or_404 from django.views.generic import ( ListView, FormView, DetailView, TemplateView, RedirectView) from chorddb.tab import parse_tablature, transpose_tablature from...
"""Translate Dutch HEEM labels to English. Usage: python translate_labels.py <dir with input texts> <dir for output texts> """ import os import codecs import argparse import json import pandas as pd from embem.machinelearningdata.count_labels import load_data from embem.emotools.heem_utils import heem_labels_en if _...
#!/usr/bin/python ''' Extract _("...") strings for translation and convert to Qt4 stringdefs so that they can be picked up by Qt linguist. ''' from subprocess import Popen, PIPE import glob import operator OUT_CPP="src/qt/yiffcoinstrings.cpp" EMPTY=['""'] def parse_po(text): """ Parse 'po' format produced by ...
""" Django settings for messager project. Generated by 'django-admin startproject' using Django 1.8.4. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build pat...
#!/usr/bin/env python import sys import os import re from pprint import pprint import getopt from time import sleep import logbook import beanstalkc log = logbook.Logger(os.path.basename(__file__) if __name__ == "__main__" else __name__) class BeanstalkWorker(object): ...
import subprocess import sys import os import setup_util def start(args, logfile, errfile): setup_util.replace_text("rails/config/database-jruby.yml", "host: .*", "host: " + args.database_host) try: subprocess.check_call("rvm jruby-1.7.8 do bundle install --gemfile=Gemfile-jruby", shell=True, cwd="rails", std...
from toolz.utils import raises from toolz.dicttoolz import (merge, merge_with, valmap, keymap, update_in, assoc, dissoc, keyfilter, valfilter, itemmap, itemfilter) inc = lambda x: x + 1 iseven = lambda i: i % 2 == 0 def test_merge(): assert merge({1: 1...
""" ArpCurses v1.0 - The ArpPoisoning tool. Copyright (C) 2016 Giovanni D'Italia 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. This progra...
"""Views for the Website submodule of the URY website. --- Copyright (c) 2013, University Radio York. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the a...
import collections import inspect import sys py3k = sys.version_info >= (3, 0) py2k = sys.version_info < (3,) py27 = sys.version_info >= (2, 7) jython = sys.platform.startswith("java") win32 = sys.platform.startswith("win") pypy = hasattr(sys, "pypy_version_info") ArgSpec = collections.namedtuple( "ArgSpec", ["ar...
#!/usr/bin/env python #-*- coding: utf-8 -*- import os import sys import subprocess import setuptools from functools import partial from setuptools import setup, Extension from distutils.sysconfig import get_python_inc try: from Cython.Build import cythonize USE_CYTHON = True except ImportError: USE_CYTH...
# -*- coding: utf-8 -*- GREGORIAN_EVENTS = { "01/01" : u"آغاز سال میلادی", "03/16" : u"تولد ریچارد استالمن (مؤسس بنیاد نرم‌افزار آزاد و پروژهٔ گنو)", "03/22" : u"روز جهانی آب", "03/23" : u"روز جهانی هواشناسی", "05/01" : u"روز جهانی کار و کارگر", "05/05" : u"روز جهانی ماما", "05/08" : u"روز جهانی صلیب سرخ و هلال ...
from openerp import api, models, fields class ResCompany(models.Model): _inherit = 'res.company' invoice_message = fields.Many2one( 'invoice.message', u'Mensagem padrão de saída', domain="[('message_type', '=', 'company')]" )
from HTMLParser import HTMLParser ContentDict = { '45': 'People that living in the modern world really cannot live without the social media sites like Twitter and Facebook. Almost all students and young adults possess the Facebook or Twitter account. It is true that social media makes people be able to connect one...
import pytest import os import shutil import py pytest_plugins = "pytester", class TestNewAPI: def test_config_cache_makedir(self, testdir): testdir.makeini("[pytest]") config = testdir.parseconfigure() with pytest.raises(ValueError): config.cache.makedir("key/name") p...
#!/usr/bin/env python """ Rust code generator, based on neovim-qt generator """ import msgpack import sys, subprocess, os import re import jinja2 import datetime INPUT = 'bindings' def decutf8(inp): """ Recursively decode bytes as utf8 into unicode """ if isinstance(inp, bytes): return inp.de...
# feedback on the End User’s use of the Software (e.g., any bugs in # the Software, the user experience, etc.). Harvard is permitted to # use such information provided by End User in making changes and # improvements to the Software without compensation or an accounting # to End User. # # 6. NON ASSERT. End User ackn...
import py from prolog.interpreter.heap import Heap from prolog.interpreter.term import AttVar, BindingVar, Callable, Number, Atom, AttMap def test_heap(): h1 = Heap() v1 = h1.newvar() v2 = h1.newvar() h1.add_trail(v1) v1.binding = 1 h2 = h1.branch() h2.add_trail(v1) v1.binding = 2 h...
#!/usr/bin/env python """Use this script to download a timeseries of mercurial commits on arbitrary machines using the credentials specified in year-in-review.ini. This script currently only extracts the timeseries for parent repositories, not for subrepositories! """ # standard library import ConfigParser import sys ...
# -*- coding: utf-8 -*- """Title translate module.""" # # (C) Pywikibot team, 2003-2018 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, division, unicode_literals import pywikibot from pywikibot import date from pywikibot import config from pywikibot.tools import deprecat...
# https://leetcode.com/problems/linked-list-cycle-ii/ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode ...
from .campaign import *
import re, os, sys from Tester import Tester from RunParallel import RunParallel # For TIMEOUT value class RunApp(Tester): @staticmethod def validParams(): params = Tester.validParams() params.addRequiredParam('input', "The input file to use for this test.") params.addParam('test_name', ...
import os import requests # pip install requests # Please NOTE: In this sample we're assuming Cloud Api Server is hosted at "https://localhost". # If it's not then please replace this with with your hosting url. # Base URL for PDF.co Web API requests BASE_URL = "https://localhost" # URL of web page to convert to PD...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json from ansible.compat.tests import unittest from ansible.compat.tests.mock import patch, MagicMock from ansible.errors import AnsibleModuleExit from ansible.modules.network.vyos import vyos_config from ansible....
#!/usr/bin/python # vim:fileencoding=utf-8 ''' ns-lookup.py: Example shows how to lookup for NS records Authors: Zdenek Vasicek (vasicek AT fit.vutbr.cz) Marek Vavrusa (xvavru00 AT stud.fit.vutbr.cz) Copyright (c) 2008. All rights reserved. This software is open source. Redistribution and use in s...
import numpy as np import pynbody from . import util, Files import os import gc def rockstar_iord_to_fpos(snapn): snap = pynbody.load(snapn) iord_to_fpos = util.init_iord_to_fpos(snap) del(snap) gc.collect() f = open(snapn+'.rockstar.halo_particles', 'rb') orig = np.fromfile(f, dtype=np.dtype('int64'), count=-1...
from threading import Lock from pprint import pformat try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django import http from django.core import signals from django.core.handlers.base import BaseHandler from django.dispatch import dispatcher from django.utils import d...
DEFAULT_OPENOFFICE_PORT = 8100 import uno from os.path import abspath, isfile, splitext from com.sun.star.beans import PropertyValue from com.sun.star.task import ErrorCodeIOException from com.sun.star.connection import NoConnectException FAMILY_TEXT = "Text" FAMILY_SPREADSHEET = "Spreadsheet" FAMILY_PRESENTATION = "...
# -*- coding: utf-8 -*- import type_mapper import get_prefix class delphi_property_parser: def __init__(self, src): self.src_ = src self.typeMapper = type_mapper.typeMapper() # E.g. the following delcaration in delphi: # property BendLen :Double read GetBendLen; # will ...
import pandas as pd from talib import MA_Type from .indicator import Indicator class BBANDS(Indicator): _NAME = 'bbands' def __init__(self, currency_pair='btc_jpy', period='1d', length=25, matype=MA_Type.EMA): super().__init__(currency_pair, period) self._length = self._bounded_length(length)...
#!/usr/bin/env python # # Use the raw transactions API to spend crowns received on particular addresses, # and send any change back to that same address. # # Example usage: # spendfrom.py # Lists available funds # spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00 # # Assumes it will talk to a crownd or Crown-Q...
"""menusortnodes submenu removed from editor menu Revision ID: 6cd40ed911a7 Revises: 59f52be1072d Create Date: 2019-07-30 16:40:13.566650 """ # revision identifiers, used by Alembic. revision = '6cd40ed911a7' down_revision = '59f52be1072d' branch_labels = None depends_on = None from alembic import op from sqlalchem...
# -*- 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 'Product.order' db.add_column(u'products_product', 'order', self.gf('dj...
"""Invenio module for common role based access control.""" from __future__ import absolute_import, print_function import pkg_resources import six from flask_principal import identity_loaded from werkzeug.utils import cached_property, import_string from . import config from .loaders import load_permissions_on_identit...
import datetime import unittest from dateutil.tz import tzutc from bloggertool.config.attrs import (attr, str_attr, bool_attr, set_of_str_attr, timestamp_attr, Record) class sample_attr(attr): from_...
from django.contrib import auth from django.utils.translation import get_language from django.views.generic import DetailView, UpdateView from pootle.core.delegate import profile from pootle.core.views import APIView from pootle.core.views.mixins import (NoDefaultUserMixin, TestUserFieldMixin, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # v1.36 # * fixed call checkfiles subroutine # v1.35 # * fixed rs-urls in handleFree(..) and freeWait(..) # * removed getInfo(..) function as it was not used anywhere (in this file) # * removed some (old?) comment blocks import re from module.network.RequestFactory impor...
#!/usr/bin/env python3 import logging import os import signal import time import pykka import pykka.debug class DeadlockActorA(pykka.ThreadingActor): def foo(self, b): logging.debug("This is foo calling bar") return b.bar().get() class DeadlockActorB(pykka.ThreadingActor): def __init__(sel...
import pytest from BeautifulSoup import BeautifulSoup def setup_module(mod): from starter import settings mod.templating = getattr(settings, 'TEMPLATING', False) def test_project_sanity(client): pass def test_finds_templates(): from django.template import loader assert loader.find_template('base...
from gi.repository import Gtk from gi.repository import Pango from lib.common import datafile_path class Statusbar(Gtk.Statusbar): '''Statusbar for main window''' def __init__(self, core, tviews): super(Statusbar,self).__init__() self.uicore = core self.tviews = tviews self.i...
""" Module implementing logging capabilities """ import time from PyQt5 import QtCore, QtWidgets, QtGui __author__ = 'Klemens Fritzsche' defaultLogFileName = 'config/logmessages.txt' class Logger(object): """ simple Logger, that prints messages to the screen and saves them to a file """ def __...
""" This dependency resolver resolves tool shed dependencies (those defined tool_dependencies.xml) installed using Platform Homebrew and converted via shed2tap (e.g. https://github.com/jmchilton/homebrew-toolshed). """ import logging import os from xml.etree import ElementTree as ET from .resolver_mixins import ( ...
import logging from os.path import join from syncloudlib import logger, fs from syncloud_platform.config import config from syncloud_platform.config.user_config import PlatformUserConfig from syncloud_platform.gaplib import linux, gen from syncloud_platform.injector import get_injector APP_NAME = 'platform' class ...
#!/usr/bin/env python import json import os import sys from argparse import ArgumentParser from PIL import Image, ImageOps from unitypack.environment import UnityEnvironment guid_to_path = {} def handle_rad_node(path, guids, names, tree, node): if len(node["folderName"]) > 0: if len(path) > 0: path = path + "...
import logging import magic # Use our monkey-patched link extractor from ..linkextractor import LxmlLinkExtractor from scrapy.exceptions import IgnoreRequest from scrapy.http import Request, HtmlResponse from scrapy.spidermiddlewares.httperror import HttpError from scrapy.utils.response import response_status_message ...
import six from twisted.internet import reactor from autobahn.twisted.wamp import ApplicationSession TICKETS = { u'user1': u'123secret', u'user2': u'456secret' } class ClientSession(ApplicationSession): def onConnect(self): realm = self.config.realm authid = self.config.extra[u'authid'] ...
""" gpr_fit_2d.py An example that uses functionality from the GPR module to regress a 2-Dimensional Function """ # ------------------------------------------------------------ # Imports # ------------------------------------------------------------ import time, os, sys, copy import numpy as np ...
#!/usr/bin/env python # Pentagon Numbers: # Find pairs of pentagonal numbers (Pn == n*(3*n-1)/2) # which are separated by another pentagonal number... # and sum to another pentagonal number # Minimize their difference MAX = 10000 def pentagonal(n): return n*(3*n-1)/2 # Perhaps the most interesting part here is t...
import time from dao.pid import * from controller.pid import * from config import * def control(key,input,Sp,min_output=None,max_output=None): dao = PidDao() def init_pid(): if not dao.get_pid_entry_for(key): if not min_output or not max_output: raise Exception("Min and max...
import fnmatch import os import re import StringIO import sys import zipfile rootPath = sys.argv[1] pattern = '*.zip' dataout = open('popbytract.csv','wb') dataout.write('LOGRECNO,GEOID,AREALAND,AREAWATER,POP100,HU100\n') for root, dirs, files in os.walk(rootPath) : for filename in fnmatch.filter(files, pattern): ...
class FourToZero: def __init__(self, i): self.position = i def initial_position(self): return self.position def primitive(self, pos): return pos == 0 def gen_moves(self): if self.position == 0: return [] elif self.position == 1: return [0] else: return [self.position - 1, self.position - 2]...
#-- GAUDI jobOptions generated on Fri Jul 24 17:21:43 2015 #-- Contains event types : #-- 13104093 - 92 files - 2038028 events - 551.09 GBytes #-- Extra information about the data processing phases: #-- Processing Pass Step-124834 #-- StepId : 124834 #-- StepName : Reco14a for MC #-- ApplicationName : B...