code stringlengths 1 199k |
|---|
<<<<<<< HEAD
<<<<<<< HEAD
"""curses.panel
Module for using panels with curses.
"""
from _curses_panel import *
=======
"""curses.panel
Module for using panels with curses.
"""
from _curses_panel import *
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
=======
"""curses.panel
Module for using panels with curses.
"""
fr... |
def convertir_eeuu(nota):
if nota >= 90: #La nota es mayor o igual a 90?
return 'A'
elif nota >= 70: #No se cumple lo de arriba, es menor a 90. Es mayor o igual a 70?
return 'B'
elif nota >= 55: #No se cumple lo de arriba, es menor a 70. Es mayor o igual a 55?
return 'C'
else: #N... |
from math import ceil, sqrt
import sys
if sys.version_info < (3, 4):
raise SystemError("Must be using Python 3.4 or higher")
def is_micropython():
return sys.implementation.name == "micropython"
if is_micropython():
from ucollections import OrderedDict
else:
from collections import OrderedDict
from ... |
from __future__ import absolute_import, unicode_literals
from config.template_middleware import TemplateResponse
from gaebusiness.business import CommandExecutionException
from gaecookie.decorator import no_csrf
from livro_app import livro_facade
from tekton import router
from tekton.gae.middleware.redirect import Redi... |
RECURSIVE_SQL_ = """
WITH RECURSIVE entity_graph(type, id, name, state, sub_type, related_type, related_id, related_is_a, dart_depth) AS (
VALUES (:entity_type, :entity_id, :name, :state, :sub_type, NULL, NULL, NULL, 0)
UNION
SELECT t.*
FROM entity_graph g
JOIN LATERAL (
... |
import pausable_unittest
class BasePauser(object):
def __init__(self):
pass
def add_actions(self):
pass
def add_action(self, method_name, method):
pausable_unittest.TestCase.add_action(method_name, method)
def do_pause(self, info):
pass
def after_pause(self):
... |
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpRes... |
import os
import socket
import time
import pytest
from unittest import mock
from mitmproxy.test import tutils
from mitmproxy import options
from mitmproxy.addons import script
from mitmproxy.addons import proxyauth
from mitmproxy import http
from mitmproxy.proxy.config import HostMatcher
import mitmproxy.net.http
from ... |
from django import template
register = template.Library()
@register.filter
def str_eq_int(value, arg):
return str(value)==str(arg)
@register.filter
def trans_for_number(value):
try:
return int(value)
except :
return value |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import now_datetime, cint, cstr
import re
from six import string_types
def set_new_name(doc):
"""
Sets the `name` property for the document based on various rules.
1. If amended doc, set suffix.
2. If `autoname` method is d... |
from detectem.plugin import Plugin
class WPSuperCachePlugin(Plugin):
name = "wp-super-cache"
homepage = "https://wordpress.org/plugins/wp-super-cache/"
tags = ["wordpress"]
matchers = [
{
"xpath": (
'//comment()[contains(.,"Cached page generated by WP-Super-Cache on")... |
import cross3d
from cross3d.abstract.abstractapplication import AbstractApplication
from Py3dsMax import mxs
from cross3d.enum import EnumGroup, Enum
from PyQt4.QtCore import QTimer
_n = mxs.pyhelper.namify
dispatch = None
_STUDIOMAX_CALLBACK_TEMPLATE = """
global cross3d
if ( cross3d == undefined ) do ( cross3d = pyma... |
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base import serialize
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class StreamMes... |
import typing
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix=commands.when_mentioned, description="Nothing to see here!")
@bot.group(hidden=True)
async def secret(ctx: commands.Context):
"""What is this "secret" you speak of?"""
if ctx.invoked_subcommand is None:
await... |
import abjad
import collections
import consort
from abjad.tools import systemtools
from abjad.tools import timespantools
music_specifiers = collections.OrderedDict([
('One', None),
('Two', None),
])
target_timespan = abjad.Timespan(0, 10)
def test_FloodedTimespanMaker_01():
timespan_maker = consort.Floo... |
from unittest import TestCase
from utils.strutils import StrUtils
class StrUtilsTest(TestCase):
def test_fill_string_up_with_blanks_appends_number_blanks_to_string_smaller_than_max(self):
result = StrUtils.fill_string_up_with_blanks('this is test', 15)
self.assertEqual('this is test ', result)
... |
import asyncio
from os import path, mkdir
from utils import gspread_api
import discord
client = None
MESSAGE_XP_VAL = 5
ONLINE_XP_VAL = 5
ONLINE_TIMEOUT = 60 * 30 # (30 Minuten)
def save(table):
g = gspread_api.Settings("dd_saves", 0)
g.set_dict(table)
def get_table():
g = gspread_api.Settings("dd_saves", ... |
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^$', 'canaa.core.views.home', name='home... |
for p in range(0,int(input())):
size = int(input())
out = '+'
out += '-' * ((size * 2) - 1)
out += '+'
print(out)
spaces = size - 1
slashes = 0
for q in range(0,size):
line = '|'
line += ' ' * spaces
line += '/' * slashes
line += '*'
line += '\\' * slashes
line += ' ' * spaces
... |
"""Basic usage of the pybotics package."""
from pybotics.geometry import vector_2_matrix
from pybotics.predefined_models import ur10
from pybotics.robot import Robot
from pybotics.tool import Tool
def main():
"""
Demonstrate pybotics usage.
View source for more info.
"""
# init robot
robot = Rob... |
from scipy.integrate import DOP853, solve_ivp
__all__ = ["DOP853", "solve_ivp"] |
import unittest
import sendinel.backend.bluetooth
class BluetoothTest(unittest.TestCase):
def test_discoveredDevices(self):
devices = {}
BluetoothTest.devices = {'00A48F': 'super Handy'}
self.serverAddress = "127"
class Action:
def getDiscoveredDevices(self):
... |
import os
import pandas as pd
import pytz
from qstrader.alpha_model.fixed_signals import FixedSignalsAlphaModel
from qstrader.asset.equity import Equity
from qstrader.asset.universe.static import StaticUniverse
from qstrader.data.backtest_data_handler import BacktestDataHandler
from qstrader.data.daily_bar_csv import C... |
"""
Mission objectives aren't clearly defined yet
"""
class MissionObjective:
def __init__(self, victory_points):
self.victory_points = victory_points
self.accomplished = 0
class NavObjective(MissionObjective)
def __init__(self, victory_points, nav):
MissionObjective.__init__(self, victory_points)
self.nav = ... |
"""
__graph_MT_post__Signal.py___________________________________________________________
Automatically generated graphical appearance ---> MODIFY DIRECTLY WITH CAUTION
____________________________________________________________________________
"""
import tkFont
from graphEntity import *
from GraphicalForm impor... |
__author__ = 'Sal Aguinaga'
__license__ = "GPL"
__version__ = "0.1.0"
__email__ = "saguinag@nd.edu"
import pprint as pp
import pandas as pd
import numpy as np
import scipy
from nltk.cluster import KMeansClusterer, GAAClusterer, euclidean_distance
import nltk.corpus
import nltk.stem
import re
import io
import json, ti... |
try:
import reactrobotics as rr;
except Exception, e:
print "Failed to import reactrobotics, {}".format(e)
print "Check you have built the code and run the /Scripts/pythonapi.sh install"
def main():
if __name__ == '__main__':
try:
main()
except Exception, e:
print "Error ", str(e) |
class Solution(object):
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
count = [0]
cols = [0] * n
s1 = [0] * (n+n)
s2 = {key: 0 for key in range(-n, n)}
def traceback(row):
if row == n:
count[0] += 1
... |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Font(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "heatmap.hoverlabel"
_path_str = "heatmap.hoverlabel.font"
_valid_props = {"color", "colorsrc", "f... |
from unittest.mock import MagicMock, call, ANY
from django.test import TestCase
from kolekti import tasks
from .. import factories
class CheckTaskTests(TestCase):
def setUp(self):
self.subscription = factories.Subscription()
self.client = factories.Client()
self.subscription.clients.add(self... |
import sys
import numpy as np
import matplotlib.pyplot as plt
vmin = -250
vmax = 200
spec = sys.argv[1]
outfile = sys.argv[2]
lines = [line.strip() for line in open(spec)]
header = lines[0].split()
glon = header[1]
glat = header[2]
beam = header[4]
data = []
for line in lines:
if not (line.startswith('%') or (line ... |
"""Support for Big Ass Fans SenseME light."""
import logging
from typing import Any
from aiosenseme import SensemeDevice
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_TEMP,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR_TEMP,
LightEntity,
)
from homeassistant.const import CONF_DEVICE
f... |
def new_join(res,*args):
sum_string = str(args[0])
for i in range(1,len(args)):
sum_string += res+str(args[i])
return sum_string
print new_join(':',1,2,3,4,5) |
"""wikisual URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... |
from __future__ import absolute_import, print_function, unicode_literals
from rest_framework import serializers
from api._base import ExcludeAndOnlySerializerMixin
from api.blog.serializers import TagSerializer # noqa
from api.member.serializers import MemberSerializer
from blog.models import Tag
from book.models imp... |
"""Test compact blocks (BIP 152).
Version 1 compact blocks are pre-segwit (txids)
Version 2 compact blocks are post-segwit (wtxids)
"""
from test_framework.mininode import *
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.blocktools import create_bloc... |
import _plotly_utils.basevalidators
class BgcolorsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name="bgcolorsrc", parent_name="violin.hoverlabel", **kwargs
):
super(BgcolorsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_... |
from __future__ import print_function
import site
import getopt, string, sys
from PIL import Image
def usage():
print("PIL Convert 0.5/1998-12-30 -- convert image files")
print("Usage: pilconvert [option] infile outfile")
print()
print("Options:")
print()
print(" -c <format> convert to format ... |
import os
import yaml
import mmap
import time
import datetime
import glob
from subprocess32 import call
'''
'JTCluster submission.
After checking that the PreCluster step finished successfully, all jobs are
send out for parallel processing.
'''
def check_precluster(lsf_file):
if len(lsf_file) == 0:
raise Ex... |
from math import atan2, pi, sqrt, cos, sin
import random
import strings
class Quadrant():
def __init__(self):
self.name = ""
self.klingons = 0
self.stars = 0
self.starbase = False
self.scanned = False
class SectorType():
def __init__(self):
self.empty, self.star,... |
import os
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP
DEBUG = True
SECRET_KEY = 'foobar'
DATABASE_ENGINE = 'django.db.backends.sqlite3'
DATABASE_NAME = 'julython.db'
DATABASE_PASSWORD = ''
DATABASE_SERVER = ''
DATABASE_USER = ''
LOGFILE_PATH = os.path.expanduser('~/julython.log')
TWITTER_... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0003_auto_20141103_1701'),
]
operations = [
migrations.AddField(
model_name='article',
name='template',
field... |
from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
from functools import reduce
from typing import Any, Generic, NamedTuple, Optional, cast
from aoc_common import T, load_puzzle_input, report_solution
class Location(NamedTuple):
row: int
column: int
class Direction(tuple[... |
from os import environ
import six
if six.PY34:
import configparser
else:
import ConfigParser as configparser
base_config = {
'wait_timeout': environ.get('TENABLEIOTEST_WAIT_TIMEOUT', '300'),
'scan_template_name': environ.get('TENABLEIOTEST_SCAN_TEMPLATE_NAME', 'basic'),
'registry_host': environ.get(... |
from __future__ import unicode_literals
import datetime
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('digest', '0042_auto_20160401_1509'),
]
operations = [
migrations.AlterM... |
def spin_words(sentence):
sentence = sentence.split()
for i, word in enumerate(sentence):
if len(word) >= 5:
sentence[i] = word[::-1]
return ' '.join(sentence)
def zip(lista):
menor_len = min([len(lst) for lst in lista])
for i in range(menor_len):
yield [lst[i] for lst in lista]
def apply(f, n):
def func(x... |
import json
def get_users():
with open('userportal.txt','rb') as f:
cxt = f.read()
return json.loads(cxt)
def validate_login(username,password):
users = get_users()
for user in users:
if user.get('username') == username and user.get('password') == password:
return True
return False
def validate_user(userna... |
import unittest
import datetime
import httpretty as HP
import json
from malaysiaflights.malindo import Malindo as Mal
class MalRequestTests(unittest.TestCase):
def init_url_helper(self):
host = 'https://mobileapi.malindoair.com'
path = ('/GQWCF_FlightEngine/GQDPMobileBookingService.svc'
... |
from random import randint
from memory import LastRecentlyUsedAlgorithm
PAGE_SIZE = 100
FRAMES = 10
NUM_REQUESTS_PER_PROCESS = 1000
class MemoryAllocationSimulation():
def __init__(self, processes, page_faults_control=False):
self.processes = processes
self.page_faults_control = page_faults_control
... |
from sqlalchemy import Column, create_engine, orm, types
from sqlalchemy.ext.declarative import declarative_base
from django.conf import settings
engine = create_engine(settings.DB_URL)
session = orm.scoped_session(orm.sessionmaker(bind=engine))
Base = declarative_base()
Base.query = session.query_property()
class Rout... |
import time
def app(env, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
if 'foo' in env['path'] :
print "going to sleep"
time.sleep(5)
m = "method : " + env['method'] + "<br>"
p = "path : " + env['path'] + "<br>"
return [ '<h1>Hello World</h1>', m, p] |
import logging as logger
from kolibri.content.utils.annotation import update_channel_metadata_cache
from kolibri.tasks.management.commands.base import AsyncCommand
from ...utils import paths, transfer
logging = logger.getLogger(__name__)
class Command(AsyncCommand):
def add_arguments(self, parser):
parser.a... |
from flask import Flask
def create_app():
app = Flask(__name__)
from application.blueprints.newsletter import newsletter
app.register_blueprint(newsletter)
#~ app.config.from_object("settings.Config")
#~ app.config.from_pyfile(config_filename)
#~ from yourapplication.model import db
#~ db.in... |
from django.shortcuts import render
from io import BytesIO
from django.http import HttpResponse
from django.core import serializers
from django.forms.models import model_to_dict
from django.views.generic.list import ListView
from django.views.generic import DetailView
from django.utils import timezone
from templated_do... |
DEBUG = False
CONFIG = {
'DEFAULT_DEBUG_LEVEL': 0,
'MAX_DESC_LEN': 128,
'BARCODE_SZ': 8,
'DESC_TERM': '\xED',
'BUY_TERM': '\xBB\xBB\xBB\xBB',
'BUY_MORE': '\xBD\xBD\xBD\xBD'
}
ERRORS = {
} |
"""
@name: Modules/House/Schedules/_test/test_schedule.py
@author: D. Brian Kimmel
@contact: D.BrianKimmel@gmail.com
@copyright: (c) 2013-2020 by D. Brian Kimmel
@license: MIT License
@note: Created on Apr 8, 2013
@summary: Test handling the schedule information for a house.
Passed all 50 tests - DBK... |
from time import sleep
import tm1637
try:
import thread
except ImportError:
import _thread as thread
Display = tm1637.TM1637(CLK=21, DIO=20, brightness=1.0)
try:
print "Starting clock in the background (press CTRL + C to stop):"
Display.StartClock(military_time=False)
print 'Continue Python script a... |
from DataSourceUser import *
from profilo import *
def test():
db=Db('mmasgisDB',-1)
db.setUserName("root")
db.setPassword("vilu7240")
db.setHost("localhost")
db.setPort("3306")
db.setRDBMS("mysql")
user=User("data",1)
user.setActiveDb(db)
ds=DataSource(user,True)
ds.writeProfile... |
import pygeoj as gj
testfile = gj.new()
testfile.add_feature(geometry=gj.Geometry(type="Point", coordinates=[(11,11)]),
properties=dict(hello=1, world=2))
testfile.add_feature(geometry=gj.Geometry(type="Point", coordinates=[(12,12)]),
properties=dict(hello=1, world=2))
for feat... |
"""
The project pages map for basic
"""
from optimus.pages.views.base import PageViewBase
class Index(PageViewBase):
"""
Index page
"""
title = "My project index"
template_name = "index.html"
destination = "index.html"
PAGES = [
Index(),
] |
import sys
import os
import json
import tempfile
import uuid
from unittest import TestCase
from flask import Flask, jsonify, request
from flask_orator import Orator, jsonify
from sqlite3 import ProgrammingError
from orator.support.collection import Collection
PY2 = sys.version_info[0] == 2
class FlaskOratorTestCase(Tes... |
import stripe
import datetime
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth import logout as logout_user
from django.contrib.auth import login as login_user
from django.db.mod... |
"""
CNN on Not MNIST using Keras
Author: Rowel Atienza
Project: https://github.com/roatienza/Deep-Learning-Experiments
"""
from __future__ import print_function
import numpy as np
import pickle
import time
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers... |
from rdflib import Graph, plugin
from rdflib.serializer import Serializer
testrdf = '''@prefix dc: <http://purl.org/dc/terms/> .
<http://example.org/about> dc:title "Someone's Homepage"@en .'''
g = Graph().parse(data=testrdf, format='n3')
print(g.serialize(format='json-ld', indent=4)) |
from ..util import xmlwriter
from ..util.subfs import SubFileSystem
from ..util.dirutils import Filepath
import io
import contextlib
REPORT_CSS = '''
body{font-family: monospace}
.images{}
.image{border: solid 1px;}
.template{margin-left: 1em;}
.indent{margin-left: 3em;}
.pcr{margin: 1em; padding: 1em;}
.products{margi... |
examples=[]
def canceling_test(numerator, denominator, digit):
if not numerator/denominator<1:
return False
if str(digit) not in str(numerator) or str(digit) not in str(denominator):
return False
new_num=("".join([i for i in str(numerator) if not i==str(digit)]))
new_den=("".join([i for i in str(denomin... |
def final(dirs):
x,y=0,0
for l in dirs:
if l=='L':
x-=1
elif l=='R':
x+=1
elif l=='U':
y+=1
elif l=='D':
y-=1
print x,y
if __name__ == "__main__":
final(raw_input()) |
from distutils.core import setup
setup(
name='discern',
version='0.1.0',
author='Jacob Schreiber',
author_email='jmschreiber91@gmail.com',
packages=['discern'],
url='http://pypi.python.org/pypi/discern/',
license='LICENSE.txt',
description='DISCERN is a method for identifying perturbatio... |
from test.util import build_grab, temp_file
from test.util import (BaseGrabTestCase, TEST_SERVER_PORT,
EXTRA_PORT1, EXTRA_PORT2)
from test_server import TestServer
import six
from grab.proxylist import BaseProxySource
ADDRESS = '127.0.0.1'
PROXY1 = '%s:%d' % (ADDRESS, TEST_SERVER_PORT)
PROXY2 = '... |
__version__ = '1.0.0' |
import _plotly_utils.basevalidators
class TickcolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self,
plotly_name="tickcolor",
parent_name="scattergeo.marker.colorbar",
**kwargs
):
super(TickcolorValidator, self).__init__(
plotly_name=... |
import hashlib
import sys
import os
from random import SystemRandom
import base64
import hmac
if len(sys.argv) < 2:
sys.stderr.write('Please include username as an argument.\n')
sys.exit(0)
username = sys.argv[1]
cryptogen = SystemRandom()
salt_sequence = [cryptogen.randrange(256) for i in range(16)]
hexseq = l... |
from __future__ import absolute_import, print_function
import sys
from .platforms import platform, PlatformError, PlatformInvalid
try:
__platform = platform()
except PlatformError as err:
print('Error initializing standard platform: {}'.format(err.args[0]),
file=sys.stderr)
__platform = PlatformIn... |
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import (
QApplication, QVBoxLayout, QTextEdit, QHBoxLayout, QPushButton, QWidget,
QSizePolicy, QToolTip)
import os
import qrcode
from electroncash import util
from electroncash.i18n import _
from .util import WindowModalDialog, MessageBox... |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('sections', '0004_auto_20170718_1232'),
]
operations = [
migrations.AlterField(
model_name='section',
name='cms_page',
field=... |
def random_func():
print("Hello from random function") |
import math
print '484 sa' |
from .proxy_only_resource import ProxyOnlyResource
class Identifier(ProxyOnlyResource):
"""Identifier.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id.
:vartype id: str
:ivar name: Resource Name.
:vartype name: str
:param kind... |
"""This module defines bitwise operations on floating point numbers by pretending that they consist of an infinite sting of bits extending to the left as well as to the right.
More precisely the infinite string of bits b = [...,b[-2],b[-1],b[0],b[1],b[2],...] represents the number x = sum( b[i]*2**i for i in range(-inf... |
class ProfileBlock:
def __init__(self, start_time, end_time, distance_start, distance_end, **extra_properties):
self.start_time = start_time
self.end_time = end_time
assert(self.start_time < self.end_time)
self.distance_start = distance_start
self.distance_end = distance_end
... |
import sys, os
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'djsupervisorctl'
copyright = u'2014, ChangeMyName'
version = '0.1'
release = '0.1'
exclude_patterns = ['_build']
pygments_style = 'sphinx'
html_theme = 'default'
html_static_path = ['_static']
htmlhelp... |
print ("Hello you dirty bastard. What's your name?")
user = raw_input(">> ")
doing = raw_input("And how are you doing? ")
print ("So let me get this straight...")
print "%s is %s and nobody cares? Unbelievable!" % (user, doing)
print ("Testing entering code on the site") |
import sublime, sublime_plugin;
import os;
try:
# ST3
from ..apis.core import Core
except (ImportError, ValueError):
# ST2
from apis.core import Core
class MappingLayoutCommand(sublime_plugin.WindowCommand):
def run(self, *args, **kwargs):
core = Core()
self.layout_list = []
... |
import os
import sys
import inspect
import unittest
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parent_dir = os.path.dirname(os.path.dirname(current_dir))
sys.path.insert(0,parent_dir)
from trendpy.factory import *
from trendpy.samplers import *
class TestFactory(unittest.Tes... |
"""empty message
Revision ID: dfaef2573287
Revises:
Create Date: 2017-03-31 21:18:52.950361
"""
from alembic import op
import sqlalchemy as sa
revision = 'dfaef2573287'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.cre... |
import argparse
import subprocess
import shutil
import os
def get_changed_files(since, until):
return subprocess.check_output([ 'git', 'diff', '--name-status', since, until], universal_newlines=True).strip()
def main(since, until, output):
print('{}..{}'.format(since, until))
files = get_changed_files(since... |
from __future__ import absolute_import
__version__ = 0.1
from . import logutils
import logging
logutils.setError()
try:
import sqlalchemy
except ImportError as e:
logging.exception(e.__class__.__name__)
logging.error('pip install sqlalchemy')
exit(-1)
try:
import pymysql
except ImportError as e:
... |
import os
import six
import sys
import gzip
import shutil
import logging
import mimetypes
from django.conf import settings
from optparse import make_option
from django.core import management
from bakery import DEFAULT_GZIP_CONTENT_TYPES
from django.core.urlresolvers import get_callable
from django.core.exceptions impor... |
from .validator import Validator
class LiepinSpider(Validator):
name = 'liepin'
concurrent_requests = 8
def __init__(self, name = None, **kwargs):
super(LiepinSpider, self).__init__(name, **kwargs)
self.urls = [
'https://www.liepin.com/zhaopin/?pubTime=&ckid=17c370b0a0111aa5&from... |
import json
import re
import scrapy
from locations.items import GeojsonPointItem
from locations.hours import OpeningHours
DAY_MAPPING = {
1: "Su",
2: "Mo",
3: "Tu",
4: "We",
5: "Th",
6: "Fr",
7: "Sa"
}
class GiantEagleSpider(scrapy.Spider):
name = "gianteagle"
allowed_domains = ("www... |
"""Forms for the ``enquiry`` app.""" |
import os
from textwrap import dedent
from twisted.trial.unittest import TestCase
import mock
from click.testing import CliRunner
from ..create import _main
def setup_simple_project(config=None, mkdir=True):
if not config:
config = dedent(
"""\
[tool.towncrier]
package = ... |
import datetime
from django.db import models
from django.contrib.auth.models import User
from django.contrib.postgres.fields import ArrayField
from django.templatetags.static import static
from django.conf import settings
from django.core.validators import MinValueValidator, MinLengthValidator, MaxLengthValidator
from ... |
class IntervalTrigger(object):
"""Trigger based on a fixed interval.
This trigger accepts iterations divided by a given interval. There are two
ways to specify the interval: per iterations and epochs. `Iteration` means
the number of updates, while `epoch` means the number of sweeps over the
training... |
from string import Template
from datetime import date
bitcoinDir = "./";
inFile = bitcoinDir+"/share/qt/Info.plist"
outFile = "Cybroscoin-Qt.app/Contents/Info.plist"
version = "unknown";
fileForGrabbingVersion = bitcoinDir+"bitcoin-qt.pro"
for line in open(fileForGrabbingVersion):
lineArr = line.replace(" ",... |
import datetime
from itertools import chain
from django.db.models import Case
from django.db.models import IntegerField
from django.db.models import Q
from django.db.models import Value
from django.db.models import When
from django.template import RequestContext
from django.template.response import TemplateResponse
fro... |
import os
import sys
import argparse
import time
import subprocess
import re
import threading
from ffparser.ffparser import FFprobeParser
from ffparser.process_utils import getstatusoutput
def getCreationTimeHachoir(fpath):
status, output = getstatusoutput("hachoir-metadata --raw --level 5 " + re.escape(fpath))
... |
import sys
import inspect
def print_config (som):
print "[SOM Configuration]"
print " epochs : %6d" % som.epochs
print " map_size_x: %6d" % som.map_size_x
print " map_size_y: %6d" % som.map_size_y
print " input_num : %6d" % som.input_num
print " input_size: %6d" % som.input_size
print ""
print "[SOM Nei... |
"""
WSGI config for littleprinter project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "littleprinter.settings")
from djang... |
__all__ = ['config', 'errors'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.