code stringlengths 1 199k |
|---|
from datetime import datetime
from urllib2 import urlopen
SITE = 'https://www.amazon.com/' # URL of the site to check
EXPECTED = 'Black Friday' # String expected to be on the page
def validate(res):
'''Return False to trigger the canary
Current this simply checks whether the EXPECTED string is present.
... |
import os
import sys
import Image
def get_size(size, org_size):
w1 = size[0]
w2 = org_size[0]
h1 = size[1]
h2 = org_size[1]
scale_w = ((100.0 / w2) * w1)
scale_h = ((100.0 / h2) * h1)
if scale_w > 100 and scale_h > 100:
return org_size
elif scale_w == scale_h:
return size... |
import sys
from heapq import heappush, heappop
maxq_left = [] # negatives #
minq_right = []
def get_median(x):
if len(minq_right) and x > minq_right[0]:
heappush(minq_right, x)
if len(minq_right) - 1 > len(maxq_left):
heappush(maxq_left, - heappop(minq_right))
else:
heappush(... |
import datetime
import decimal
import hashlib
import logging
import operator
import re
import sys
import threading
import uuid
from bisect import bisect_left
from bisect import bisect_right
from collections import deque
from collections import namedtuple
try:
from collections import OrderedDict
except ImportError:
... |
""" Reformulation of print statements.
Consult the developer manual for information. TODO: Add ability to sync
source code comments with developer manual sections.
"""
from nuitka.nodes.AssignNodes import (
ExpressionTargetTempVariableRef,
ExpressionTempVariableRef,
StatementAssignmentVariable,
Statemen... |
from twisted.trial import unittest
from buildbot.status.builder import SUCCESS
from buildbot.status.mail import MailNotifier
class FakeLog(object):
def __init__(self, text):
self.text = text
def getName(self):
return 'log-name'
def getStep(self):
class FakeStep(object):
d... |
"""
***************************************************************************
ModelerUtils.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
***************************************************... |
import requests
from requests.auth import HTTPBasicAuth
import config
def _url(path):
return ('https://communities.cyclos.org/' + config.COMMUNITY
+ '/api/' + path)
def authentication(name, password):
return HTTPBasicAuth(name, password)
def auth_data_for_login():
return requests.get(_url('auth/... |
'''
@author: Dimitrios Kanellopoulos
@contact: jimmykane9@gmail.com
'''
from google.appengine.api import users
import webapp2
class LoginRequiredHandler(webapp2.RequestHandler):
def get(self):
continue_url = self.request.get('continue')
self.redirect(users.create_login_url(continue_url))
app = webap... |
from morsel.actuators.ackermann_drive import AckermannDrive as Base
from morsel.actuators.panda.wheel_drive import WheelDrive
class AckermannDrive(WheelDrive, Base):
def __init__(self, **kargs):
super(AckermannDrive, self).__init__(**kargs) |
def makearq():
path = "modelo_entrada2.txt"
arq = open(path, 'w+')
data = '|'.join( [ str(i) for i in range(10000)] )
print(data)
arq.write(data)
arq.close()
makearq() |
'''
Created on Dec 15, 2014
@author: jadiel
'''
from tasksgraph.callableobject import AbstractTask
from sklearn.metrics import recall_score
from sklearn.metrics import precision_score
from sklearn.metrics import accuracy_score
from sklearn.metrics import f1_score
class Corpus:
'''
Contains the data together wit... |
class Solution(object):
def reverseBits(self, n):
"""
:type n: int
:rtype: int
"""
tmp = bin(n)[2 :]
binN = "0" * (32 - len(tmp)) + tmp
return int(binN[: : -1], 2) |
""" objbrowser package
"""
__all__ = ['browse', 'execute', 'create_object_browser', 'logging_basic_config']
import sys, os, logging, pprint, inspect
from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5 import QtWidgets
from objbrowser.objectbrowser import ObjectBrowser
from objbrowser.version import PROGRAM_NAME... |
import tempfile, subprocess, re, cgi, os, dateutil.parser, dateutil.tz, pystache
from PIL import Image, ImageChops, ImageDraw
def trim(path, margin):
image = Image.open(path).convert('RGB')
colour = image.getpixel((0,0))
background = Image.new('RGB', image.size, colour)
diff = ImageChops.difference(image, backgroun... |
"""This module contains utility functions for patch editing."""
from stgit import utils
from stgit.commands import common
from stgit.lib import git
from stgit import run
from tempfile import NamedTemporaryFile
import os
def run_commit_msg_hook(repo, message):
"""Run the commit-msg git hook manually when editing a p... |
import sys
import os
from nose.tools import assert_equals, assert_items_equal
from askap.iceutils import IceSession
from askap.slice import TypedValues
from askap.interfaces import TypedValueType as TVT
import askap.interfaces as AI
from askap.iceutils.typedvalues import *
from askap.interfaces import Direction, Coord... |
__author__ = "Mario Lukas"
__copyright__ = "Copyright 2017"
__license__ = "GPL v2"
__maintainer__ = "Mario Lukas"
__email__ = "info@mariolukas.de"
from fabscan.lib.util.FSInject import injector
from fabscan.scanner.interfaces.FSScanActor import FSScanActorInterface
from fabscan.scanner.interfaces.FSHardwareController i... |
"""
EasyBuild support for building and installing ESPResSo, implemented as an easyblock
@author: Josh Berryman <the.real.josh.berryman@gmail.com>
@author: Fotis Georgatos (Uni.Lu)
@author: Kenneth Hoste (Ghent University)
"""
import os
import easybuild.tools.environment as env
import easybuild.tools.toolchain as toolch... |
from cone.app.interfaces import IApplicationNode
from cone.app.interfaces import ILayout
from cone.app.model import AppRoot
from pyramid.security import authenticated_userid
from pyramid.threadlocal import get_current_request
from zope.component import adapter
from zope.interface import implementer
@implementer(ILayout... |
import logging
import sys
import traceback
from time import sleep, time
from threading import Thread
from flask import Flask, current_app
from flask.ext.sqlalchemy import SQLAlchemy
import memcache
from sqlalchemy.orm import mapper, relationship, backref
from bartendro import db, app
from bartendro import fsm
from bart... |
'''
Created on 2015-3-31
@author: 张天得
'''
from gateside.autotesting.Gat.dataobject.testcase.teststep import TestStep
class InterfaceTestStep(TestStep):
'''
接口测试TestStep基类
'''
def __init__(self):
'''
Constructor
''' |
from __future__ import absolute_import
from flask import Blueprint, render_template
index_bp = Blueprint('index', __name__)
@index_bp.route("/")
def home():
return render_template("index/home.html") |
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator
from decimal import Decimal
class UserProfile(models.Model):
"""Stores all the general account information."""
user = models.OneToOneField(User) # Käyttäjä, jonka profi... |
import os
import cgi
import urllib
import jinja2
import webapp2
from random import randint
from datetime import date,datetime
from google.appengine.api import users,mail,memcache
from google.appengine.ext import ndb
from webapp2_extras import sessions
from skipflog import *
app_name='susyandsteve'
config={'webapp2_extr... |
"""
CPython 3.1 bytecode opcodes
This is a like Python 3.1's opcode.py with some classification
of stack usage.
"""
from xdis.opcodes.base import (
def_op,
extended_format_ATTR,
extended_format_CALL_FUNCTION,
finalize_opcodes,
format_MAKE_FUNCTION_default_argc,
format_extended_arg,
init_opda... |
import sys, socket, json, random, hashlib, struct, thread
from threading import Thread
import logging.handlers, logging
from stun import StunServer
from jsocket import JsonSocket
from config import SERVER_PORT, OTHER_PORT, OTHER_SERVER, LOG_FILENAME
from config import OTHER_SERVER_REQUEST_TCP, OTHER_SERVER_REQUEST_UDP
... |
from __future__ import absolute_import
import cgi
import zlib
from .common import (
HTTP_OK,
)
from .. import (
util,
wireproto,
)
stringio = util.stringio
urlerr = util.urlerr
urlreq = util.urlreq
HGTYPE = 'application/mercurial-0.1'
HGERRTYPE = 'application/hg-error'
class webproto(wireproto.abstractserve... |
"""
Django settings for pickup project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
import socket
... |
from click_extra.platform import LINUX
from ..base import PackageManager
from ..version import TokenizedString, parse_version
class Snap(PackageManager):
platforms = frozenset({LINUX})
requirement = "2.0.0"
global_args = ("--color=never",)
version_regex = r"snap\s+(?P<version>\S+)"
"""
.. code-b... |
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 'Submission.similarity'
db.add_column('pootle_app_submission', 'similarity',
self.gf('django.db.mo... |
import os
from tests.component import (ComponentTestBase,
ComponentTestGitRepository,
skipUnless)
from tests.component.deb.fixtures import RepoFixtures
from nose.tools import ok_
from gbp.scripts.clone import main as clone
class TestClone(ComponentTestBase):
... |
"""
plugin for URLResolver
Copyright (C) 2020 gujal
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.
... |
"""
/***************************************************************************
Name : GdalTools
Description : Integrate gdal tools into qgis
Date : 17/Sep/09
copyright : (C) 2009 by Lorenzo Masini and Giuseppe Sucameli (Faunalia)
email : lorenxo86@gmail.com - br... |
""" Makefile generator which generates nmake files and VC8 SLN/VCPROJ files """
import os
import umake
import types
import re
umake.my_exec_file(os.path.join(umake.UMAKE_ROOT, "umake_win_makefile.py"), None, globals())
import md5
import log
project_extension = "vcproj"
workspace_extension = "sln"
def hexify(str):
r... |
from __future__ import print_function
import mx
import os
import tempfile
import zipfile
import shutil
from os.path import join, exists
def defaultFindbugsArgs():
args = ['-textui', '-low', '-maxRank', '15']
if mx.is_interactive():
args.append('-progress')
return args
def _get_spotbugs_attribute(p, ... |
"""
WSGI config for DjangoProTest project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICAT... |
import os
from twisted.web import server, static, resource
from buildbot.status.web.base import HtmlResource, ITopBox, build_get_class
from buildbot import interfaces, util
from buildbot.status.builder import SUCCESS, WARNINGS, FAILURE, EXCEPTION
from buildbot.status.web.baseweb import WebStatus
from waterfall import J... |
from pymate.matenet import MateNET, MateMXDevice
from time import sleep
from settings import SERIAL_PORT
print "MATE emulator (MX)"
bus = MateNET(SERIAL_PORT)
port = bus.find_device(MateNET.DEVICE_MX)
mate = MateMXDevice(bus, port)
mate.scan()
print "Revision:", mate.revision
print "Getting log page... (day:-1)"
logpag... |
from itertools import izip
from tcms.core.utils.tcms_router import connection
__all__ = ('SQLExecution',
'get_groupby_result',
'GroupByResult',
'workaround_single_value_for_in_clause')
def workaround_single_value_for_in_clause(build_ids):
'''Workaround for using MySQL-python 1.2.4
... |
"""
Tests for :module:`pagure.lib.encoding_utils`.
"""
from __future__ import unicode_literals, absolute_import
import chardet
import os
import unittest
import sys
sys.path.insert(0, os.path.join(os.path.dirname(
os.path.abspath(__file__)), '..'))
from pagure.lib import encoding_utils
class TestGuessEncoding(unitte... |
class Epsilon:
"""Null symbol used for epsilon transitions"""
pass
class NFAException(Exception):
pass
class NFAInvalidInput(NFAException):
pass
class NFA(object):
def __init__(self, alphabet):
"""
:param alphabet: Sequence of symbols making up the input alphabet
:return: Non... |
import sys
import re
sn = sys.argv[1].upper()
SRCDIR = "."
if len(sys.argv) > 2:
SRCDIR = sys.argv[2]
def parseLine(line):
m = re.match(r'^\s*from\s+([^\s]+)\s+import\s+\*\s+#\s*FIXED$', line)
pam = re.match(r'^\s*parseHelp\(\"([^\"]+)\"\)', line)
if(m != None):
f = open(SRCDIR + "/" + m.group(1) + ".py", "... |
"""
FILE: html.py
AUTHOR: Cody Precord
@summary: Lexer configuration module for HTML/DHTML/SGML.
@todo: Add Netscape/Microsoft Tag Extenstions (maybe)
@todo: Styleing needs lots of tweaking
"""
__author__ = "Cody Precord <cprecord@editra.org>"
__svnid__ = "$Id: html.py 59542 2009-03-15 00:23:37Z CJP $"
__revision__ = "... |
import abc
from core.lib.geo.grid import latlon_to_grid
__author__ = 'Federico Schmidt'
class WeatherSeriesMaker:
__metaclass__ = abc.ABCMeta
def __init__(self, system_config, max_paralellism):
self.system_config = system_config
@abc.abstractmethod
def create_series(self, location, forecast, ext... |
"""
@author: Peter Morgan <pete@daffodil.uk.com>
"""
from Qt import QtGui, QtCore, Qt, pyqtSignal
from img import Ico
import xwidgets
class GroupListModel(QtCore.QAbstractTableModel):
class C:
data_count = 0
group_code = 1
group_description = 2
def __init__(self):
QtCore.QAbstrac... |
from osgeo import ogr
import os.path
import psycopg2
import os.path
import subprocess
import util
import osr
from urllib import urlencode
from urllib2 import urlopen
import json
def import_shapefile(datastore, shapefile, table, overwrite=False):
#ogrds = _connect_to_db(datastore['host'], datastore['port'],datastore... |
from tquakes import *
print "*"*50+"\nRUNNING tquakes-eterna\n"+"*"*50
conf=loadConf("configuration")
predict="util/Eterna/ETERNA34/PREDICT.EXE"
station=loadConf(".stationrc")
print "Searching prepared quakes..."
qlist=System("ls data/quakes/*/.prepare 2> /dev/null")
if len(qlist)==0:
print "\tNo quakes prepared."
... |
import sys
import smbus
import math
import time
import RPi.GPIO as GPIO
def detector_setup(pins):
''' Sets a list of detector pins to input mode. '''
GPIO.setmode(GPIO.BOARD) # clarify which pin nums to use
for p in pins:
GPIO.setup(p, GPIO.IN) # set all pins as inputs
def read_byte(i2c, reg):
return bus.read_byt... |
OVH_SERVICE_NAME = None # "sms-XXYYYYY-Z"
OVH_APP_KEY = None
OVH_SECRET_KEY = None
OVH_CONSUMER_KEY = None
SENDER = None
RECIPIENTS = [] |
# first push all the element into a list by inorder
# then sort the array
# inorder visit the tree, then if the element is not equal to the
# array, change the values
class Solution:
# @param root, a tree node
# @return a tree node
def inorderVisit(self, root, contradict) :
if not r... |
import sys
from xml.sax import make_parser
from handlers import PyXMLConversionHandler
dh = PyXMLConversionHandler(sys.stdout)
parser = make_parser()
parser.setContentHandler(dh)
parser.parse(sys.stdin) |
import toxclient
import time
import xmlrpclib
import sys
import threading
import logging
import StringIO
import traceback
from xmlrpclib import Fault
logger = logging.getLogger('Toxxmlrpc_Server')
class Toxxmlrpc_Server(threading.Thread):
def __init__(self, srv_obj, path, password=None, client_id=None, disable_auto... |
import feedparser
import unicodedata
class FeedReader:
def __init__(self):
self.feeds = {'AP': {'top_headlines': 'http://hosted2.ap.org/atom/APDEFAULT/3d281c11a96b4ad082fe88aa0db04305',
'us': 'http://hosted2.ap.org/atom/APDEFAULT/386c25518f464186bf7a2ac026580ce7',
... |
import logging
logger = logging.getLogger(__name__)
import os
import bauble.utils.desktop as desktop
desktop.open = lambda x: x
import bauble
from bauble.test import BaubleTestCase
from unittest import TestCase
from bauble.plugins.plants import Family, Genus, Species, \
SpeciesDistribution, VernacularName, Geograph... |
import pytest
@pytest.fixture
def create_menu(remote, token):
"""
Creates a Menu "testmenu0" with a display_name "Test Menu0"
:param remote: The xmlrpc object to connect to.
:param token: The token to authenticate against the remote object.
"""
menu = remote.new_menu(token)
remote.modify_men... |
from django.conf import settings
from django import forms
from django.contrib.auth.models import User
from petri.bulletin.forms import BulletinForm
from petri.introduction.models import Introduction
class IntroductionForm(BulletinForm):
def save(self, instance=None, commit=True):
return super(IntroductionFo... |
import os
import sys
import pipes
class printer:
def __init__(self):
self.con = cups.Connection()
self.printer = self.con.getDefault()
pass
def print_strings (self, afile):
if not afile:
return
if sys.platform == 'linux':
''' Is this linux? '''
self.con.printFile(self.printer... |
import random
global userNumber
global tailResult
global headResult
coinSides = ['HEADS', 'TAILS']
def coinFlip(userNumber):
tailResult = 0
headResult = 0
for i in range(userNumber):
x = random.choice(coinSides)
if x == 'HEADS':
headResult += 1
elif x == 'TAILS':
tailResult += 1
print (x + " Heads: " +... |
import argparse
import traceback
import time
from stocker.common.version import stocker_version
def create_parser(desc, additional_help):
"""Common command line parser for every Stocker executable"""
parser = argparse.ArgumentParser(description="%s, version: %s\n%s"\
% (desc, stocker_version, additi... |
from random import randint
import numpy
def quicksort(iterable):
"""Return a generator object which will yield elements in order."""
if len(iterable) < 2:
for item in iterable:
yield item
else:
first, last = iterable[0], iterable[-1]
middle = iterable[len(iterable) // 2]
... |
"""packetradio, module for use with the RFM69HCW packet radio
created Dec 19, 2016 OM
work in progress - Mar 21, 2018
work in progress - Jan 18, 2020"""
"""
Copyright 2017, 2018, 2019, 2020 Owain Martin
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public Lic... |
import PyTango
try:
import EdfFile
except ImportError:
EdfFile = None
from Lima import Core
def getDataFromFile(filepath,index = 0) :
try:
datas = getDatasFromFile(filepath,index,index+1)
return datas[0]
except:
import traceback
traceback.print_exc()
return Core.Processlib.Data... |
from PyQt4.Qt import QApplication, QMessageBox, QDialog, QVBoxLayout, QLabel, QThread, SIGNAL
import PyQt4.QtCore as QtCore
from binascii import unhexlify
from binascii import hexlify
from struct import pack,unpack
from sys import stderr
from time import sleep
from base64 import b64encode, b64decode
import electrum
fro... |
import urlparse
import urllib
import urllib2
import json
import errno
import shutil
import tempfile
import os
import time
from PyQt4.QtCore import QObject, pyqtSignal, QTimer
from .strava import StravaUploader, StravaError
BASE_BB_URL = 'http://127.0.0.1:18888'
SUPPORTED_VERSIONS = ['2.6.0.8']
class BBClient(QObject):
... |
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from electrum_dvc.i18n import _
from util import *
import re
import math
def make_password_dialog(self, wallet, msg, new_pass=True):
self.pw = QLineEdit()
self.pw.setEchoMode(2)
self.new_pw = QLineEdit()
self.new_pw.setEchoMode(2)
self.conf_pw = Q... |
from pyGBot import log
from pyGBot.format import encodeOut
from pyGBot.Plugins.system.Commands import BaseCommand
from pyGBot.Plugins.system.Auth import AuthLevels as AL
class JoinChannel(BaseCommand):
level = AL.Admin
def __init__(self, bot, channel, user, args):
if args == '':
bot.noteout(... |
import numpy as np
def learn_read_signal_and_tags(filename, channel_list):
from sva2py import sva2py
s = sva2py(filename)
signal = np.zeros((len(channel_list), np.shape(s.channel(1,type='int'))[0]))
for channel in range(len(channel_list)):
ch = s.channel(channel_list[channel])
signal[channel] = ch
fs = s.sampl... |
"""package-wide constants"""
import os
from brown.core.brush_pattern import BrushPattern
from brown.core.pen_pattern import PenPattern
from brown.utils.color import Color
from brown.utils.units import ZERO, Inch, Mm
def _resolve_bool_env_variable(var):
value = os.environ.get(var)
return not (value is None or va... |
default_app_config = 'volunteer.apps.shifts.config.ShiftsConfig' |
from __future__ import unicode_literals
import frappe
import unittest
class TestItemQualityInspectionParameter(unittest.TestCase):
pass |
import numpy as np
import bet.sampling.adaptiveSampling as asam
import bet.sampling.basicSampling as bsam
import bet.postProcess.postTools as ptools
import scipy.io as sio
from scipy.interpolate import griddata
sample_save_file = 'sandbox3d'
param_domain = np.array([[-900, 1500], [.07, .15], [.1, .2]])
lam3 = 0.012
xmi... |
import os.path
from urllib.request import urlretrieve
from ligotimegps import __version__ as VERSION
project = 'ligotimegps'
copyright = "2010-2016, Kipp Cannon; 2017-2018 Duncan Macleod"
author = 'Duncan Macleod'
release = VERSION
extensions = [
'sphinx.ext.intersphinx',
'sphinx.ext.napoleon',
'sphinx_auto... |
import threading
class KillableThread(threading.Thread):
"""A base class for threads that die on command.
Subclasses' run() loops test if self.keep_alive is False.
Instead of sleeping, they should call nap().
And any subclass method, meant to be called by other
threads, that interrupts a nap() shoul... |
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = 0
for num in nums:
ans ^= num
return ans |
import gi
try:
gi.require_version('Gtk', '3.0')
except Exception as e:
print(e)
exit(1)
from gi.repository import Gtk
from comun import _
class EditAlbum(Gtk.Dialog):
def __init__(self, parent, album):
#
Gtk.Dialog.__init__(self)
self.set_title(_('Edit Album'))
self.set_m... |
import time
import logging
logger = logging.getLogger(__name__)
import re
import urllib
import urllib2
from ..htmlcleanup import stripHTML
from .. import exceptions as exceptions
from base_adapter import BaseSiteAdapter, makeDate
class TwilightedNetSiteAdapter(BaseSiteAdapter):
def __init__(self, config, url):
... |
import numpy as np
class VariableSlot(object):
def __init__(self, val, trainable):
self._val = val
self._grad = None
self._trainable = trainable
def load(self, another):
assert type(another) is VariableSlot
assert type(self.val) is type(another.val)
assert self.va... |
"""
Validity is module for validation created to help implement primitive and complex validation rules.
It implements :ref:`comparators` and :ref:`logical_operators`
Each of them extended from :class:`.Base` class and can be referred in documentation and examples as *validator*.
*validators* categories
~~~~~~~~~~~~~~~~... |
import pickle
from os import path
from time import time
from errorclass import *
DEBUG = True
PRINT = True
class Staff :
"""包含员工的详细信息"""
def __init__(self, Id, gender='男', name="") :
self.Id = Id
self.gender = gender
self.name = name
self.wTime = 0
self.wType = StaffConta... |
__author__ = 'student'
import turtle
turtle.shape('turtle')
a = 1
while a < 100:
turtle.forward(a)
turtle.right(10)
turtle.forward(a)
turtle.right(10)
a += 1 |
import geocode
from vegancity.models import FeatureTag, CuisineTag, Vendor, VeganDish, Review
from django.contrib.gis.geos import Point
def master_search(query, initial_queryset=None):
master_results = (address_search(query) |
Vendor.objects.approved().search(query) |
Fea... |
from copy import deepcopy
import numpy as np
from .errors import InvalidArgument
from .rng_tools import _eprop_distribution
from .test_functions import nonstring_container, is_integer
""" Helper functions for graph classes """
def _edge_prop(prop):
''' Return edge property `name` as a distribution dict '''
if i... |
"""
InaSAFE Disaster risk assessment tool developed by AusAid - **Aggregator.**
Contact : ole.moller.nielsen@gmail.com
.. note:: 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 versio... |
"""
InaSAFE Disaster risk assessment tool developed by AusAid and World Bank
- **Impact function Test Cases.**
.. note:: 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 2 of t... |
import io, gevent, weakref
from sakura.common.events import EventSourceMixin
from sakura.common.gpu.tools import write_rgb_frame
from sakura.common.gpu.openglapp import MouseMoveReporting
from sakura.common.gpu.openglapp.streamer import Streamer
class OpenglAppBase(EventSourceMixin):
def __init__ (self, handler):
... |
from . import server, client
from gi.repository import GObject
from .cards import cards
RL = GObject.SIGNAL_RUN_LAST
class GameSeat(GObject.GObject):
__gsignals__ = {
'join': (RL, None, ()),
'leave': (RL, None, ()),
'update': (RL, None, ()),
}
def __init__(self, snr):
super(G... |
qf = qepcad_formula
var('t012,e01,e10,e12,e21')
top_c = e01*e10^2*e12^2*e21*t012 - e12^3 - 1
bot_c = e21^3*t012 + t012 - e01^2*e10*e12*e21^2
cyan_pos = qf.and_(top_c > 0, bot_c > 0)
cyan_neg = qf.and_(top_c < 0, bot_c < 0)
cyan_0 = qf.and_(top_c== 0, bot_c== 0)
top_y = e01*e10^3*e12^2*e21*t012 + e01*e12^2*e21*t012 - ... |
"""
:mod:`terrain` -- Calculate terrain multiplier
===============================================================================
This module is called by the module
:term:`all_multipliers` to calculate the terrain multiplier for an input tile
for 8 directions and output as NetCDF format.
:References:
Yang, T., Na... |
import pygame
GAME_NAME = "Push into the Pit"
SCREEN_SIZE = (640, 448)
LEVEL_SIZE = (10, 7)
TILE_SIZE = 64
IMAGE_CHAR_UP = pygame.image.load('images/char_up.png')
IMAGE_CHAR_DOWN = pygame.image.load('images/char_down.png')
IMAGE_CHAR_LEFT = pygame.image.load('images/char_left.png')
IMAGE_CHAR_RIGHT = pygame.image.load(... |
"""
mpsvm_classify_ripley.py
Performs binary classification on Ripley's synthetic dataset using
a MinMaxSvm with mixing coefficient of 0.5.
"""
from __future__ import division, print_function
import argparse
import os
import numpy as np
import pymp
METHOD = pymp.Methods.dccp_weighted
def parse_dataset(filenames=('synth... |
def not_found(*args):
'''
Simple reminder that you:
a) didn't set a default not_found handler.
b) missed configuring routes
'''
return "I have no idea what you're looking for, bro.\nDo you even lift?\n"
class Request_Router(object):
def __init__(self, not_found_handler=not_found):
# ... |
import os
import re
from rest_framework.parsers import JSONParser
from django.contrib.auth.models import User, check_password
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.hashers import PBKDF2PasswordHasher
from mocambola.serializers import UserSerializer
from mucua.models import Muc... |
""" Usage:
./hatt2egsa.py
"""
""" Example HATT lines:
1,6985.90,-14252.00,0
2,7002.70,-14366.20,0
3,7016.20,-14421.50,0
4,7033.40,-14477.40,0
5,7062.10,-14549.30,0
6,7084.00,-14611.10,0
7,7128.50,-14702.80,0
8,7143.90,-14725.10,0
9,7154.20,-14731.00,0
10,7185.70,-14761.90,0"""
""" Correct values EGSA87 (GGRS87, GR8... |
"""
Copyright (C) 2013 Arpit Chauhan, Inderjit Sidhu and Archit Pandey
This file is part of cryptographic-protocols-arduino-and-PC source code.
cryptographic-protocols-arduino-and-PC 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 Sof... |
import threading
from boto.s3.connection import S3Connection
from boto.s3.key import Key
from boto.s3.bucket import Bucket
import boto.exception
import logging
import Queue
import time
import sys
import re
class S3SyncWorker(threading.Thread):
def __init__(self, queue, done_signal, dest_bucket, logger, creds, pre_chec... |
import os, sys, gi, requests, re, datetime, random,\
requests.exceptions as ecs, urllib.parse as urlparse,\
sqlite3 as lite
from io import BytesIO
from PIL import Image
from gi.repository import Gtk, Gdk, GdkPixbuf, GObject, GLib
sys.path.append(".")
from settings import icns, set_user_agent,\
ua_browsers_dsc, ua_brows... |
"""
Configurations
"""
__author__ = "pwxc"
import config_default
class Dict(dict):
"""
Simple dict but support access as x.y style.
"""
def __init__(self, names=(), values=(), **kw):
super(Dict, self).__init__(**kw)
for k, v in zip(names, values):
self[k] = v
def __getatt... |
"""
Reading and writing BVH body model movement files.
"""
from __future__ import with_statement
from imusim.trajectories.rigid_body import SampledBodyModel, SampledJoint, \
PointTrajectory
from imusim.maths.quaternions import Quaternion
from imusim.maths.transforms import convertCGtoNED, convertNEDtoCG
import ... |
'''
Created on May 5, 2014
@author: riccardo
Model an affiliation
fields:
name
country code
'''
class Affiliation(object):
__name=""
__countryCode=""
def __init__(self, name, countryCode):
self.__name = name
self.__countryCode = countryCode
def get_name(self):
return self.__name
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.