code stringlengths 1 199k |
|---|
from rest_framework.pagination import PageNumberPagination as DrfPageNumberPagination
class PageNumberPagination(DrfPageNumberPagination):
# Client can control the page using this query parameter.
page_query_param = 'page'
# Client can control the page size using this query parameter.
# Default is 'None... |
"""
------
Urls
------
Arquivo de configuração das urls da aplicação blog
Autores:
* Alisson Barbosa Ferreira <alissonbf@hotmail.com>
Data:
============== ==================
Criação Atualização
============== ==================
29/11/2014 29/11/2014
============== ==================
"""
from django.conf... |
import re
import defaults
from lib import *
class MKGuitestFailed(MKException):
def __init__(self, errors):
self.errors = errors
MKException.__init__(self, _("GUI Test failed"))
class GUITester:
def __init__(self):
self.guitest = None
self.replayed_guitest_step = None
sel... |
import sqlite3
import RPi.GPIO as GPIO
import os, sys, time
conn = sqlite3.connect( os.path.join( os.path.dirname(os.path.realpath(sys.argv[0])), 'db/timelapsecontroller.db'))
conn.row_factory = sqlite3.Row
sleep=2
def set_pid(pid=None):
c = conn.cursor()
try:
# Update the DB counter
c.execute("UPDATE timel... |
import os
import re
import time
import xbmc
import xbmcvfs
import xbmcgui
import urllib2
import bjsonrpc
from bjsonrpc.handlers import BaseHandler
from quasar.addon import ADDON, ADDON_PATH
from quasar.logger import log
from quasar.config import JSONRPC_EXT_PORT, QUASARD_HOST
from quasar.osarch import PLATFORM
from qua... |
from jinja2 import Environment, FileSystemLoader
import yaml
from tornado.ioloop import IOLoop
from tornado.web import RequestHandler
from bokeh.application import Application
from bokeh.application.handlers import FunctionHandler
from bokeh.embed import server_document
from bokeh.layouts import column
from bokeh.model... |
from setuptools import setup, find_packages
import os
version = '0.5'
setup(name='uwosh.emergency.master',
version=version,
description="",
long_description=open("README.txt").read() + "\n" +
open(os.path.join("docs", "HISTORY.txt")).read(),
# Get more strings from http://... |
"""
Date :
Author : Vianney Gremmel loutre.a@gmail.com
"""
def memo(f):
class Memo(dict):
def __missing__(self, key):
r = self[key] = f(key)
return r
return Memo().__getitem__
@memo
def isprime(n):
for d in xrange(2, int(n**0.5) + 1):
if n % d == 0:
return... |
import io
from bs4 import BeautifulSoup
from bs4 import SoupStrainer
import urllib2
import urlparse
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from sel... |
import unittest
import os
import logging
import re
import shutil
import datetime
import oeqa.utils.ftools as ftools
from oeqa.selftest.base import oeSelfTest
from oeqa.utils.commands import runCmd, bitbake, get_bb_var
from oeqa.utils.decorators import testcase
from oeqa.utils.network import get_free_port
class BitbakeP... |
from omf import feeder
import omf.solvers.gridlabd
feed = feeder.parse('GC-12.47-1.glm')
maxKey = feeder.getMaxKey(feed)
print(feed[1])
feed[maxKey + 1] = {
'object': 'node', 'name': 'test_solar_node', 'phases': 'ABCN',
'nominal_voltage': '7200'
}
feed[maxKey + 2] = {
'object': 'underground_line', 'name': 'test_sola... |
import re
from gourmet.plugin import ExporterPlugin
from gourmet.convert import seconds_to_timestring, float_to_frac
from . import gxml2_exporter
from gettext import gettext as _
GXML = _('Gourmet XML File')
class GourmetExportChecker:
def check_rec (self, rec, file):
self.txt = file.read()
self.rec... |
__author__= "barun"
__date__ = "$20 May, 2011 12:25:36 PM$"
from metrics import Metrics
from wireless_fields import *
DATA_PKTS = ('tcp', 'udp', 'ack',)
def is_control_pkt(pkt_type=''):
return pkt_type not in DATA_PKTS
class TraceAnalyzer(object):
'''
Trace Analyzer
'''
def __init__(self, file_name... |
from solrinterface import SolrInterface, UNTOKENIZED_PREFIX, SORTED_PREFIX
from fields2solrdoc import Fields2SolrDoc
from cql2solrlucenequery import Cql2SolrLuceneQuery |
"""
ScormDropDown Idevice.
"""
import logging
from exe.engine.idevice import Idevice
from exe.engine.path import Path
from exe.engine.field import ClozeField, TextAreaField
from exe.engine.persist import Persistable
from HTMLParser import HTMLParser
from exe.engine.mimetex import compile
from exe.engin... |
import sys
import os
sys.path.insert(0, os.path.abspath('../west'))
extensions = [
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.pngmath',
'sphinx.ext.mathjax',
'sphinx.ext.viewcode',
'sphinx.ext.autodoc',
'sphinx.ext.graphviz',
'sphinx.ext.autosummary',
'sphinx.ext.intersphinx',
'sp... |
from property import *
iaf_neuronparams = {'E_L': -70.,
'V_th': -50.,
'V_reset': -67.,
'C_m': 2.,
't_ref': 2.,
'V_m': -60.,
'tau_syn_ex': 1.,
'tau_syn_in': 1.33}
STDP_synapseparams... |
import sys
from timer import Timer
import os
import pandas as pd
import nipy
import numpy as np
import re
import argparse
def get_images_list(path, regexp, number_images=None):
im_list=[]
dir_list=os.listdir(path)
if regexp=="NO":
im_list=dir_list
return dir_list
reg=re.compile(regexp)
... |
from setuptools import setup, find_packages, Extension
recoil_module = Extension('_recoil', sources=['recoil_interface.c', 'recoil.c'])
def readme():
with open('README.rst') as f:
return f.read()
setup(
name="pyrecoil",
version="0.3.1",
packages=find_packages(),
ext_modules=[recoil_module],
... |
from random import uniform as randfloat
class BankAccount:
'A simple class to store money.'
money = 0
owner = ""
def __init__(self, owner, money):
self.owner = owner
self.money = round(money, 2)
def getOwner(self):
return self.owner
def getMoney(self):
return self... |
import woo.core, woo.dem
from woo.dem import *
import woo.utils
from minieigen import *
from math import *
from woo import utils
m=woo.utils.defaultMaterial()
zeroSphere=woo.utils.sphere((0,0,0),.4) # sphere which is entirely inside the thing
for p in [woo.utils.sphere((0,0,0),1,mat=m),woo.utils.ellipsoid((0,0,0),semiA... |
from roam.api import RoamEvents
from PyQt4.QtGui import QLineEdit, QPlainTextEdit
from PyQt4.QtCore import QEvent
from roam.editorwidgets.core import EditorWidget, registerwidgets
class TextWidget(EditorWidget):
widgettype = 'Text'
def __init__(self, *args):
super(TextWidget, self).__init__(*args)
d... |
from django.apps import apps as django_apps
from django.core.exceptions import ObjectDoesNotExist
from django.views.generic.base import ContextMixin
class SubjectOffstudyViewMixinError(Exception):
pass
class SubjectOffstudyViewMixin(ContextMixin):
"""Adds subject offstudy to the context.
Declare with Subjec... |
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
import django_filters
from rest_framework import viewsets
from rest_framework.response import Response
from api.serializers import UserSerializer, AddressSerializer, DestinationSerializer, GuestSerializer, MessageSerializer, Open... |
from dnfpyUtils.stats.statistic import Statistic
import numpy as np
class Trajectory(Statistic):
"""
Abstract class for trajectory
"""
def __init__(self,name,dt=0.1,dim=0,**kwargs):
super().__init__(name=name,size=0,dim=dim,dt=dt,**kwargs)
self.trace = [] #save the trace
def ... |
import PyKDE4.kdeui as __PyKDE4_kdeui
import PyQt4.QtCore as __PyQt4_QtCore
import PyQt4.QtGui as __PyQt4_QtGui
class KIconDialog(__PyKDE4_kdeui.KDialog):
# no doc
def getIcon(self, *args, **kwargs): # real signature unknown
pass
def iconSize(self, *args, **kwargs): # real signature unknown
... |
import os
import DT
import sys
import time
import marshal
import stat
def phfunc(name, obj):
marshal.dump(obj, open(name,'w'))
if __name__=='__main__':
bt = time.time()
fname=sys.argv[1]
mtime=os.stat(fname)[stat.ST_MTIME]
cform=sys.argv[1]+'.dtcc'
try:
cmtime=os.stat(cform)[stat.ST_MTIM... |
import os
import sys
import getopt
import smtplib
try: from email.mime.text import MIMEText
except ImportError:
# Python 2.4 (CentOS 5.x)
from email.MIMEText import MIMEText
import socket
import email.utils
THIS_SERVER = socket.gethostname()
SMTP_SERVER = 'YOUR_SMTP_HERE'
SMTP_PORT = 25
SMTP_SSL = False
SMTP_AU... |
import CCDroplet
import CC_params
import CC_out
import LiquidVaporEq |
import os
from subprocess import PIPE
from subprocess import Popen
import jinja2
DIST_PATH = "..\\build\\exe.win32-3.6"
INSTALL_FILES = []
INSTALL_DIRS = []
os.chdir(os.path.join(os.path.dirname(__file__), DIST_PATH))
for root, dirs, files in os.walk("."):
for f in files:
INSTALL_FILES += [os.path.join(root... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from builtins import round
import gdb
import re
import zlib
import sys
from datetime import timedelta
if sys.version_info.major >= 3:
long = int
from crash.exceptions import DelayedAttributeError
from crash.... |
import os
import unittest
import inotify.constants
import inotify.calls
import inotify.adapters
import inotify.test_support
try:
unicode
except NameError:
_HAS_PYTHON2_UNICODE_SUPPORT = False
else:
_HAS_PYTHON2_UNICODE_SUPPORT = True
class TestInotify(unittest.TestCase):
def __init__(self, *args, **kwar... |
from bottle import request
from sqlalchemy import exc
from libraries.database import engine as db
from libraries.template import view
from libraries.status import Status
from libraries.authentication import login_required
from libraries.forms import Name as Form
from libraries.forms import Blank as BlankForm
from libra... |
"""
S. Leon @ ALMA
Classes, functions to be used for the array configuration evaluation with CASA
HISTORY:
2011.11.06:
- class to create the Casas pads file from a configuration file
2011.11.09:
- Class to compute statistics on the baselines
2012.03.07L:
- Class to manipulate the vis... |
from __future__ import absolute_import
import time
import threading
from . import log
class IndexError(Exception):
"""IndexError: a Data History index is out of range
"""
pass
class DataFailure(Exception):
"""DataError: a problem occurred while trying to collect the data,
(ie, while calling module.c... |
import Image
class Path:
##
# Creates a path object.
#
# @param xy Sequence. The sequence can contain 2-tuples [(x, y), ...]
# or a flat list of numbers [x, y, ...].
def __init__(self, xy):
pass
##
# Compacts the path, by removing points that are close to each
# other. ... |
import os
import sys
import time
import types
import yaml
import logging
import subprocess
from collections import OrderedDict
from contextlib import contextmanager
from lava_dispatcher.config import get_device_config
class InfrastructureError(Exception):
"""
Exceptions based on an error raised by a component o... |
import web
import json
import datetime
import time
import uuid
from onsa_jeroen import *
render_xml = lambda result: "<result>%s</result>"%result
render_json = lambda **result: json.dumps(result,sort_keys=True,indent=4)
render_html = lambda result: "<html><body>%s</body></html>"%result
render_txt = lambda result: resul... |
import requests
from bs4 import BeautifulSoup
import sys
import os
import pandas
import re
targetURL = "http://www.ubcpress.ca/search/subject_list.asp?SubjID=45"
bookLinks = "http://www.ubcpress.ca/search/"
outputDir = "UBC_Output"
def main():
r = requests.get(targetURL)
soup = BeautifulSoup(r.content, "html.pa... |
'''
Author: Thomas Beucher
Module: Experiments
Description: Class used to generate all the trajectories of the experimental setup and also used for CMAES optimization
'''
import numpy as np
import time
from GlobalVariables import pathDataFolder
from TrajMaker import TrajMaker
from Utils.FileWriting import checkIfFolder... |
from __future__ import print_function
import sys
import os
import time
import numpy as np
np.random.seed(1234) # for reproducibility
import theano
import theano.tensor as T
import lasagne
import cPickle as pickle
import gzip
import binary_net
from pylearn2.datasets.mnist import MNIST
from pylearn2.utils import serial
... |
from hba_util import HBA
from raid_util import Raid_Util
from subdev import *
def test_create_remove_raid(raid_util, bdevs):
sub_dev_list = []
for bdev in bdevs:
path = '/dev/' + bdev
sub_dev_list.append(path)
raid_util.set_sub_dev_list(sub_dev_list)
raid_util.zero_raid_sub_dev()
rai... |
import re,os,itertools,sys,csv
from collections import defaultdict #Assumption: Python version >= 2.5
import functools
import pybel
class descriptorsFilesProcessor():
def __init__(self):
pass
def match_ids_to_string_fp_features(self,string_fp_file,jCompoundMapperStringFeatures=False):
id2string_fp_features = {} #... |
'''
Implementation in scipy form of the Double Pareto-Lognormal Distribution
'''
import numpy as np
from scipy.stats import rv_continuous, norm
def _pln_pdf(x, alpha, nu, tau2):
A1 = np.exp(alpha * nu + alpha ** 2 * tau2 / 2)
fofx = alpha * A1 * x ** (-alpha - 1) *\
norm.cdf((np.log(x) - nu - alpha * ta... |
from __future__ import print_function
__author__ = 'gpanda'
"""References:
[1] easy thread-safe queque, http://pymotw.com/2/Queue/
"""
import argparse
import collections
import fileinput
import os
import pprint
import re
import string
import sys
import threading
import time
import Queue
from libs import driver
from lib... |
import paypalrestsdk
import logging
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from settings import PAYPAL_MODE, PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET
def paypal_create(request):
"""
MyApp > ... |
"""
This is the single point of entry to generate the sample configuration
file for mvpn. It collects all the necessary info from the other modules
in this package. It is assumed that:
* every other module in this package has a 'list_opts' function which
return a dict where
* the keys are strings which are the grou... |
"""
invenio.ext.sqlalchemy
----------------------
This module provides initialization and configuration for
`flask.ext.sqlalchemy` module.
"""
import sqlalchemy
from flask.ext.registry import RegistryProxy, ModuleAutoDiscoveryRegistry
from flask.ext.sqlalchemy import SQLAlchemy as FlaskSQLAlchemy
from s... |
def capable(d1,d2):
for key in d1.keys():
if not d2.has_key(key) or d1[key] > d2[key]
return False
return True
def main(s):
count = {}
for c in s:
if count.has_key(c):
count[c] += 1
else:
count[c] = 1
A_count = { key:count[key]/2 for key in count.keys() }
i = 0
f
while A_co... |
import gzip
import os
def writePolys(pl, f):
"""Write a list of polygons pl into the file f.
The result is under the form [[[ra1, de1],[ra2, de2],[ra3, de3],[ra4, de4]], [[ra1, de1],[ra2, de2],[ra3, de3]]]"""
f.write('[')
for idx, poly in enumerate(pl):
f.write('[')
for iv, v in enumerat... |
import os
import shutil
import struct
from cStringIO import StringIO
from tempfile import mkstemp
from tests import TestCase, add
from mutagen.mp4 import MP4, Atom, Atoms, MP4Tags, MP4Info, \
delete, MP4Cover, MP4MetadataError
from mutagen._util import cdata
try: from os.path import devnull
except ImportError: dev... |
from PySide.QtNetwork import QHostInfo, QHostAddress
def getAddress(hostname, preferIPv6=None):
info=QHostInfo()
adr=info.fromName(hostname).addresses()
if not adr: return None
if preferIPv6 is None:
return adr[0].toString()
for a_ in adr:
a=QHostAddress(a_)
if preferIPv6:
... |
import unittest
from Powers import Powers
from Polynomial import Polynomial
import Taylor
class Sine(unittest.TestCase):
def test_terms(self):
s = Taylor.Sine(1, 0)
self.assert_(not s[0])
self.assert_(not s[2])
self.assert_(not s[4])
self.assert_(s[1] == Polynomial(1, terms={... |
import work_queue as wq
def divide(dividend, divisor):
import math
return dividend/math.sqrt(divisor)
def main():
q = wq.WorkQueue(9123)
for i in range(1, 16):
p_task = wq.PythonTask(divide, 1, i**2)
# if python environment is missing at worker...
#p_task.specify_environment("env... |
import argparse
import csv
import codecs
import configparser
import xml.etree.ElementTree as ET
import re
from SvgTemplate import SvgTemplate, TextFilter, ShowFilter, BarcodeFilter, StyleFilter, SvgFilter
from SvgTemplate import clean_units, units_to_pixels, strip_tag
class LabelmakerInputException(Exception):
pass
d... |
from __future__ import division
import itertools
import operator
import collections
debug = True
to_bin = lambda integer: zero_filler(bin(integer)[2:])
def zero_filler(filling_string):
result = ""
if len(filling_string) != 4:
result = filling_string
else:
return filling_string
while len(... |
from __future__ import print_function
import sys
import argparse
import gentoolkit
from .app_util import format_options_respect_newline
from gentoolkit.base import mod_usage, main_usage
DEFAULT_OPT_INDENT = 2
DEFAULT_COL_INDENT = 25
class ArgumentParserWrapper(object):
"""A simple wrapper around argparse.ArgumentParse... |
from utils.mysqldb import *
import os
def main():
conf_file = "/home/ivana/.mysql_conf"
mapping_file = "encode_esr1_xps.tsv"
for dependency in [conf_file, mapping_file]:
if not os.path.exists(dependency):
print(dependency,"not found")
exit()
encode_exp_id = {}
encode_file_id = {}
ucsc_ids = []
with o... |
from pyramid.view import view_config
@view_config(name='sso', renderer='templates/login.pt')
def sign_on(context, request):
""" Perform the SAML2 SSO dance.
- If the request already has valid credentials, process the 'SAMLRequest'
query string value and return a POSTing redirect.
- If processing the P... |
import MySQLdb as mdb
import uuid, pprint
def generate(data):
gdata = []
for grade in range(1,4):
for clazz in range(1,10):
if grade != data['grade_number'] and clazz != data['class_number']:
gdata.append("insert into classes(uuid, grade_number, class_number, school_uuid) values('%s', %d, %d, '%s');" % (unic... |
"""
MoinMoin wiki stats about updated pages
Config example::
[wiki]
type = wiki
wiki test = http://moinmo.in/
The optional key 'api' can be used to change the default
xmlrpc api endpoint::
[wiki]
type = wiki
api = ?action=xmlrpc2
wiki test = http://moinmo.in/
"""
import xmlrpc.client
from di... |
import os, sys, re, json
from praw2 import Reddit
reload(sys)
try:
from xbmc import log
except:
def log(msg):
print(msg)
sys.setdefaultencoding("utf-8")
CLIENT_ID = 'J_0zNv7dXM1n3Q'
CLIENT_SECRET = 'sfiPkzKDd8LZl3Ie1WLAvpCICH4'
USER_AGENT = 'sparkle streams 1.0'
class SubRedditEvents(object):
as_reg... |
from enigma import eTimer, iServiceInformation, iPlayableService, ePicLoad, RT_VALIGN_CENTER, RT_HALIGN_LEFT, RT_HALIGN_RIGHT, RT_HALIGN_CENTER, gFont, eListbox, ePoint, eListboxPythonMultiContent, eServiceCenter, getDesktop
from Components.MenuList import MenuList
from Screens.Screen import Screen
from Screens.Service... |
import argparse
import sys
from suricata.update import commands, config
from suricata.update.version import version
try:
from suricata.update.revision import revision
except:
revision = None
default_update_yaml = config.DEFAULT_UPDATE_YAML_PATH
show_advanced = False
if "-s" in sys.argv or "--show-advanced" in s... |
"""
Classes and functions wrapping the apt-pkg library.
The apt_pkg module provides several classes and functions for accessing
the functionality provided by the apt-pkg library. Typical uses might
include reading APT index files and configuration files and installing
or removing packages.
"""
from .object import objec... |
"""Module implementing configuration details at runtime.
"""
import grp
import pwd
import threading
from ganeti import constants
from ganeti import errors
_priv = None
_priv_lock = threading.Lock()
def GetUid(user, _getpwnam):
"""Retrieve the uid from the database.
@type user: string
@param user: The username to ... |
def standard_process_to_geoserver():
# check no data value
print "standard_process_to_geoserver"
def _process():
# process to 3857 or 4326
print "process to 3857 or 4326" |
from openerp.osv import osv, fields
import openerp.tools as tools
from openerp.tools.translate import _
from tools import config
import openerp.netsvc as netsvc
import decimal_precision as dp
class sale_order_line(osv.Model):
def product_id_change(self, cr, uid, ids, pricelist, product, qty=0,
u... |
"""
* Copyright (c) 2017 SUSE LLC
*
* openATTIC 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; version 2.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY W... |
from Tkinter import *
import ttk
import time
from PIL import ImageTk,Image
from functools import partial
import os
import tkMessageBox
from urllib2 import *
from threading import Thread
import urllib as u
from window import *
def netControl():
try:
u.urlopen("http://example.com")
return True
exc... |
from .plots import Plot,PlotError
from .. import context
from .. import items
from .. import maps
from .. import waypoints
from .. import monsters
from .. import dialogue
from .. import services
from .. import teams
from .. import characters
import random
from .. import randmaps
from .. import stats
from .. import spel... |
import sys
reload(sys)
sys.setdefaultencoding('UTF8')
if len(sys.argv)>1: #si el argumento existe
archive = open(sys.argv[1],"r")
text = []
for i in archive:
text.append(i)
for j in i:
print unicode(j) |
from datetime import datetime
from mechanize import Browser
from FrenchLawModel import Text, Article, Version, Law
from page import ConstitutionPage, ArticlePage
class LegifranceClient(object):
host = 'http://www.legifrance.gouv.fr/'
def __init__(self):
self.user_agent = 'Mozilla/4.0 (compatible; MSIE 6... |
import BaseHTTPServer
import thread
import urlparse
import string
from move import Move
from move import MoveInfo
from battery import BatteryStatus
move = Move()
def sendResponse(s, code, message):
print "... ", s.path
s.send_response(code)
s.send_header("Content-type", "text/html")
s.end_headers()
m = "<html... |
from datetime import datetime
import cProfile
class ProfileMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if hasattr(request, 'profiler'):
profiler = cProfile.Profile()
profiler.enable()
resp... |
from distutils.core import setup
import sys
import py2exe
try:
scriptName = sys.argv[3]
except IndexError:
print "Usage: python setup.py py2exe -i nombreApp"
sys.exit(2)
setup(
name=scriptName,
version="2.0",
description="Aplicacion Python creada con py2exe",
author="Pueyo Luciano",
author_email="Pueyo... |
'''
Filter text output by date ranges
'''
import os
import csv
import sys
import dateutil.parser
import argparse
import metadata
settings = None
def get_settings():
''' Return command-line settings '''
parser = argparse.ArgumentParser(description='Filter text corpus by date range. Only updates the metadata file.')
... |
"""
support for presenting detailed information in failing assertions.
"""
import py
import sys
import pytest
from _pytest.monkeypatch import monkeypatch
from _pytest.assertion import util
def pytest_addoption(parser):
group = parser.getgroup("debugconfig")
group.addoption('--assert', action="store", dest="asse... |
from b_hash import b_hash
from b_hash import NoData
from jenkins import jenkins
from h3_hash import h3_hash
from jenkins import jenkins_fast, jenkins_wrapper
from graph import *
from collections import deque
from bitstring import BitArray
import math
class bdz(b_hash):
"""Class for perfect hash function generated b... |
"""
celery.utils.log
~~~~~~~~~~~~~~~~
Logging utilities.
"""
from __future__ import absolute_import, print_function
import logging
import numbers
import os
import sys
import threading
import traceback
from contextlib import contextmanager
from billiard import current_process, util as mputil
from kombu.five ... |
"""
Defines the core learning framework.
The framework defined by `score`, `predict`, and `SGD` is defined in
section 3.2 of the paper. See `evenodd.py` for a simple example
(corresponding to table 3).
This core framework is also all that is needed for simple semantic
parsing: section 4.1 of the paper and `evaluate_sem... |
"""
Pyboard:
Switch pins: Y1 or X19
usage:
>>> init()
>>> loop()
"""
from pyb import ExtInt,Pin
pinId = 'X19' # interrupt 0 'Y1' # interrupt 6
flag= False
interCount=0
eObj = None
def callback(line):
global flag
flag += 1
def init():
global eObj
eObj=ExtInt(pinId, ExtInt.IRQ_FALLING, Pin.PULL_UP, callba... |
from __future__ import absolute_import
from __future__ import unicode_literals
from dnfpluginscore import _
import dnf.cli
class RepoClosure(dnf.Plugin):
name = "repoclosure"
def __init__(self, base, cli):
super(RepoClosure, self).__init__(base, cli)
if cli is None:
return
cl... |
import sys,numpy,matplotlib
import matplotlib.pyplot, scipy.stats
import library
def colorDefiner(epoch):
if epoch == '0':
theColor='blue'
elif epoch == '0.5':
theColor='red'
elif epoch == '1':
theColor='green'
elif epoch == '1.5':
theColor='orange'
else:
prin... |
import sys
import pickle
import os
import hashlib
import pprint
import time
from optparse import OptionParser
VERSION=1.0
def parseOptions():
usage = """
%prog [options]\n
Scrub a given directory by calculating the md5 hash of every file and compare
it with the one stored in the ... |
"""Utilities functions which assist in the generation of commonly required data
structures from the products of placement, allocation and routing.
"""
from collections import defaultdict
from six import iteritems, itervalues
import warnings
from rig.place_and_route.machine import Machine, Cores, SDRAM, SRAM
from rig.pl... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "json_schema.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
import sys
import pygame
from pygame.locals import *
venx = 640
veny = 448
class Pieza(pygame.sprite.Sprite): # 64x64 px tamaño
def __init__(self, tipo):
pygame.sprite.Sprite.__init__(self)
if tipo == 0:
self.image = load_image("tablero.png", True)
elif tipo == 1:
se... |
import string, traceback, sim_core
r0 = SIM_get_register_number(conf.cpu0, "r0")
nat0 = SIM_get_register_number(conf.cpu0, "r0.nat")
ar_kr6 = SIM_get_register_number(conf.cpu0, "ar.kr6")
def read_gr(regno):
cpu = SIM_current_processor()
return SIM_read_register(cpu, r0 + regno), SIM_read_register(cpu, nat0 + re... |
import os
from pathlib import Path
from scripts.build_env import BuildEnv, Platform
from scripts.platform_builder import PlatformBuilder
class pugixmlLinuxBuilder(PlatformBuilder):
def __init__(self,
config_package: dict=None,
config_platform: dict=None):
super().__init__(c... |
"""
Copyright (C) 2014 David Vavra (vavra.david@email.cz)
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 the License, or
(at your option) any later version.
... |
from dragonnest.settings import STATIC_ROOT
from skills.models import *
from PIL import Image, ImageDraw, ImageFont
import os
_ASCIIMAP = [chr(n) for n in ([45] + range(48, 58) + range(65, 91) + [95] + range(97, 123))]
_ALPHABET = dict(zip(range(64), _ASCIIMAP))
_ALPHABET_REVERSE = dict(zip(_ASCIIMAP, range(64)))
_FONT... |
"""
Virtualization installation functions.
Currently somewhat Xen/paravirt specific, will evolve later.
Copyright 2006-2008 Red Hat, Inc.
Michael DeHaan <mdehaan@redhat.com>
Original version based on virtguest-install
Jeremy Katz <katzj@redhat.com>
Option handling added by Andrew Puch <apuch@redhat.com>
Simplified for ... |
import tests
import gtk
import pango
from zim.index import Index, IndexPath, IndexTag
from zim.notebook import Path
from zim.gui.pageindex import FGCOLOR_COL, \
EMPTY_COL, NAME_COL, PATH_COL, STYLE_COL
# Explicitly don't import * from pageindex, make clear what we re-use
from zim.config import ConfigDict
from zim.plu... |
from _sigar import * |
import os
import shutil
import logging
import json
from yaml_log import configure_logger
diamond_back_home = os.path.expanduser(os.path.join('~/.config', 'diamondback'))
diamond_back_config = os.path.join(diamond_back_home, 'diamondback.json')
diamond_back_filelist = os.path.join(diamond_back_home, 'filelist')
outputFi... |
import os
import sys
INSTALLER_VERSION = '"latest"'
def create_installer_config(path):
"""Create a basicl installation configuration file"""
config = u"template=file:///etc/ister.json\n"
jconfig = u'{"DestinationType" : "physical", "PartitionLayout" : \
[{"disk" : "vda", "partition" : 1, "size" : "512M"... |
import os
import pwd
import sys
import ConfigParser
def get_config(p, section, key, env_var, default):
if env_var is not None:
value = os.environ.get(env_var, None)
if value is not None:
return value
if p is not None:
try:
return p.get(section, key)
except... |
from gene_acronym_query import GeneAcronymQuery
query = GeneAcronymQuery()
gene_info = query.get_data('ABAT')
for gene in gene_info:
print "%s (%s)" % (gene['name'], gene['organism']['name']) |
"""Options list for system config."""
import os
from collections import OrderedDict
from lutris import runners
from lutris.util import display, system
def get_optirun_choices():
"""Return menu choices (label, value) for Optimus"""
choices = [("Off", "off")]
if system.find_executable("primusrun"):
ch... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.