code stringlengths 1 199k |
|---|
from ...imports import *
class PlottableAxis:
scale = 'log'
lim = [None, None]
size_normalization = 1
'''
General class definition for a plottable axis,
which can appear as either an xaxis or yaxis.
The standard items to include in the definition
of a plottable object are:
source... |
import pdb
import os
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import functools
from glob import glob
from tensorflow.contrib.data import TFRecordDataset
from tensorflow.contrib.ffmpeg import decode_audio
NUM_CLASSES = len(np.load('data/classes.npy'))
identity = lambda x: x
def amplitud... |
from gruffy import SideBar
g = SideBar(800)
g.title = "Gruffy's Graph"
g.theme_pastel()
g.transparent = True
g.data("Apples", [1, 2, 3, 4, 4, 3])
g.data("Oranges", [4, 8, 7, 9, 8, 9])
g.data("Watermelon", [2, 3, 1, 5, 6, 8])
g.data("Peaches", [9, 9, 10, 8, 7, 9])
g.labels = {0: '2003', 2: '2004', 4: '2005.09'}
g.additi... |
import os
import sys
import subprocess
import logging
import json
logger = logging.getLogger("ash")
def _walk_up(bottom):
"""
walk up a dir tree. Code adapted from https://gist.github.com/1098474
"""
bottom = os.path.realpath(bottom)
#get files in current dir
names = os.listdir(bottom)
dirs,... |
from decimal import Decimal, getcontext
def nthroot (n, A, precision):
getcontext().prec = precision
n = Decimal(n)
x_0 = A / n #step 1: make a while guess.
x_1 = 1 #need it to exist before step 2
while True:
#step 2:
x_0, x_1 = x_1, (1 / n)*((n - 1)*x_0 + (A / (x_0 ** (n - 1))))... |
import picamera
import time
import pygame
import tty
import sys
import os
from PIL import Image
from PIL import ImageOps
cam = picamera.PiCamera()
cam.resolution = (640, 480)
cam.framerate=80
cam.hflip = True
cam.vflip=True
tty.setraw(sys.stdin)
now=time.time()
file_string ="data/forward/img_" + time.strftime("%y%m%d_%... |
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import subprocess
import chainer.computational_graph
import c... |
"""Foyer
"""
from __future__ import print_function
import os
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import foyer.version
requirements = [line.strip() for line in open('requirements.txt').readlines()]
if sys.argv[-1] == 'publish':
os.system('pyt... |
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('projeto101', '0008_auto_20160817_2041'),
]
operations = [
migrations.AddField(
model_na... |
import time
import psutil
import datetime
import threading
from DataManager import DataManager
class PerformanceCollector:
def __init__(self):
self.dump_interval = 30 # Seconds
self.data_manager = DataManager()
self.cpu_thread = threading.Thread(target=self.collect_cpu_performance)
... |
import sys
import argparse
import re
import string
import aspell
import time
import csv
table = string.maketrans("","")
exclude = set(string.punctuation)
speller = aspell.Speller('lang', 'en')
def test_trans(s):
return s.translate(table, string.punctuation)
def ignoreword(s):
match1 = re.search('@[A-Z0-9.-]+',s... |
from .constant import Constant
__NR_Linux = Constant('__NR_Linux',4000)
__NR_syscall = Constant('__NR_syscall',(4000 + 0))
__NR_exit = Constant('__NR_exit',(4000 + 1))
__NR_fork = Constant('__NR_fork',(4000 + 2))
__NR_read = Constant('__NR_read',(4000 + 3))
__NR_write = Constant('__NR_write',(4000 + 4))
__NR_... |
import _plotly_utils.basevalidators
class CustomdataValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(self, plotly_name="customdata", parent_name="violin", **kwargs):
super(CustomdataValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
"""
Django settings for mybook project.
Generated by 'django-admin startproject' using Django 1.9.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
BASE_DI... |
import os
import sys
import subprocess
import pytest
main_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
empty_python_output = """\
import prophy
"""
def tr(str_):
""" Facilitates testing strings output from windows cmd-line programs. """
return str_.translate(None, b'\r')
d... |
from __future__ import absolute_import, unicode_literals, print_function, division
import re
import sublime_plugin
import sublime
from collections import defaultdict
import tempfile
import binascii
try:
from .sublimerepl import manager, SETTINGS_FILE
except (ImportError, ValueError):
from sublimerepl import man... |
import sys
import os
import hyperspy.api as hs
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
from keras.models import load_model
from scipy import optimize, misc
crop_min = 600.
crop_max = 680.
dispersion = 0.4
spectra_path = '/home/mike/Mn_Valences/Test_Spectra/NMC_531_Z1/ICA-Triple-GB_Se... |
"""
BitBake 'Fetch' implementations
Classes for obtaining upstream sources for the
BitBake build tools.
"""
from future_builtins import zip
import os
import subprocess
import logging
import bb
from bb import data
from bb.fetch2 import FetchMethod
from bb.fetch2 import FetchError
from bb.fetch2 import logger
fro... |
from flask import Flask, Response, request
import flask
import argparse
import requests
from flask.ext.cors import CORS
from security import logged_in_route
parser = argparse.ArgumentParser(description='Interface Backend')
parser.add_argument("-p", "--port", type=int, help="the port to run server on", default=80)
parse... |
import _plotly_utils.basevalidators
class R0Validator(_plotly_utils.basevalidators.AnyValidator):
def __init__(self, plotly_name="r0", parent_name="barpolar", **kwargs):
super(R0Validator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.... |
from django.conf.urls import url
from django.views.generic import TemplateView
from interface import views
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'),
url(r'^orgs$', views.OrganizationListView.as_view(), name='organization-list'),
url(r'^projects$', views.Projec... |
import os
from os import path as osp
DATA_DIR = osp.realpath(osp.join(osp.dirname(__file__), '../../data/'))
def reference_data_path(sub_path):
return osp.join(DATA_DIR, sub_path) |
import numpy as np
import scipy.ndimage as ndi
import scipy.sparse as sp
from discretize.utils.code_utils import is_scalar
from scipy.spatial import cKDTree, Delaunay
from scipy import interpolate
import discretize
from discretize.utils.code_utils import deprecate_function
import warnings
num_types = [int, float]
def r... |
"""
ERP+
"""
__author__ = 'António Anacleto'
__credits__ = []
__version__ = "1.0"
__maintainer__ = "António Anacleto"
__status__ = "Development"
__model_name__ = 'linha_leitura_tecnica.LinhaLeituraTecnica'
import auth, base_models
from orm import *
from form import *
try:
from my_contador import Contador
except:
... |
import sys
if __name__ == '__main__':
if len(sys.argv) == 2:
line = bytes.fromhex(sys.argv[1]).decode('ascii', 'ignore')
print(line)
print(''.join('{:02X}'.format(ord(i)) for i in line)) |
from __future__ import absolute_import, print_function, unicode_literals
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "s_analyzer.settings.default")
application = get_wsgi_application() |
import struct
import io
import sys
import datetime
import re
try:
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
except ImportError:
from io import StringIO
try:
import lzf
HAS_PYTHON_LZF = True
except ImportError:
HAS_PYTHON_LZF = False
RED... |
from pyspark.ml.wrapper import JavaParams
@staticmethod
def _mml_from_java(java_stage):
"""
Given a Java object, create and return a Python wrapper of it.
Used for ML persistence.
Meta-algorithms such as Pipeline should override this method as a classmethod.
"""
def __get_class(clazz):
"... |
from adapter import urllib2_oauth
import compat
import util
class Client(object):
request_token_url = None
authorize_url = None
access_token_url = None
def __init__(self, client, token=None,
adapter=urllib2_oauth.Adapter, **fetch_parameters):
self.adapter = adapter
self.... |
from __future__ import print_function
from time import strftime, gmtime
import time
import compute_opportunities
import sys
if len(sys.argv) < 2 or (sys.argv[1] != "True" and sys.argv[1] != "False"):
print("Usage: trading.py <real trading mode>")
print(" real trading mode is True or False")
sys.exit(1)
rea... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "template_korean.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue... |
from __future__ import absolute_import
from __future__ import print_function
import os
import numpy
import matplotlib.pyplot as plt
import datetime
import clawpack.visclaw.colormaps as colormap
import clawpack.visclaw.gaugetools as gaugetools
import clawpack.clawutil.data as clawutil
import clawpack.amrclaw.data as amr... |
from unittest import TestCase, mock
from preggy import expect
import thumbor.server
from tests.fixtures.custom_error_handler import (
ErrorHandler as CustomErrorHandler,
)
from thumbor.app import ThumborServiceApp
from thumbor.config import Config
from thumbor.server import (
configure_log,
get_application,... |
"""
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""
__all__ = [
"IntegerValue",
]
import qy
import qy.llvm as llvm
class IntegerValue(qy.Value):
"""
Integer value in the wrapper language.
"""
def __invert__(self):
"""
Return the result of bitwise inversion.
"""
... |
import os
script = os.environ['PROCESSINGSCRIPT']
if script == 'redis-to-bigquery':
os.system("python redis-to-bigquery.py")
elif script == 'twitter-to-redis':
os.system("python twitter-to-redis.py")
else:
print "unknown script %s" % script |
from django.contrib import admin
from src.basic.messages.models import Message
class MessageAdmin(admin.ModelAdmin):
list_display = ('from_user', 'to_user', 'subject', 'to_status', 'from_status', 'created', 'content_type', 'object_id')
admin.site.register(Message, MessageAdmin) |
"""Search Giphy."""
import random
from plumeria import config
from plumeria.command import commands, CommandError
from plumeria.command.parse import Text
from plumeria.plugin import PluginSetupError
from plumeria.util import http
from plumeria.util.ratelimit import rate_limit
api_key = config.create("giphy", "key",
... |
import _plotly_utils.basevalidators
class DyValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="dy", parent_name="waterfall", **kwargs):
super(DyValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwa... |
"""
The 'instructions' widget for Morse Trainer.
Used to show a QLabel containing instructions. Read only.
instructions = Instructions()
"""
from PyQt5.QtWidgets import (QApplication, QWidget, QComboBox, QLabel,
QTextEdit, QHBoxLayout, QVBoxLayout, QGroupBox)
class Instructions(QWidget):
... |
from __future__ import unicode_literals
from abc import abstractmethod
from six import with_metaclass
from ..policy import ABCPolicyUtilMeta, PolicyUtil
class AbstractActionGenerator(with_metaclass(ABCPolicyUtilMeta, PolicyUtil)):
"""
Abstract base class for action generators, which determine what actions are t... |
f = open("game_actions.yml","w+")
for actor in range(1,6):
for turn in range(1,4):
f.write("ac_game1-actor" + str(actor) + "turn" + str(turn) + ":\n")
f.write(" description: \"{ actor: " + str(actor) + ", moves: 'ruldruldrl' }\"\n")
f.write(" turn: firstgameturns" + str(turn) + "\n\n")
f.close(... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flaskext.mysql import MySQL
from flask_login import LoginManager
from flask_mail import Mail
from .momentjs import momentjs
from flask_babel import Babel
from flask.json import JSONEncoder
app = Flask(__name__)
app.config.from_object('config')
mysql =... |
"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base.domain import Domain
from twilio.rest.lookups.v1 import V1
class Lookups(Domain):
def __init__(self, twilio):
"""
Initialize the Lookups Domain
:returns: Domain for Lookup... |
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy as np
import os,cython
sourcefiles = ['floyd.pyx']
this_dir = os.path.split(cython.__file__)[0]
extensions = [
Extension("floyd", sourcefiles,
include_dirs=[np.get_include(),t... |
import sys
import os
import subprocess
argv_size = len(sys.argv)
if argv_size != 3 and argv_size != 4:
print("Usage protos_compiler.py PROTO_COMPILER_FILE_PATH [proto dir] [proto extension]")
sys.exit(0)
try:
proto_compiler_file_path = sys.argv[1]
directory = sys.argv[2]
if argv_size == 4:
extension = sys... |
"""Testing suite for Multivariate Normal class.
"""
from __future__ import print_function, division
import unittest as ut
import numpy as np
import numpy.testing as npt
import scipy.stats as scs
from multidensity import MvN
class MvNTestCase(ut.TestCase):
"""Test MvN distribution class."""
def test_pdf(self):
... |
import equibel as eb
def test_expanding_cardinality():
G = eb.star_graph(3)
G.add_formula(1, 'p')
G.add_formula(2, 'p')
G.add_formula(3, '~p')
R_semantic, num_expanding_iterations = eb.iterate_expanding_fixpoint(G, method=eb.SEMANTIC, opt_type=eb.CARDINALITY, simplify=True)
assert(R_semantic.for... |
from nbconvert.preprocessors.sanitize import SanitizeHTML
from traitlets import Set
class PlotlySanitizeHTML(SanitizeHTML):
def __init__(self, **kw):
super(PlotlySanitizeHTML, self).__init__(**kw)
# Add Plotly key to safe_output_keys:
safe_keys = self.safe_output_keys.update(['text/vnd.plotl... |
from django.conf.urls import url
from test_views.views import IndexView, TestView, LoginRequiredView
urlpatterns = [
url(r'^$', IndexView()),
url(r'^test$', TestView()),
url(r'^login_required$', LoginRequiredView()),
] |
import unittest
import os
import redis
import hashlib
import subprocess
import binascii
import RandomIO
from sys import platform as _platform
if _platform.startswith('linux') or _platform == 'darwin':
cat_cmd = 'cat'
iotools_call = ['IOTools.py']
elif _platform == 'win32':
cat_cmd = 'type'
iotools_call ... |
import sys
if sys.version_info[0] == 2:
import mock
else:
from unittest import mock
from unittest import TestCase
from uuid import uuid4
import vcr
from message_api.channel import MessageApi
class TestChannelCreate(TestCase):
def setUp(self):
self.project_id = str(uuid4().hex)
self.api_key =... |
from django.utils import simplejson
from dajaxice.decorators import dajaxice_register
from dajaxice.core import dajaxice_functions
from dajax.core import Dajax
import os, glob, zipfile
from datetime import datetime
from lighthouse.templateGen.lapack_le.lapack_le import generateTemplate, generateTemplate_C
dir_download ... |
class OpsimulateError(Exception):
"""General Opsimulate Error"""
class ModuleValidationError(OpsimulateError):
"""Error with module contents"""
class ModuleMetadataError(ModuleValidationError):
"""Error with format of module metadata"""
class ModuleScriptsExecutableError(ModuleValidationError):
"""Error... |
from django.test import TestCase
from scrapper import models, crawler, tasks
class DefaultTest(TestCase):
def setup(self):
models.Criterion.objects.create(type='hash_tag', value=u'مصر')
models.Criterion.objects.create(type='hash_tag', value=u'وطن')
models.Criterion.objects.create(type='hash_... |
import pytest
@pytest.fixture
def atac_alignment_quality_metric_low(testapp, award, encode_lab,
analysis_step_run_atac_encode4_alignment,
ATAC_bam):
item = {
"step_run": analysis_step_run_atac_encode4_alignment['@id'],
"... |
import sys
import re
import json
import gzip
re_filename = re.compile(".*[.-][Jj]?([0-9]+)[Jj]?\.json.gz")
re_arrived = re.compile("^atmost: arrived '(.+)'")
re_linking = re.compile("^atmost: linking '(.+)': \(predicted=([0-9.-]+)G±([0-9.-]+)G\|available=([0-9.-]+)G\)")
re_linked = re.compile("^atmost: linked '(.+)':... |
from django.core.urlresolvers import resolve
from collections import OrderedDict
from ndc.models import Tag
def menus(request):
menus = OrderedDict([
('timetable', {'title': 'Timetable', 'icon': 'calendar', 'color': 'blue'}),
('sessions', {'title': 'Session', 'icon': 'video', 'color': 'green'}),
... |
"""
Domain sharding for Django static files.
"""
VERSION = (0, 1)
__version__ = '.'.join([str(x) for x in VERSION]) |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('letter', '0002_auto_20200303_1117'),
('guide', '0005_action_mail_intent'),
]
operations = [
migrations.AddField(
model_name='action',
... |
"""Definitions for tt's built-in Boolean operators."""
class BooleanOperator(object):
"""A thin wrapper around a Boolean operator."""
def __init__(self, precedence, eval_func, default_symbol_str,
default_plain_english_str):
self._precedence = precedence
self._eval_func = eval_fu... |
import ctypes
import ctypes.util
import _ctypes
import hashlib
import base64
import time
import logging
import sys
import os
addrtype = 0
class _OpenSSL:
"""
Wrapper for OpenSSL using ctypes
"""
def __init__(self, library):
self.time_opened = time.time()
"""
Build the wrapper
... |
from __future__ import unicode_literals
import logging
import re
from rbtools.api.errors import APIError
from rbtools.clients.errors import InvalidRevisionSpecError
from rbtools.deprecation import RemovedInRBTools40Warning
from rbtools.utils.match_score import Score
from rbtools.utils.repository import get_repository_i... |
"""
Compute streamfunction and velocity potential from the long-term-mean
flow.
This example uses the xarray interface.
Additional requirements for this example:
* xarray (http://xarray.pydata.org)
* matplotlib (http://matplotlib.org/)
* cartopy (http://scitools.org.uk/cartopy/)
"""
import cartopy.crs as ccrs
import ma... |
from django.views.generic.edit import FormView
from django.core.urlresolvers import reverse, reverse_lazy
from django.shortcuts import get_object_or_404, redirect
from django.views.generic.base import TemplateResponseMixin, View, TemplateView
from django.contrib.auth.tokens import default_token_generator
from django.u... |
"""
This is the getkey module. It is meant for small files that are human readable and are small enough to be loaded into
memory. It depends on PyNaCl.
NOTE:
THIS MODULE COMES WITH NO GUARANTEES WHATSOEVER.
Untested on Mac and Windows systems.
Tested with Python 3.5.2 on Linux (Ubuntu Mate 16.04.3) systems.
Tested with... |
from lib import primes_up_to
NUM_ROWS = 15
def compute():
data = map(int, DATA.split())
return max_sum(data, 0, frozenset(range(0, NUM_ROWS)), {})
def max_sum(data, column, free_rows, cache):
if column == NUM_ROWS - 1:
x, = free_rows
return data[x * NUM_ROWS + column]
if free_rows not in cache:
cache[free_row... |
"""
Django settings for events project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
import environ
ROOT_DIR = environ.Path(__file__) - 3 # (events/config/setting... |
from price_dump import *
import matplotlib.pyplot as plt
import math
data = get_first_N(15, show=True)
price = prices(data)
float_price = map(float, price)
logs = list(map(math.log10,float_price))
bins = range(0, len(price))
plt.plot(bins, logs[::-1])
plt.show() |
from __future__ import division
import optparse
from mpi4py import MPI
import numpy as np
from serial import find_solution, write_results
from settings import SEARCH_SPACE
def refine_work(work, p, new_min, verbose=False, split=False, split_min=4):
"""
Filter remaining work based on newly found solution and spli... |
'''
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
... |
import os
import pytest
from appdirs import user_config_dir
import genomepy
import genomepy.utils
from tests import linux, travis
def test_head_annotations(caplog, capsys):
genomepy.functions.head_annotations("ASM14646v1", provider="ncbi", n=1)
captured = capsys.readouterr().out.strip()
assert "NCBI" in cap... |
import math
import numpy as np
import matplotlib.pyplot as plt
from porousmedialab.phcalc import Acid
import seaborn as sns
from matplotlib.colors import ListedColormap
sns.set_style("whitegrid")
def custom_plot(lab, x, y, ttl='', y_lbl='', x_lbl=''):
plt.figure()
ax = plt.subplot(111)
plt.plot(x, y, lw=3)
... |
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pip... |
from molecule.driver import basedriver
class ProxmoxDriver(basedriver.BaseDriver):
def __init__(self, molecule):
super(ProxmoxDriver, self).__init__()
self.molecule = molecule |
"""Update encrypted deploy password in Travis config file
"""
from __future__ import print_function
import base64
import json
import os
from getpass import getpass
import yaml
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from cryptography.hazmat.backends import default_backend
from crypt... |
import sys, os
sys.path.insert(0, os.path.abspath('files/codes'))
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = ... |
from dcbase.tests.baseTestCase import BaseTestCase |
import unittest
import os
import sys
if __name__ == "__main__":
test_dirs = os.listdir('./tests')
loader = unittest.TestLoader()
for directory in test_dirs:
if directory == "app":
test_path = "./tests/{}".format(directory)
suite = loader.discover(test_path)
result... |
import re
import markdown
from django.conf import settings
from django.template.loader import render_to_string
from filer.models import File
from .base import MarkymarkExtension
class FilerPostprocessor(markdown.postprocessors.Postprocessor):
"""
Filer markdown extension for django-filer to show files and image... |
from unittest import TestCase
from src.utilise.json_serialiser import JsonSerialiser
from src.utilise.built_in_extensions import *
import typing
__author__ = 'James Stidard'
JSS = typing.TypeVar( 'JSS', bound=JsonSerialiser )
class Thing(JsonSerialiser):
str_attr = "string"
int_attr = 23
bool_attr = Tr... |
import six
from ...errors.httpconflictexception import HttpConflictException
import saklient
str = six.text_type
class SnapshotInMigrationException(HttpConflictException):
## 要求された操作を行えません。このスナップショット または これより新しいスナップショットから他のリソースへのコピー処理が進行中です。完了後に再度お試しください。
## @param {int} status
# @param {str} code=None
... |
import argparse , ast , json
from influxdb import InfluxDBClient
def write(client,data):
result = client.write_points(data)
print "{\"status\":\""+str(result)+"\"}"
def query(client,query):
result = client.query(query)
print json.dumps(result.raw)#, indent=4, sort_keys=True)
def createDB(client,dbname):... |
import os
BASEDIR = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
TESTING = False
SECRET_KEY = 'secret'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + \
os.path.join(BASEDIR, 'bucketlist.sqlite')
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///... |
"""
Genetic Algorithm for solving Selective Travelling Salesman Problem.
:Author: Fabio Scala <fabio.scala@gmail.com>
"""
import logging
import random
import time
import numpy
class GaSolver(object):
""" Genetic algorithm based on `A. Piwonska selective travelling salesman algorithm <http://yadda.icm.edu.pl/baztech... |
import time
while True:
print "I need to make sure I'm still alive."
time.sleep(1) |
from django import template
from djqgrid import json_helpers
register = template.Library()
@register.simple_tag(takes_context=True)
def jqgrid(context, grid, prefix='', pager=True, urlquery=None, **kwargs):
"""
Adds a complete jqGrid - HTML and JavaScript - to the template.
Two HTML elements are added, a ``... |
from conan.packager import ConanMultiPackager
if __name__ == "__main__":
builder = ConanMultiPackager()
builder.add_common_builds(shared_option_name="IlmBase:shared")
builder.run() |
"""Fifth step for RITE: train or test classifier with extract feature"""
if __name__ == '__main__':
pass |
from __future__ import print_function
import argparse
import logging
from clang.cindex import Config
from operator import itemgetter
import sys
from analyzer.designparam import DesignAnalysis
from analyzer.jsonparam import TasksConfig
def write_source_files(output, hardware_file, software_file):
hardware_output = m... |
from tests.test_helper import *
class TestSearch(unittest.TestCase):
def test_text_node_is(self):
node = Search.TextNodeBuilder("name")
self.assertEqual({"is": "value"}, (node == "value").to_param())
def test_text_node_is_not(self):
node = Search.TextNodeBuilder("name")
self.asse... |
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HSS3_if1_CompleteLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HSS3_if1_CompleteLHS.
"""
# Flag t... |
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from future_builtins import *
import bisect
import codecs
from PyQt4.QtCore import (QAbstractItemModel, QModelIndex, QString,
QVariant, Qt)
from PyQt4.QtCore import pyqtSignal as Signal
KEY, NODE = rang... |
""" This package has the class that allows for you to access a neo4j database using the py2neo library. """
__author__ = "Manoel Horta Ribeiro" |
from model import *
from sqlalchemy.orm import sessionmaker
from cassiopeia import riotapi
from cassiopeia.type.api.exception import APIError
import secret_keys
import time
import sys
def query_riot_api(function, *args):
while(True):
try:
data = function(*args)
except APIError as err:
... |
"""configuration for jmoiron.net"""
class Config(object):
DEBUG = False
TESTING = False
DATABASE_URI = "mongodb://localhost:27017/"
DATABASE_NAME = "jmoiron"
SECRET_KEY = '\x10t\x98\xaeR:0\xc2\xea\x8frl b=\xde'
USE_LESS = True
class DevelopmentConfig(Config):
DEBUG = True
OFFLINE_MODE = ... |
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import pyodbc
import yaml
import pprint
from sqlalchemy import create_engine, Column, MetaData, Table, Index
from sqlalchemy import Integer, String, Text, Float, Boolean, BigInteger, Numeric, SmallInteger
import ConfigParser, os
fileLocation = os.path.dirname(os.pa... |
from setuptools import setup
setup(name="moheve",
version="0.1",
description="Mohawk authentication for Eve APIs",
keywords="python-eve mohawk moheve",
url="https://github.com/xander-wr/moheve/",
author="https://github.com/xander-wr/",
author_email="hello@xander.frl",
license="... |
from core.config import Settings
from core.syslog import Syslog
from core import utils
import redis
r = redis.StrictRedis(host=self.settings.redis.host,
port=int(self.settings.redis.port),
db=int(self.settings.redis.db)) |
import piston
import tornado.httpserver
import tornado.web
import tornado.options
import tornado.ioloop
import tornado.gen
import tornado.httpclient
import urllib
import pony
class UserHandler(piston.BaseHandler):
def read(self, user_id):
print "RRRRR"
query = "h"
client = tornado.httpclient... |
import os
from unittest import TestCase
from nose.tools import ok_
from mock import Mock
from lamvery.actions.build import BuildAction
def default_args():
args = Mock()
args.conf_file = '.lamvery.yml'
args.dry_run = True
args.no_libs = False
args.single_file = False
return args
class BuildAction... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.