prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
from __future__ import unicode_literals
from django.forms import MediaDefiningClass, Media
from django.forms.utils import flatatt
from django.utils.text import slugify
from django.utils.safestring import mark_safe
from django.utils.six import text_type
from django.utils.six import with_metaclass
from wagtail.utils.c... | me=None):
self.register_hook_name = register_hook_name
self.construct_hook_name = construct_hook | _name
# _registered_menu_items will be populated on first access to the
# registered_menu_items property. We can't populate it in __init__ because
# we can't rely on all hooks modules to have been imported at the point that
# we create the admin_menu and settings_menu instances
s... |
from django.db import models
class ThingItem(object):
def __init__(self, value, display):
self.value = value
self.display = display
def __iter__(self):
return ( | x for x in [self.value, self.display])
def __len__(self):
return 2
class Things(object):
def __iter__(self):
return (x for x in [ThingItem(1, 2), ThingItem(3, 4)])
class ThingWithIterableChoices(models.Model):
# Testing | choices= Iterable of Iterables
# See: https://code.djangoproject.com/ticket/20430
thing = models.CharField(max_length=100, blank=True, choices=Things())
|
------------End of Important Marks-------------------------
#Library import
import subprocess
import socket
import os
import sys
import time
import random
import threading
import json
import Queue
import ipaddress
import resource
from jsoncomment import JsonComment
#Custom import
from SonarPulse import Pulse, PulseT... | rqueue):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = tname
self.prqueue = prqueue
def run(self):
while True:
item = self.prqueue.get()
if item is None:
break # End Loop and finish thread
#print '... | r(Evalue)
print >> sys.stderr, 'LISP-Sonar Error: ' + str(Evalue)
#-------------------------------------------------------------------
# Main
#
TimeStamp = int(time.time())
print 'LISP-Sonar \t\t\t: ' + Revision
print '\tRun \t\t\t: '+ time.strftime("%d.%m.%Y %H:%M:%S")
# Identify Machine and Da... |
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import os
import warnings
from pymatgen.core.structure import Structure
from pymatgen.core.units import Ha_to_eV, bohr_to_ang
from pymatgen.io.abinit.abiobjects import *
from pymatgen.util.testing import PymatgenTest
class ... |
class ElectronsTest(PymatgenTest):
def test_base(self):
default_electrons = Electrons() |
self.assertTrue(default_electrons.nsppol == 2)
self.assertTrue(default_electrons.nspinor == 1)
self.assertTrue(default_electrons.nspden == 2)
abivars = default_electrons.to_abivars()
# new = Electron.from_dict(default_electrons.as_dict())
# Test pickle
self.se... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Point of Sale',
'version': '1.0.1',
'category': 'Point Of Sale',
'sequence': 20,
'summary': 'Touchscreen Interface for Shops',
'description': """
Quick and Easy sale process
===========... | _template.xml',
'views/point_of_sale_report.xml',
'views/point_of_sale_view.xml',
'views/pos_order_view.xml',
'views/product_view.xml',
'view | s/pos_category_view.xml',
'views/account_journal_view.xml',
'views/pos_config_view.xml',
'views/pos_session_view.xml',
'views/point_of_sale_sequence.xml',
'data/point_of_sale_data.xml',
'views/pos_order_report_view.xml',
'views/account_statement_view.xml',
... |
dFound import settings
from codex.baseview import BaseView
from wechat.models import Lost, Found, User
__author__ = "Epsirom"
class WeChatHandler(object):
logger = logging.getLogger('WeChat')
def __init__(self, view, msg, user):
"""
:type view: WeChatView
:type msg: dict
:t... | _id})
def url_found_list(self):
return settings.get_url('u/found/list', {'user': self.user.open_id})
def url_mine(self):
return settings.get_url('u/mine',{'user':self.user.open_id})
class WeChatEmptyHandler(WeChatHandler):
def check(self):
return True
def handle(self):
... | rn self.reply_text('The server is busy')
class WeChatError(Exception):
def __init__(self, errcode, errmsg, *args, **kwargs):
super(WeChatError, self).__init__(errmsg, *args, **kwargs)
self.errcode = errcode
self.errmsg = errmsg
def __repr__(self):
return '[errcode=%d] %s' % (... |
from yowsup.layers import YowLayer, YowLayerEvent, YowProtocolLayer
from .protocolentities import *
class YowIbProtocolLayer(YowProtocolLayer):
def __ini | t__(self):
handleMap = {
"ib": (self.recvIb, self.sendIb),
"iq": (None, self.sendIb)
}
super(YowIbProtocolLayer, self).__init__(handle | Map)
def __str__(self):
return "Ib Layer"
def sendIb(self, entity):
if entity.__class__ == CleanIqProtocolEntity:
self.toLower(entity.toProtocolTreeNode())
def recvIb(self, node):
if node.getChild("dirty"):
self.toUpper(DirtyIbProtocolEntity.fromProtocolTre... |
from django.db import migrations, models
cla | ss Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Bar',
| fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
],
),
]
|
import datetime
import release
def | test_release() | :
rel = release.Release("mysql-3.23.22-beta", "1234-05-06")
print(vars(rel))
assert vars(rel) == {
"raw_label": "mysql-3.23.22-beta",
"raw_date": "1234-05-06",
"majormin": "3.23",
"pre": "mysql-",
"post": ".22-beta",
"date": datetime.datetime(1234, 5, 6, 0, 0)... |
# -*- coding: utf-8 -*-
c | lass Solution(object):
''' https://leetcode.com/problems/count-primes/
'''
def countPrimes(self, n):
if n <= 2:
return 0
is_prime = [True] * n
ret = 0
for i in range(2, n):
if not is_prime[i]:
continue
ret += 1
... | is_prime[i*m] = False
return ret
|
#=======================================================================
# RegIncrSC.py
#=======================================================================
from pymtl import *
|
class RegIncrSC( SystemCModel ):
sclinetrace = True
|
def __init__( s ):
s.in_ = InPort ( Bits(32) )
s.out = OutPort( Bits(32) )
s.set_ports({
"clk" : s.clk,
"rst" : s.reset,
"in_" : s.in_,
"out" : s.out,
})
|
import time, os
from autotest.client import test, os_dep, utils
from autotest.client.shared import error
class btreplay(test.test):
version = 1
# http://brick.kernel.dk/snaps/blktrace-git-latest.tar.gz
def setup(self, tarball = 'blktrace-git-latest.tar.gz'):
tarball = utils.unmap_url(self.bindir,... | self, dev="", devices="", extra_args='', tmpdir=None):
# @dev: The device against which the trace will be replayed.
# e.g. "sdb" or "md_d1"
# @devices: A space-separat | ed list of the underlying devices
# which make up dev, e.g. "sdb sdc". You only need to set
# devices if dev is an MD, LVM, or similar device;
# otherwise leave it as an empty string.
if not tmpdir:
tmpdir = self.tmpdir
os.chdir(self.srcdir)
alldev... |
self.domain_dn) not in str(res1[0].dn))
self.assertTrue(self._lost_and_found_dn(self.ldb_dc2, self.domain_dn) not in str(res2[0].dn))
self.assertEqual(str(res1[0]["name"][0]), res1[0].dn.get_rdn_value())
self.assertEqual(str(res2[0]["name"][0]), res2[0].dn.get_rdn_value())
# Delete bot... | lf._check_deleted(self.ldb_dc1, self.ou2)
# Check deleted on DC2
self._check_deleted(self.ldb_dc2, self.ou1)
self._check_deleted(self.ldb_dc2, self.ou2)
self._check_deleted(self.ldb_dc1, ou1_child)
self._check_deleted(self.ldb_dc1, ou2_child)
| # Check deleted on DC2
self._check_deleted(self.ldb_dc2, ou1_child)
self._check_deleted(self.ldb_dc2, ou2_child)
def test_ReplConflictsRenamedVsNewRemoteWin(self):
"""Tests resolving a DN conflict between a renamed object and a new object"""
self._disable_inbound_repl(self.dnsname... |
if path[1:2] != ":" or b[1:2] == ":":
# Path doesn't start with a drive letter, or cases 4 and 5.
b_wins = 1
# Else path has a drive letter, and b doesn't but is absolute.
elif len(path) > 3 or (len(path) == 3 and
... | . Returns a 2-tuple
"(drive,path)"; either part may be empty"""
if p[1:2] == ':':
return p[0:2], p[2:]
return '', p
# Parse UNC paths
def splitunc(p):
"""Split a pathname into UNC mount point an | d relative path specifiers.
Return a 2-tuple (unc, rest); either part may be empty.
If unc is not empty, it has the form '//host/mount' (or similar
using backslashes). unc+rest is always the input path.
Paths containing drive letters never have an UNC part.
"""
if p[1:2] == ':':
... |
#!/usr/bin/python
import urllib
prin | t dir(urllib)
|
help(urllib.urlopen)
|
#!/usr/bin/python
#
# Copyright (c) 2017 Zim Kalinowski, <zikalino@microsoft.com>
# Copyright (c) 2019 Matti Ranta, (@techknowlogick)
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
AN... |
sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DBforMariaDB/servers/testser
ver/databases/db1"
resource_group:
description:
- Resource group name.
returned: | always
type: str
sample: testrg
server_name:
description:
- Server name.
returned: always
type: str
sample: testserver
name:
description:
- Resource name.
returned: always
... |
#
# Copyright (C) 2013 Uninett AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 3 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope... | http://www.gnu.org/licenses/>.
#
"""Django URL configuration for messages tool"""
from django.conf.urls import url
from nav.web.messages import views
from nav.web.messages.feeds import ActiveMessagesFeed
urlpatterns = [
url(r'^$', views.redirect_to_active),
url(r'^active/$', views.active, name='messages-home... |
url(r'^create/$', views.save, name='messages-create'),
url(r'^edit/(?P<message_id>\d+)$', views.save, name='messages-edit'),
url(r'^active/$', views.active, name='messages-active'),
url(r'^scheduled/$', views.planned, name='messages-planned'),
url(r'^archive/$', views.historic, name='messages-histo... |
be properties (simplifies serializing)
self.lock2 = 0
self.verbose = 0
for key in kw.keys():
self.__dict__[key] = kw[ke | y]
def __str__(self):
attrs = []
for item in self:
if isinstance(item,Node):
attrs.append( str(item) )
else:
attrs.append( repr(item) )
attrs = ','.join(attrs)
return "%s(%s)"%(self.__class__.__name__,attrs)
def safe_repr(... | _repr(tank) ) # can we use repr here ?
else:
attrs.append( repr(item) )
# this is the dangerous bit:
for key, val in self.__dict__.items():
if isinstance(val,Node):
if str(val) not in tank:
attrs.append( '%s=%s'%(key,val.safe_re... |
import json, logging, os, re, subprocess, shlex
from tools import get_category_by_status
log = logging.getLogger()
meta_files = ['Disassembly', 'Stacktrace', 'Registers',
'SegvAnalysis', 'ProcMaps', "BootLog" , "CoreDump",
"BootDmesg", "syslog", "UbiquityDebug.gz", "Casper.gz",
"UbiquityPar... | description'].splitlines():
if "proccmdline" in lin | e.lower():
cmdline = ":".join(line.split(":")[1:]).strip()
try:
toks = shlex.split(cmdline)
except ValueError as e:
log.error("error while parsing cmdline: %s" % cmdline)
log.exception(e)
continue
if len(toks... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from ..config import BaseAnsibleContainerConfig
from ..utils.visibility import getLogger
logger = getLogger(__name__)
class K8sBaseConfig(BaseAnsibleContainerConfig):
@property
def image_namespace(self):
namespace = self.project_name
... | super(K8sBaseConfig, self).set_env(env)
if self._config.get('volumes'):
for vol_key in self._config['volumes']:
# Remove settings not meant for this engine
for engine_name in self | .remove_engines:
if engine_name in self._config['volumes'][vol_key]:
del self._config['volumes'][vol_key][engine_name]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from . import NeuralLayer
from deepy.utils import build_activation, FLOATX
import numpy as np
import theano
import theano.tensor as T
from collections import OrderedDict
OUTPUT_TYPES = ["sequence", "one"]
INPUT_TYPES = ["sequence", "one"]
class RNN(NeuralLayer):
"""
... | map["mask"].dimshuffle(0, 'x')
new_h = mask * new_h + (1 - mask) * h
return new_h
def produce_input_sequences(self, x, mask=None, second_input=None):
self._sequence_map.clear()
if self._input_type == "sequence":
self._sequence_map["x"] = T.dot(x, self.W_i)
... | elif self._mask:
# (time, batch)
self._sequence_map["mask"] = self._mask
# Second input
if second_input:
self._sequence_map["second_input"] = T.dot(second_input, self.W_i2)
elif self._second_input:
self._sequence_map["second_input"] ... |
"""
Utility Mixins for unit tests
"""
import json
import sys
from django.conf import settings
from django.urls import clear_url_caches, resolve
from django.test import TestCase
from mock import patch
from util.db import CommitOnSuccessManager, OuterAtomic
class UrlResetMixin(object):
"""Mixin to reset urls.py ... | tUp()
patcher = patch(tracker)
self.mock_tracker = patcher.start()
self.addCleanup(patcher.stop)
def assert_no_events_were_emitted(self):
"""
Ensures no events were emitted since the last event r | elated assertion.
"""
self.assertFalse(self.mock_tracker.emit.called) # pylint: disable=maybe-no-member
def assert_event_emitted(self, event_name, **kwargs):
"""
Verify that an event was emitted with the given parameters.
"""
self.mock_tracker.emit.assert_any_call( ... |
#! /usr/bin/env python2
import rif | t
rift.init("main.so")
print(rift. | call(lib.main, rift.c_int))
|
# -*- coding: utf-8 -*-
# --------------------------------------------------
# Задача 1
# --------------------------------------------------
"""
Напишите функцию-генератор, которая будет принимать
последовательность, где каждый элемент кортеж с двумя
значениями (длинна катетов треугольника) и возвращать
длинну гипотен... | апишите генератор-выражение, которое будет вычислять
и возвращать длинну окружности. Каждый элемент является
радиусом.
"""
l = [7, 9.06, 44, 21. | 3, 6, 10.00001, 53]
# --------------------------------------------------
# Задача 3
# --------------------------------------------------
"""
Напишите пример реализации встроенной функции filter.
"""
def myfilter1(fun, l):
pass
# --------------------------------------------------
# Задача 4
# -------------------... |
from __future__ import annotations
import contextlib
import os
from typing import Generator
from typing import Sequence
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import PatchesT
from pre_commit.en | vcontext import Var
from pre_commit.hook import Hook
from pre_commit.languages import helpers
from pre_commit.prefix import Prefix
from pre_commit.util import clean_path_on_failure
ENVIRONMENT_DIR = 'coursier'
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
def install_enviro... | : str,
additional_dependencies: Sequence[str],
) -> None: # pragma: win32 no cover
helpers.assert_version_default('coursier', version)
helpers.assert_no_additional_deps('coursier', additional_dependencies)
envdir = prefix.path(helpers.environment_dir(ENVIRONMENT_DIR, version))
channel = prefi... |
import time
import threading
import logging
import serial
import io
import sim900
import sys
if __name__ == "__main__":
#this is a bad file for recording the diode temps and voltages
#eventually it will be merged with recording the resistance bridges
#and actually use the sim900 file functions
#cre... | olts = dio_volts.rstrip()
sim.close_sim922()
print "diode"
time.sleep(1)
#get rox1 info
sim.connect_sim921_1()
rox1_res = sim.get_resistance()
rox1_temp = sim.get_temp()
sim.close_sim921_1()
print "rox1"
... | #get rox3 info
sim.connect_sim921_6()
rox3_res = sim.get_resistance()
rox3_temp = sim.get_temp()
sim.close_sim921_6()
print "rox2"
time.sleep(1)
#write it all to file
current_time = time.strftime("%Y%m%d-%H%M%S")
... |
import virtool.subtractions.files
from sqlalchemy import select
from virtool.subtractions.models import SubtractionFile
async def test_create_subtraction_files(snapshot, tmp_path, pg, pg_session):
test_dir = tmp_path / "subtractions" / "foo"
test_dir.mkdir(parents=True)
test_dir.joinpath("subtraction.fa.g... | ", subtraction_files, test_dir
)
rows = list()
async with pg_session as session:
assert (
await session. | execute(select(SubtractionFile))
).scalars().all() == snapshot
|
import _plotly_utils.basevalidators
class ViolinmodeValidator(_plotly_ | utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="violinmode", parent_name="layout", **kwargs):
super(ViolinmodeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
rol... | **kwargs
)
|
se, pylab mode should not import any names into the user namespace.
# c.IPKernelApp.pylab_import_all = True
# The name of the IPython directory. This directory is used for logging
# configuration (through profiles), history storage, etc. The default is usually
# $HOME/.ipython. This options can also be specified throu... | l.show_rewritten_input = True
# Set the color scheme | (NoColor, Linux, or LightBG).
# c.ZMQInteractiveShell.colors = 'Linux'
#
# c.ZMQInteractiveShell.separate_in = '\n'
# Deprecated, use PromptManager.in2_template
# c.ZMQInteractiveShell.prompt_in2 = ' .\\D.: '
#
# c.ZMQInteractiveShell.separate_out = ''
# Deprecated, use PromptManager.in_template
# c.ZMQInterac... |
import logging
import socket
from functools import wraps
from django.conf import settings
from django.http import (
Http404,
HttpResponse,
HttpResponseForbidden,
HttpResponseRedirect
)
from django.shortcuts import render
from django.utils.http import is_safe_url
from django.views.decorators.cache impor... | log.critical('Failed to connect to memcached (%r): %s' %
((host, port), exc))
return False
finally:
s.close()
def dev_or_authorized(func):
"""Show view for admin and developer instances, else 404"""
@wraps(func)
def _dev_or_authorized(request, *args, **kwargs):
... | args, **kwargs)
raise Http404
return _dev_or_authorized
ERROR = 'ERROR'
INFO = 'INFO'
@dev_or_authorized
@never_cache
def monitor_view(request):
"""View for services monitor."""
# Dict of infrastructure name -> list of output tuples of (INFO,
# msg) or (ERROR, msg)
status = {}
# No... |
# Copyright 2012 Free Software Foundation, Inc.
#
# This fil | e is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful... | ails.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
'''
Blocks and utilities for Video SDL module
'''
# The presence of this file turns th... |
#!/usr/bin/env python
#encoding:utf-8
import os
import sys
import requests
import MySQLdb
from bs4 import BeautifulSoup
from bs4 import SoupStrainer
if len(sys.argv) != 4:
print 'Invalid parameters!'
exit(1)
print '=' * 60
print 'start:', sys.argv
aim_category_id = int(sys.argv[1])
start_point = (int(sys.ar... | oup(url, SoupStrainer(id='attachpayform'))
attach_form = soup.find('form', id='attachpayform')
link = attach_form.table.find_all('a')[-1]
except | Exception as e:
print 'Error! file url:', url
else:
download_file(link['href'], filename)
# Crawl detail data of one post.
def crawl_detail(detail_category, title, detail_url):
print '-' * 100
print 'Crawling Post:', detail_category, title, '=>', detail_url
record['detail_category'] = d... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJA | NGO_SETTINGS_MODULE", "huntnet.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.a | rgv)
|
# Copyright | (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from ggrc import db
from ggrc.models.mixins import CustomAttributable, BusinessO | bject, Timeboxed
from ggrc.models.object_document import Documentable
from ggrc.models.object_person import Personable
from ggrc.models.object_owner import Ownable
from ggrc.models.relationship import Relatable
from ggrc.models.track_object_state import HasObjectState, track_state_for_class
class Threat(
HasObjec... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('member', '0007_auto_20150501_2124'),
]
oper | ations = [
migrations.AddField(
model_name='member',
name='avatar',
field=models.URLField(default='https://dn-tmp.qbox.me/chendian/cat_mouse_reading.jpg', verbose_name='\u5934\u50cf', blank=True),
),
migrations.AlterField(
model_name='member', |
name='description',
field=models.TextField(default='', verbose_name='\u4e2a\u4eba\u4ecb\u7ecd', blank=True),
),
]
|
"""
I came up with this the first try. So, that's why this is posted in duplicate.
"""
import sys
try | :
columns = int(input("How many columns? "))
rows = int(input("How many rows? "))
tall = int(input("How tall should the boxes be? "))
wide = int(input("How wide should the boxes be? "))
except Exception as e:
print(e)
print("You hav | e fail")
print("Try type valid integer")
sys.exit(1)
i = 0
j = 0
k = 0
m = 0
while j <= rows:
print("+",end="")
while k < columns:
while i < wide:
print("-",end="")
i += 1
print("+",end="")
i = 0
k += 1
print('\r')
k = 0
if j < rows:
... |
def extractTranslasiSanusiMe(i | tem):
'''
Parser for 'translasi.sanusi.me'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel... | =tl_type)
return False
|
HT),
MultiContentEntryText(pos=(0, 40), size=(250, 20), font=0, text=_("Uphops: ") + uphops),
MultiContentEntryText(pos=(250, 40), size=(250, 20), font=0, text=_("Maxdown: ") + maxdown, flags=RT_HALIGN_RIGHT)]
return res
def CCcamShareViewListEntry(caidprovider, providername, numberofcards, numberofreshare):... | = [(caidprovider | , providername, numberofcards),
MultiContentEntryText(pos=(10, 5), size=(800, 35), font=1, text=providername),
MultiContentEntryText(pos=(1050, 5), size=(50, 35), font=1, text=numberofcards, flags=RT_HALIGN_RIGHT),
MultiContentEntryText(pos=(1100, 5), size=(50, 35), font=1, text=numberofreshare, flags=RT_HA... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2016-11-28 13:41
# flake8: noqa
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import normandy.recipes.validators
class Migration(mi... | l',
name='creator',
),
migrations.RemoveField(
model_name='appro | valrequest',
name='approval',
),
migrations.RemoveField(
model_name='approvalrequest',
name='creator',
),
migrations.RemoveField(
model_name='approvalrequest',
name='recipe',
),
migrations.RemoveField(
... |
"""
Creates a list of studies currently being used for synthesis.
"""
import re
#from stephen_desktop_conf import *
from microbes import studytreelist as microbelist
from plants import studytreelist as plantslist
from metazoa import studytreelist as metalist
from fungi impor | t studytreelist as fungilist
studytreelist = []
studytreelist.extend(plantslist)
studytreelist.extend(met | alist)
studytreelist.extend(fungilist)
studytreelist.extend(microbelist)
for i in studytreelist:
studyid=i.split('_')[0]
print studyid+".json"
|
# before we break json, grab a copy of the orig_dumps function
_orig_dumps = json.dumps
delattr(json, 'loads')
reload(c)
if _orig_dumps:
# basic test of swift.common.client.json_loads using json.loads
data = {
'string': 'val... | .assertTrue(conn.http_conn[1].has_been_read)
except Asserti | onError:
msg = '%s did not read resp on server error' % method.__name__
self.fail(msg)
except Exception, e:
raise e.__class__("%s - %s" % (method.__name__, e))
def test_reauth(self):
c.http_connection = self.fake_http_connection(401)
def ... |
#!/usr/bin/python
# *****************************************************************************
#
# Copyright (c) 2016, EPAM SYSTEMS INC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#... | format(args.cluster_name, kernel_path, args.os_user))
local('sudo mv /tmp/{}/kernel_var.json '.format(args.cluster_name) + kernel_path)
local('mkdir -p | ' + kernels_dir + 'py3spark_' + args.cluster_name + '/')
kernel_path = kernels_dir + "py3spark_" + args.cluster_name + "/kernel.json"
template_file = "/tmp/{}/pyspark_dataengine_template.json".format(args.cluster_name)
with open(template_file, 'r') as f:
text = f.read()
text = text.replace('CLUS... |
#!/usr/bin/env python
from nose.tools import ok_
from nose.tools import eq_
import networkx as nx
from networkx.algorithms.approximation import min_weighted_dominating_set
from networkx.algorithms.approximation import min_edge_dominating_set
class TestMinWeightDominatingSet:
def test_min_weighted_dominating_set(... | g | raph.add_edge(2, 5)
graph.add_edge(3, 4)
graph.add_edge(3, 6)
graph.add_edge(5, 6)
vertices = set([1, 2, 3, 4, 5, 6])
# due to ties, this might be hard to test tight bounds
dom_set = min_weighted_dominating_set(graph)
for vertex in vertices - dom_set:
... |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test RPCs related to blockchainstate.
Test the following RPCs:
- gettxoutsetinfo
- getdifficul... | equal(res['hash_serialized_2'], res3['hash_serialized_2'])
def _test_getblockheader(self):
node = self.nodes[0]
assert_raises_jsonrpc(-5, "Block not found",
node.getblockheader, "nonsense")
besthash = node.getbestblockhash()
secondbesthash = node.getb... | assert_equal(header['confirmations'], 1)
assert_equal(header['previousblockhash'], secondbesthash)
assert_is_hex_string(header['chainwork'])
assert_is_hash_string(header['hash'])
assert_is_hash_string(header['previousblockhash'])
assert_is_hash_string(header['merkleroot'])
... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... | efault('fake_rabbit', True)
conf.set_default('rpc_backend', 'cinder.openstack.common.rpc.impl_fake')
conf.set_default('iscsi_num_targets', 8)
conf.set_default('verbose', | True)
conf.set_default('sql_connection', "sqlite://")
conf.set_default('sqlite_synchronous', False)
conf.set_default('policy_file', 'cinder/tests/policy.json')
conf.set_default('xiv_proxy', 'cinder.tests.test_xiv.XIVFakeProxyDriver')
|
# -*- coding: utf-8 -*-
"""Define the base module for server test."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
from influxdb.tests import using_pypy
from influxdb.tests.server_tests.influxdb_instanc... | s a fresh
database: 'db'.
"""
# 'influxdb_temp | late_conf' attribute must be set on the class itself !
@classmethod
def setUpClass(cls):
"""Set up an instance of the ManyTestCasesWithServerMixin."""
_setup_influxdb_server(cls)
def setUp(self):
"""Set up an instance of the ManyTestCasesWithServerMixin."""
self.cli.create_... |
#!/usr/bin/env python
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
#
# mockredis
#
# This module helps start and stop redis instances for unit-testing
# redis must be pre-installed for this to work
#
import os
import signal
import subprocess
import logging
import socket
import time
import red... | process.Popen(['tar', 'xzvf', redis_url],
cwd=redis_bdir)
process.wait()
if process.returncode is not 0:
raise SystemError('untar '+redis_url)
if not os.path.exists(redis_exe):
process = subprocess.Popen(['make', 'PREFIX=' + redis_bdir, 'install... | cwd=redis_bdir + '/redis-'+redis_ver)
process.wait()
if process.returncode is not 0:
raise SystemError('install '+redis_url)
def get_redis_path():
if not os.path.exists(redis_exe):
install_redis()
return redis_exe
def redis_version():
'''
Determine redis-server ... |
import web
from gothonweb import map
urls = (
'/game', 'GameEngine',
'/', 'Index',
)
app = web.applic | ation(urls, globals())
#little hack so that debug mode works with sessions
if web.config.get('_session') is None:
store = web.session.DiskStore('sessions')
session = web.session.Session(app, store,
initia | lizer={'room':None})
web.config._session = session
else:
session = web.config._session
render = web.template.render('templates/', base="layout")
class Index(object):
def GET(self):
# this is used to "setup" the session with starting values
session.room = map.START
web.seeother("/g... |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Provides a web interface for dumping graph data as JSON.
This is meant to be used with /load_from_prod in order to easily grab
data for a graph to a loca... | y or test_key.kind() != 'TestMetadata':
# Bad test_path passed in.
self.response.out.write(json.dumps([]))
return
# List of datastore entities that will be dumped.
entities = []
entities.extend(self._GetTestAncestors([test_key]))
# Get the Row enti | ties.
q = graph_data.Row.query()
print test_key
q = q.filter(graph_data.Row.parent_test == utils.OldStyleTestKey(test_key))
if end_rev:
q = q.filter(graph_data.Row.revision <= int(end_rev))
q = q.order(-graph_data.Row.revision)
entities += q.fetch(limit=num_points)
# Get the Anomaly a... |
# Copyright 2016 Casey Jaymes
# This file is part of PySCAP.
#
# PySCAP 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 Fou | ndation, either version 3 of the License, or
# (at your option) any later version.
#
# PySCAP is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.... | see <http://www.gnu.org/licenses/>.
import logging
from scap.model.oval_5.sc.EntityItemType import EntityItemType
logger = logging.getLogger(__name__)
class EntityItemEncryptMethodType(EntityItemType):
MODEL_MAP = {
'elements': [
],
'attributes': {
},
}
def get_value_enu... |
from setuptools import setup, find_packages
setup(
name='zeit.content.gallery',
version='2.9.2.dev0',
author='gocept, Zeit Online',
author_email='zon-backend@zeit.de',
url='http://www.zeit.de/',
description="vivi Content-Type Portraitbox",
packages=find_packages('src'),
package_dir={''... | 'zeit.push>=1.21.0.dev0',
'zeit.wysiwyg',
'zope.app.appsetup',
'zope.app.testing',
'zope.component',
'zope.formlib',
'zope.interface',
'zope.publisher',
'zope.security',
'zope.testing',
],
entry_points={
'fanstatic | .libraries': [
'zeit_content_gallery=zeit.content.gallery.browser.resources:lib',
],
},
)
|
icCursor
from superdesk.upload import url_for_media
from superdesk.errors import SuperdeskApiError, ProviderError
from superdesk.media.media_operations import process_file_from_stream, decode_metadata
from superdesk.media.renditions import generate_renditions, delete_file_on_error, get_renditions_spec
from superdesk.m... | params = {name: value for (name, value) in findall if name in names}
for name, value in findall:
query = query.replace('%s:(%s)' % (name, value), '')
quer | y = query.strip()
# escape dashes
for name, value in params.items():
params[name] = value.replace('-', r'\-')
if query:
params['q'] = query
return params
class ScanpixDatalayer(DataLayer):
def set_credentials(self, user, password):
self._user = user
self._password =... |
"""Code for CLI base"""
import logging
import pathlib
import click
import coloredlogs
import yaml
from flask.cli import FlaskGroup, with_appcontext
# General, logging
from scout import __version__
from scout.commands.convert import convert
from scout.commands.delete import delete
from scout.commands.download import d... | "--port", help="Specify on what port to listen for the mongod")
@click.option("-h", "--host", help="Specify the host for the mongo database.")
@click.option(
"-f",
"--flask-config",
type=click.Path(exists=True),
help="Path to a PYTHON config file",
)
@with_appcontext
def cli(**_):
"""scout: manage ... |
cli.add_command(convert)
cli.add_command(index_command)
cli.add_command(view_command)
cli.add_command(update_command)
cli.add_command(download_command)
cli.add_command(serve)
|
from distutils.core import setup
setup(
name="kafka-python",
version="0.1-alpha",
author="David Arthur",
author_email="mumrah@gmail.com",
url="h | ttps://github.com/mumrah/kafka-python",
packages=["kafka"],
license="Copyright 2012, David Arthur under Apache License, v2.0",
description="Pure Python client for Apache Kafka",
long_description=open("README.md").read(),
)
| |
self.call_backs[system_socket.fileno()] = (
system_socket, self.process_message)
self.system_socket = system_socket
def process_player_command(self, a_socket):
""" Process a command from the scenario player.
"""
# receive the command
command = a_socket.r... | ize,
serial_stopbits)
# Open a socket to listen for commands from the scenario player
address = "tcp://*:{0}".format(self.command_listen_port)
self.logger.info("Command subscription at {0}".format(address))
command_socket = self.context.... | _socket.setsockopt( |
import os
path = | os.path.dirname(os.path.realpath(__file__))
sbmlFilePath = os.path.join(path, 'BIOMD0000000045.xml')
with open(sbmlFilePath,'r') as f:
sbmlString = f.read()
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
return True
if modul... | ibsbml.readSBMLFromString(sbmlString) |
#-*- coding:utf-8 -*-
'''
显示命令的输出结果。
'''
import threading
from gi.repository import Gtk, Gdk, GObject, GLib, GtkSource, Pango
from VcEventPipe import *
class ViewLog:
'''
显示日志。
1,来了新命令,是否更新当前的日志。
2,命令来了新的日志,并显示后,是否滚动。
'''
# 设定一个栏目的枚举常量。
(
COLUMN_TAG_LINE_NO, # 行号
COLUMN_TAG... | yntax(True) # 语法高亮
|
return src_buffer
def set_scrollable(self, is_scrollable):
# 更新日志后,不再滚动。
self.is_scrollable = is_scrollable
if is_scrollable: # 想滚动
self._scroll_to_end() # 马上滚动到最后
else: #不想滚动
pass # 什么都不用做。
def get_scrollable(self, is... |
from vkapp.bot.models import Blogger, News, AdminReview, Publication
from .usersDAO import get_or_create_blogger
from datetime import datetime, timedelta, time
def new_news(link, media, uid, pic):
blogger = get_or_create_blogger(uid)
news = News(link=link, blogger=blogger, media=media, pic=pic)
news.save(... | view = AdminReview.objects.filter(news=news)
if len(review)==0:
return 0
else:
return review[0].rating
def is_news_published(news):
published_info = Publi | cation.objects.filter(news=news)
if len(published_info) == 0:
return False
else:
return True
|
from modes import *
# mode_traffic
field_rate_down = 'rate_down'
field_bw_down = 'bw_down'
field_rate_up = 'rate_up'
field_bw_up = 'bw_up'
# mode_temp
field_cpum = 'cpum'
field_cpub = 'cpub'
field_sw = 'sw'
field_hdd = 'hdd'
# mode_fan_speed
field_fan_speed = 'fan_speed'
# mode_xdsl
field_snr_down = 'snr_down'
fiel... | speed
],
mode_xdsl: [
field_snr_down,
field_snr_up
],
mode_xdsl_errors: [
field_fec,
field_crc,
field_hec,
field_es,
field_ses
| ],
mode_switch1: [
field_rx1,
field_tx1
],
mode_switch2: [
field_rx2,
field_tx2
],
mode_switch3: [
field_rx3,
field_tx3
],
mode_switch4: [
field_rx4,
field_tx4
],
mode_switch_bytes: [
field_rx_bytes,
fiel... |
ion values from a file which it wrote to in the previous run of the program",default=0)
mutex_parser_IC_THRESH.add_argument('--info_threshold_Wyatt_Clark_percentile','-WCTHRESHp',help="Provide the percentile p. All annotations having information content below p will be discarded")
mutex_parser_IC_THRESH.ad... | tps://github.com/dateutil/dateutil/. All annotations made after this date will be picked up")
parser.add_argument('--single_file','-single',default=0,help="Set to 1 in order to output the results of each individual species in a single file.")
mutex_parser_select_references.add_argument('--select_references... | t is possible to include references in case you wish to select annotations made by a few references. This will prompt the program to interpret string which have the keywords \'GO_REF\',\'PMID\' and \'Reactome\' as a GO reference. Strings which do not contain that keyword will be interpreted as a file path which the pro... |
import argparse
from models import Service
from models import Base
import helpers
import traceback
import sys
import os
import importlib
import shutil
@helpers.handle_dbsession()
def prepare_service_db(sqlsession, name, desc, models, uses_blueprint):
s = sqlsession.query(Service).filter_by(name=name).first()
... | yet.')
return False
else:
destination = os.path.join('services/', servicename)
try:
shuti | l.copytree(path, destination)
except Exception as e:
print(e)
traceback.print_tb(sys.exc_info()[2])
shutil.rmtree(destination)
return False
else:
print('Service is faulty, please consult the errors.')
return False
print... |
import sys
def suite(n,s):
p = -1
fin = ''
c = 0
for i in range(0,n+1):
if i == n:
if s[i-1]==p:
fin = fin+str(c)+str(p)
else:
fin = fin+str(c)+str(p)
p = s[i]
c = 1
break
... |
p = s[i]
c = 1
else:
if s[i]==p:
c = c+1
else:
fin = fin+str(c)+str(p)
p = s[i]
c = 1
print fin
return
if __name__ == '__main__':
n = int(raw_input())
s = raw_input(... | suite(n,s)
|
from django import forms
class PutForm(forms.Form):
body = forms.CharField(widget=forms.Textarea( | ))
tube = forms.CharField(initial='default')
priority = forms.IntegerField(initial=2147483648)
delay = forms.IntegerField(initial=0)
ttr = for | ms.IntegerField(initial=120)
|
#!/usr/bin/env python3
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Lic... | vious branch: {}, first commit: {}".format(upstream_previous, previous_branch_first_comm | it))
# Find all commits between that commit and the current release branch
command = "git rev-list {}..{}".format(previous_branch_first_commit, upstream_release)
all_release_commits = subprocess.check_output(command, shell=True).decode('UTF-8')
for commit_id in all_release_commits.splitlines():
try:
# wai... |
equencies = atwork_subtour_frequency.isna()
logger.warning("WARNING Bad atwork subtour frequencies for %s work tours" % bad_tour_frequencies.sum())
logger.warning("WARNING Bad atwork subtour frequencies: num_tours\n%s" %
tour_counts[bad_tour_frequencies])
logger.warning("W... | lds', 'joint_tour_frequency')
# tours.composition
tours['composition'] = infer_joint_tour_composition(persons, tours, joint_tour_participants)
assert skip_controls or check_controls('tours', 'composition')
# tours.tdd
tours['tdd'] = infer_tour_scheduling(configs_dir, tours)
assert skip_control... | assert skip_controls or check_controls('tours', 'atwork_subtour_frequency')
tours['stop_frequency'] = infer_stop_frequency(configs_dir, tours, trips)
assert skip_controls or check_controls('tours', 'stop_frequency')
# write output files
households.to_csv(os.path.join(output_dir, outputs['households']... |
# -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | r agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
You can run this example like this:... | n
import time
import luigi
class Foo(luigi.WrapperTask):
task_namespace = 'examples'
def run(self):
print("Running Foo")
def requires(self):
for i in range(10):
yield Bar(i)
class Bar(luigi.Task):
task_namespace = 'examples'
num = luigi.IntParameter()
def run(... |
from __future__ import absolute_import
from scrapy.spiders import Spider
from scrapy.selector import Selector
from scrapy import Request
import sys
from Schoogle.items import O_Item
from sys import getsizeof
from datetime import datetime
import time
import re
mport string
def reduce(text):
return "".join([c for c in... | ('%Y-%m-%d %H:%M:%S')
current_item['page_size'] = getsizeof(response.body)
current_item['full_html'] = response.body_as_unicode() # not sure if we really want this..
current_item['full_text'] = " ".join(prune(response.xpath('/ | /text()').extract()))
current_item['secure'] = 'https' in str(response.request)
current_item['links'] = links
yield current_item
except Exception as e:
print "______________________________________________________________"
print " ERROR THROW ON ITEM YIELD"
print e
pass
# recursive page sea... |
import math
curr = 0
goal = 1000000
potential_nums = [ | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
outpu | t_num = []
if __name__ == '__main__':
for i in xrange(10, 0, -1):
print (curr, i, "outer loop")
for j in xrange(i + 1):
print (curr, j, "inner loop")
temp = math.factorial(i - 1) * j + curr
if temp >= goal:
print (temp)
curr += (m... |
yml" in config_file_paths and not app_config:
with open(config_file_paths["app_yml"]) as app_yml:
self._app_config = load(app_yml, self._YAMLLoader)
# If the overrides file exists, override the app config values
# with ones from app.override.yml
if "app_o... | ontroller_config in self.controllers_config.viewitems():
controller_config = controller_config.copy()
controller_config.pop("controller")
for path_config in controller_config.viewvalues():
if path_config.get("tools.sessions.storage_type") == "redis":
... | l", {}).get("engine.sqlalchemy.on", False)
@property
def use_jinja2(self):
return "jinja2" in self.app_config
@property
def use_webassets(self):
return self.use_jinja2 and self.app_config["jinja2"].get("use_webassets", False)
@property
def use_email(self):
return "emai... |
import argparse
import sys
import os
from annotated_set import loadData
from data_structures import CanonicalDerivation
from canonical_parser import CanonicalParser
from derivation_tree import DerivationTree
from conversion.ghkm2tib import ghkm2tib
#from lib.amr.dag import Dag
class ExtractorCanSem:
def __init_... | parser = argparse.ArgumentParser(description='CanSem Extraction Algorithm for SHRG',
fromfile_prefix_chars='@',
prog='%s extract-cansem'%sys.argv[0])
parser.add_argument('nl_file', type=str, help="Natural Language File")
... | _argument('--ghkmDir', nargs='?', default='/home/kmh/Files/Tools/stanford-ghkm-2010-03-08', help="GHKM directory")
parser.add_argument('--tiburonLoc', nargs='?', default='/home/kmh/Files/Tools/newtib/tiburon', help="Tiburon executable file")
parser.add_argument('--prefix', nargs='?', default=False, help... |
#!/usr/bin/env python
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
from calibre.gui2.complete2 import LineEdit
from calibre.gui2.widgets import ... | idget=completer_widget, sort_func=sort_func)
@property
def store_name(self):
return 'lineedit_history_'+ | self._name
def initialize(self, name):
self._name = name
self.history = history.get(self.store_name, [])
self.set_separator(None)
self.update_items_cache(self.history)
self.setText('')
self.editingFinished.connect(self.save_history)
def save_history(self):
... |
import re
import traceback
from urllib.parse import quote
from requests.utils import dict_from_cookiejar
from sickchill import logger
from sickchill.helper.common import convert_size, try_int
from sickchill.oldbeard import tvcache
from sickchill.oldbeard.bs4_parser import BS4Parser
from sickchill.providers.torrent.To... | response = self.get_url(self.urls["login"], post_data=login_params, returns="t | ext")
if not response:
logger.warning("Unable to connect to provider")
return False
if re.search("Username or password incorrect", response):
logger.warning("Invalid username or password. Check your settings")
return False
return True
def se... |
Ival:
self.transitionIval = finishIval
self.transitionIval.start()
else:
# Create a sequence that lerps the color out, then
# parents the fade to hidden
self.transitionIval = self.getFadeOutIval(t,finishIval)
self.tra... | terboxIval = None
| if self.letterbox:
self.letterbox.stash()
def letterboxOn(self, t=0.25, finishIval=None):
"""
Move black bars in over t seconds.
|
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... | """
Check package manager against uncompleted transactions.
:rtype bool
"""
return False
def print_uncompleted_transaction_hint(self):
"""
Print friendly messag | e about they way to fix the issue
"""
pass
def get_available_packages_in_repos(self, repositories):
"""
Gets all (both installed and available) packages that are available at given repositories.
:type repositories resource_management.libraries.functions.repository_util.CommandRepository
:ret... |
# -*- coding: utf-8 -*-
'''
Rupture
version 1.4.0
build 5
'''
from bs4 import BeautifulSoup
import datetime
import requests
import socket
import pickle
import time
import ssl
from .utils import six
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
cl... | )
with open(filepath, 'wb') as handle:
for block in response.iter_content(1024):
if not block:
break
| handle.write(block)
return filepath
def http_get_image(self, url, filepath, **kwargs):
return self.http_download(url, filepath, **kwargs)
def parse_float_or_none(self, s):
if s:
return float(str(s).strip().replace(',', '').replace('+', ''))
return s
def... |
from django.conf.urls.defaults import *
from django_de.apps.authors.models import Author
urlpatterns = patterns('django.vi | ews.generic.list_detail',
(r'^$', 'object_list',
dict(
queryset = Author.objects. | order_by('name', 'slug'),
template_object_name = 'author',
allow_empty=True,
),
)
)
|
from seleniumbase import BaseCase
class GitHubTests(BaseCase):
def test_github(self):
# Selenium can trigger GitHub's anti-automation system:
# "You have triggered an abuse detection mechanism."
# "Please wait a few minutes before you try again."
# To avoid this automation blocker,... | leniumbase"] | ')
self.slow_click('a[title="fixtures"]')
self.slow_click('a[title="base_case.py"]')
self.assert_text("Code", "nav a.selected")
|
from spacewiki.app import create_app
from spa | cewiki import model
from spacewiki.test import create_test_app
import unittest
class UiTestCase(unittest.TestCase):
def setUp(self):
self._app = create_test_app()
with self._app.app_context():
model.syncdb()
self.app = self._app.test_client()
def test_index(self):
s... | ual(self.app.get('/').status_code, 200)
def test_no_page(self):
self.assertEqual(self.app.get('/missing-page').status_code, 200)
def test_all_pages(self):
self.assertEqual(self.app.get('/.all-pages').status_code, 200)
def test_edit(self):
self.assertEqual(self.app.get('/index/edit... |
#######################################################################
# This file is part of Pyblosxom.
#
# Copyright (C) 2010-2011 by the Pyblosxom team. See AUTHORS.
#
# Pyblosxom is distributed under the MIT license. See the file
# LICENSE for distribution details.
###############################################... | pt OSError:
pass
def test_get_tagsfile(self):
req = Request({"datadir": self.get_datadir()}, {}, {})
cfg = {"datadir": self.get_datadir()}
self.assertEquals(tags.get_tagsfile(cfg),
os.path.join(self.get_datadir(), os.pardir,
... | adir(), "tags.db")
cfg = {"datadir": self.get_datadir(), "tags_filename": tags_filename}
self.assertEquals(tags.get_tagsfile(cfg), tags_filename)
def test_tag_cloud_no_tags(self):
# test no tags
self.request.get_data()["tagsdata"] = {}
tags.cb_head(self.args)
... |
"""
This page is in the table of contents.
Winding is a script to set the winding profile for the skeinforge chain.
The displayed craft sequence is the sequence in which the tools craft the model and export the output.
On the winding dialog, clicking the 'Add Profile' button will duplicate the selected profile and gi... | eletes the selected profile.
The profile selection is the setting. If you hit 'Save and Close' the selection will be saved, if you hit 'Cancel' the selection will not be saved. However; adding and deleting a profile is a permanent action, for example 'Cancel' will not bring back any deleted profiles.
To change the ... | ort
import __init__
from fabmetheus_utilities import settings
from skeinforge_application.skeinforge_utilities import skeinforge_profile
import sys
__author__ = 'Enrique Perez (perez_enrique@yahoo.com)'
__date__ = '$Date: 2008/21/04 $'
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.... |
# coding: utf-8
"""
Qc API
Qc API # noqa: E501
The version of the OpenAPI document: 3.0.0
Contact: cloudsupport@telestream.net
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from telestream_cloud_qc.configuration import Configuration
class... | aderByteCountTest. # noqa: E501
:rtype: bool
"""
return self._checked
@checked.setter
def checked(self, checked):
"""Sets the checked of this HeaderByteCountTest.
:param checked: The checked of this HeaderByteCountTest. # noqa: E501
:type: bool
"""
... | items(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
... |
_params:
for k, v in self.breakfast_data.items():
# All POST parameters' names are shown.
self.assertContains(response, k, status_code=500)
# Non-sensitive POST parameters' values are shown.
self.assertContains(response, 'baked-beans-value', status_cod... | lf.assertNotIn('sauce', body)
self.assertNotIn('worcestershire', body)
if check_for_POST_params:
for k, v in self.brea | kfast_data.items():
# All POST parameters are shown.
self.assertIn(k, body)
self.assertIn(v, body)
def verify_safe_email(self, view, check_for_POST_params=True):
"""
Asserts that certain sensitive info are not displayed in the email report... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/gugu/w/calibre/src/calibre/gui2/dialogs/quickview.ui'
#
# Created: Thu Jul 19 23:32:31 2012
# by: PyQt4 UI code generator 4.9.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_f... | self.books_table.setRowCount(0)
| self.books_table.setObjectName(_fromUtf8("books_table"))
self.gridlayout.addWidget(self.books_table, 1, 1, 1, 1)
self.hboxlayout = QtGui.QHBoxLayout()
self.hboxlayout.setObjectName(_fromUtf8("hboxlayout"))
self.search_button = QtGui.QPushButton(Quickview)
self.search_butt... |
base_location=req.httprequest.url_root.rstrip('/'),
HTTP_HOST=wsgienv['HTTP_HOST'],
REMOTE_ADDR=wsgienv['REMOTE_ADDR'],
)
req.session.authenticate(db, login, key, env)
return set_cookie_and_redirect(req, redirect_url)
def set_cookie_and_redirect(req, redirect_url):
redirect = we... | lename.encode('utf8')
escaped = urllib2.quote(filename)
browser = req.httprequest.user_agent.browser
version = int((req.httprequest.user_agent.version or '0').split('.')[0])
if browser == 'msie' and version < 9:
return "attachment; filename=%s" % escaped
elif browser == 'safari':
ret... | % escaped
#----------------------------------------------------------
# OpenERP Web web Controllers
#----------------------------------------------------------
html_template = """<!DOCTYPE html>
<html style="height: 100%%">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<m... |
"""Test that arguments passed to a script Menu.main(loop=True) execute
properly."""
##==============================================================#
## SECTION: Imports #
##==============================================================#
from testlib import *
##===========... | =============================#
## SECTION: Global Definitions #
##==============================================================#
SCRIPT = "script_1.py"
##==============================================================#
## SECTION: Class Definitions #
... | ===========================================#
class TestCase(unittest.TestCase):
def _cleanup(self):
rmfile("foo")
rmfile("bar")
rmfile("caz")
def setUp(self):
self._cleanup()
self.assertFalse(op.exists("foo"))
self.assertFalse(op.exists("bar"))
self.ass... |
tests.factories import WhitelistFactory, BlacklistFactory, \
RegistrationCenterFactory, RegistrationFactory
from register.tests.test_center_csv import CenterFileTestMixin
from libya_elections.phone_numbers import get_random_phone_number, format_phone_number
from libya_elections.tests.utils import ResponseCheckerMix... | combinatio | ns of line endings (\r\n, \n, \r)
numbers = [get_random_phone_number() for i in range(4)]
punctuated_numbers = [format_phone_number(number)
for number in numbers]
file_content = ("""%s\r\n%s\n \n%s\r%s""" % (
punctuated_numbers[0],
punctuated... |
h00020'},
(
(176, 0), (176, 1556), (295, 0), (330, 141), (334, 950),
(342, 141), (342, 318), (342, 780), (342, 950), (342, 1051),
(342, 1178), (342, 1556), (402, 59), (458, 1114), (492, 975),
(496, 119), (579, -20), (662, 975), (666, 119), (686, -20),
(686, 1114), (819, 119), (819, 975), (900, -2... | 47, 934), (688, 1462),
)
: {'char' : '"', 'name' : 'glyph00026'},
(
(18, 1311), (18, 1462), (481, 0), (481, 1311), (651, 0),
(651, 1311), (1114, 1311), (1114, 1462),
)
: {'char' : 'T', 'name' : 'glyph00027'},
(
(201, 0), (201, 1462), (371, 147), (371, 1315), (578, 147),
(606, 0), (618,... | , 'name' : 'glyph00028'},
(
(82, 0), (82, 133), (106, 1309), (106, 1462), (289, 154),
(858, 1309), (1065, 1329), (1065, 1462), (1087, 0), (1087, 154),
)
: {'char' : 'Z', 'name' : 'glyph00029'},
(
(201, 0), (201, 1462), (371, 0), (371, 1462),
)
: {'char' : 'l', 'name' : 'glyph00030'},
(... |
"""Two different implementations of merge sort. First one is the standard sort
that creates the result to new list on each level. Second one is an in-place
sort that uses two alternating buffers and offsets to limit memory usage
to O(2n).
"""
def sort(lst):
"""Standard merge sort.
Args:
lst: List to ... | lst[to] = buf[j]
to += 1
def sort_in_place(lst):
"""In-place merge sort.
Args:
lst: List to sort
"""
helper(lst, [None] * | len(lst), 0, len(lst), False)
|
#!/usr/bin/en | v python
from distutils.core import setup
setup(name='Ajax Select',
version='1.0',
description='Django-jQuery jQuery-powered auto-complete fields for ForeignKey and ManyToMany fields',
author='Crucial Felix',
author_email='crucialfelix@gmail.com',
url='http://code.google.com/p/django-aja... | |
ListaIdevice.persistenceVersion = 5
MultichoiceIdevice.persistenceVersion = 9
GenericIdevice.persistenceVersion = 11
MultiSelectIdevice.persistenceVersion = 1
OrientacionesalumnadofpdIdevice.persistenceVersion = 9
OrientacionestutoriafpdIdevice.persis... | age._name = "invalidpackagename"
log.debug( | "load() about to doUpgrade newPackage \""
+ newPackage._name + "\" " + repr(newPackage) )
if hasattr(newPackage, 'resourceDir'):
log.debug("newPackage resourceDir = "
+ newPackage.resourceDir)
else:
... |
"""Defines the URL routes for the Team API."""
from django.conf import settings
from django.conf.urls import patterns, url
from .views import (
MembershipDetailView,
MembershipListView,
TeamsDetailView,
TeamsListView,
TopicDetailView,
TopicListView
)
TEAM_ID_PATTERN = r'(?P<team_id>[a-z\d_-]+... | e_id_pattern}$'.format(
topic_id_pattern=TOPIC_ID_PATTERN,
course_id_pattern=settings.COURSE_ID_PATTERN,
),
TopicDetailView.as_view(),
name="topics_detail"
),
url(
| r'^v0/team_membership/$',
MembershipListView.as_view(),
name="team_membership_list"
),
url(
r'^v0/team_membership/{team_id_pattern},{username_pattern}$'.format(
team_id_pattern=TEAM_ID_PATTERN,
username_pattern=settings.USERNAME_PATTERN,
),
Memb... |
import unittest
from pytba import VERSION
from pytba import api as client
class TestApiMethods(unittest.TestCase):
def setUp(self):
client.set_api_key("WesJordan", "PyTBA-Unit-Test", VERSION)
def test__tba_get(self):
# Query with proper key should succeed
team = client.tba_get('team/f... | self.assertEqual(len(event.matches), 140)
self.assertEqual(event.rankings[1][1], '2056')
def test__team_matches(self):
matches = client.team_matches('frc2363', 2016)
self.assertEqual(len(matches), 62)
self.assertEqual(matches[-1]['alliances | ']['opponent']['score'], 89)
if __name__ == '__main__':
unittest.main()
|
input = """
a(1).
a( | 2) | a(3).
ok1 :- #max{V:a(V)} = 3.
b(3).
b(1) | b(2).
ok2 :- #max{V:b(V)} = 3.
"""
output = """
a(1).
a(2) | a(3).
ok1 :- #max{V:a(V)} = 3.
b(3).
b(1) | b(2).
ok2 :- | #max{V:b(V)} = 3.
"""
|
'''
we all know the classic "guessing game" with higher or lower prompts. lets do a role reversal; you create a program that will guess numbers between 1-100, and respond appropriately based on whether users say that the number is too high or too low. Try to make a program that can guess your number based on user input... | x = guess - 1
if min > max:
got_ | answer = True
print('ERROR! ERROR! ERROR! Master did not answer the questions properly!') |
import sht21
with sht21.SHT21(1) as sht21:
print "temp: %s"%sht21.read_temperature()
print "humi: %s"%sht21.read_humidi | ty()
| |
import os
import sys
from src import impl as rlcs
import utils as ut
import analysis as anls
import matplotlib.pyplot as plt
import logging
import pickle as pkl
import time
config = ut. | loadConfig('config')
sylbSimFolder=config['sylbSimFolder']
transFolder=config['transFolder']
lblDir=config['lblDir']
onsDir=config['onsDir']
resultDir=config['resultDir']
queryList = [['DHE','RE','DHE','RE','KI','TA','TA','KI','NA','TA','TA','KI','TA','TA','KI','NA'],['TA','TA','KI','TA','TA','KI','TA','TA','KI','TA'... | I'], ['TA','TA','KI','TA','TA','KI'], ['TA', 'TA','KI', 'TA'],['KI', 'TA', 'TA', 'KI'], ['TA','TA','KI','NA'], ['DHA','GE','TA','TA']]
queryLenCheck = [4,6,8,16]
for query in queryList:
if len(query) not in queryLenCheck:
print 'The query is not of correct length!!'
sys.exit()
masterData = ut.getA... |
additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | de-toplevel
from .expr import Var
shape = (shape,) | if isinstance(shape, (PrimExpr, Integral)) else sh |
#-*- coding: utf-8 -*-
'''
Created on 23 mar 2014
@author: mariusz
@author: tomasz
'''
import unittest
from selearea import get_ast, get_workareas
class seleareaTest(unittest.TestCase):
def get_fc_pages(self):
urls = {
"http://fc.put.poznan.pl",
"http://fc.put.poznan.pl/re... | ical_ | pages(self):
urls = {
"http://www.bis.put.poznan.pl/",
"http://www.bis.put.poznan.pl/"
}
return [get_ast(url) for url in urls]
def test_get_wrong_page(self):
url = "putpoznan.pl"
with self.assertRaises(ValueError):
get_ast(url)
... |
"""
Copyright (c) 2011, 2012, Regents of the University of California
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this l... |
SERVER['docroot'] = path
except:
SERVER['docroot'] = None
class InverseFilter(logging.Filter):
| def filter(self, record):
return not logging.Filter.filter(self, record)
def start_logging():
observer = log.PythonLoggingObserver()
observer.start()
for logtype, config in LOGGING.iteritems():
if logtype == "raven":
from raven.handlers.logging import SentryHandler
... |
# -*- coding: utf-8 -*-
'''
Created on 17/2/16.
@author: love
'''
import paho.mqtt.client as mqtt
import json
import ssl
def on_connect(client, userdata, flags, rc):
print("Connected with result code %d"%rc)
client.publish("Login/HD_Login/1", json.dumps({"userName": user, "passWord": "Hello,anyone!"}),qos=0,re... |
user = raw_input("请输入用户名:")
client.user_data_set(user)
client.loop_start()
while True:
s = raw_input("请先输入'join'加入房间,然后输入任意聊天字符:\n")
if s:
if s=="join":
client.p | ublish("Chat/HD_JoinChat/2", json.dumps({"roomName": "mqant"}),qos=0,retain=False)
elif s=="start":
client.publish("Master/HD_Start_Process/2", json.dumps({"ProcessID": "001"}),qos=0,retain=False)
elif s=="stop":
client.publish("Master/HD_Stop_Process/2", json... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.