code stringlengths 1 199k |
|---|
import sys
test_cases = open(sys.argv[1], 'r')
test_lines = (line.rstrip() for line in test_cases)
vampir_pts = 3
zombie_pts = 4
witch_pts = 5
for test in test_lines:
data = test.split(',')
vamp_num = int(data[0].split(':')[-1])
zomb_num = int(data[1].split(':')[-1])
witch_num = int(data[2].split(':')[-1])
total_h... |
import ttc_util
import traceback
import itertools
import os
import copy
import math
import sys
import random
import transpose
OKGREEN = '\033[92m'
FAIL = '\033[91m'
WARNING = '\033[93m'
ENDC = '\033[0m'
class transposeGenerator:
def __init__(self, perm, loopPermutations, size, alpha, beta, maxNumImplementations,
... |
import gettext
from gettext import gettext as _
gettext.textdomain('slidewall')
import logging
logger = logging.getLogger('slidewall')
from slidewall_lib.AboutDialog import AboutDialog
class AboutSlidewallDialog(AboutDialog):
__gtype_name__ = "AboutSlidewallDialog"
def finish_initializing(self, builder): # pyli... |
from adafruit_display_text.label import Label
class ApplicationScreen(object):
""" This is the interface for application screens """
pyportal = None
logger = None
def change_to_state(self, state_name, current_state, states):
if current_state:
self.logger.debug('Exiting %s', current_state.name)
... |
from unittest.mock import MagicMock
from randovania.gui.lib import common_qt_lib
def test_get_network_client(skip_qtbot, qapp):
qapp.network_client = MagicMock()
assert common_qt_lib.get_network_client() is qapp.network_client
def test_get_game_connection(skip_qtbot, qapp):
qapp.game_connection = MagicMock(... |
import logging
import traceback
from ftplib import FTP
from pathlib import PurePath
from FileListRetriever import FileListRetriever
class FTPRetriever(FileListRetriever):
"""
File retriever for files held on an FTP server.
"""
def __init__(self, instrument_id, logger, configuration=None):
super(... |
import os
import re
import six
def digits_only(string):
"""Return all digits that the given string starts with."""
match = re.match(r'(?P<digits>\d+)', string)
if match:
return int(match.group('digits'))
return 0
def to_unicode(string):
try:
return six.u(string)
except: # noqa: ... |
import json
import pytest
from newmansound.model import Artist, Album, Song
from newmansound.restweb import app, PlaylistService, SongService
from newmansound.schema import AlbumSchema, ArtistSchema, SongSchema
from tests.fixtures import client, engine, playlist_service, session
from tests.helpers import add_album, add... |
import subprocess
from mycroft.tts import TTS, TTSValidator
__author__ = 'jdorleans'
NAME = 'spdsay'
class SpdSay(TTS):
def __init__(self, lang, voice):
super(SpdSay, self).__init__(lang, voice)
def execute(self, sentence):
subprocess.call(
['spd-say', '-l', self.lang, '-t', self.voi... |
import re
from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo
class OneFichierCom(SimpleHoster):
__name__ = "OneFichierCom"
__type__ = "hoster"
__version__ = "0.76"
__pattern__ = r'https?://(?:www\.)?(?:(?P<ID1>\w+)\.)?(?P<HOST>1fichier\.com|alterupload\.com|cjoint\.net|d... |
from __future__ import unicode_literals
from django.contrib.auth.models import User
import factory
from pages.models import Page
class UserFactory(factory.DjangoModelFactory):
class Meta:
model = User
username = factory.Sequence(lambda n: "user_%d" % n)
class PageFactory(factory.DjangoModelFactory):
... |
from vsg.rules import blank_line_above_line_starting_with_token
from vsg import token
lTokens = []
lTokens.append(token.entity_declaration.end_keyword)
class rule_016(blank_line_above_line_starting_with_token):
'''
This rule checks for blank lines above the **end entity** keywords.
**Violation**
.. code... |
"""
A read-only cached version of @property
"""
class cached_property(object):
def __init__(self, method, name=None):
self.method = method
self.name = name or method.__name__
self.__doc__ = method.__doc__
def __get__(self, instance, cls):
if instance is None:
return s... |
import jinja2
from jinja2 import nodes
from jinja2.ext import Extension
class RegionExtension(Extension):
tags = set(['region'])
def __init__(self, environment):
super(RegionExtension, self).__init__(environment)
environment.extend(regions=dict())
def parse(self, parser):
next(parser... |
from corpustools import ccat
import unittest
from lxml import etree
import io
import cStringIO
class TestCcatHyph(unittest.TestCase):
'''Test how ccat handles hyph
'''
def test_hyph1(self):
'''Test the default treatment of hyph tags
'''
xml_printer = ccat.XMLPrinter()
buffer ... |
import unittest
from ...compatibility import StringIO
from ..helperfunctions import _xml_to_list
from ...worksheet import Worksheet
class TestAssembleWorksheet(unittest.TestCase):
"""
Test assembling a complete Worksheet file.
"""
def test_assemble_xml_file(self):
"""Test writing a worksheet wit... |
import requests
import json
import os
def onde(palavras):
tam = len(palavras)
if(palavras[1] == u'fica' or palavras[1] == u'é' or palavras[1] == u'e'):
try:
if(tam == 3):
req=requests.get('http://maps.googleapis.com/maps/api/geocode/json?address='+palavras[2])
elif(tam == 4):
req=requests.get('http://... |
from bbio import *
import itertools
ss = input("Enter the Number\n")
qq = 1
for i in range(ss+1):
if i != 0:
qq = qq * i
print qq
"\n"
s = " "
strg = ""
for ii in range(ss+1):
if ii != 0:
strg = strg + str(ii)
comb = itertools.permutations(strg)
for x in comb:
print s.join(x) |
<<<<<<< Updated upstream
This is a testing file for editing.
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< Updated upstream
<<<<<<< Updated upstream
<<<<<<< HEAD
=======
>>>>>>> Stashed changes
=======
>>>>>>> Stashed changes
does
=======
>>>>>>> Stashed changes
====... |
import pygame
pygame.display.set_caption("multi bingo")
screen = pygame.display.set_mode((0,0))
screen.fill([0,0,0])
pygame.mouse.set_visible(False)
meter = pygame.image.load('graphics/assets/silver_register_cover.png').convert()
number = pygame.image.load('playtime/assets/number.png').convert_alpha()
feature = pygame.... |
"""
A script to estimate the HIV epidemic model parameters using ABC for the toy data.
"""
from sandbox.util.PathDefaults import PathDefaults
from wallhack.viroscopy.model.HIVModelUtils import HIVModelUtils
from wallhack.viroscopy.model.HIVABCParameters import HIVABCParameters
from sandbox.predictors.ABCSMC import ABCS... |
import sys
sys.path.append("../")
import settings
from modules import manager
def main():
"""
python postgresql_backup.py filepath <from gmail address> <to address> <gmail username> <gmail application password>
"""
manage=manager.init(settings=settings)
postgresql=settings.Postgresql("postgresql",m... |
from __future__ import division, print_function
from argparse import ArgumentParser, SUPPRESS
from atom_tools import rmsdDist
import copy
from glob import glob
from lineMD import eventLoop, determineSplit, getFinishedRuns, stitchTrajectory # and exportRestarts
from numpy import zeros
from operator import attrgetter
im... |
__author__ = 'civa'
import tornado.web
class GeneralHandler(tornado.web.RequestHandler):
def url_scheme(self):
return r"/api/general/([a-zA-Z0-9_\-]+)/?$"
def get(self):
return '' |
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tableaubord', '0051_auto_20170508_1813'),
]
operations = [
migrations.AlterField(
model_name='evenement',
name='d... |
"""
This file contains all the forms for the debate modules.
"""
from django.forms import ModelForm, Textarea, TextInput
from django.forms.models import modelformset_factory
from apps.ecidadania.debate.models import Debate, Note, Row, Column
class DebateForm(ModelForm):
"""
Returns an empty form for creating a ... |
def welcome_message():
import random
from pymc.util import chat
message_builder = chat.MessageBuilder()
element = chat.TextElement("I can haz ")
message_builder.append(element)
colorz = ["yellow", "gold", "aqua", "blue", "light_purple", "red", "green"]
text = "colorz!"
for char in text:
... |
import os
from ROOT import TCanvas
from cmstoolsac3b.test.test_histotoolsbase import TestHistoToolsBase
from cmstoolsac3b.rendering import CanvasBuilder
from cmstoolsac3b.wrappers import HistoWrapper
import cmstoolsac3b.diskio as diskio
class TestRendering(TestHistoToolsBase):
def setUp(self):
super(TestRen... |
"""This module is responsible for the translation of the content of the DB into
a suitable data structure (which can be list, tree or forest) for the views to
interact with. To this purpose, the underlying structures are built from the
DB content and wrapped in QAbstractItemModel subclasses that expose those
properties... |
import enigma
import pprint
import NavigationInstance
from enigma import iServiceInformation
nin = NavigationInstance.instance
print dir(nin.RecordTimer)
pprint.pprint(nin.RecordTimer.timer_list)
print dir(nin.RecordTimer.timer_list[0])
first = nin.RecordTimer.timer_list[0]
print "EIT:"
print first.eit
print first.begi... |
"""Models for racks and rack items"""
from __future__ import unicode_literals
import json
from itertools import chain
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from nav.models.fields import VarcharField
from nav.models.manage import Room, Sensor
class RackManager(models.... |
"""
BORIS
Behavioral Observation Research Interactive Software
Copyright 2012-2022 Olivier Friard
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 o... |
import os
import MySQLdb
HOST = os.getenv("DB_HOST")
USER = os.getenv("DB_USERNAME")
PASS = os.getenv("DB_PASSWORD")
NAME = os.getenv("DB_NAME")
if HOST != "":
conn = MySQLdb.connection (host=HOST, user=USER, passwd=PASS, db=NAME)
strstat = [ 'Accepted!', 'Wrong answer', 'Time limit exceeded', 'Memory limit exceeded',... |
import util
from .models import * |
import random
from mathmaker.lib import shared
from mathmaker.lib.tools.wording import setup_wording_format_of
from mathmaker.lib.core.root_calculus import Value
from mathmaker.lib.document.content import component
class sub_object(component.structure):
def __init__(self, build_data, picture='true', **options):
... |
from sheepsense import db
from sheepsense.model import List_C
import sheepsense.model.entry
import sheepsense.model.trial
class Run():
def __init__(
self,
id=None, identifier=None, trial=None, trialid=None, name=None, enddate=None,
serial=None, order=None, ordr=None, judge=None, ... |
"GPropertyGrid unittest suite"
import unittest
import load_module
import propertygrid
import properties
LOADER = unittest.TestLoader()
SUITE = LOADER.loadTestsFromModule(propertygrid)
SUITE.addTests(LOADER.loadTestsFromModule(properties))
RUNNER = unittest.TextTestRunner(verbosity=2)
RESULT = RUNNER.run(SUITE) |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('rango', '0003_auto_20160117_1552'),
]
operations = [
migrations.AddField(
model_name='bares',
name='slug',
field=mode... |
import unittest
from ripe.atlas.tools.helpers.sanitisers import sanitise
class TestSanitisersHelper(unittest.TestCase):
def test_sanitise(self):
self.assertEqual("clean", sanitise("clean"))
for i in list(range(0, 32)) + [127]:
self.assertEqual("unclean", sanitise("unclean" + chr(i)))
... |
"""
Definition of the wflow_gr4 model.
----------------------------------
Usage:
wflow_gr4 [-l loglevel][-c configfile][-f][-h] -C case -R Runid -
-C: set the name of the case (directory) to run
-R: set the name runId within the current case
-c name of the config file (in the case directory)
-f: Force... |
from sqlalchemy import (
Integer,
String,
Column,
UniqueConstraint,
Index,
ForeignKey,
)
from sqlalchemy.orm import (
synonym,
relationship,
backref,
)
from sqlalchemy.dialects.postgresql import JSON
from ..models import (
DBSession,
Base
)
from ..lib import EnumIntType
from ... |
from collections import namedtuple
import StringIO
import json
import urllib
import urllib2
import os
import collections
import urlparse
import gzip
import re
import sys
import zipfile
from CTMagic import Whatype
newLine = os.linesep
conversations = []
objects = []
Errors = []
hosts = collections.OrderedDict()
request_... |
import copy, os, pyPdf, sys
def main():
if len(sys.argv) > 1:
if os.path.isfile(sys.argv[1]):
name_input = sys.argv[1]
else:
sys.exit("file %s not found" % sys.argv[1])
else:
sys.exit("missing origin file operand")
if len(sys.argv) > 2:
name_output = s... |
from gnuradio import gr, gr_unittest
from gnuradio import blocks
import ieee802_15_4_swig as ieee802_15_4
import numpy as np
class qa_costas_loop_cc (gr_unittest.TestCase):
def setUp (self):
self.tb = gr.top_block ()
def tearDown (self):
self.tb = None
def test_001_t (self): # perfect sync, ... |
def _H(prev, trans):
for c in trans:
prev = (prev*31+ord(c)) % 1000000007
return prev
def find_hash(string, prev, hashes):
for h in hashes:
_h = _H(prev, string)
token = h-7*_h
while token < 0:
token += 1000000007
token %= 1000000007
if token < 100... |
import matplotlib.pyplot as mpp
import unittest
import timetools.synchronization.clock as sc
import timetools.synchronization.oscillator as tso
import timetools.synchronization.oscillator.noise.gaussian as tsong
import timetools.synchronization.time as st
import timetools.synchronization.compliance.visualization as tsc... |
"""
This script is a member of the system
"Detector of cyber-harassment" developed
for the Master's thesis "Detection of cyber-harassment on social network"
realized by Emilien Peretti during the academic year on 2016-2017 within the framework of
the IT Master's degree in sciences
at the university of Mons.
Author :... |
from test_support import gcc, gnatprove
gcc("always_fail.adb", opt=["-c", "-gnatv"])
print("--")
gnatprove("--version") |
from math import sqrt, atan, sin, cos, pi
import matplotlib
import cairo
import os.path
r3b2 = sqrt(3.0)/2.0
yoffset = 2 * r3b2 / 3
br3 = 1.0/sqrt(3.0)
c_rad = 0.1
scaling = 200
offset = 250, 250
linew = 10
partlinew = 6
text_size = 40
text_offsetx = 20
text_offsety = -10
gap_greater = 1
dashed_no = True
dashes_list = ... |
'''!
@file epwins.py
@package gui.epwins
@brief Windows classes for epcalc gui
This holds window classes for generating and updating (level ups) characters.
@date (C) 2016-2020
@author Marcus Schwamberger
@email marcus@lederzeug.de
@version 1.5
----
@todo The following has to be implemented:
- a separate Character Stat... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('investments', '0008_auto_20180927_1306'),
]
operations = [
migrations.CreateModel(
name='NewInvestment',
fields=[
... |
from pytest import fixture, mark
from pylada import vasp_program
@fixture
def path():
from os.path import dirname
return dirname(__file__)
@mark.skipif(vasp_program is None, reason="vasp not configured")
def test(tmpdir, path):
from pylada.crystal import Structure
from pylada.vasp import Vasp
from e... |
"""
Django settings for firma_e 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__))
SECRET_KEY = ... |
import sys
import re
import pdb
def is_failtree(linetree):
#perl -pe 's/.*\([^a-z]+ .*//'
if re.search(r'.*\([^a-z]+ .*', linetree) is not None:
return True
else:
return False
def gen_failtree(words):
#use failnode labels?
assert len(words) > 0
#if ("" not in words):
# pdb... |
import datetime
import logging
import os
import sys
import warnings
from configobj import ConfigObj
sys.path.append('scripts')
from scripts import pfp_batch
from scripts import pfp_log
warnings.filterwarnings("ignore", category=Warning)
logger = logging.getLogger("pfp_log")
class Bunch:
def __init__(self, **kwds):
... |
from __future__ import unicode_literals
import shogi
import unittest
from mock import patch
from shogi import CSA
TEST_CSA = """'----------棋譜ファイルの例"example.csa"-----------------
'バージョン
V2.2
'対局者名
N+NAKAHARA
N-YONENAGA
'棋譜情報
'棋戦名
$EVENT:13th World Computer Shogi Championship
'対局場所
$SITE:KAZUSA ARC
'開始日時
$START_TIME:2003... |
"""
Classifier is an image classifier specialization of Net.
"""
import numpy as np
import caffe
class Classifier(caffe.Net):
"""
Classifier extends Net for image class prediction
by scaling, center cropping, or oversampling.
Parameters
----------
image_dims : dimensions to scale input for cropp... |
""" Test specific of JobParameters with and without the flag in for ES backend
flag in /Operations/[]/Services/JobMonitoring/useESForJobParametersFlag
"""
import os
import time
import DIRAC
DIRAC.initialize() # Initialize configuration
from DIRAC.WorkloadManagementSystem.Client.WMSClient import WMSClient
from DIRAC.... |
from math import*
from random import*
from sys import*
def insertionsort(A,p,r):
for i in range(p+1,r+1):
key = A[i]
j = i-1
while j>=p and A[j] > key:
A[j+1] = A[j]
j -= 1
A[j+1] = key
def maxHeapify(A, i, heapSize, p):
left = 2*i + 1 - p
right = 2*i + 2 - p
if left-p < heapSize and A[left] > A[i]:
... |
"""abydos.tests.distance.test_distance_ncd_lzss.
This module contains unit tests for abydos.distance.NCDlzss
"""
import unittest
from abydos.distance import NCDlzss
class NCDlzssTestCases(unittest.TestCase):
"""Test NCDlzss functions.
abydos.distance.NCDlzss
"""
cmp = NCDlzss()
def test_ncd_lzss_dis... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: azure_rm_managed_disk
version_added: "2.4"
short_description: M... |
from __future__ import unicode_literals, print_function
import os
import sys
from signal import signal, SIGPIPE, SIG_DFL
import argparse
import twitter_bot_utils as tbu
from . import TwitterMarkov
from . import checking
from . import __version__ as version
TWEETER_DESC = 'Post markov chain ("ebooks") tweets to Twitter'... |
from operations import *
_gradient_registry = {}
class RegisterGradient:
""" A decorator for registering the gradient function for an
op type."""
def __init__(self, op_type):
""" Creates a new decorator with 'op_type' as the Operation type.
"""
self._op_type = eval(op_type)
def __call__(self, f):
""" Regis... |
class Vorstand(object):
pass |
import unittest
import snake.geometry
import copy
class TestPoint(unittest.TestCase):
def test_zero_point(self):
point = snake.geometry.Point()
self.assertEqual(point.x, 0)
self.assertEqual(point.y, 0)
def test_vector_point(self):
first_point = snake.geometry.Point(2, 3)
... |
"""
Module for testing _data.py
"""
import os as _os # For loading fixtures
import numpy as _n
import spinmob as _s
import unittest as _ut
a = b = c = d = x = y = f = None
class Test_fitter(_ut.TestCase):
"""
Test class for fitter.
"""
debug = False
def setUp(self):
# Path to the spin... |
import sys
import os
import os.path
sys.path.insert(0, os.path.abspath(os.pardir))
import matholymp
extensions = [
'sphinx.ext.autodoc',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'matholymp'
copyright = u'2014-2022, Joseph Samuel Myers'
version = matholymp.__version__
... |
import math
import random
import time
import ModuleOperators
def mr_num(n):
(r, s) = (n - 1, 0)
while r % 2 == 0:
r //= 2
s += 1
return (r, s)
def isPrime(number, rounds):
#checking by list of prime numbers
f = open('prime_numbers_list.txt', 'r')
for line in f:
if number ... |
import math
def vec2_from_direction(angle, length):
return Vec2(math.cos(angle), math.sin(angle)) * length
def radians_to_degrees(angle):
return (angle / math.pi) * 180
class Vec2:
def __init__(self, x, y = None):
if y is None:
#This is a tuple
self.x = x[0]
self.... |
import numpy as np
import pandas as pd
def create(target):
'''
Create NutritionTarget
Parameters
----------
target : pd.DataFrame
Nutrient constraints. Nutrient amounts are in SI units (i.e. g most of
the time).
Index: str. Nutrient name, may contain spaces.
Columns:
... |
from .base import XMLObject
class Source(XMLObject):
@property
def text(self):
# this should probably be a list of elements rather than `text`
return self.xml.text or "" |
from django.conf.urls.defaults import include, patterns, url
from django.conf import settings
from django.contrib import admin
from django.contrib.auth.decorators import login_required
from lizard_riool import views
from lizard_ui.urls import debugmode_urlpatterns
admin.autodiscover()
urlpatterns = patterns(
'',
... |
network_listing = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>Index of /observations/swob-ml/partners/bc-env-snow</title>
</head>
<body>
<h1>Index of /observations/swob-ml/partners/bc-env-snow</h1>
<pre><img src="/icons/blank.gif" alt="Icon "> <a href="?C=N;O=D">Name</a> ... |
"""Python module for running unit tests.
:author: David Hoese (davidh)
:contact: david.hoese@ssec.wisc.edu
:organization: Space Science and Engineering Center (SSEC)
:copyright: Copyright (c) 2013 University of Wisconsin SSEC. All rights reserved.
:date: Mar 2013
:license: GNU GPLv3
Copyright... |
from astropy.io import fits
import numpy
from ximpol.utils.matplotlib_ import pyplot as plt
from ximpol.utils.logging_ import logger, startmsg, abort
from ximpol.evt.binning import xBinnedCountSpectrum
from ximpol.evt.binning import xBinnedMap
from ximpol.evt.binning import xBinnedModulationCube
from ximpol.evt.subsele... |
"""Pylons environment configuration"""
import os
from mako.lookup import TemplateLookup
from pylons.configuration import PylonsConfig
from pylons.error import handle_mako_error
from sqlalchemy.pool import NullPool
from sqlalchemy import engine_from_config, create_engine
try:
from MySQLdb.converters import conversio... |
import sys
sys.setrecursionlimit(2000)
from fractions import *
from math import *
def row(n):
if n in d:
return d[n]
o = int(floor(sqrt(9+8*(n-1))-3)/4.0)+1
l = o*2
r = 4*o+1
q = 2*o*(o-1)+o-1
i = n-q-1
if i <= r/2: # top half
p = [Fraction(1)/(1<<i)]
for j in range(i... |
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
... |
from requests import Request
from requests_oauthlib import OAuth1
from requests_oauthlib.oauth1_auth import SIGNATURE_TYPE_BODY
from .tool_base import ToolBase
from .launch_params import LAUNCH_PARAMS_REQUIRED
from .utils import parse_qs, InvalidLTIConfigError
class ToolOutbound(ToolBase):
def __init__(self, consum... |
import os
def mkdir(data_dir):
if not os.path.exists(data_dir):
os.makedirs(data_dir) |
from django.conf.urls import include
from django.urls import path
from integrations import views
app_name = 'integrations'
urlpatterns = [
path('', views.HomeView.as_view(), name="index"),
path('dhis/', include('integrations.dhis.urls')),
path('xapi/', include('integrations.xapi.urls')),
] |
from flask.ext.restful import Resource
from models.audio.composer import ComposerSchema, Composer
from util import marshmallow_with
from util import inject_user
class ComposerIndexEndpoint(Resource):
@inject_user
@marshmallow_with(ComposerSchema, many=True)
def get(self):
return Composer.query.all() |
import codecs
from database_access import *
import MySQLdb
import simplejson
if __name__ == '__main__':
insertSource = False
idDataSource = 56
print "Transforming SI drive data"
fname = "si_drive_1005_bycity.json"
with codecs.open(fname,"rb",encoding='utf-8') as f:
se_data = f.read()
jso... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import keras
seed = 123
np.random.seed(seed) # for reproducibility
xl = pd.ExcelFile("data.xlsx")
df = xl.parse(xl.sheet_names[0])
df.head()
disciplinas = np.unique(df.disciplina)
disciplinas_dict = {}
for i,it in enumerate(disciplinas):
discip... |
from PyQt4 import QtCore
class Loader(QtCore.QObject):
progress = QtCore.pyqtSignal(int)
done = QtCore.pyqtSignal()
def __init__(self, extension):
super(Loader, self).__init__()
if not isinstance(extension, list):
raise TypeError
self.extension = extension
self.da... |
'''
SASSIE: Copyright (C) 2011 Joseph E. Curtis, Ph.D.
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.
T... |
"""**Vector Module**
.. tip:: Provides functionality for manipulation of vector data. The data can
be in-memory or file based.
Resources for understanding vector data formats and the OGR library:
Treatise on vector data model: http://www.esri.com/news/arcuser/0401/topo.html
OGR C++ reference: http://www.gdal.org/ogr... |
""" The GuiStateDirector generates the state object from the models.
The GuiStateDirector gets the information from the table and state model and generates state objects. It delegates
the main part of the work to an StateDirectorISIS object.
"""
from __future__ import (absolute_import, division, print_function)
import... |
import sys
from ctypes import *
def LoadLibrary():
try:
libcrypto = cdll.LoadLibrary('libcrypto.so')
except:
try:
libcrypto = cdll.LoadLibrary('libeay32.dll')
except:
raise Exception("Couldn't load OpenSSL lib ...")
return libcrypto
class ECC_key:
def __init__(self, pubkey_x = 0, pubkey_y = 0, privkey =... |
"""
Created on Sun Sep 15 00:37:11 2013
@author: mapologo
Program Assignment for Coursera's Linear and Integer Programming
"""
import numpy as np
def get_values(line, num_type="int"):
"""(str) -> list
Return a list of numbers of type num_type from a line of str values
separated with spaces
>>> get_value... |
'''
Created on 18 nov. 2016
@author: Jordi Marsal
Fast module exponentiation
2 classes to choose, exp2 is better for high numbers
'''
class exprap:
def __init__(self, base, exponent, modul, debug=False):
self.base=base
self.exponent=exponent
self.modul=modul
self.debug=debug
... |
import sys
from PyKDE4.kdeui import *
from PyKDE4.kio import KFileDialog
from PyKDE4.kdecore import i18n, KAutostart
from PyQt4.QtGui import *
from PyQt4.QtCore import SIGNAL, Qt
from ..configmanager import *
from .. import iomediator, interface, model
from .dialogs import GlobalHotkeyDialog
from . import generalsettin... |
from . import polygon2d
def render_svg(obj, filename):
polygons = polygon2d.polygon(obj)
with open(filename, "w") as fp:
box = obj.bounding_box()
box_size = box.size()
fp.write('<svg xmlns="http://www.w3.org/2000/svg" ')
fp.write('width="{}mm" height="{}mm" '.format(box_size.x, b... |
import sys,os,math,collections
from math import *
class Data:
def __init__(self, x,y,idd):
self.X=x
self.Y=y
self.ID=idd
def read_data(filename):
f = open(filename,'r')
L_object=[]
for line in f:
line.strip()
... |
r"""The sensorgraph subsystem is an embedded event based scripting engine for IOTile devices.
It is designed to allow you to embed a small set automatic actions that should
be run whenever events happen inside the device. Sensorgraph is structured as
a dependency tree where actions are linked by named FIFOs that route... |
from .module_definition import ModuleDefinition
from .link_type import LinkType
class Calls(ModuleDefinition):
@property
def name(self):
return 'Calls'
@property
def contacts_link_type(self):
return LinkType.RELATIONSHIP
@property
def contacts_link_name(self):
return 'cal... |
import lldb
from xnu import *
def _showStructPacking(symbol, prefix, begin_offset=0, typedef=None):
"""
recursively parse the field members of structure.
params : symbol (lldb.SBType) reference to symbol in binary
prefix (string) string to be prefixed for each line of output. Useful for r... |
__author__="aabilio"
__date__ ="$06-may-2011 11:03:38$"
from Descargar import Descargar
from utiles import salir, formatearNombre, printt
import sys
class CSur(object):
'''
Descripción de la clase CSur que maneja lo descarga de los vídeos de Canal Sur
'''
def __init__(self, url=""):
self._UR... |
import os, sys, math, errno, argparse
pretend = False
verbose = False
def get_media_path(configfile):
with open(configfile, "r") as f:
for line in f:
if (line.strip()).startswith('media_path'):
item, value = (line.strip()).split(" ",2)
return(value)
def check_free_percent(rootfolder):
statv= os.statvfs(r... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import numpy as np
import pytest
from astropy import units
from astropy.io import fits
from pypeit import specobjs
from pypeit.core import save
from pypeit.tests... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.