code stringlengths 1 199k |
|---|
"""
Classes and functions to handle storage devices.
This exports:
- two functions for get image/blkdebug filename
- class for image operates and basic parameters
"""
from __future__ import division
import errno
import logging
import os
import shutil
import re
import functools
import collections
from avocado.core i... |
import numpy as np
def lnbin(x, BinNum):
"""
Logarithmically bins a numpy array, returns (midpoints, Freq)
This function take the input of a data vector x, which is to be binned;
it also takes in the amount bins one would like the data binned into. The
output is two vectors, one containing the norma... |
"""
Generic LVM interface wrapper
Incapsulates the actual LVM mechanics.
"""
import errno
import os
import re
import pwd
import grp
import logging
from collections import namedtuple
import pprint as pp
import threading
from itertools import chain
from subprocess import list2cmdline
from vdsm import constants
import mis... |
def decode(data):
try:
value, idx = __decode(data, 0)
retval = (True, value)
except Exception as e:
retval = (False, e.message)
finally:
return retval
def encode(data):
try:
value = __encode(data)
retval = (True, value)
except Exception, e:
ret... |
from atlas import *
from physics import *
from physics import Quaternion
from physics import Vector3D
import server
class Repairing(server.Task):
"""A very simple Repair system for Repairing structures."""
materials = ["wood"]
def consume_materials (self) :
""" A method which gets the material to be... |
__author__ = 'Yan Yan'
'''
Deployment toolkit.
'''
import os, re
from datetime import datetime
from fabric.api import *
env.user = 'michael'
env.sudo_user = 'root'
env.hosts = ['192.168.0.3']
db_user = 'www-data'
db_password = 'www-data'
_TAR_FILE = 'dist-awesome.tar.gz'
_REMOTE_TMP_TAR = '/tmp/%s' % _TAR_FILE
_REMOTE_... |
import sys
import string
f = sys.stdin
g = sys.stdout
echo = 0
while 1:
l = f.readline()
if not l: break
ll=string.strip(l)
if ll=='BEGIN-LOG':
echo = 1
elif ll=='END-LOG':
echo = 0
elif echo:
l=string.replace(l,"-0.000"," 0.000") # squish annoying negative zeros
g.write(l) |
import codecs
import sys
from src.view.FileProcessingOutput import FileProcessingOutput
class FileProcessing():
def __init__(self):
self.fileProcessingOutput = FileProcessingOutput()
def read_input_file(self, file_path, file_type):
'''
Lectura de archivo y procesamiento de archivos
... |
import serial
class SerialConnection:
"""RS-232 connection to the Agilent power supply"""
def __init__(self, port='/dev/usb/ttyUSB0', baudrate=9600, parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS):
"""Initialize the connection"""
self.serial = serial.Serial(port=port, baudrate=baudrate, parity=parity,... |
import atk as __atk
import gio as __gio
import gobject as __gobject
import gobject._gobject as __gobject__gobject
class PrintStatus(__gobject.GEnum):
# no doc
def __init__(self, *args, **kwargs): # real signature unknown
pass
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda... |
"""The plunger file handler for the MD3 format.
The module supports export only for now.
"""
import math
import struct
try:
from plunger import toolbox
except ImportError:
import sys
sys.path.append('..')
import toolbox
sys.path.pop()
format = "md3"
extension = ".md3"
needs_dir = False
does_export =... |
import os
import json
import re
from optparse import OptionParser
import tweepy
import time
class UserTimeline:
def __init__(self,inputDir,outputDir):
self.inputDir = inputDir
self.outputDir = outputDir
os.system("mkdir -p %s"%(outputDir))
# Get the names of the files under the input directory and save them in... |
import math
import random
import GameData
from Util.TileTypes import *
from Util import Line, StarCallback
def initializeRandom( x, y ):
dist = math.sqrt( x ** 2 + y ** 2 )
angle = math.atan2( x, y ) / math.pi * 5
rand = ( random.random() * 7 ) - 3.5
val = ( ( dist + angle + rand ) % 10 )
if val > 5... |
from blivet.util import stringize, unicodeize
from pykickstart.constants import AUTOPART_TYPE_PLAIN, AUTOPART_TYPE_BTRFS, AUTOPART_TYPE_LVM, \
AUTOPART_TYPE_LVM_THINP
class PartSpec(object):
def __init__(self, mountpoint=None, fstype=None, size=None, max_size=None,
grow=False, btr=False, lv=Fal... |
import bpy
from .utils import MultiCamContext
class MultiCamFadeError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return repr(self.msg)
class BlendObj(object):
def __init__(self, **kwargs):
self.children = set()
p = self.parent = kwargs.get('parent'... |
import time
import traceback
from .optionparser import args
debug_level=args.debug or 0
debug_file=args.debug_file
timestamp=args.time
if debug_file:
import re
debug_file = re.compile(debug_file)
if debug_level > 0: print('DEBUG_LEVEL=',debug_level)
if debug_file: print('DEBUG_FILE=',debug_file)
def debug (mess... |
class ContainerError(ValueError):
"""Error signaling something went wrong with container handling"""
pass
class Container(object):
"""A container is an object that manages objects it contains.
The objects in a container each have a .container attribute that
points to the container. This attribute is... |
import os
import duplicity.backend
hsi_command = "hsi"
class HSIBackend(duplicity.backend.Backend):
def __init__(self, parsed_url):
duplicity.backend.Backend.__init__(self, parsed_url)
self.host_string = parsed_url.hostname
self.remote_dir = parsed_url.path
if self.remote_dir:
... |
from canaimagnulinux.wizard.interfaces import IChat
from canaimagnulinux.wizard.interfaces import ISocialNetwork
from canaimagnulinux.wizard.utils import CanaimaGnuLinuxWizardMF as _
from collective.beaker.interfaces import ISession
from collective.z3cform.wizard import wizard
from plone import api
from plone.z3cform.f... |
import application
import platform
import exceptions
from ctypes import c_char_p
from libloader import load_library
import paths
if platform.architecture()[0][:2] == "32":
lib = load_library("api_keys32", x86_path=paths.app_path("keys/lib"))
else:
lib = load_library("api_keys64", x64_path=paths.app_path("keys/lib"))
... |
import itertools
from django.conf import settings
from django.contrib.syndication.views import Feed, FeedDoesNotExist
from django.utils import timezone
from schedule.feeds.ical import ICalendarFeed
from schedule.models import Calendar
class UpcomingEventsFeed(Feed):
feed_id = "upcoming"
def feed_title(self, obj... |
import logging
from django.db import models
class BaseModel(models.Model):
class Meta:
# Makes django recognize model in split modules
app_label = 'sdn'
# Turns this into an abstract model (does not create table for it)
abstract = True
# Default exception for models in manager
... |
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers import Embedding
from keras.layers import LSTM,Flatten
import numpy as np
import loadpkl
(X_train, y_train),(X_test, y_test) = loadpkl.load_data()
X_train = np.array(X_train)
y_train = np.array(y_train)
print X_tra... |
"""
Module with universal etree module
"""
__all__ = ('etree', )
try:
from lxml import etree
except ImportError:
try:
import xml.etree.cElementTree as etree
except (ImportError, SystemError):
import xml.etree.ElementTree as etree |
import func_module
import yum
class DummyCallback(object):
def event(self, state, data=None):
pass
class Yum(func_module.FuncModule):
version = "0.0.1"
api_version = "0.1.0"
description = "Package updates through yum."
def update(self, pkg=None):
ayum = yum.YumBase()
ayum.doG... |
"""
Python SDK for Weibo
Simple wrapper for weibo oauth2
author: seraphwlq@gmail.com
"""
import time
from utils.http import request
from utils.http import SDataDict
from utils.http import encode_params
from utils.const import WEIBO_DOMAIN
from utils.const import WEIBO_VERSION
from utils.errors import WeiboAPIError
from... |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class GetCategories(Choreography):
def __init__(self, temboo_session):
"""
Create a ne... |
import cv2
from Tkinter import *
from PIL import Image, ImageTk
import tkFileDialog
appname = "example"
class App(object):
def __init__(self, root=None):
if not root:
root = Tk()
self.root = root
self.initUI()
def initUI(self):
self.root.title(appname)
menubar... |
try:
import unittest2 as unittest
except ImportError:
import unittest
try:
import mock
from mock import call
except ImportError:
import unittest.mock as mock
from unittest.mock import call
from fsresck.nbd.request import NBDRequestSocket, recvexactly, Error, \
NBDRequest
from fsresck.com... |
'''
Created on Jan 19, 2013
@author: dsnowdon
'''
import os
import tempfile
import datetime
import json
import logging
from naoutil.jsonobj import to_json_string, from_json_string
from naoutil.general import find_class
import robotstate
from event import *
from action import *
from naoutil.naoenv import make_environmen... |
import re
err = "La contraseña no es segura"
msg = "Escriba una contraseña al menos 8 caracteres alfanumericos"
def ismayor8(a):
"""
Compara si es mayor a 8 caracteres
"""
if (len(a) < 8):
return False
return True
def minus(a):
"""
compara si existe alguna letra minuscula
"""
... |
from typing import List
class Solution:
def transformArray2(self, arr: List[int]) -> List[int]:
while True:
arr2 = [a for a in arr]
changed = 0
for id in range(1, len(arr) - 1):
l = arr[id - 1]
r = arr[id + 1]
m = arr[id]
... |
import sqlite3
def main():
print('connect')
db = sqlite3.connect('db-api.db')
cur = db.cursor()
print('create')
cur.execute("DROP TABLE IF EXISTS test")
cur.execute("""
CREATE TABLE test (
id INTEGER PRIMARY KEY, string TEXT, number INTEGER
)
""")
print('i... |
import math
import numpy as np
import oeqLookuptable as oeq
def get(*xin):
l_lookup = oeq.lookuptable(
[
1849,0,
1850,0,
1851,0,
1852,0,
1853,0,
1854,0,
1855,0,
1856,0,
1857,0,
1858,0,
1859,0,
1860,0,
1861,0,
1862,0,
1863,0,
1864,0,
1865,0,
1866,0,
1867,0,
1868,0,
1869,0,
1870,0,
1871,0,
1872,0,
1873,0,
1874,0,
187... |
from shutil import rmtree
from tempfile import mkdtemp
from omdbapi import OMDbAPI
from scrusubtitles import ScruSubtitles
from scrusubtitles import ScruSubtitlesListener
from scrusubtitles import ScruSubtitlesLogger
class TestService(ScruSubtitlesListener, ScruSubtitlesLogger):
def __init__(self):
super(Te... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('domains', '0003_auto_20161103_1031'),
]
operations = [
migrations.RemoveField(
model_name='domain',
... |
'''
adaboost.py script can be used to train and test adaboost with a SGDclassifier
for mnist data. Look up commandline options for more information.
'''
import argparse
import cPickle as pickle
import numpy as np
import pylab as pl
import time
from sklearn.ensemble import AdaBoostClassifier
from sklearn.linear_model im... |
from collections import namedtuple
import fcntl
import os
import shutil
from pcs.common.tools import format_os_error
FileMetadata = namedtuple(
"FileMetadata",
[
"file_type_code",
"path",
"owner_user_name",
"owner_group_name",
"permissions",
"is_binary",
],
)
... |
import gobject
import gtk
class Downloader(gtk.Dialog):
def __init__(self, path):
self.__is_cancelled = False
gtk.Dialog.__init__(self, title = "", buttons = (gtk.STOCK_CANCEL,
gtk.RESPONSE_CANCEL))
self.set_default_size(300, 100)
... |
'''Class path for jar files and directories. Cache all jars content.
JAVA_HOME must be set.
Class path is list of jar files and folders for classes lookup.
Separator ":", (";", ",") are also supported
See START.txt for details
'''
import os
import zipfile
def read_class_path(class_path):
'''Cache content of all jar... |
"""
3D.py is the interface for plotting Skeleton Wireframes in a 3D
perspective using matplotlib
"""
from matplotlib import pyplot as plt
from matplotlib import animation
from mpl_toolkits.mplot3d import Axes3D
import Colour
class View:
def __init__(self, bodies, **kwargs):
""" data is a from Load.B... |
import json
from flask_pluginengine import current_plugin
def get_json_from_remote_server(func, default={}, **kwargs):
"""
Safely manage calls to the remote server by encapsulating JSON creation
from Piwik data.
"""
rawjson = func(**kwargs)
try:
data = json.loads(rawjson)
if isin... |
"""Test MQTT connections."""
import unittest
from infopanel import mqtt
from infopanel.tests import load_test_config
class TestMqtt(unittest.TestCase):
"""Test connectivity with MQTT."""
@classmethod
def setUpClass(cls):
cls.conf = load_test_config()
def setUp(self):
"""Set up each test.... |
import json
from base64 import b64encode
import sickbeard
from sickbeard import logger
from .generic import GenericClient
from synchronousdeluge import DelugeClient
class DelugeDAPI(GenericClient):
drpc = None
def __init__(self, host=None, username=None, password=None):
super(DelugeDAPI, self).__init__(... |
from core.engine import hplayer
player = hplayer.addplayer('mpv', 'gadagne')
player.addInterface('osc', 4000, 4001)
player.addInterface('http', 8080)
defaultFile = 'media0.mp4'
push1File = 'media1.mp4'
push2File = 'media2.mp4'
push3File = 'media3.mp4'
player.on('end', lambda: player.play(defaultFile))
player.on(['push1... |
"""
Loader
import modules from zip files that are stored in ./libs/ directory
author: Steve Göring
contact: stg7@gmx.de
2014
"""
import os
import sys
for m in filter(lambda x: ".zip" in x, os.listdir(os.path.dirname(os.path.realpath(__file__)) + "/libs")):
sys.path.insert(0, os.path.dirname(os.p... |
import os
from datetime import datetime
import json
import warnings
import numpy as np
from netCDF4 import Dataset
from nansat.utils import gdal
try:
import scipy
except:
IMPORT_SCIPY = False
else:
IMPORT_SCIPY = True
import pythesint as pti
from nansat.mappers.sentinel1 import Sentinel1
from nansat.mappers... |
import sys
import os
import io
from pkg_resources import parse_version
import wx
if parse_version(wx.__version__) < parse_version('2.9'):
tmpApp = wx.PySimpleApp()
else:
tmpApp = wx.App(False)
from psychopy import experiment
from psychopy.experiment.components import getAllComponents
ignoreObjectAttribs = True
... |
from fife.extensions.pychan import Icon
class Slot(Icon):
def _setImage(self, source):
self._image = source
def _getImage(self):
return self._image
image = property(_getImage, _setImage) |
"""Containes classes defining concrete container game objects like crates,
barrels, chests, etc."""
__all__ = ["WoodenCrate",]
from composed import ImmovableContainer
class WoodenCrate (ImmovableContainer):
def __init__ (self, ID, name = 'Wooden Crate', \
text = 'A battered crate', gfx = 'crate', **kwar... |
import socket
import string
import datetime
import time
import sqlite3
import pytz
from datetime import timedelta
import sys
from flarm_db import flarmdb
from pysqlite2 import dbapi2 as sqlite
from open_db import opendb
import ephem
import argparse
from flogger_dump_flights import dump_flights
from flogger_dump_tracks ... |
from urllib.request import urlopen
for line in urlopen('https://secure.ecs.soton.ac.uk/status/'):
line = line.decode('utf-8') # Decoding the binary data to text.
if 'Core Priority Devices' in line: #look for 'Core Priority Devices' To find the line of text with the list of issues
linesIWant = line.spl... |
'''
ThunderGate - an open source toolkit for PCI bus exploration
Copyright (C) 2015-2016 Saul St. John
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 Licen... |
import logging
from scap.model.oval_5 import WINDOWS_VIEW_ENUMERATION
from scap.model.oval_5.defs.independent.StateType import StateType
logger = logging.getLogger(__name__)
class FileHashStateElement(StateType):
MODEL_MAP = {
'tag_name': 'filehash_state',
'elements': [
{'tag_name': 'fil... |
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_O_IBK_WSYH_ECCIF').setMaster(sys.argv[2])
sc = SparkContext(conf = conf)
sc.setLogLevel('WAR... |
__author__="Adam Schubert <adam.schubert@sg1-game.net>"
__date__ ="$12.10.2014 2:20:45$"
import tests.DwaTestCase as DwaTestCase
import unittest
import time
class UserTest(DwaTestCase.DwaTestCase):
def setUp(self):
DwaTestCase.DwaTestCase.setUp(self)
self.user = self.d.user()
self.username = self.credenti... |
__author__ = "Matheus Marotzke"
__copyright__ = "Copyright 2017, Matheus Marotzke"
__license__ = "GPLv3.0"
import numpy as np
class Truss:
"""Class that represents the Truss and it's values"""
def __init__(self, nodes, elements):
self.nodes = nodes # List of nodes in the Truss
... |
"""
This file is part of xcos-gen.
xcos-gen 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.
xcos-gen is distributed i... |
from ..core.standard import (YubiOathCcid, TYPE_HOTP)
from ..core.controller import Controller
from ..core.exc import CardError, DeviceLockedError
from .ccid import CardStatus
from yubioath.yubicommon.qt.utils import is_minimized
from .view.get_password import GetPasswordDialog
from .keystore import get_keystore
from .... |
import unittest
import test_dot
import test_math
import test_trans
import test_lapack
suite = unittest.TestSuite([test_dot.suite(),
test_math.suite(),
test_trans.suite(),
test_lapack.suite
])
if __name__ == "... |
from distutils.core import setup
setup(name='nala',
version='0.0.1',
description='file/directory watcher libraries',
author='Eugenio Paolantonio',
author_email='me@medesimo.eu',
url='https://github.com/g7/python-nala',
packages=[
"nala"
],
requires=['gi.repository.GLib', 'gi.repository.GObject', 'gi.repo... |
class Solution(object):
def __init__(self):
self.l=[]
def helper(self,root,level):
if not root:
return None
else:
if level<len(self.l):
self.l[level].append(root.val)
else:
self.l.append([root.val])
self.help... |
from .submaker import Submaker
import zipfile
import os
import shutil
import logging
logger = logging.getLogger(__name__ )
class SuperSuSubmaker(Submaker):
def make(self, workDir):
supersuZipProp = self.getTargetConfigProperty("root.methods.supersu.path")
assert supersuZipProp.getValue(), "Must set ... |
class CharacterSubstitutions(object):
character_substitutions = dict()
def standard_text_from_block(block, offset, max_length):
str = ''
for i in range(offset, offset + max_length):
c = block[i]
if c == 0:
return str
else:
str += chr(c - 0x30)
return str
d... |
import librosa
import numpy as np
import help_functions
def extract_mfccdd(fpath, n_mfcc=13, winsize=0.25, sampling_rate=16000):
'''
Compute MFCCs, first and second derivatives
:param fpath: the file path
:param n_mfcc: the number of MFCC coefficients. Default = 13 coefficients
:param winsize: the t... |
import numpy as np
class Combiner(object):
def forward(self, input_array, weights, const):
## Define in child
pass
def backprop(self, error_array, backprop_array, learn_weight = 1e-0):
## Define in child
pass
class Linear(Combiner):
def forward(self, input_array, weights, con... |
import numpy as np
import pytest
from hyperspy import signals
from hyperspy.misc.utils import (
is_hyperspy_signal,
parse_quantity,
slugify,
strlist2enumeration,
str2num,
swapelem,
fsdict,
closest_power_of_two,
shorten_name,
is_binned,
)
from hyperspy.exceptions import VisibleDep... |
from __future__ import division
import spidev
import time
import os
import gc
import sys
import math
global tune1, tune2, tunerout, volts2, volume1, volume2, volumeout, IStream
tune1 = False
tune2 = False
tunerout = False
volts2 = False
volume1 = False
volume2 = False
volumeout = False
IStream = False # start system o... |
from pyload.plugin.internal.SimpleCrypter import SimpleCrypter
class FiletramCom(SimpleCrypter):
__name = "FiletramCom"
__type = "crypter"
__version = "0.03"
__pattern = r'http://(?:www\.)?filetram\.com/[^/]+/.+'
__config = [("use_premium" , "bool", "Use premium account if available" ... |
"""
Copyright 2016 Jacob C. Wimberley.
This file is part of Weathredds.
Weathredds 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 l... |
"""
A finite state machine specialized for regular-expression-based text filters,
this module defines the following classes:
- `StateMachine`, a state machine
- `State`, a state superclass
- `StateMachineWS`, a whitespace-sensitive version of `StateMachine`
- `StateWS`, a state superclass for use with `StateMachineWS`
... |
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('events', '0021_auto_20171023_1358'),
]
operations = [
migrations.AlterField(
model_name='inductioninterest',
name='age',
field=models.CharField(max_length=10... |
"""
This file: csm_notation.py
Last modified: November 8, 2010
Package: CurlySMILES Version 1.0.1
Author: Axel Drefahl
E-mail: axeleratio@yahoo.com
Internet: http://www.axeleratio.com/csm/proj/main.htm
Python module csm_notation implements a class for managing
a Curl... |
import collections
import functools
import re
import wrappers
class History(object):
"""
Tracking of operations provenance.
>>> h = History("some_op")
>>> print str(h)
some_op()
>>> h.add_args(["w1", "w2"])
>>> print str(h)
some_op(
w1,
w2,
)
>>> h.add_kws({"a_key... |
"""
Scan a list of services and update Observation records in the notary database.
For running scans without connecting to the database see util/simple_scanner.py.
"""
from __future__ import print_function
import argparse
import errno
import logging
import os
import sys
import threading
import time
import notary_common... |
"""Module containing everything regarding patches in SeedDB"""
import logging
from django import forms
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from django.views.decorators.http import require_POST
from nav.models.cabling import Patch, Cabling
from nav.models.manage im... |
from chapter02.exercise2_3_5 import recursive_binary_search
from chapter02.textbook2_3 import merge_sort
from util import between
def sum_search(S, x):
n = S.length
merge_sort(S, 1, n)
for i in between(1, n - 1):
if recursive_binary_search(S, x - S[i], i + 1, n) is not None:
return True
... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('anagrafica', '0046_delega_stato'),
]
operations = [
migrations.AlterIndexTogether(
name='delega',
index_together=set([('persona', 'tipo',... |
import re
from simpleparse.parser import Parser
from simpleparse.dispatchprocessor import *
grammar = """
root := transformation
transformation := ( name, index, assign, expr )
assign := '='
expr := ( trinary )
/ ( term )
trinary := ( term, '?', term, ':', term )
term := ( factor, binaryop, term )
/ ( fac... |
from snmp_helper import snmp_get_oid,snmp_extract
COMMUNITY_STRING = 'galileo'
SNMP_PORT = 161
IP = '184.105.247.70'
a_device = (IP, COMMUNITY_STRING, SNMP_PORT)
OID = '1.3.6.1.2.1.1.1.0'
snmp_data = snmp_get_oid(a_device, oid=OID)
output = snmp_extract(snmp_data)
print output |
import numpy
import math
import pylab
from scipy.optimize import curve_fit
import math
import scipy.stats
import lab
def fit_function(x, a, b):
return b*(numpy.exp(x/a)-1)
FileName='/home/federico/Documenti/Laboratorio2/Diodo/dati_arduino/dati.txt'
N1, N2 = pylab.loadtxt(FileName, unpack="True")
errN2 = numpy.array([... |
__author__ = 'milletluo'
configs = {
'db': {
'host': '127.0.0.1'
}
} |
from datetime import date, datetime
from textwrap import dedent
from unittest.mock import patch
from freezegun import freeze_time
from mitoc_const import affiliations
import ws.utils.dates as date_utils
from ws import enums, models, settings
from ws.lottery import run
from ws.tests import TestCase, factories
class Sing... |
import json
import os
from datetime import datetime
import mock
import pytest
from dateutil.tz import tzlocal, tzoffset
from barman.infofile import (BackupInfo, Field, FieldListFile, WalFileInfo,
load_datetime_tz)
from testing_helpers import build_mocked_server
BASE_BACKUP_INFO = """backup_... |
import random
import time
class role:
name=""
lv=1
exp=0
nextLv=1000
hp=100
mp=30
stra=5
inte=5
spd=5
defe=5
rest=5
void=5
dropItems=[None]
dropPrecent=[100]
command=['attack','void','def','fireball']
def __init__(self,name,lv):
self.name=name
... |
from syncloud_platform.snap.models import App, AppVersions
from syncloud_platform.snap.snap import join_apps
def test_join_apps():
installed_app1 = App()
installed_app1.id = 'id1'
installed_app_version1 = AppVersions()
installed_app_version1.installed_version = 'v1'
installed_app_version1.current_ve... |
"""Shutdown Timer - Small Windows shutdown timer.
Created 2013, 2015 Triangle717
<http://Triangle717.WordPress.com>
Shutdown Timer 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, ... |
def absMat(matrice):
'''Renvoie la matrice avec la valeur absolue de tous ses coefficients. Renvoie False si échec.
- matrice
- complexe
'''
if type(matrice) is not list:
raise Exception("absMat : Pas une matrice.")
#~ return False
if not len(matrice):
raise Exception("ab... |
import sys
import re
def isSectionStart(line, interface=""):
sectionpattern = "^[0-9]+:\\s+%s"
return re.match(sectionpattern%interface, line) != None
def printSection(interface, lines):
in_section = False
for line in lines:
if in_section:
if isSectionStart(line):
ret... |
"""
Implements a queue efficiently using only two stacks.
"""
from helpers import SingleNode
from stack import Stack
class QueueOf2Stacks:
def __init__(self):
self.stack_1 = Stack()
self.stack_2 = Stack()
def enqueue(self, value):
self.stack_1.push(value)
def dequeue(self):
s... |
import os
import xbmc
import xbmcaddon
import pyxbmct
from lib import utils
import plugintools
from itertools import tee, islice, chain, izip
_addon = xbmcaddon.Addon()
_addon_path = _addon.getAddonInfo('path')
def previous_and_next(some_iterable):
prevs, items, nexts = tee(some_iterable, 3)
prevs = chain([None... |
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
exce... |
'''
Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges.
Have you met this question in a real interview?
Example
Example 1
Input:
nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99
Output:
["2", "4->49", "51->74", "76->99"]
Explanation:
in range[... |
"""Simulation of controlled dumbbell around Itokawa with
simulated imagery using Blender
This will generate the imagery of Itokawa from a spacecraft following
a vertical descent onto the surface.
4 August 2017 - Shankar Kulumani
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from... |
import os
import sys
import patoolib
import pytest
import importlib
basedir = os.path.dirname(__file__)
datadir = os.path.join(basedir, 'data')
patool_cmd = os.path.join(os.path.dirname(basedir), "patool")
if sys.version_info[0] > 2:
fnameattr = '__name__'
else:
fnameattr = 'func_name'
def _need_func(testfunc, ... |
from module.common.json_layer import json_loads
from module.network.RequestFactory import getURL
from module.plugins.internal.MultiHoster import MultiHoster
class MyfastfileCom(MultiHoster):
__name__ = "MyfastfileCom"
__type__ = "hook"
__version__ = "0.02"
__config__ = [("hosterListMode", "all;lis... |
from fnmatch import fnmatch
from django.db.models import F, Max
from django.utils.functional import cached_property
from pootle_store.models import Store
from .models import StoreFS
from .utils import StoreFSPathFilter, StorePathFilter
class FSProjectResources(object):
def __init__(self, project):
self.proj... |
import unittest
import os
from ...workbook import Workbook
from ..helperfunctions import _compare_xlsx_files
class TestCompareXLSXFiles(unittest.TestCase):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'set_start_... |
from conf import *
import socket
import os
from threading import Thread
import time
def get_cookie(request_lines):
#print("cookie data is: " + request_lines[-3])
data = request_lines[-3].split(":")[-1]
return (data.split("=")[-1])
def error_404(addr,request_words):
print("File not Found request")
lo... |
"""
Some utilities for bools manipulation.
Copyright 2013 Deepak Subburam
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.
"""
de... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.