code
stringlengths
1
199k
""" Setup file for the Cython port of PyGalileo """ import os, shutil from os import path from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext from Cython.Build import cythonize this_dir = path.abspath(path.dirname(__file__)) src_dir_path = path.join(this_dir...
""" Copyright 2016, Paul Powell, All rights reserved. """ import abc class Matchup: __metaclass__ = abc.ABCMeta def __init__(self, teams): self.teams = teams # Set these in _play win winner and loser are determined self.winner = None self.loser = None # Return a winner Team o...
from poppy_4dof_arm_mini import Poppy4dofArmMini
""" logstash output module """ from .output import output import json import socket import logging import datetime class logstash(output): """ class to handle logstash json output """ T_UDP = 0 T_TCP = 1 aProto = ["UDP", "TCP"] # ---------------------------------------------------------- def __...
""" Methods to perform a GLUE type model calibration. """ import os import numpy import math import datetime import zipfile import wsconf import bbgc_db import FileManager from CalculateFunctions import DerivedOutputs as CaOut import ReportGenerator import logging import logging.config logging.config.fileConfig('lo...
""" This is an example of how to copy files via paramiko. """ import os import sys import paramiko server = "172.34.5.111" username = "ubuntu" key_filename = os.path.expanduser("~/.aws/keys/ec2_instances.pem") sshcon = paramiko.SSHClient() sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy()) sshcon.connect( ...
from rob_interface import * def webcam_test(r): import pyopencv as cv cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE) capture = cv.CaptureFromCAM(0) def repeat(): frame = cv.QueryFrame(capture) cv.ShowImage("w1", frame) while True: repeat() def fix_date_to_front(r): fname_lis...
import gtk import pygtk class ChartControl(gtk.Table): def __init__(self, chart): gtk.Table.__init__(self, 21, 3) self.set_row_spacings(2) self.set_col_spacings(6) self.set_border_width(6) self.chart = chart self._init_title() self._init_background() s...
import sys import numpy from subprocess import Popen, PIPE def read_output_feat_dim (exp): p = Popen (['am-info', exp+'/final.mdl'], stdout=PIPE) for line in p.stdout: if b'number of pdfs' in line: return int(line.split()[-1]) def compute_priors (exp, ali_tr, ali_cv=None): dim = read_out...
__author__ = 'Davide' import numpy as np from numpy.lib.stride_tricks import as_strided def main(): a = np.array([1, 2, 3, 4, 5], dtype=np.int8) b = np.array([3], dtype=np.int8) c = as_strided(b, shape=(5,), strides=(0,)) print(a + c) if __name__ == "__main__": main()
import os,sys,numpy import matplotlib.pyplot as plt import pyfits from Script.Utils import LiMa from ctoolsAnalysis.config import get_config,get_default_config try: get_ipython().magic(u'pylab') except : pass try: #conf file provided config = get_config(sys.argv[-1]) except : print "usage : python "+sy...
import os import sys import numpy as np from itertools import combinations_with_replacement from collections import defaultdict, OrderedDict from scipy.interpolate import interp1d import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as pyplot DATA_DIR = os.getenv('GBRS_DATA', '.') def get_chromosome_info(ca...
from chatterbot import ChatBot bot = ChatBot( "NaiveBot", # Nom storage_adapter="chatterbot.storage.JsonFileStorageAdapter", input_adapter="chatterbot.input.TerminalAdapter", output_adapter="chatterbot.output.TerminalAdapter", logic_adapters=[ # Désactiver le logic_adapters pour le learning ...
import os import numpy as np import pandas as pd df = pd.DataFrame(columns=['pre-job input', 'opening input file', 'upto appmgr start', 'initialisation', 'event loop', 'ending']) filecount = 0 included = 0 for subdir, dirs, files in os.walk('/work/d60/d60/shared/optimisation/benchmark/test1/output'): for file in fi...
from __future__ import absolute_import import unittest import networkx as nx from algorithm.expanding.expander import * class TestTIES(unittest.TestCase): def test_convert_graph_to_indicated(self): # Arrange expander = Expander() graph = nx.Graph() graph.add_edge(0, 1) graph....
def log2enestep(ifile, ofile): step = 0 for line in ifile: if line.startswith(" Step"): step = int(line.split()[1]) elif line.startswith(" Potential"): ofile.write("%s %s\n" % (line.split()[-1], step)) def main(): import sys if len(sys.argv) != 2: impo...
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ] operations = [ migrations.CreateModel( ...
class Process: def next(self, game, action): pass class SandwichProcess(Process): def __init__ (self): self.state = 0 def next(self, game, action): if self.state == 0: self.state = 1 game.process_push(self) self.pre(game) elif self.state ==...
import subprocess import argparse import os try: import awscli except ImportError as e: print("You haven't installed awscli!" " Please install by 'pip install awscli'.") exit() def query_latest_version(dataset): cmd = ['aws', 's3', 'ls', '--no-sign-request', 's3://openneuro/%s/' % d...
import logging import re import string from PyQt4.QtCore import QObject, SIGNAL, pyqtSignal, QString, QDir import constants class Utils(object): def __init__(self): ''' ''' self.log = logging.getLogger('Utils') #self.log.debug('__init__ start') #self.log.debug('__init__ end')...
"""Browser widgets for items $Id: boolwidgets.py 39064 2005-10-11 18:40:10Z philikon $ """ __docformat__ = 'restructuredtext' from zope.interface import implements from zope.schema.vocabulary import SimpleVocabulary from zope.app.form.browser.widget import SimpleInputWidget, renderElement from zope.app.form.browser.wid...
""" mediatum - a multimedia content repository Copyright (C) 2007 Arne Seifert <seiferta@in.tum.de> Copyright (C) 2007 Matthias Kramm <kramm@in.tum.de> Copyright (C) 2011 Werner F. Neudenberger <neudenberger@ub.tum.de> This program is free software: you can redistribute it and/or modify it under the terms of the ...
"""Test Vector Normalization """ __author__ = 'Brandyn A. White <bwhite@cs.umd.edu>' __license__ = 'GPL V3' import unittest import hadoopy from normalize import Mapper, Reducer class Test(hadoopy.Test): def __init__(self, *args, **kw): super(Test, self).__init__(*args, **kw) def test_map(self): ...
import unittest import umlgen.Base.SwComponent.PortInterface.RequiredPort class RequiredPortTest(unittest.TestCase): def setUp(self): # self._testInstance = umlgen.Base.SwComponent.PortInterface.RequiredPort.RequiredPort() # Start of user code setUp # End of user code pass def te...
import sys import math import h5py as h5 import numpy as np import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import discopy.util as util xscale = "log" yscale = "log" GAM = 1.66666666667 RMAX = 0.8 GR = False CM = mpl.cm.afmhot def plotCheckpoint(file): print("Loading {0:s}...".format(file)) ...
""" Copyright (C) 2014 Technische Universität Berlin, Fakultät IV - Elektrotechnik und Informatik, Fachgebiet Regelungssysteme, Einsteinufer 17, D-10587 Berlin, Germany This file is part of PaPI. PaPI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as publish...
import os import sys if __name__== "__main__": startrun = int(sys.argv[1]) endrun = int(sys.argv[2]) + 1 print "Commands:" for run in range(startrun, endrun): print "./pd_led_pmt_combinedfit_analysis "+ str(run) for run in range(startrun, endrun): print "Doing:" print "./pd_l...
""" Interface to telemetry streams -- log, network, or serial. Copyright (C) 2014-2015 Tau Labs, http://taulabs.org Copyright (C) 2015-2016 dRonin, http://dronin.org Licensed under the GNU LGPL version 2.1 or any later version (see COPYING.LESSER) """ import socket import time import array import select import errno im...
from django.contrib import admin from edc_base.modeladmin_mixins import audit_fieldset_tuple from edc_base.fieldsets import Remove from bcpp_visit_schedule.constants import T1, T2, T3 from ..admin_site import bcpp_subject_admin from ..forms import LabourMarketWagesForm from ..models import LabourMarketWages from .grant...
""" The primary geometry elements, layout and organization classes. The objects found here are intended to correspond directly to elements found in the GDSII specification. The fundamental gdsCAD object is the Layout, which contains all the information to be sent to the mask shop. A Layout can contain multiple Cells wh...
from manitae.maps.MapTile import MapTile class GrassTile(MapTile): color = "green" def __init__(self, tile=None): super(GrassTile, self).__init__(tile) self.tile_type = GrassTile
from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Peer', fields=[ ('id', models.AutoField(verbose...
from argparse import ArgumentParser from PIL import Image import numpy as np import os def rgb_to_hsv(c): # c = c.astype(np.float64) / 65535 # to 0 -> 1 r = c[:, :, 0] g = c[:, :, 1] b = c[:, :, 2] amax = np.argmax(c, axis=2) amin = np.argmin(c, axis=2) [yy, xx] = np.mgrid[0:c.shape[0], 0:c.shape[1]] yy = np.ra...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: docker_image short_description: Manage docker images. version_a...
import serial, sys import rospy class MotorController: def __init__(self, zeros, port): self.test_mode=False try: self.ser = serial.Serial(port) #self.ser.open() self.ser.write(chr(0xAA)) self.ser.flush() except serial.serialutil.SerialExceptio...
""" pc_wnd_main_srv This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. revision 0.1 2017/abr mlabru initial release (Linux/Python) """ __version__ = "$revision: 0.1$" __author__ = "Milton A...
import espressopp import math import gromacs class FileBuffer(): def __init__(self): self.linecount=0 self.lines=[] self.pos=0 def appendline(self, line): self.lines.append(line) def readline(self): try: line=self.lines[self.pos] except: ...
import django import os import sys sys.path.insert(0,'/home/reed/github/multi_realtor') print(sys.path) os.environ['DJANGO_SETTINGS_MODULE'] = 'multi_realtor.settings' django.setup() BOT_NAME = 'housescraper' SPIDER_MODULES = ['housescraper.spiders'] NEWSPIDER_MODULE = 'housescraper.spiders' ROBOTSTXT_OBEY = True ITEM_...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('main', '0001_initial'), ] operations = [ migrations.AddField( model_name='faculty', name='collage', field=models.Fore...
import os import signal import sys from .lib.core.input import CliArgumentParser from .lib.find_dns import find_dns from .lib.hostname_scan import hostname_scan from .lib.ping_sweeper import ping_sweeper from .lib.service_scan import service_scan from .lib.snmp_walk import snmp_walk from .lib.virtual_host_scanner impor...
from bitarray import bitarray from netzob.Common.Utils.Decorators import typeCheck, NetzobLogger from netzob.Inference.Vocabulary.Search.SearchTask import SearchTask class SearchResults(list): def __str__(self): return "{0} occurence(s) found.".format(len(self)) @NetzobLogger class SearchResult(object): ...
from datetime import datetime, timedelta from . import db class RoleInvite(db.Model): __tablename__ = 'role_invite' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String) event_id = db.Column(db.Integer, db.ForeignKey('events.id', ondelete='CASCADE')) event = db.relationship('Even...
''' user.models Powered by https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#auth-custom-user ''' from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser class HDUserManager(BaseUserManager): def create_user(self, email, password=None): if not email...
from gettext import gettext from gi.repository import Gdk from gi.repository import Gio from gi.repository import GnomeBuilder from gi.repository import GObject from gi.repository import Gtk import os import relevance SUFFIXES = { '.c': '.h', '.h': '.c', '.cc': '.hh', '.hh': '.cc', '.cxx': '.hxx', ...
from flask import Flask, render_template from flask_bootstrap import Bootstrap from flask_moment import Moment from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_nav import Nav from config import config bootstrap = Bootstrap() moment = Moment() db = SQLAlchemy() nav = Nav() login_ma...
from django.db import models from vamdctap.bibtextools import * class Term: l = 0 s = 0 class Species(models.Model): id = models.IntegerField(null=False, primary_key=True, blank=False) atomsymbol = models.CharField(max_length=6, db_column='AtomSymbol', blank=True) atomnuclearcharge = models.IntegerF...
""" this piece of code is an example of how to use the parametric design gearwheel You can also use this file as a FreeCAD macro from the GUI You can also copy-paste this code in your own design files If you don't know which value to set to a constraint-parameter, just comment it. Default value is used, if you don't se...
from gi.repository import Gtk from cgi import escape from gettext import gettext as _ from lollypop.define import Lp class ToolbarPlayback(Gtk.Bin): """ Playback toolbar """ def __init__(self): """ Init toolbar """ Gtk.Bin.__init__(self) builder = Gtk.Buil...
import subprocess import json import os.path SYSFS_TURBO_PATH='/sys/devices/system/cpu/intel_pstate/no_turbo' SYSFS_NUMA_PATH='/sys/devices/system/node/online' SYSFS_PSTATES_PATH='/sys/devices/system/cpu/intel_pstate/num_pstates' SYSFS_CSTATES_PATH='/sys/devices/system/cpu/cpuidle/current_driver' ''' Reference: 1. Inte...
from numpy.testing import * import numpy.distutils.fcompiler intel_32bit_version_strings = [ ("Intel(R) Fortran Intel(R) 32-bit Compiler Professional for applications"\ "running on Intel(R) 32, Version 11.1", '11.1'), ] intel_64bit_version_strings = [ ("Intel(R) Fortran IA-64 Compiler Professional for appl...
""" ISO country codes from http://www.bcpl.net/~jspath/isocodes.html """ import csv import os from lino import adamo factbookDir = os.path.dirname(__file__) def populate(q): s = """\ ad Andorra, Principality of ae United Arab Emirates af Afghanistan, Islamic State of ag Antigua and Barbuda ai An...
from sys import argv script, input_file = argv def print_all(f): print(f.read()) def rewind(f): f.seek(0) def print_a_line(line_count, f): print(line_count, f.readline()) current_file = open(input_file) print("First let's print the whole file:\n") print_all(current_file) print("Now let's rewind, kind of lik...
import pytest from helperFunctions.virtual_file_path import ( get_base_of_virtual_path, get_top_of_virtual_path, join_virtual_path, merge_vfp_lists, split_virtual_path ) @pytest.mark.parametrize('virtual_path, expected_output', [ ('', []), ('a|b|c', ['a', 'b', 'c']), ('|a|b|c|', ['a', 'b', 'c']), ]) def...
from math import pi, sqrt import numpy as np from ase.units import Hartree from ase.parallel import paropen from gpaw.utilities import pack from gpaw.analyse.wignerseitz import wignerseitz from gpaw.setup_data import SetupData from gpaw.gauss import Gauss from gpaw.io.fmf import FMF from gpaw.utilities.blas import gemm...
import unittest import ossie.utils.testing import os from omniORB import any class ComponentTests(ossie.utils.testing.ScaComponentTestCase): """Test for all component implementations in interleave_ss_1i""" def testScaBasicBehavior(self): ##################################################################...
"""**SAFE (Scenario Assessment For Emergencies) - API** The purpose of the module is to provide a well defined public API for the packages that constitute the SAFE engine. Modules using SAFE should only need to import functions from here. Contact : ole.moller.nielsen@gmail.com .. note:: This program is free software; y...
""" =================================================== Faces recognition example using eigenfaces and SVMs =================================================== The dataset used in this example is a preprocessed excerpt of the "Labeled Faces in the Wild", aka LFW_: http://vis-www.cs.umass.edu/lfw/lfw-funneled.tgz (233...
import math from brown.common import * brown.setup() flowable = Flowable((Mm(0), Mm(0)), Mm(500), Mm(30), Mm(10)) staff = Staff((Mm(0), Mm(0)), Mm(500), flowable, Mm(1)) unit = staff.unit clef = Clef(staff, unit(0), "treble") KeySignature(clef.bounding_rect.width + unit(0.5), staff, "g_major") center = unit(20) n1 = No...
from __future__ import unicode_literals from wiki.core.version import get_version VERSION = (0, 3, 0, 'beta', 3) __version__ = get_version(VERSION)
import Adafruit_BluefruitLE from Adafruit_BluefruitLE.services import UART ble = Adafruit_BluefruitLE.get_provider() def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network ...
""" Bagger_Controll_Modul V:0.3.1 Programm Modul zum aufsetzen der Befehle, welche zur Inbetriebnahme und Steuerung des Baggers notwendig sind. """ import time from RPi import GPIO import pygame from nanpy import ArduinoApi from nanpy import SerialManager from threading import * import logging import os import date...
from copy import copy from StringIO import StringIO class LumpBuilderMock(object): def __init__(self): self.call_history = [] def delete_path(self, path): self.call_history.append(['delete_path', path]) def mkdir(self, path): self.call_history.append(['mkdir', path]) def get_node...
from pyspark import SparkContext, SparkConf, SQLContext, Row, HiveContext from pyspark.sql.types import * from datetime import date, datetime, timedelta import sys, re, os st = datetime.now() conf = SparkConf().setAppName('PROC_DP_CBOD_TDACNACN_I').setMaster(sys.argv[2]) sc = SparkContext(conf = conf) sc.setLogLevel('W...
"""Import to graph task.""" from f8a_worker.base import BaseTask import requests from os import environ from selinon import StoragePool from f8a_worker.models import Ecosystem class GraphImporterTask(BaseTask): """Import to graph task.""" _SERVICE_HOST = environ.get("BAYESIAN_DATA_IMPORTER_SERVICE_HOST", "bayes...
class Word(unicode): def __init__(self, string): super(Word, self).__init__(string) if not u':' in string: self.tag, self.expression = None, string else: self.tag, self.expression = string.split(u':', 1) self.__length__ = len(string)
import numpy as np import pandas as pd import pystan path_to_data = 'https://raw.githubusercontent.com/astrobayes/BMAD/master/data/Section_10p1/M_sigma.csv' data_frame = dict(pd.read_csv(path_to_data)) data = {} data['obsx'] = np.array(data_frame['obsx']) data['errx'] = np.array(data_frame['errx']) data['obsy'] = np.ar...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = r''' --- module: postgresql_ping short_description: Check remote PostgreSQL server availability descripti...
""" moa.provider.core ----------------- Provides templates from the Moa package. """ import os import shutil import Yaco from moa.template import provider class Local(provider.ProviderBase): def __init__(self, name, data): super(Local, self).__init__(name, data) self.directory = os.path.abspath( ...
from modules.mmpython import mediainfo import struct import re import stat import os import fourcc PACKET_TYPE_HEADER = 0x01 PACKED_TYPE_METADATA = 0x03 PACKED_TYPE_SETUP = 0x05 PACKET_TYPE_BITS = 0x07 PACKET_IS_SYNCPOINT = 0x08 STREAM_HEADER_VIDEO = '<4sIQQIIHII' STREAM_HEADER_AUDIO = '<4sIQQIIHHHI' _print =...
from functools import total_ordering import h5py from progressbar import ProgressBar import numpy import random from rdkit import Chem from sklearn.manifold import MDS def fingerprint_with_new_index(smiles_file_path, random_order): prefix = smiles_file_path[:smiles_file_path.rfind('.')] smiles_file = h5py.File(...
from PySide import QtCore, QtGui class Ui_AssetBrowserWidget(object): def setupUi(self, AssetBrowserWidget): AssetBrowserWidget.setObjectName("AssetBrowserWidget") AssetBrowserWidget.resize(1000, 800) self.verticalLayout = QtGui.QVBoxLayout(AssetBrowserWidget) self.verticalLayout.set...
class AbstractCCGCategory(object): ''' Interface for categories in combinatory grammars. ''' # Returns true if the category is primitive def is_primitive(self): raise AssertionError, 'AbstractCCGCategory is an abstract interface' # Returns true if the category is a function application ...
""" WSGI config for My_Django_Experimental_Website project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdef...
'''Wrappers and tools for image manipulation.''' import pygame def load(filename): '''Load image with alpha channel (if it's possible).''' image = pygame.image.load(filename) return image if not pygame.display.get_init() else image.convert_alpha() def horizontal_flip(image): '''Perform horizontal flip t...
from setuptools import setup, find_packages def readme(): with open("README.md", 'r') as f: return f.read() setup( name="idnest", description="A RESTful API for nested identifier association", version="0.0.1", long_description=readme(), author="Brian Balsamo", author_email="balsamo@u...
from __future__ import (absolute_import, division, print_function) from mantid.kernel import Logger from ui.sans_isis.diagnostics_page import DiagnosticsPage from ui.sans_isis.work_handler import WorkHandler from sans.common.enums import IntegralEnum from sans.gui_logic.gui_common import get_detector_strings_for_diagno...
import unittest """215. Kth Largest Element in an Array https://leetcode.com/problems/kth-largest-element-in-an-array/description/ Find the **k** th largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. **Example 1:** **Input:** [3,2,1,5,6,4...
import os from django.contrib.gis.utils import LayerMapping from .models import Site site_mapping = { 'id' : 'ID', 'name': 'NAME', 'lat': 'ID', 'lon': 'ID', 'elevation': 'ID', 'shape' : 'POINT', } site_shp = os.path.abspath( os.path.join(os.path.dirname(__file__), 'data', 'sample_points_fiel...
import urllib, urllib2 import datetime import traceback import sickbeard from sickbeard import logger from sickbeard.common import UNAIRED from sickbeard import db from sickbeard import exceptions, helpers from sickbeard.exceptions import ex from lib.tvdb_api import tvdb_api, tvdb_exceptions class TVRage: def __ini...
""" DB model for a counter to keep track of next uidNumber and gidNumber to use for new LDAP objects. """ from django.db import models, transaction class Counters(models.Model): """ Keep track of next uidNumber and gidNumber to use for new LDAP objects. """ scheme = models.CharField(max_length=20, db_index=...
def iteration_factorial(num): result = num for member in range(1, num): result *= member return result def recursion_factorial(num): if num == 1: return 1 else: return num * recursion_factorial(num - 1) number = int(input("please input number")) if number > 10: print("num...
"""Utility functions to support Experiment classes """ import re scriptTarget = "PsychoPy" unescapedDollarSign_re = re.compile(r"^\$|[^\\]\$") # detect "code wanted" valid_var_re = re.compile(r"^[a-zA-Z_][\w]*$") # filter for legal var names nonalphanumeric_re = re.compile(r'\W') # will match all bad var name chars ...
from django.contrib import admin from .models import Exam, Question class QuestionInline(admin.TabularInline): model = Question extra = 3 class ExamAdmin(admin.ModelAdmin): fieldsets = [(None, {'fields': ['title']})] inlines = [QuestionInline] admin.site.register(Exam, ExamAdmin)
import unittest from pyAmore.baseline.interface import mlp_network from pyAmore.baseline.materials import * from pyAmore.baseline.network_fit_strategies import * from pyAmore.baseline.network_predict_strategies import * from pyAmore.baseline.neuron_fit_strategies import * from pyAmore.baseline.neuron_predict_strategies...
from __future__ import unicode_literals from django.db import models, migrations import datetime class Migration(migrations.Migration): dependencies = [ ('rules', '0027_auto_20141231_0953'), ] operations = [ migrations.AlterField( model_name='category', name='created_...
from mock import (call, patch, MagicMock) import os import subprocess from testscenarios import TestWithScenarios from unittest import TestCase from c2dconfigutils.cu2dTrigger import JobTrigger class TestGenerateTrigger(TestWithScenarios, TestCase): scenarios = [ ('ci', { 'project': 'f...
from django.http import HttpResponseNotAllowed, JsonResponse from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from django.conf import settings def issue_notification(acting_user, verb, target, recipients='WATCHERS', **notification_kwargs): # Create a not...
"""Base classes for trpg.""" class _Base: __slots__ = "_items" def __getitem__(self, i): return self._items[i] def __iter__(self): return iter(self._items) def __len__(self): return len(self.__iter__()) def __contains__(self): return x in self.__iter__() def __eq__(self, x...
"""Run test for local worker. Set-up new data store with single experiment. Create prediction to test the local worker code. """ from pymongo import MongoClient import os import shutil import unittest from neuropythy.freesurfer import add_subject_path from scodata import SCODataStore from scodata.mongo import MongoDBFa...
from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty from mantid.kernel import Direction from mantid.simpleapi import * from mantid import mtd class OptimizeCrystalPlacementByRun(PythonAlgorithm): def summary(self): return "Optimizes the sample position for each run in a peaks w...
"""This plugin depends on the HR3 plugin, as it uses its parser internally""" import base, hr3 class YouFmParser(hr3.HR3Parser): """YouFM""" __station__ = 'YouFM' def __init__(self, url='http://www3.admin.hr-online.de/playlist/playlist.php?tpl=youfm', stream='mms://212.211.137.135/3219youfm_live.wmv...
from django.test import TestCase from django.utils import timezone from girox.event.models import Event class EventModelTest(TestCase): def setUp(self): self.title = 'Evento 1' self.event = Event.objects.create( title=self.title, description='Descrição do Evento...', ...
""" !--------------------------------------------------------------------------! ! LICENSE INFO: ! !--------------------------------------------------------------------------! ! This file is part of fortebiopkg. ...
def main(argv=None): from argparse import ArgumentParser import random parser = ArgumentParser(description="Generat a random problem instance.") parser.add_argument('-s', '--seed', type=int, help='seed for random number generator') parser.add_argument('-r', '--resources', type=int, help='number of r...
from blueman.Functions import * from blueman.plugins.AppletPlugin import AppletPlugin import gtk import gobject class StatusIcon(AppletPlugin, gtk.StatusIcon): __unloadable__ = False __icon__ = "blueman" def on_entry_changed(self, entry, ic, image): if ic.has_icon(self.get_option("icon")): icon = gtk.STOCK_APPL...
TIMESCALE = 1000; # in ps
def is_false(): """ @rtype: bool """ if True: return False else: return True
import os import sys from Bio import SeqIO from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord def blocks(sequence, block_length): """Yield successive n-sized blocks from l.""" for i in xrange(0, len(sequence), block_length): yield sequence[i:i+block_length] if __name__ == '__main__': #define...
from django.apps import AppConfig class NotificationManagementConfig(AppConfig): """ Notification manager app Config """ name = 'app_dir.notification_management' verbose_name = 'Notification Management' app_label = 'notification_management' def ready(self, ): pass
import sys import time import re import MySQLdb import MySQLdb.cursors import traceback import functions as func class mysqlClient(): def __init__(self, host, port, user=func.get_config("monitor_mysql","user"), password=func.get_config("monitor_mysql","passwd"), db='mysql'): self.ip = host self.port...