commit
stringlengths 40
40
| subject
stringlengths 1
3.25k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| old_contents
stringlengths 0
26.3k
| lang
stringclasses 3
values | proba
float64 0
1
| diff
stringlengths 0
7.82k
|
|---|---|---|---|---|---|---|---|
1bba6908b29e6a58d7ad98af588ef116d3129b85
|
move code to separate method and take care with bool8 overflows
|
kameleon_mcmc/mcmc/samplers/DiscreteKameleon.py
|
kameleon_mcmc/mcmc/samplers/DiscreteKameleon.py
|
"""
Copyright (c) 2013-2014 Heiko Strathmann
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
*
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
*
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the author.
"""
import numpy
from numpy.random import randn
from kameleon_mcmc.distribution.Distribution import Distribution
from kameleon_mcmc.kernel.Kernel import Kernel
from kameleon_mcmc.mcmc.samplers.MCMCSampler import MCMCSampler
from kameleon_mcmc.distribution.DiscreteRandomWalkProposal import DiscreteRandomWalkProposal
class DiscreteKameleon(MCMCSampler):
"""
Kameleon MCMC on discrete domains
"""
def __init__(self, distribution, kernel, Z, threshold, spread):
if not isinstance(distribution, Distribution):
raise TypeError("Target must be a Distribution object")
if not isinstance(kernel, Kernel):
raise TypeError("Kernel must be a Kernel object")
if not type(Z) is numpy.ndarray:
raise TypeError("History must be a numpy array")
if not len(Z.shape) == 2:
raise ValueError("History must be a 2D numpy array")
if not Z.shape[1] == distribution.dimension:
raise ValueError("History dimension does not match target dimension")
if not Z.shape[0] > 0:
raise ValueError("History must contain at least one point")
if not type(threshold) is float:
raise TypeError("Threshold must be a float")
if not type(spread) is float:
raise TypeError("Spread must be a float")
if not (spread > 0. and spread < 1.):
raise ValueError("Spread must be a probability")
MCMCSampler.__init__(self, distribution)
self.kernel = kernel
self.Z = Z
self.threshold = threshold
self.spread = spread
def __str__(self):
s = self.__class__.__name__ + "=["
s += "kernel=" + str(self.kernel)
s += "threshold=" + str(self.threshold)
s += "spread=" + str(self.spread)
s += ", " + MCMCSampler.__str__(self)
s += "]"
return s
def construct_proposal(self, y):
k = self.kernel.kernel(y, self.Z)
diff = y - self.Z
beta = randn(len(self.Z))
weighted_sum = sum((k * beta).T * diff, 0)
thresholded_sum = weighted_sum > self.threshold
xor = thresholded_sum != y
# return distribution object that adds noise to the xor point
return DiscreteRandomWalkProposal(xor[0], self.spread)
def adapt(self, mcmc_chain, step_output):
"""
Nothing for this one since it uses oracle samples
"""
pass
|
Python
| 0
|
@@ -1563,16 +1563,134 @@
t randn%0A
+from operator import xor%0A%0Afrom kameleon_mcmc.distribution.DiscreteRandomWalkProposal import DiscreteRandomWalkProposal
%0Afrom ka
@@ -1862,101 +1862,8 @@
ler%0A
-from kameleon_mcmc.distribution.DiscreteRandomWalkProposal import DiscreteRandomWalkProposal%0A
%0A%0Acl
@@ -3536,24 +3536,22 @@
f co
-nstruct_proposal
+mpute_xor_step
(sel
@@ -3611,16 +3611,132 @@
+%0A # take care about bool8 overflows preventing larger values%0A diff = y.astype(numpy.int64)%0A diff =
diff
- = y
- s
@@ -3894,14 +3894,19 @@
-xor =
+return xor(
thre
@@ -3920,13 +3920,98 @@
_sum
- != y
+, y)%5B0%5D%0A %0A def construct_proposal(self, y):%0A xored = self.compute_xor_step(y)
%0A
@@ -4131,19 +4131,18 @@
osal(xor
-%5B0%5D
+ed
, self.s
|
2eff2b835fe4a042c06b92844c9fa5c92cbeb3ea
|
change json to yaml when publishing legacy latest files (#186)
|
runtime_builders/publish_builders.py
|
runtime_builders/publish_builders.py
|
#!/usr/bin/python
# Copyright 2017 Google Inc. All rights reserved.
# 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 or 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.
import argparse
import glob
import json
import logging
import os
import yaml
import sys
import builder_util
def main():
logging.getLogger().setLevel(logging.INFO)
parser = argparse.ArgumentParser()
parser.add_argument('--manifest', '-m',
help='path to runtime.yaml manifest',
required=True)
parser.add_argument('--directory', '-d',
help='path to builder config directory for '
'publishing latest')
args = parser.parse_args()
try:
if not args.manifest.endswith('.yaml'):
logging.error('Please provide path to runtime.yaml manifest.')
with open(args.manifest, 'r') as f:
manifest = yaml.safe_load(f)
builder_util.verify_manifest(manifest)
builder_util.copy_to_gcs(args.manifest, builder_util.MANIFEST_FILE)
if args.directory:
_publish_latest(args.directory)
except ValueError as ve:
logging.error('Error when parsing JSON! Check file formatting. \n{0}'
.format(ve))
except KeyError as ke:
logging.error('Config file is missing required field! \n{0}'
.format(ke))
def _publish_latest(builder_dir):
for f in glob.glob(os.path.join(builder_dir, '*.json')):
with open(f, 'r') as f:
config = json.load(f)
latest = config['latest']
project_name = config['project']
parts = os.path.splitext(latest)
project_prefix = os.path.join(builder_util.RUNTIME_BUCKET_PREFIX,
project_name, '-')
latest_file = parts[0][len(project_prefix):]
file_name = '{0}.version'.format(project_name)
full_path = builder_util.RUNTIME_BUCKET_PREFIX + file_name
builder_util.write_to_gcs(full_path, latest_file)
if __name__ == '__main__':
sys.exit(main())
|
Python
| 0
|
@@ -638,20 +638,8 @@
lob%0A
-import json%0A
impo
@@ -1632,12 +1632,12 @@
ing
-JSON
+yaml
! Ch
@@ -1918,20 +1918,20 @@
dir, '*.
-json
+yaml
')):%0A
@@ -1984,13 +1984,18 @@
g =
-json.
+yaml.safe_
load
|
dfbedc63d6d8bce2a90feda98989f763eee1f2f4
|
update example to latest changes in Bites
|
Samples/Python/bites_sample.py
|
Samples/Python/bites_sample.py
|
import Ogre
import OgreRTShader
import OgreOverlay
import OgreBites
class SampleApp(OgreBites.ApplicationContext, OgreBites.InputListener):
def __init__(self):
OgreBites.ApplicationContext.__init__(self, "PySample", False)
OgreBites.InputListener.__init__(self)
self.addInputListener(self)
def keyPressed(self, evt):
if evt.keysym.sym == OgreBites.SDLK_ESCAPE:
self.getRoot().queueEndRendering()
return True
def loadResources(self):
self.enableShaderCache()
# load essential resources for trays/ loading bar
Ogre.ResourceGroupManager.getSingleton().initialiseResourceGroup("Essential")
self.createDummyScene()
self.trays = OgreBites.TrayManager("Interface", self.getRenderWindow())
self.addInputListener(self.trays)
# show loading progress
self.trays.showLoadingBar(1, 0)
ret = OgreBites.ApplicationContext.loadResources(self)
# clean up
self.trays.hideLoadingBar()
self.destroyDummyScene()
return ret
def setup(self):
OgreBites.ApplicationContext.setup(self)
root = self.getRoot()
scn_mgr = root.createSceneManager(Ogre.ST_GENERIC)
shadergen = OgreRTShader.ShaderGenerator.getSingleton()
shadergen.addSceneManager(scn_mgr) # must be done before we do anything with the scene
# overlay/ trays
scn_mgr.addRenderQueueListener(self.getOverlaySystem())
self.trays.showFrameStats(OgreBites.TL_TOPRIGHT)
self.trays.refreshCursor()
# enable per pixel lighting
rs = shadergen.getRenderState(OgreRTShader.cvar.ShaderGenerator_DEFAULT_SCHEME_NAME)
rs.addTemplateSubRenderState(shadergen.createSubRenderState(OgreRTShader.cvar.PerPixelLighting_Type))
scn_mgr.setAmbientLight(Ogre.ColourValue(.1, .1, .1))
light = scn_mgr.createLight("MainLight")
lightnode = scn_mgr.getRootSceneNode().createChildSceneNode()
lightnode.setPosition(0, 10, 15)
lightnode.attachObject(light)
cam = scn_mgr.createCamera("myCam")
cam.setNearClipDistance(5)
cam.setAutoAspectRatio(True)
camnode = scn_mgr.getRootSceneNode().createChildSceneNode()
camnode.attachObject(cam)
self.camman = OgreBites.CameraMan(camnode)
self.camman.setStyle(OgreBites.CS_ORBIT)
self.camman.setYawPitchDist(Ogre.Radian(0), Ogre.Radian(0.3), 15)
self.addInputListener(self.camman)
# must keep a reference to ctrls so it does not get deleted
self.ctrls = OgreBites.AdvancedRenderControls(self.trays, cam)
self.addInputListener(self.ctrls)
vp = self.getRenderWindow().addViewport(cam)
vp.setBackgroundColour(Ogre.ColourValue(.3, .3, .3))
ent = scn_mgr.createEntity("Sinbad.mesh")
node = scn_mgr.getRootSceneNode().createChildSceneNode()
node.attachObject(ent)
if __name__ == "__main__":
app = SampleApp()
app.initApp()
app.getRoot().startRendering()
app.closeApp()
|
Python
| 0
|
@@ -279,44 +279,8 @@
elf)
-%0A self.addInputListener(self)
%0A%0A
@@ -1100,24 +1100,60 @@
.setup(self)
+%0A self.addInputListener(self)
%0A%0A ro
|
34d1447dd64213ec272818bd1a99a18a01babf2b
|
handle missing licence from epmc fulltext
|
octopus/modules/epmc/client.py
|
octopus/modules/epmc/client.py
|
from octopus.core import app
from octopus.lib import dataobj
import urllib, requests
from lxml import etree
class EuropePMCException(Exception):
def __init__(self, httpresponse, *args, **kwargs):
super(EuropePMCException, self).__init__(*args, **kwargs)
self.response = httpresponse
class EPMCFullTextException(Exception):
def __init__(self, message, rawstring, *args, **kwargs):
super(EPMCFullTextException, self).__init__(message, *args, **kwargs)
self.raw = rawstring
class EuropePMC(object):
@classmethod
def get_by_pmcid(cls, pmcid, page=1):
return cls.field_search("PMCID", pmcid, page=page)
@classmethod
def get_by_pmid(cls, pmid, page=1):
return cls.field_search("EXT_ID", pmid, page=page)
@classmethod
def get_by_doi(cls, doi, page=1):
return cls.field_search("DOI", doi, page=page)
@classmethod
def title_exact(cls, title, page=1):
return cls.field_search("TITLE", title, page=page)
@classmethod
def title_approximate(cls, title, page=1):
return cls.field_search("TITLE", title, fuzzy=True, page=page)
@classmethod
def field_search(cls, field, value, fuzzy=False, page=1):
wrap = "\"" if not fuzzy else ""
url = app.config.get("EPMC_REST_API") + "search/query=" + field + ":" + wrap + urllib.quote_plus(value, safe="/") + wrap
url += "&resultType=core&format=json&page=" + urllib.quote_plus(str(page))
print url
resp = requests.get(url)
if resp.status_code != 200:
raise EuropePMCException(resp)
j = resp.json()
results = [EPMCMetadata(r) for r in j.get("resultList", {}).get("result", [])]
return results
@classmethod
def fulltext(cls, pmcid):
url = app.config.get("EPMC_REST_API") + pmcid + "/fullTextXML"
print url
resp = requests.get(url)
if resp.status_code != 200:
raise EuropePMCException(resp)
return EPMCFullText(resp.text)
class EPMCMetadata(dataobj.DataObj):
def __init__(self, raw):
super(EPMCMetadata, self).__init__(raw)
@property
def pmcid(self):
return self._get_single("pmcid", self._utf8_unicode(), allow_coerce_failure=False)
@property
def pmid(self):
return self._get_single("pmid", self._utf8_unicode(), allow_coerce_failure=False)
@property
def doi(self):
return self._get_single("doi", self._utf8_unicode(), allow_coerce_failure=False)
@property
def in_epmc(self):
return self._get_single("inEPMC", self._utf8_unicode(), allow_coerce_failure=False)
@property
def is_oa(self):
return self._get_single("isOpenAccess", self._utf8_unicode(), allow_coerce_failure=False)
@property
def issn(self):
return self._get_single("journalInfo.journal.issn", self._utf8_unicode(), allow_coerce_failure=False)
@property
def essn(self):
return self._get_single("journalInfo.journal.essn", self._utf8_unicode(), allow_coerce_failure=False)
@property
def title(self):
return self._get_single("title", self._utf8_unicode(), allow_coerce_failure=False)
class EPMCFullText(object):
def __init__(self, raw):
self.raw = raw
try:
self.xml = etree.fromstring(self.raw)
except:
raise EPMCFullTextException("Unable to parse XML", self.raw)
@property
def title(self):
title_elements = self.xml.xpath("//title-group/article-title")
if len(title_elements) > 0:
return title_elements[0].text
return None
@property
def is_aam(self):
manuscripts = self.xml.xpath("//article-id[@pub-id-type='manuscript']")
return len(manuscripts) > 0
def get_licence_details(self):
# get the licence type
l = self.xml.xpath("//license")
if len(l) > 0:
l = l[0]
type = l.get("license-type")
url = l.get("{http://www.w3.org/1999/xlink}href")
# get the paragraph describing the licence
para = self.xml.xpath("//license/license-p")
if len(para) > 0:
para = para[0]
p = etree.tostring(para)
return type, url, p
|
Python
| 0
|
@@ -3929,24 +3929,74 @@
l = l%5B0%5D%0A
+ else:%0A return None, None, None%0A
type
|
20202ab774bc064cb23d2c8a7c811e08d968b8da
|
Add forgotten import.
|
fedmsg/commands/relay.py
|
fedmsg/commands/relay.py
|
# This file is part of fedmsg.
# Copyright (C) 2012 Red Hat, Inc.
#
# fedmsg is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# fedmsg 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with fedmsg; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Authors: Ralph Bean <rbean@redhat.com>
#
"""
"""
from fedmsg.commands import BaseCommand
from fedmsg.consumers.relay import RelayConsumer
from kitchen.iterutils import iterate
class RelayCommand(BaseCommand):
""" Relay connections from active loggers to the bus.
``fedmsg-relay`` is a service which binds to two ports, listens for
messages on one and emits them on the other. ``fedmsg-logger``
requires that an instance of ``fedmsg-relay`` be running *somewhere*
and that it's inbound address be listed in the config as one of the entries
in :term:`relay_inbound`.
``fedmsg-relay`` becomes a necessity for integration points that cannot
bind consistently to and serve from a port. See :doc:`topology` for the
mile-high view. More specifically, ``fedmsg-relay`` is a
SUB.bind()->PUB.bind() relay.
"""
daemonizable = True
name = 'fedmsg-relay'
def run(self):
# Do just like in fedmsg.commands.hub and mangle fedmsg.d/ to work
# with moksha's expected configuration.
moksha_options = dict(
zmq_subscribe_endpoints=",".join(list(iterate(
self.config['relay_inbound']
))),
zmq_subscribe_method="bind",
)
self.config.update(moksha_options)
# Flip the special bit that allows the RelayConsumer to run
self.config[RelayConsumer.config_key] = True
from moksha.hub import main
for publish_endpoint in self.config['endpoints']['relay_outbound']:
self.config['zmq_publish_endpoints'] = publish_endpoint
try:
return main(
# Pass in our config dict
options=self.config,
# Only run this *one* consumer
consumers=[RelayConsumer],
# Tell moksha to quiet its logging.
framework=False,
)
except zmq.ZMQError:
self.log.debug("Failed to bind to %r" % publish_endpoint)
raise IOError("Failed to bind to any outbound endpoints.")
def relay():
command = RelayCommand()
return command.execute()
|
Python
| 0
|
@@ -824,16 +824,28 @@
%22%22%0A%22%22%22%0A%0A
+import zmq%0A%0A
from fed
|
6780b069dcbe180edb78038184f8829df843e7c2
|
use event injector according to advice at users@qpid.apache.org
|
main.py
|
main.py
|
#!/usr/bin/env python2
import threading
from multiprocessing import Queue
try:
from Tkinter import *
except ImportError:
from tkinter import *
import time
import proton
from proton.reactor import Container, AtMostOnce
from proton.handlers import MessagingHandler
class ChatWindow(object):
def __init__(self, root):
self.root = root
frame = Frame(root)
frame.pack()
self.chatlog = Text(frame)
self.chatlog.pack()
self.input = Frame(frame)
self.input.pack()
self.field_var = StringVar()
self.field = Entry(self.input, textvariable=self.field_var)
self.field.pack(side=LEFT)
self.button = Button(self.input, text="Send", command=self.send_message, state=DISABLED)
self.button.pack(side=LEFT)
self.messenger = None
def inject_messenger(self, messenger):
self.receive_message('Welcome to Chat for All!')
self.button.configure(state=NORMAL)
self.messenger = messenger
def send_message(self):
self.messenger.send_message(self.field_var.get())
self.field_var.set("")
def receive_message(self, message):
self.chatlog.insert(END, time.strftime("%H:%M:%S") + ': ' + message + '\n')
self.root.update()
class ChatMesssenger(MessagingHandler):
def __init__(self, gui, sender_address, receiver_address):
super(ChatMesssenger, self).__init__()
self.gui = gui
self.sender_address = sender_address
self.receiver_address = receiver_address
self.sender = None
self.ready_to_send = False
self.outgoing_queue = Queue()
def on_start(self, event):
print('on_start')
event.container.create_receiver(self.receiver_address)
event.container.create_sender(self.sender_address, options=AtMostOnce())
def on_sendable(self, event):
print('on_sendable')
self.sender = event.sender
self.ready_to_send = True
self.send_messages()
# TODO: ??? I cannot send my messages from on_sendable because I do not always have something to send here
# and if I miss one on_sendable and do not send anything, it will not be called again the next time
def on_message(self, event):
print("on_message")
self.gui.receive_message(str(event.message.body))
def send_messages(self):
if not self.ready_to_send:
return
while self.sender.credit:
if self.outgoing_queue.empty():
return
message = proton.Message()
body = self.outgoing_queue.get()
message.body = body
self.sender.send(message)
self.ready_to_send = False
def send_message(self, body):
self.outgoing_queue.put(body)
self.send_messages()
class GuiThread(threading.Thread):
def __init__(self, initialized_event):
super(GuiThread, self).__init__()
self.gui_initialized_event = initialized_event
self.chat_window = None
def run(self):
root = Tk()
self.chat_window = ChatWindow(root)
self.gui_initialized_event.set()
root.mainloop()
class MessagingThread(threading.Thread):
def __init__(self, router_address, initialized, gui):
self.router_address = router_address
self.initialized = initialized
self.gui = gui
self.m = None
self.r = None
super(MessagingThread, self).__init__()
def run(self):
self.m = ChatMesssenger(self.gui,
sender_address=self.router_address,
receiver_address=self.router_address)
self.r = Container(self.m)
self.m.container = self.r
self.initialized.set()
self.r.run()
def main():
"""GUI and Proton reactor are two separate threads"""
router_address = sys.argv[1]
gui_initialized = threading.Event()
messenger_initialized = threading.Event()
gui = GuiThread(gui_initialized)
gui.start()
gui_initialized.wait()
messenger = MessagingThread(router_address, messenger_initialized, gui.chat_window)
messenger.start()
messenger_initialized.wait()
gui.chat_window.inject_messenger(messenger.m)
gui.join()
print("joined gui")
# TODO: Is this the correct way to stop a Reactor from the outside?
messenger.r.stop()
messenger.join()
print("joined messenger")
if __name__ == '__main__':
main()
|
Python
| 0
|
@@ -220,17 +220,50 @@
MostOnce
+, EventInjector, ApplicationEvent
%0A
-
from pro
@@ -1583,16 +1583,54 @@
ddress%0A%0A
+ self.events = EventInjector()%0A
@@ -1780,16 +1780,64 @@
start')%0A
+ event.container.selectable(self.events)%0A
@@ -2114,36 +2114,34 @@
self.
-send
+on
_message
s()%0A
@@ -2128,17 +2128,24 @@
_message
-s
+_to_send
()%0A
@@ -2491,28 +2491,26 @@
def
-send
+on
_message
s(self):
@@ -2505,14 +2505,29 @@
sage
-s(self
+_to_send(self, _=None
):%0A
@@ -2965,22 +2965,58 @@
elf.
-send_messages(
+events.trigger(ApplicationEvent('message_to_send')
)%0A%0A%0A
|
b9243eacec4868464cfc6dbeb826af63b0952c18
|
Fix get_initial to take current value into account. Thanks @d0ugal
|
feedhq/profiles/views.py
|
feedhq/profiles/views.py
|
from django.contrib import messages
from django.contrib.sites.models import RequestSite
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import redirect
from django.utils.translation import ugettext as _
from django.views import generic
from password_reset import views
from .forms import (ChangePasswordForm, ProfileForm, CredentialsForm,
ServiceForm, DeleteAccountForm, SharingForm)
from ..decorators import login_required
class UserMixin(object):
success_url = reverse_lazy('profile')
def get_object(self):
return self.request.user
def get_form_kwargs(self):
kwargs = super(UserMixin, self).get_form_kwargs()
kwargs.update({
'instance': self.request.user,
})
return kwargs
def form_valid(self, form):
form.save()
messages.success(self.request, form.success_message)
return super(UserMixin, self).form_valid(form)
class Stats(UserMixin, generic.DetailView):
def get_context_data(self, **kwargs):
ctx = super(Stats, self).get_context_data(**kwargs)
ctx.update({
'categories': self.request.user.categories.count(),
'feeds': self.request.user.feeds.count(),
'entries': self.request.user.entries.count(),
})
return ctx
stats = login_required(Stats.as_view())
class ReadLater(UserMixin, generic.TemplateView):
template_name = 'profiles/read_later.html'
read_later = login_required(ReadLater.as_view())
class PasswordView(UserMixin, generic.FormView):
template_name = 'profiles/change_password.html'
form_class = ChangePasswordForm
password = login_required(PasswordView.as_view())
class ProfileView(UserMixin, generic.FormView):
form_class = ProfileForm
template_name = 'profiles/edit_profile.html'
def get_initial(self):
return {'ttl': 365}
profile = login_required(ProfileView.as_view())
class Sharing(UserMixin, generic.FormView):
form_class = SharingForm
template_name = 'profiles/sharing.html'
success_url = reverse_lazy('sharing')
sharing = login_required(Sharing.as_view())
class Export(UserMixin, generic.TemplateView):
template_name = 'profiles/export.html'
export = login_required(Export.as_view())
class ServiceView(generic.FormView):
FORMS = {
'readability': CredentialsForm,
'readitlater': CredentialsForm,
'instapaper': CredentialsForm,
'none': ServiceForm,
}
success_url = reverse_lazy('read_later')
def get_template_names(self):
return ['profiles/services/%s.html' % self.kwargs['service']]
def get_form_kwargs(self):
kwargs = super(ServiceView, self).get_form_kwargs()
kwargs.update({
'user': self.request.user,
'service': self.kwargs['service'],
})
return kwargs
def get_form_class(self):
return self.FORMS[self.kwargs['service']]
def form_valid(self, form):
form.save()
if form.user.read_later:
messages.success(
self.request,
_('You have successfully added %s as your reading list '
'service') % form.user.get_read_later_display(),
)
else:
messages.success(
self.request,
_('You have successfully disabled reading list integration'),
)
return super(ServiceView, self).form_valid(form)
services = login_required(ServiceView.as_view())
class Recover(views.Recover):
search_fields = ['email']
recover = Recover.as_view()
class Destroy(generic.FormView):
success_url = reverse_lazy('destroy_done')
form_class = DeleteAccountForm
template_name = 'profiles/user_confirm_delete.html'
def get_form_kwargs(self):
kwargs = super(Destroy, self).get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
def form_valid(self, form):
form.save()
return redirect(self.get_success_url())
destroy = login_required(Destroy.as_view())
class DestroyDone(generic.TemplateView):
template_name = 'profiles/account_delete_done.html'
destroy_done = DestroyDone.as_view()
class Bookmarklet(generic.TemplateView):
template_name = 'profiles/bookmarklet.html'
def get_context_data(self, **kwargs):
ctx = super(Bookmarklet, self).get_context_data(**kwargs)
ctx['site'] = RequestSite(self.request)
ctx['scheme'] = 'https' if self.request.is_secure() else 'http'
return ctx
bookmarklet = login_required(Bookmarklet.as_view())
|
Python
| 0
|
@@ -1881,16 +1881,41 @@
%7B'ttl':
+ self.request.user.ttl or
365%7D%0Apr
|
27d920372b215da7cb2625ce6d7d3f3666bf16e9
|
Improve spelling
|
openfisca_country_template/variables/housing.py
|
openfisca_country_template/variables/housing.py
|
# -*- coding: utf-8 -*-
# This file defines the variables of our legislation.
# A variable is property of a person, or an entity (e.g. a household).
# See http://openfisca.org/doc/variables.html
# Import from openfisca-core the common python objects used to code the legislation in OpenFisca
from openfisca_core.model_api import *
# Import the entities specifically defined for this tax and benefit system
from openfisca_country_template.entities import *
# This variable is a pure input: it doesn't have a formula
class accomodation_size(Variable):
value_type = float
entity = Household
definition_period = MONTH
label = u"Size of the accomodation, in square metters"
# This variable is a pure input: it doesn't have a formula
class rent(Variable):
value_type = float
entity = Household
definition_period = MONTH
label = u"Rent paid by the household"
# Possible values for the housing_occupancy_status variable, defined further down
class HousingOccupancyStatus(Enum):
__order__ = "owner tenant free_lodger homeless"
owner = u'Owner'
tenant = u'Tenant'
free_lodger = u'Free logder'
homeless = u'Homeless'
class housing_occupancy_status(Variable):
value_type = Enum
possible_values = HousingOccupancyStatus
default_value = HousingOccupancyStatus.tenant
entity = Household
definition_period = MONTH
label = u"Legal housing situation of the household concerning their main residence"
|
Python
| 0.998348
|
@@ -680,11 +680,10 @@
met
-te
r
+e
s%22%0A%0A
@@ -1130,10 +1130,10 @@
e lo
-g
d
+g
er'%0A
|
d40b7bdb2cfa846aa170222d8e6eeb477cbf8633
|
update pipeline-demo
|
pipeline/demo/pipeline-demo.py
|
pipeline/demo/pipeline-demo.py
|
from pipeline.backend.pipeline import PipeLine
from pipeline.component.dataio import DataIO
from pipeline.component.input import Input
from pipeline.component.intersection import Intersection
from pipeline.component.hetero_lr import HeteroLR
from pipeline.interface.data import Data
from pipeline.backend.config import Backend
from pipeline.backend.config import WorkMode
guest = 9999
hosts = [10000, 10001]
arbiter = 10002
guest_train_data = {"name": "breast_b", "namespace": "hetero"}
host_train_data = [{"name": "breast_a", "namespace": "hetero"},
{"name": "breast_a", "namespace": "hetero"},
{ "name": "breast_a", "namespace": "hetero"}]
input_0 = Input(name="train_data")
print ("get input_0's init name {}".format(input_0.name))
pipeline = PipeLine().set_initiator(role='guest', party_id=9999).set_roles(guest=9999, host=hosts, arbiter=arbiter)
dataio_0 = DataIO(name="dataio_0")
dataio_0.get_party_instance(role='guest', party_id=9999).algorithm_param(with_label=True, output_format="dense")
dataio_0.get_party_instance(role='host', party_id=[10000, 10001]).algorithm_param(with_label=False)
intersect_0 = Intersection(name="intersection_0")
hetero_lr_0 = HeteroLR(name="hetero_lr_0", early_stop="weight_diff")
print ("get input_0's name {}".format(input_0.name))
pipeline.add_component(dataio_0, data=Data(data=input_0.data))
pipeline.add_component(intersect_0, data=Data(data=dataio_0.output.data))
pipeline.add_component(hetero_lr_0, data=Data(train_data=intersect_0.output.data))
# pipeline.set_deploy_end_component([dataio_0])
# pipeline.deploy_component([dataio_0])
pipeline.compile()
pipeline.fit(backend=Backend.EGGROLL, work_mode=WorkMode.STANDALONE,
feed_dict={input_0:
{"guest": {9999: guest_train_data},
"host": {
10000: host_train_data[0],
10001: host_train_data[1]
}
}
})
print (pipeline.get_component("intersection_0").get_output_data())
print (pipeline.get_component("dataio_0").get_model_param())
print (pipeline.get_component("hetero_lr_0").get_model_param())
# pipeline.get_component("intersection_0").summary("intersect_count", "intersect_rate")
# predict
pipeline = PipeLine().predict(backend=Backend.EGGROLL, work_mode=WorkMode.STANDALONE,
feed_dict={input_0:
{"guest":
{9999: guest_train_data},
"host": {
10000: host_train_data[0],
10001: host_train_data[1]
}
}
})
with open("output.pkl", "wb") as fout:
fout.write(pipeline.dump())
|
Python
| 0
|
@@ -19,120 +19,121 @@
end.
-pipeline import PipeLine%0Afrom pipeline.component.dataio import DataIO%0Afrom pipeline.component.input import Input
+config import Backend%0Afrom pipeline.backend.config import WorkMode%0Afrom pipeline.backend.pipeline import PipeLine
%0Afro
@@ -157,28 +157,22 @@
ent.
-intersect
+data
io
-n
import
Inte
@@ -167,28 +167,22 @@
import
-Intersection
+DataIO
%0Afrom pi
@@ -242,30 +242,31 @@
ine.
-interface.data
+component.input
import
Data
@@ -261,20 +261,21 @@
import
-Data
+Input
%0Afrom pi
@@ -285,83 +285,91 @@
ine.
-backend.config import Backend%0Afrom pipeline.backend.config import WorkMode%0A
+component.intersection import Intersection%0Afrom pipeline.interface.data import Data
%0A%0Agu
@@ -630,17 +630,16 @@
%7B
-
%22name%22:
@@ -711,25 +711,24 @@
data%22)%0Aprint
-
(%22get input_
@@ -1259,17 +1259,16 @@
)%0A%0Aprint
-
(%22get in
@@ -1757,32 +1757,33 @@
+
%7B%22guest%22: %7B9999:
@@ -1822,32 +1822,33 @@
+
%22host%22: %7B%0A
@@ -1833,32 +1833,35 @@
%22host%22: %7B%0A
+
@@ -1923,32 +1923,35 @@
+
10001: host_trai
@@ -1983,32 +1983,33 @@
%7D%0A
+
@@ -2042,24 +2042,25 @@
+
%7D)%0A%0Aprint (p
@@ -2052,25 +2052,24 @@
%7D)%0A%0Aprint
-
(pipeline.ge
@@ -2114,33 +2114,32 @@
ut_data())%0Aprint
-
(pipeline.get_co
@@ -2182,17 +2182,16 @@
))%0Aprint
-
(pipelin
@@ -2349,29 +2349,16 @@
pipeline
- = PipeLine()
.predict
@@ -2431,29 +2431,16 @@
-
-
feed_dic
@@ -2479,37 +2479,24 @@
-
%7B%22guest%22:%0A
@@ -2530,29 +2530,16 @@
-
-
%7B9999: g
@@ -2585,37 +2585,24 @@
-
-
%22host%22: %7B%0A
@@ -2595,37 +2595,24 @@
%22host%22: %7B%0A
-
@@ -2696,37 +2696,24 @@
-
10001: host_
@@ -2763,32 +2763,10 @@
-
- %7D%0A
+%7D%0A
@@ -2794,35 +2794,18 @@
- %7D%0A
+%7D%0A
@@ -2899,10 +2899,8 @@
dump())%0A
-%0A%0A
|
2ee27b5b177bcb056889096a265b7a1ef2c21aff
|
Be more deterministic in the discriminator
|
adhocracy/lib/instance/discriminator.py
|
adhocracy/lib/instance/discriminator.py
|
import logging
from adhocracy import model
from pylons import config
log = logging.getLogger(__name__)
class InstanceDiscriminatorMiddleware(object):
def __init__(self, app, domain):
self.app = app
self.domain = domain
log.debug("Host name: %s." % domain)
def __call__(self, environ, start_response):
environ['adhocracy.domain'] = self.domain
instance_key = config.get('adhocracy.instance')
if instance_key is None:
path = environ.get('PATH_INFO', '')
if path.startswith('/i/'):
instance_key = path.split('/')[2]
environ['PATH_INFO'] = path[len('/i/' + instance_key):]
else:
host = environ.get('HTTP_HOST', "")
host = host.replace(self.domain, "")
host = host.split(':', 1)[0]
host = host.strip('.').strip()
instance_key = host
if instance_key:
instance = model.Instance.find(instance_key)
if instance is None:
log.debug("No such instance: %s, defaulting!" % instance_key)
else:
model.instance_filter.setup_thread(instance)
try:
return self.app(environ, start_response)
finally:
model.instance_filter.setup_thread(None)
def setup_discriminator(app, config):
# warn if abdoned adhocracy.domains is used
if config.get('adhocracy.domains') is not None:
raise AssertionError('adhocracy.domains is not supported anymore. '
'use adhocracy.domain (without the s) with only '
'one domain')
domain = config.get('adhocracy.domain').strip()
return InstanceDiscriminatorMiddleware(app, domain)
|
Python
| 0.999985
|
@@ -62,16 +62,59 @@
t config
+%0Afrom paste.deploy.converters import asbool
%0A%0Alog =
@@ -506,32 +506,115 @@
ce_key is None:%0A
+ if asbool(config.get('adhocracy.urls_without_hostname', 'false')):%0A
path
@@ -657,16 +657,20 @@
+
+
if path.
@@ -688,16 +688,20 @@
'/i/'):%0A
+
@@ -742,16 +742,20 @@
'/')%5B2%5D%0A
+
|
39e6b8e9e5d3edaf8448b7ebc4ab17989b012ba1
|
Add a test for setter and deleter.
|
server/kcsapi/model_test.py
|
server/kcsapi/model_test.py
|
#!/usr/bin/env python
import pytest
import model
class TestJsonSerializableObject(object):
def test_default_getter(self):
class DefaultGetter(model.JsonSerializableObject):
# Can decorate without any arguments.
@model.jsonproperty
def field_foo(self):
return 'foo'
g = DefaultGetter()
# field_foo can be used as a normal getter.
assert g.field_foo == 'foo'
# And is automatically exported.
assert g.json() == '{"field_foo": "foo"}'
def test_named_getter(self):
class NamedGetter(model.JsonSerializableObject):
# This field is exported as "FOO".
# Note that parameters should be named; you can't do this way:
# @model.jsonproperty('FOO')
@model.jsonproperty(name='FOO')
def field_foo(self):
return 'foo'
g = NamedGetter()
assert g.field_foo == 'foo'
assert g.json() == '{"FOO": "foo"}'
def test_named_conservative_getter(self):
class NamedConservativeGetter(model.JsonSerializableObject):
def __init__(self, value):
self.value = value
# If you prefer, it's possible not to export if the value is null.
# (In python, if the value is None.)
@model.jsonproperty(store_if_null=False)
def field_foo(self):
return self.value
assert NamedConservativeGetter('foo').json() == '{"field_foo": "foo"}'
assert NamedConservativeGetter(None).json() == '{}'
def test_named_aggressive_getter(self):
class NamedAggressiveGetter(model.JsonSerializableObject):
def __init__(self, value):
self.value = value
# By default, a null value is exported.
@model.jsonproperty()
def field_foo(self):
return self.value
assert NamedAggressiveGetter('foo').json() == '{"field_foo": "foo"}'
assert NamedAggressiveGetter(None).json() == '{"field_foo": null}'
def test_non_primitive_value_getter(self):
class NonPrimitiveObject(object):
pass
class NonPrimitiveValueGetter(model.JsonSerializableObject):
# The getter cannot return a non primitive value.
@model.jsonproperty
def field_foo(self):
return NonPrimitiveObject()
with pytest.raises(TypeError):
NonPrimitiveValueGetter().json()
def test_non_primitive_serializable_value_getter(self):
class NonPrimitiveSerializableObject(model.JsonSerializableObject):
@model.jsonproperty
def field_child_foo(self):
return 'child_foo'
class NonPrimitiveSerializableValueGetter(
model.JsonSerializableObject):
# OK if the non primitive value is JSON serializable.
@model.jsonproperty
def field_foo(self):
return NonPrimitiveSerializableObject()
assert (NonPrimitiveSerializableValueGetter().json() ==
'{"field_foo": {"field_child_foo": "child_foo"}}')
def main():
pytest.main(args=[__file__.replace('.pyc', '.py')])
if __name__ == '__main__':
main()
|
Python
| 0
|
@@ -3170,16 +3170,911 @@
o%22%7D%7D')%0A%0A
+ def test_getter_setter_deleter(self):%0A class GetterSetterDeleter(model.JsonSerializableObject):%0A def __init__(self, foo):%0A self._foo = foo%0A%0A @model.jsonproperty%0A def field_foo(self):%0A return self._foo%0A%0A # Setters and deleters can be used just like the standard property.%0A @field_foo.setter%0A def field_foo(self, foo):%0A self._foo = foo%0A%0A @field_foo.deleter%0A def field_foo(self):%0A del self._foo%0A%0A gsd = GetterSetterDeleter(123)%0A assert gsd.field_foo == 123%0A assert gsd.json() == '%7B%22field_foo%22: 123%7D'%0A gsd.field_foo = 456%0A assert gsd.field_foo == 456%0A assert gsd.json() == '%7B%22field_foo%22: 456%7D'%0A del gsd.field_foo%0A with pytest.raises(AttributeError):%0A assert gsd.field_foo%0A%0A
%0Adef mai
|
1abeecd3806d4766ecd321e93574950df9da0f43
|
Work on build failure issue (conflicting files)
|
cs207rbtree/cs207rbtree/test_RedBlackTree.py
|
cs207rbtree/cs207rbtree/test_RedBlackTree.py
|
from pytest import raises
import unittest
import numpy as np
from RedBlackTree import *
import os
class RedBlackTreeTest(unittest.TestCase):
def test_smoke(self):
"Smoke test to make sure unbalanced tree is working"
db = self.get_f("/tmp/test1.dbdb")
db.set("rahul", "aged")
db.set("pavlos", "aged")
db.set("kobe", "stillyoung")
assert db.get("pavlos")=="aged"
db.commit()
db.close()
newdb = self.get_f("/tmp/test1.dbdb")
assert newdb.get("pavlos")=="aged"
newdb.close()
os.remove('/tmp/test1.dbdb')
def test_inits(self):
"Test init methods."
db = self.get_f("/tmp/test2.dbdb")
db.close()
os.remove('/tmp/test2.dbdb')
def test_set_get(self):
"Test that we can set a value and then retrieve it with get()."
db = self.get_f("/tmp/test3.dbdb")
db.set("pavlos", "aged")
assert db.get("pavlos")=="aged"
db.close()
os.remove('/tmp/test3.dbdb')
def test_set_commit_get(self):
"Test that we can set a value then retrieve it after committing."
db = self.get_f("/tmp/test4.dbdb")
db.set("pavlos", "aged")
db.commit()
db.close()
db = self.get_f("/tmp/test4.dbdb")
assert db.get("pavlos") == "aged"
db.close()
os.remove('/tmp/test4.dbdb')
def test_set_no_commit(self):
"Test that getting after setting without committing will raise a KeyError."
db = self.get_f("/tmp/test5.dbdb")
db.set("pavlos", "aged")
db.close()
db = self.get_f("/tmp/test5.dbdb")
with raises(KeyError):
db.get("pavlos")=="aged"
db.close()
os.remove('/tmp/test5.dbdb')
def test_get_multiple(self):
"Test that we can set multiple values."
db = self.get_f("/tmp/test6.dbdb")
db.set("kobe", "baby")
db.set("rahul", "veryyoung")
db.set("pavlos", "stillyoung")
db.set("andy", "old")
db.set("lisa", "ancient")
assert db.get("rahul")=="veryyoung"
assert db.get("pavlos")=="stillyoung"
assert db.get("lisa")=="ancient"
assert db.get("andy")=="old"
db.close()
os.remove('/tmp/test6.dbdb')
def test_delete(self):
"Test that we can delete a node."
db = self.get_f("/tmp/test7.dbdb")
db.set("kobe", "baby")
db.set("allison", "veryyoung")
db.set("greg", "stillyoung")
db.set("yi", "old")
db.set("cathy", "ancient")
db.delete("greg")
with raises(KeyError):
db.get("greg")
with raises(KeyError):
db.delete("greg")
assert db.get("allison")=="veryyoung"
assert db.get("yi")=="old"
assert db.get("cathy")=="ancient"
assert db.get("kobe")=="baby"
db.close()
os.remove('/tmp/test7.dbdb')
def test_close(self):
"Test that we can close a file."
db = self.get_f("/tmp/test8.dbdb")
db.close()
with raises(ValueError):
db._assert_not_closed()
os.remove('/tmp/test8.dbdb')
def test_delete_root(self):
"Test that we can delete a root node and have expected behavior."
db = self.get_f("/tmp/test7.dbdb")
db.set("kobe", "baby")
db.set("yi", "old")
db.set("cathy", "ancient")
db.set("greg", "stillyoung")
db.set("allison", "veryyoung")
db.delete("kobe")
with raises(KeyError):
db.get("kobe")
with raises(KeyError):
db.delete("kobe")
assert db.get("allison")=="veryyoung"
assert db.get("yi")=="old"
assert db.get("cathy")=="ancient"
assert db.get("greg")=="stillyoung"
db.close()
os.remove('/tmp/test7.dbdb')
def test_set_set_commit(self):
"""
Test that we can set a value, replace it with a new value,
and the new value will be there post-commit.
"""
db = self.get_f("/tmp/test8.dbdb")
db.set("pavlos", "aged")
assert db.get("pavlos") == "aged"
db.set("pavlos", "young")
assert db.get("pavlos") == "young"
db.commit()
db.close()
db = self.get_f("/tmp/test8.dbdb")
assert db.get("pavlos") == "young"
db.close()
os.remove('/tmp/test8.dbdb')
def test_set_set(self):
"Test that we can set a value and then replace it with a new value."
db = self.get_f("/tmp/test9.dbdb")
db.set("pavlos", "aged")
assert db.get("pavlos") == "aged"
db.set("pavlos", "young")
assert db.get("pavlos") == "young"
db.close()
os.remove('/tmp/test9.dbdb')
def test_getRoot(self):
"Test that we can correctly recall the root key."
db = self.get_f("/tmp/test10.dbdb")
db.set("kobe", "baby")
db.set("rahul", "veryyoung")
db.set("pavlos", "stillyoung")
assert db.rootKey() == "pavlos"
db.close()
os.remove('/tmp/test10.dbdb')
def test_nonexistantKey(self):
"Test that we can correctly reject nonexistant keys."
db = self.get_f("/tmp/test11.dbdb")
db.set("rahul", "veryyoung")
db.set("pavlos", "stillyoung")
db.commit()
with raises(KeyError):
db.get("kobe")
os.remove('/tmp/test11.dbdb')
if __name__=='__main__':
try: # pragma: no cover
unittest.main() # pragma: no cover
except SystemExit as inst: # pragma: no cover
if inst.args[0] is True: # pragma: no cover
raise # pragma: no cover
|
Python
| 0
|
@@ -1,12 +1,67 @@
+import sys%0Asys.path.insert(0, os.path.abspath('../'))%0A%0A
from pytest
|
ce02f48ea85b64a5a4503b22d3fb324c521904d0
|
Enable graphiql only when DEBUG=True
|
saleor/urls.py
|
saleor/urls.py
|
from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from django.contrib.staticfiles.views import serve
from graphene_django.views import GraphQLView
from .cart.urls import urlpatterns as cart_urls
from .checkout.urls import urlpatterns as checkout_urls
from .core.sitemaps import sitemaps
from .core.urls import urlpatterns as core_urls
from .order.urls import urlpatterns as order_urls
from .product.urls import urlpatterns as product_urls
from .search.urls import urlpatterns as search_urls
from .userprofile.urls import urlpatterns as userprofile_urls
from .data_feeds.urls import urlpatterns as feed_urls
from .dashboard.urls import urlpatterns as dashboard_urls
admin.autodiscover()
urlpatterns = [
url(r'^', include(core_urls)),
url(r'^account/', include('allauth.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^cart/', include(cart_urls, namespace='cart')),
url(r'^checkout/', include(checkout_urls, namespace='checkout')),
url(r'^dashboard/', include(dashboard_urls, namespace='dashboard')),
url(r'^graphql', GraphQLView.as_view(graphiql=True)),
url(r'^order/', include(order_urls, namespace='order')),
url(r'^products/', include(product_urls, namespace='product')),
url(r'^profile/', include(userprofile_urls, namespace='profile')),
url(r'^search/', include(search_urls, namespace='search')),
url(r'^selectable/', include('selectable.urls')),
url(r'^feeds/', include(feed_urls, namespace='data_feeds')),
url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps},
name='django.contrib.sitemaps.views.sitemap'),
url(r'', include('payments.urls'))
]
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += [
url(r'^static/(?P<path>.*)$', serve)
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
Python
| 0.000041
|
@@ -1235,12 +1235,22 @@
iql=
-True
+settings.DEBUG
)),%0A
|
3bac87763eb92738f8c211930d2554f624395c43
|
test w test params, test with ndim >1
|
ogusa/tests/test_parameters.py
|
ogusa/tests/test_parameters.py
|
import os
import tempfile
import pytest
from ogusa.parameters import Specifications, revision_warnings_errors
# JSON_REVISION_FILE = """{
# "revision": {
# "frisch": 0.3
# }
# }"""
@pytest.fixture(scope='module')
def revision_file():
f = tempfile.NamedTemporaryFile(mode="a", delete=False)
f.write(JSON_REVISION_FILE)
f.close()
# Must close and then yield for Windows platform
yield f
os.remove(f.name)
def test_create_specs_object():
specs = Specifications()
assert specs
# def test_read_json_revision(revision_file):
# exp = {"frisch": 0.3}
# act1 = Specifications.read_json_revision(JSON_REVISION_FILE)
# assert exp == act1
# act2 = Specifications.read_json_revision(JSON_REVISION_FILE)
# assert exp == act2
def test_update_specifications_with_dict():
spec = Specifications()
new_spec_dict = {
'frisch': 0.3,
}
spec.update_specifications(new_spec_dict)
assert spec.frisch == 0.3
assert len(spec.errors) == 0
def test_update_specification_with_json():
spec = Specifications()
new_spec_json = """
{
"frisch": 0.3
}
"""
spec.update_specifications(new_spec_json)
assert spec.frisch == 0.3
assert len(spec.errors) == 0
def test_implement_reform():
specs = Specifications()
new_specs = {
'tG1': 30,
'T': 80,
'frisch': 0.3,
'tax_func_type': 'DEP'
}
specs.update_specifications(new_specs)
assert specs.frisch == 0.3
assert specs.tG1 == 30
assert specs.T == 80
assert specs.tax_func_type == 'DEP'
assert len(specs.errors) == 0
# assert len(specs.warnings) == 0
def test_implement_bad_reform1():
specs = Specifications()
# tG1 has an upper bound at T / 2
new_specs = {
'tG1': 50,
'T': 80,
}
specs.update_specifications(new_specs, raise_errors=False)
assert len(specs.errors) == 0 # > 0
# assert specs.errors['tG1'] == 'ERROR: tG1 value 50 > max value 40.0\n' # to redo when can have param valid values depend on others'
# assert len(specs.warnings) == 0
def test_implement_bad_reform2():
specs = Specifications()
# tG1 has an upper bound at T / 2
new_specs = {
'T': 80,
'tax_func_type': 'not_a_functional_form'
}
specs.update_specifications(new_specs, raise_errors=False)
assert len(specs.errors) > 0
assert specs.errors['tax_func_type'][0] == 'tax_func_type "not_a_functional_form" must be in list of choices DEP, DEP_totalinc, GS, linear.'
# assert len(specs.warnings) == 0
def test_revision_warnings_errors():
user_mods = {'frisch': 0.41}
ew = revision_warnings_errors(user_mods)
assert len(ew['errors']) == 0
assert len(ew['warnings']) == 0
user_mods = {'frisch': 0.1}
bad_ew = revision_warnings_errors(user_mods)
assert len(bad_ew['errors']) > 0
assert len(bad_ew['warnings']) == 0
## Commenting out because I don't think ParamTools allows this yet
# def test_simple_eval():
# specs = Specifications()
# specs.T = 100
# assert specs.simple_eval('T / 2') == 50
# assert specs.simple_eval('T * 2') == 200
# assert specs.simple_eval('T - 2') == 98
# assert specs.simple_eval('T + 2') == 102
|
Python
| 0
|
@@ -33,16 +33,35 @@
pytest%0A
+import numpy as np%0A
from ogu
@@ -541,16 +541,282 @@
specs%0A%0A%0A
+def test_create_specs_object_test():%0A specs = Specifications(test=True)%0A assert specs%0A%0A%0Adef test_compute_default_params():%0A specs = Specifications()%0A specs.alpha_G = np.ones((10, 1))%0A specs.compute_default_params()%0A assert specs.alpha_G%5B10%5D == 1%0A%0A%0A
# def te
|
aedf9938a26ddd67520ed5e957e56d468affccd5
|
fix dict iterable
|
ogusa/tests/test_parameters.py
|
ogusa/tests/test_parameters.py
|
import os
import sys
CUR_PATH = os.path.abspath(os.path.dirname(__file__))
sys.path.append(os.path.join(CUR_PATH, "../../"))
import pytest
import pickle
from ogusa.parameters import (get_parameters, read_tax_func_estimate,
USER_MODIFIABLE_PARAMS)
from ogusa import parameters
def test_parameters_user_modifiable():
output_base = "./OUTPUT"
dd = get_parameters(output_base, test=False, guid='', user_modifiable=True, metadata=False)
assert set(dd.keys()) == set(USER_MODIFIABLE_PARAMS)
def test_parameters_metadata_policy():
output_base = "./OUTPUT"
dd_standard = get_parameters(output_base, test=False, guid='', user_modifiable=True, metadata=False)
dd_meta = get_parameters(output_base, test=False, guid='', user_modifiable=True, metadata=True)
for k, v in dd_meta.iteritems():
assert dd_standard[k] == dd_meta[k]['value']
assert set(dd_meta.keys()) == set(USER_MODIFIABLE_PARAMS)
dd_standard = get_parameters(output_base, test=False, guid='', user_modifiable=True, metadata=False)
dd_meta = get_parameters(output_base, test=False, guid='', user_modifiable=True, metadata=True)
for k, v in dd_meta.iteritems():
assert dd_standard[k] == dd_meta[k]['value']
assert set(dd_meta.keys()) == set(USER_MODIFIABLE_PARAMS)
assert 'validations' in dd_meta['frisch']
def test_parameters_metadata_baseline():
output_base = "./OUTPUT"
dd_standard = get_parameters(output_base, test=True, guid='', user_modifiable=True, metadata=False)
dd_meta = get_parameters(output_base, test=True, guid='', user_modifiable=True, metadata=True)
for k, v in dd_meta.iteritems():
assert dd_standard[k] == dd_meta[k]['value']
assert set(dd_meta.keys()) == set(USER_MODIFIABLE_PARAMS)
dd_standard = get_parameters(output_base, test=True, guid='', user_modifiable=True, metadata=False)
dd_meta = get_parameters(output_base, test=True, guid='', user_modifiable=True, metadata=True)
for k, v in dd_meta.iteritems():
assert dd_standard[k] == dd_meta[k]['value']
assert set(dd_meta.keys()) == set(USER_MODIFIABLE_PARAMS)
assert 'validations' in dd_meta['frisch']
# @pytest.mark.parametrize("baseline", [True, False])
# @pytest.mark.parametrize(
# "guid,tx_func_est_path,exp_tx_func_est_path",
# [('', None, "./TxFuncEst_{}.pkl"),
# ('', "test.pkl", "test.pkl"),
# (9, None, "./TxFuncEst_{}9.pkl")])
# def test_tx_func_est_path(monkeypatch, baseline, guid, tx_func_est_path,
# exp_tx_func_est_path):
# """
# Make sure tax parameter paths work as expected
# monkeypatch is a pytest plugin that mocks functions and modules
# """
# output_base = "./OUTPUT"
# mocked_fn = parameters.read_tax_func_estimate
# baseline_policy = "baseline" if baseline else "policy"
#
# def read_tax_func_estimate_mock(pickle_path, pickle_file):
# assert (
# pickle_path == exp_tx_func_est_path.format(baseline_policy) and
# pickle_file == "TxFuncEst_{0}{1}.pkl".format(baseline_policy,
# guid)
# )
# return mocked_fn(pickle_path, pickle_file)
#
# monkeypatch.setattr(parameters, "read_tax_func_estimate", read_tax_func_estimate_mock)
# try:
# parameters.get_parameters(output_base, test=False, baseline=baseline, guid=guid)
# except IOError: #file doesn't exist
# pass
|
Python
| 0.000024
|
@@ -813,36 +813,32 @@
k, v in dd_meta.
-iter
items():%0A
@@ -822,32 +822,32 @@
d_meta.items():%0A
+
assert d
@@ -1167,36 +1167,32 @@
k, v in dd_meta.
-iter
items():%0A
@@ -1637,36 +1637,32 @@
k, v in dd_meta.
-iter
items():%0A
@@ -1965,32 +1965,32 @@
metadata=True)%0A
+
for k, v in
@@ -2001,12 +2001,8 @@
eta.
-iter
item
|
ae5977e960b1f4d7953b1929ad1e2ab96e746fce
|
Add a quick test for `every` mode
|
tests/test_arguments.py
|
tests/test_arguments.py
|
import pytest
import datetime
import argparse
from ding import ding
# Valid arguments
def test_time_a_second_in_the_past():
a_second_ago = datetime.datetime.now() - datetime.timedelta(seconds=1)
time_str = str(a_second_ago.time()).split('.')[0]
assert ding.get_args(['at', time_str])
def test_time_a_minute_in_the_future():
a_second_ago = datetime.datetime.now() + datetime.timedelta(minutes=1)
time_str = str(a_second_ago.time()).split('.')[0]
assert ding.get_args(['at', time_str])
def test_time_in_1s():
assert ding.get_args(['in', '1s'])
def test_time_in_1m():
assert ding.get_args(['in', '1m'])
def test_time_in_1m():
assert ding.get_args(['in', '1h'])
def test_time_in_1h_1m_1s():
assert ding.get_args(['in', '1h', '1m', '1s'])
# Invalid arguments
def test_no_arguments():
with pytest.raises(SystemExit) as excinfo:
assert ding.get_args([])
def test_insufficient_arguments_in():
with pytest.raises(SystemExit) as excinfo:
assert ding.get_args(['in'])
def test_insufficient_arguments_at():
with pytest.raises(SystemExit) as excinfo:
assert ding.get_args(['at'])
def test_in_wrong_suffix():
with pytest.raises(SystemExit) as excinfo:
assert ding.get_args(['in', '1x'])
def test_in_partly_wrong_suffix():
with pytest.raises(SystemExit) as excinfo:
assert ding.get_args(['in', '1s', '1x'])
def test_at_invalid_separator():
with pytest.raises(SystemExit) as excinfo:
assert ding.get_args(['in', '15', '30'])
def test_at_invalid_hour():
with pytest.raises(SystemExit) as excinfo:
assert ding.get_args(['at', '25'])
def test_at_invalid_minute():
with pytest.raises(SystemExit) as excinfo:
assert ding.get_args(['at', '22:71'])
def test_at_characters_in_string():
with pytest.raises(SystemExit) as excinfo:
assert ding.get_args(['at', '22a:71'])
def test_notimer_not_at_end():
with pytest.raises(SystemExit) as excinfo:
assert ding.get_args(['--no-timer', 'in', '1s'])
# Test optional args
def test_argument_no_timer():
assert ding.get_args(['in', '1s', '--no-timer'])
assert ding.get_args(['in', '1s', '-n'])
def test_argument_alternative_command():
assert ding.get_args(['in', '1s', '--command', 'beep'])
assert ding.get_args(['in', '1s', '-c', 'beep'])
def test_argument_inexistent():
with pytest.raises(SystemExit) as excinfo:
assert ding.get_args(['in', '1s', '--inexistent-argument'])
|
Python
| 0.000063
|
@@ -1144,24 +1144,150 @@
gs(%5B'at'%5D)%0A%0A
+def test_insufficient_arguments_at():%0A with pytest.raises(SystemExit) as excinfo:%0A assert ding.get_args(%5B'every'%5D)%0A%0A
def test_in_
|
10b828cd80a0ce7702a49d2e7b3cc6ce82997ab8
|
Fix test_basic_api.
|
tests/test_basic_api.py
|
tests/test_basic_api.py
|
# -*- coding: utf-8 -*-
"""
Pygments basic API tests
~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2006-2007 by Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
import os
import unittest
import StringIO
import random
from pygments import lexers, formatters, filters, format
from pygments.token import _TokenType, Text
from pygments.lexer import RegexLexer
from pygments.formatters.img import FontNotFound
test_content = [chr(i) for i in xrange(33, 128)] * 5
random.shuffle(test_content)
test_content = ''.join(test_content) + '\n'
class LexersTest(unittest.TestCase):
def test_import_all(self):
# instantiate every lexer, to see if the token type defs are correct
for x in lexers.LEXERS.keys():
c = getattr(lexers, x)()
def test_lexer_classes(self):
a = self.assert_
ae = self.assertEquals
# test that every lexer class has the correct public API
for lexer in lexers._iter_lexerclasses():
a(type(lexer.name) is str)
for attr in 'aliases', 'filenames', 'alias_filenames', 'mimetypes':
a(hasattr(lexer, attr))
a(type(getattr(lexer, attr)) is list, "%s: %s attribute wrong" %
(lexer, attr))
result = lexer.analyse_text("abc")
a(isinstance(result, float) and 0.0 <= result <= 1.0)
inst = lexer(opt1="val1", opt2="val2")
if issubclass(lexer, RegexLexer):
if not hasattr(lexer, '_tokens'):
# if there's no "_tokens", the lexer has to be one with
# multiple tokendef variants
a(lexer.token_variants)
for variant in lexer.tokens:
a('root' in lexer.tokens[variant])
else:
a('root' in lexer._tokens, '%s has no root state' % lexer)
tokens = list(inst.get_tokens(test_content))
txt = ""
for token in tokens:
a(isinstance(token, tuple))
a(isinstance(token[0], _TokenType))
if isinstance(token[1], str):
print repr(token[1])
a(isinstance(token[1], unicode))
txt += token[1]
ae(txt, test_content, "%s lexer roundtrip failed: %r != %r" %
(lexer.name, test_content, txt))
def test_get_lexers(self):
a = self.assert_
ae = self.assertEquals
# test that the lexers functions work
for func, args in [(lexers.get_lexer_by_name, ("python",)),
(lexers.get_lexer_for_filename, ("test.py",)),
(lexers.get_lexer_for_mimetype, ("text/x-python",)),
(lexers.guess_lexer, ("#!/usr/bin/python -O\nprint",)),
(lexers.guess_lexer_for_filename, ("a.py", "<%= @foo %>"))
]:
x = func(opt="val", *args)
a(isinstance(x, lexers.PythonLexer))
ae(x.options["opt"], "val")
class FiltersTest(unittest.TestCase):
def test_basic(self):
filter_args = {
'whitespace': {'spaces': True, 'tabs': True, 'newlines': True},
'highlight': {'names': ['isinstance', 'lexers', 'x']},
}
for x in filters.FILTERS.keys():
lx = lexers.PythonLexer()
lx.add_filter(x, **filter_args.get(x, {}))
text = file(os.path.join(testdir, testfile)).read().decode('utf-8')
tokens = list(lx.get_tokens(text))
roundtext = ''.join([t[1] for t in tokens])
if x not in ('whitespace', 'keywordcase'):
# these filters change the text
self.assertEquals(roundtext, text,
"lexer roundtrip with %s filter failed" % x)
def test_raiseonerror(self):
lx = lexers.PythonLexer()
lx.add_filter('raiseonerror', excclass=RuntimeError)
self.assertRaises(RuntimeError, list, lx.get_tokens('$'))
def test_whitespace(self):
lx = lexers.PythonLexer()
lx.add_filter('whitespace', spaces='%')
text = file(os.path.join(testdir, testfile)).read().decode('utf-8')
lxtext = ''.join([t[1] for t in list(lx.get_tokens(text))])
self.failIf(' ' in lxtext)
def test_keywordcase(self):
lx = lexers.PythonLexer()
lx.add_filter('keywordcase', case='capitalize')
text = file(os.path.join(testdir, testfile)).read().decode('utf-8')
lxtext = ''.join([t[1] for t in list(lx.get_tokens(text))])
self.assert_('Def' in lxtext and 'Class' in lxtext)
class FormattersTest(unittest.TestCase):
def test_public_api(self):
a = self.assert_
ae = self.assertEquals
ts = list(lexers.PythonLexer().get_tokens("def f(): pass"))
out = StringIO.StringIO()
# test that every formatter class has the correct public API
for formatter, info in formatters.FORMATTERS.iteritems():
a(len(info) == 4)
a(info[0], "missing formatter name") # name
a(info[1], "missing formatter aliases") # aliases
a(info[3], "missing formatter docstring") # doc
try:
inst = formatter(opt1="val1")
except (ImportError, FontNotFound):
continue
inst.get_style_defs()
inst.format(ts, out)
def test_encodings(self):
from pygments.formatters import HtmlFormatter
# unicode output
fmt = HtmlFormatter()
tokens = [(Text, u"ä")]
out = format(tokens, fmt)
self.assert_(type(out) is unicode)
self.assert_(u"ä" in out)
# encoding option
fmt = HtmlFormatter(encoding="latin1")
tokens = [(Text, u"ä")]
self.assert_(u"ä".encode("latin1") in format(tokens, fmt))
# encoding and outencoding option
fmt = HtmlFormatter(encoding="latin1", outencoding="utf8")
tokens = [(Text, u"ä")]
self.assert_(u"ä".encode("utf8") in format(tokens, fmt))
def test_styles(self):
from pygments.formatters import HtmlFormatter
fmt = HtmlFormatter(style="pastie")
def test_unicode_handling(self):
# test that the formatter supports encoding and Unicode
tokens = list(lexers.PythonLexer(encoding='utf-8').get_tokens("def f(): 'ä'"))
for formatter, info in formatters.FORMATTERS.iteritems():
try:
inst = formatter(encoding=None)
except (ImportError, FontNotFound):
# some dependency or font not installed
continue
out = format(tokens, inst)
if formatter.unicodeoutput:
self.assert_(type(out) is unicode)
inst = formatter(encoding='utf-8')
out = format(tokens, inst)
self.assert_(type(out) is str)
# Cannot test for encoding, since formatters may have to escape
# non-ASCII characters.
def test_get_formatters(self):
a = self.assert_
ae = self.assertEquals
# test that the formatters functions work
x = formatters.get_formatter_by_name("html", opt="val")
a(isinstance(x, formatters.HtmlFormatter))
ae(x.options["opt"], "val")
x = formatters.get_formatter_for_filename("a.html", opt="val")
a(isinstance(x, formatters.HtmlFormatter))
ae(x.options["opt"], "val")
|
Python
| 0.000002
|
@@ -108,9 +108,9 @@
-200
-7
+8
by
@@ -5451,29 +5451,189 @@
-inst.get_style_defs()
+try:%0A inst.get_style_defs()%0A except NotImplementedError:%0A # may be raised by formatters for which it doesn't make sense%0A pass
%0A
|
67c6506bcc454eeba3aca223fe1de415eb684e4d
|
Replace os.tempnam with tempfile for python3 (#537)
|
tests/test_binary_io.py
|
tests/test_binary_io.py
|
# Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD+Patents license found in the
# LICENSE file in the root directory of this source tree.
#! /usr/bin/env python2
"""Binary indexes (de)serialization"""
import numpy as np
import unittest
import faiss
import os
def make_binary_dataset(d, nb, nt, nq):
assert d % 8 == 0
x = np.random.randint(256, size=(nb + nq + nt, int(d / 8))).astype('uint8')
return x[:nt], x[nt:-nq], x[-nq:]
class TestBinaryFlat(unittest.TestCase):
def __init__(self, *args, **kwargs):
unittest.TestCase.__init__(self, *args, **kwargs)
d = 32
nt = 0
nb = 1500
nq = 500
(_, self.xb, self.xq) = make_binary_dataset(d, nb, nt, nq)
def test_flat(self):
d = self.xq.shape[1] * 8
index = faiss.IndexBinaryFlat(d)
index.add(self.xb)
D, I = index.search(self.xq, 3)
tmpnam = os.tempnam()
try:
faiss.write_index_binary(index, tmpnam)
index2 = faiss.read_index_binary(tmpnam)
D2, I2 = index2.search(self.xq, 3)
assert (I2 == I).all()
assert (D2 == D).all()
finally:
os.remove(tmpnam)
class TestBinaryIVF(unittest.TestCase):
def __init__(self, *args, **kwargs):
unittest.TestCase.__init__(self, *args, **kwargs)
d = 32
nt = 200
nb = 1500
nq = 500
(self.xt, self.xb, self.xq) = make_binary_dataset(d, nb, nt, nq)
def test_ivf_flat(self):
d = self.xq.shape[1] * 8
quantizer = faiss.IndexBinaryFlat(d)
index = faiss.IndexBinaryIVF(quantizer, d, 8)
index.cp.min_points_per_centroid = 5 # quiet warning
index.nprobe = 4
index.train(self.xt)
index.add(self.xb)
D, I = index.search(self.xq, 3)
tmpnam = os.tempnam()
try:
faiss.write_index_binary(index, tmpnam)
index2 = faiss.read_index_binary(tmpnam)
D2, I2 = index2.search(self.xq, 3)
assert (I2 == I).all()
assert (D2 == D).all()
finally:
os.remove(tmpnam)
if __name__ == '__main__':
unittest.main()
|
Python
| 0
|
@@ -318,16 +318,32 @@
mport os
+%0Aimport tempfile
%0A%0Adef ma
@@ -978,28 +978,50 @@
mpnam =
-os.
temp
-nam()
+file.NamedTemporaryFile().name
%0A
@@ -1952,20 +1952,42 @@
m =
-os.
temp
-nam()
+file.NamedTemporaryFile().name
%0A%0A
|
f347a01bce5ecbfcc14f0742917046a23935c7c5
|
fix tests
|
tests/test_callables.py
|
tests/test_callables.py
|
import contextlib
from hacheck.compat import nested
import mock
import json
import os
from unittest import TestCase
import hacheck.haupdown
import hacheck.spool
# can't use an actual mock.sentinel because it doesn't support string ops
sentinel_service_name = 'testing_service_name'
class TestCallable(TestCase):
@contextlib.contextmanager
def setup_wrapper(self, args=frozenset()):
with nested(
mock.patch.object(hacheck, 'spool', return_value=(True, {})),
mock.patch.object(hacheck.haupdown, 'print_s'),
mock.patch('sys.argv', ['ignored', sentinel_service_name] + list(args))
) as (mock_spool, mock_print, _1):
yield mock_spool, mock_print
def test_basic(self):
with self.setup_wrapper() as (spooler, _):
spooler.status.return_value = (True, {})
hacheck.haupdown.main()
spooler.configure.assert_called_once_with('/var/spool/hacheck', needs_write=False)
def test_exit_codes(self):
with self.setup_wrapper() as (spooler, mock_print):
spooler.status.return_value = (True, {})
self.assertEqual(0, hacheck.haupdown.main())
mock_print.assert_any_call('UP\t%s', sentinel_service_name)
spooler.status.return_value = (False, {'reason': 'irrelevant'})
self.assertEqual(1, hacheck.haupdown.main())
mock_print.assert_any_call('DOWN\t%s\t%s', sentinel_service_name, 'irrelevant')
def test_up(self):
with self.setup_wrapper() as (spooler, mock_print):
hacheck.haupdown.up()
spooler.up.assert_called_once_with(sentinel_service_name)
self.assertEqual(mock_print.call_count, 0)
def test_down(self):
os.environ['SSH_USER'] = 'testyuser'
os.environ['SUDO_USER'] = 'testyuser'
with self.setup_wrapper() as (spooler, mock_print):
hacheck.haupdown.down()
spooler.down.assert_called_once_with(sentinel_service_name,
'testyuser')
self.assertEqual(mock_print.call_count, 0)
def test_down_with_reason(self):
with self.setup_wrapper(['-r', 'something']) as (spooler, mock_print):
hacheck.haupdown.down()
spooler.down.assert_called_once_with(sentinel_service_name, 'something')
self.assertEqual(mock_print.call_count, 0)
def test_status(self):
with self.setup_wrapper() as (spooler, mock_print):
spooler.status.return_value = (True, {})
hacheck.haupdown.status()
spooler.status.assert_called_once_with(sentinel_service_name)
mock_print.assert_called_once_with("UP\t%s", sentinel_service_name)
def test_status_downed(self):
with self.setup_wrapper() as (spooler, mock_print):
spooler.status_all_down.return_value = [(sentinel_service_name, {'service': sentinel_service_name, 'reason': ''})]
self.assertEqual(hacheck.haupdown.status_downed(), 0)
mock_print.assert_called_once_with("DOWN\t%s\t%s", sentinel_service_name, mock.ANY)
def test_list(self):
with self.setup_wrapper() as (spooler, mock_print):
with mock.patch.object(hacheck.haupdown, 'urlopen') as mock_urlopen:
mock_urlopen.return_value.read.return_value = json.dumps({
"seen_services": ["foo"],
"threshold_seconds": 10,
})
self.assertEqual(hacheck.haupdown.halist(), 0)
mock_urlopen.assert_called_once_with('http://127.0.0.1:3333/recent', timeout=mock.ANY)
mock_print.assert_called_once_with("foo")
|
Python
| 0.000001
|
@@ -600,39 +600,16 @@
ignored'
-, sentinel_service_name
%5D + list
@@ -865,16 +865,31 @@
wn.main(
+'status_downed'
)%0A
@@ -1033,32 +1033,55 @@
f.setup_wrapper(
+%5Bsentinel_service_name%5D
) as (spooler, m
@@ -1191,32 +1191,40 @@
k.haupdown.main(
+'status'
))%0A m
@@ -1412,16 +1412,24 @@
wn.main(
+'status'
))%0A
@@ -1563,32 +1563,55 @@
f.setup_wrapper(
+%5Bsentinel_service_name%5D
) as (spooler, m
@@ -1922,32 +1922,55 @@
f.setup_wrapper(
+%5Bsentinel_service_name%5D
) as (spooler, m
@@ -2294,16 +2294,39 @@
mething'
+, sentinel_service_name
%5D) as (s
@@ -2574,32 +2574,55 @@
f.setup_wrapper(
+%5Bsentinel_service_name%5D
) as (spooler, m
|
9a81d1070cae8adece92702b795bf44c66005562
|
Remove trailing whitespace
|
tests/test_configure.py
|
tests/test_configure.py
|
# Run these tests with 'nosetests':
# install the 'python-nose' package (Fedora/CentOS or Ubuntu)
# run 'nosetests' in the root of the repository
import unittest
from mock import patch
import configure
class BasicTests(unittest.TestCase):
def setUp(self):
# 'setUp' breaks Pylint's naming rules
# pylint: disable=C0103
self.cohttp_url = "https://github.com/mirage/ocaml-cohttp" \
"/archive/ocaml-cohttp-0.9.8/ocaml-cohttp-0.9.8.tar.gz"
def test_rewrite_to_distfiles(self):
url = "http://github.com/xenserver/planex"
res = configure.rewrite_to_distfiles(url)
self.assertEqual(res, "file:///distfiles/ocaml2/planex")
# Decorators are applied bottom up
@patch('os.path.exists')
@patch('configure.call') # configure adds subprocess.call to its namespace
def test_fetch_url(self, mock_subprocess_call, mock_os_path_exists):
mock_os_path_exists.return_value = False
mock_subprocess_call.return_value = 0
configure.fetch_url(self.cohttp_url)
assert mock_os_path_exists.called
mock_subprocess_call.assert_called_with(["curl", "-k", "-L", "-o",
"planex-build-root/SOURCES/ocaml-cohttp-0.9.8.tar.gz",
self.cohttp_url])
@patch('os.path.exists')
@patch('configure.call')
def test_fetch_url_existing_file(self, mock_subprocess_call,
mock_os_path_exists):
mock_os_path_exists.return_value = True
mock_subprocess_call.return_value = 0
configure.fetch_url(self.cohttp_url)
mock_os_path_exists.assert_called_with(
"planex-build-root/SOURCES/ocaml-cohttp-0.9.8.tar.gz")
assert not mock_subprocess_call.called
@patch('os.path.exists')
@patch('configure.call')
def test_fetch_url_with_rewrite(self, mock_subprocess_call,
mock_os_path_exists):
def rewrite(_url):
return "http://rewritten.com/file.tar.gz"
mock_os_path_exists.return_value = False
mock_subprocess_call.return_value = 0
configure.fetch_url(self.cohttp_url, rewrite=rewrite)
mock_os_path_exists.assert_called_with(
"planex-build-root/SOURCES/file.tar.gz")
mock_subprocess_call.assert_called_with(["curl", "-k", "-L", "-o",
"planex-build-root/SOURCES/file.tar.gz",
"http://rewritten.com/file.tar.gz"])
def test_make_extended_git_url(self):
base_url = "https://github.com/xenserver/planex"
extended_url = "https://github.com/xenserver/planex#1.0.0/" \
"%{name}-%{version}.tar.gz"
res = configure.make_extended_git_url(base_url, "1.0.0")
self.assertEqual(res, extended_url)
# We don't handle 'v1.0.0'
def test_parse_extended_git_url(self):
url = "git://github.com/xenserver/planex#1.0.0/" \
"%{name}-%{version}.tar.gz"
res = configure.parse_extended_git_url(url)
expected = ("git", "github.com", "/xenserver/planex", "1.0.0",
"%{name}-%{version}.tar.gz")
self.assertEqual(res, expected)
def test_roundtrip_extended_git_url(self):
base_url = "git://github.com/xenserver/planex"
url = configure.make_extended_git_url(base_url, "1.0.0")
res = configure.parse_extended_git_url(url)
expected = ("git", "github.com", "/xenserver/planex", "1.0.0",
"%{name}-%{version}.tar.gz")
self.assertEqual(res, expected)
def test_name_from_spec(self):
res = configure.name_from_spec("tests/data/ocaml-cohttp.spec")
self.assertEqual(res, "ocaml-cohttp")
def test_check_spec_name(self):
# check_spec_name does not exit if the name is correct
configure.check_spec_name("tests/data/ocaml-cohttp.spec")
def test_check_spec_name_fail(self):
# check_spec_name exits if the name is not correct
# self.assertRaises(SystemExit, configure.check_spec_name(
# "tests/data/bad-name.spec")) should work, but doesn't
try:
configure.check_spec_name("tests/data/bad-name.spec")
self.fail()
except SystemExit:
pass
def test_sources_from_spec(self):
res = configure.sources_from_spec("tests/data/ocaml-cohttp.spec")
self.assertEqual(res, [self.cohttp_url])
|
Python
| 0.00121
|
@@ -338,17 +338,16 @@
le=C0103
-
%0A
@@ -619,17 +619,16 @@
les(url)
-
%0A
@@ -747,33 +747,32 @@
os.path.exists')
-
%0A @patch('con
@@ -1156,33 +1156,32 @@
-k%22, %22-L%22, %22-o%22,
-
%0A %22pl
@@ -1223,33 +1223,32 @@
p-0.9.8.tar.gz%22,
-
%0A sel
@@ -1262,24 +1262,16 @@
p_url%5D)%0A
-
%0A%0A @p
@@ -1284,33 +1284,32 @@
os.path.exists')
-
%0A @patch('con
@@ -1313,33 +1313,32 @@
configure.call')
-
%0A def test_fe
@@ -1378,33 +1378,32 @@
subprocess_call,
-
%0A
@@ -1747,24 +1747,16 @@
.called%0A
-
%0A%0A @p
@@ -1777,17 +1777,16 @@
exists')
-
%0A @pa
@@ -1806,17 +1806,16 @@
e.call')
-
%0A def
@@ -1870,17 +1870,16 @@
ss_call,
-
%0A
@@ -2343,17 +2343,16 @@
%22, %22-o%22,
-
%0A
@@ -2396,17 +2396,16 @@
tar.gz%22,
-
%0A
@@ -2446,17 +2446,16 @@
r.gz%22%5D)%0A
-
%0A%0A de
@@ -3159,36 +3159,32 @@
(res, expected)%0A
-
%0A%0A def test_r
@@ -3548,20 +3548,16 @@
pected)%0A
-
%0A%0A de
|
cc934035033eff97ac698d9fa9b54b38dd2fbe9d
|
Update main.py
|
main.py
|
main.py
|
# Under MIT License, see LICENSE.txt
import sys
import argparse
from PyQt5.QtWidgets import QApplication
from qtpy import QtCore
from Controller.MainController import MainController
__author__ = 'RoboCupULaval'
def argumentParser(argument):
""" Argument parser """
parser = argparse.ArgumentParser(description='option pour initialiser le UI-debug')
parser.add_argument('use_type', metavar='use_type', type=str, default='sim',
help='use_type = sim: utilise les data de grsim dans le port 10024 (il faut set le port de '
'grsim a 10024 pour que ca marche) use_type = real: utilise le port normal de la '
'vision (10020)')
args_ = parser.parse_args(argument)
return args_
if __name__ == '__main__':
args = argumentParser(None)
app = QApplication(sys.argv)
if args.use_type == 'sim':
port = 10024
elif args.use_type == 'kalman':
port = 10022
else: # real-life
port = 10020
f = MainController(port)
f.show()
sys.exit(app.exec_())
#except NameError:
# pass
|
Python
| 0
|
@@ -57,16 +57,31 @@
rgparse%0A
+import warnings
%0A%0A%0Afrom
@@ -987,16 +987,71 @@
= 10022%0A
+ elif args.use_type == 'real':%0A port = 10020%0A
else
@@ -1054,16 +1054,22 @@
else: #
+ force
real-li
@@ -1071,16 +1071,119 @@
al-life%0A
+ warnings.warn(%22Unrecognized use_type argument. force real-life.%22, SyntaxWarning, stacklevel=2)%0A
|
c5c67d08470de703ebcd249439c5c189c487e505
|
Add a lock
|
main.py
|
main.py
|
from subprocess import Popen, PIPE
import threading
import Queue
import argparse
from itertools import product
class Tailor(threading.Thread):
def __init__(self, queue, server, file):
threading.Thread.__init__(self)
self.server = server
self.file = file
self.queue = queue
self.daemon = True
self.running = True
self.start()
def put_in_queue(self, data):
self.queue.put((self.server, self.file, data))
def connect(self):
command = ['ssh', '-t', self.server] if self.server not in ('localhost', 'local', '') else []
self.tail_process = Popen(
command + ['tail', '-f', self.file],
stdout = PIPE,
stdin = PIPE,
stderr = PIPE
)
def run(self):
self.connect()
line = self.tail_process.stdout.readline()
while line:
line = self.tail_process.stdout.readline().strip()
self.put_in_queue(line)
self.stop()
def stop(self):
if not self.running:
return self
self.running = False
print "Closing: %s:%s" % (self.server, self.file)
try:
self.tail_process.terminate()
finally:
self._Thread__stop()
return self
def run(files, servers):
queue = Queue.Queue()
trailers = [Tailor(queue, server, file) for server, file in product(servers, files)]
colors = { f: (91 + i) % 100 for i,f in enumerate(files) } if len(files)>1 else None
tail(queue, colors, trailers)
def print_with_color(data, color):
print "\033[%dm%s\033[0m" % (color, data)
def tail(queue, colors, trailers):
try:
while True:
if queue.empty():
continue
server, file, data = queue.get_nowait()
if colors:
print_with_color(data + "\r", colors[file])
else:
print data + "\r"
except KeyboardInterrupt:
for t in trailers:
t.stop().join()
def parse_args():
parser = argparse.ArgumentParser(description = 'Tail a file across multiple servers')
parser.add_argument('files',
type = str,
help = 'The path to the file you want to tail'
)
parser.add_argument('servers',
type = str,
default = 'local',
nargs = '?',
help = 'A comma seperated list of servers to connect to. local for files on your computer'
)
args = parser.parse_args()
servers = map(lambda x: x.strip(), args.servers.split(','))
files = map(lambda x: x.strip(), args.files.split(','))
return files, servers
if __name__ == "__main__":
run(*parse_args())
|
Python
| 0.00001
|
@@ -177,18 +177,45 @@
er, file
-):
+, lock):%0A self.lock = lock
%0A thr
@@ -479,24 +479,186 @@
nect(self):%0A
+ #I was getting some weird results where one thread would block out another%0A #acquiring releasing the lock seems to work%0A self.lock.acquire()%0A try:%0A
command
@@ -743,24 +743,26 @@
else %5B%5D%0A
+
self.tail_pr
@@ -776,16 +776,18 @@
Popen(%0A
+
co
@@ -821,16 +821,18 @@
.file%5D,%0A
+
st
@@ -850,16 +850,18 @@
,%0A
+
stdin =
@@ -862,24 +862,26 @@
din = PIPE,%0A
+
stderr
@@ -892,16 +892,87 @@
IPE%0A
+ )%0A except:%0A self.stop()%0A finally:%0A self.lock.release(
)%0A%0A def
@@ -1464,16 +1464,42 @@
Queue()%0A
+ lock = threading.Lock()%0A
traile
@@ -1530,16 +1530,22 @@
er, file
+, lock
) for se
@@ -1670,16 +1670,86 @@
se None%0A
+ if colors:%0A for f in files:%0A print_with_color(f, colors%5Bf%5D)%0A
tail(q
@@ -2259,16 +2259,41 @@
l a file
+%5Bs%5D across locally and/or
across
@@ -2765,18 +2765,45 @@
turn fil
-es
+ter(bool, files), filter(bool
, server
@@ -2803,16 +2803,17 @@
servers
+)
%0A%0Aif __n
|
473ff95fcd1ac784cc3492a4727d668a10270594
|
add today filter
|
main.py
|
main.py
|
# -*- coding: utf-8 -*-
import sys
import urllib
import subprocess
import argparse
# Constants
URL = "http://www.gifu-nct.ac.jp/gakka/keijiyou/keijiyou.pdf"
LOCALPDF = "keijiyou.pdf"
LOCALTEXT = "keijiyou.txt"
def download():
urllib.urlretrieve(URL, LOCALPDF)
def pre_parse():
cmd = "pdftotext -raw " + LOCALPDF + " " + LOCALTEXT
#print("done:" + cmd)
let = subprocess.check_call( cmd.split(" ") )
return let
def filter1(gakunen, gakka, map):
return filter(lambda item:item['gakka'] is gakka and item['gakunen'] is gakunen, map)
def filter2(gakunen, map):
return filter(lambda item:item['gakunen'] is gakunen, map)
def parse():
map = []
for line in open(LOCALTEXT, "r"):
terms = line.split(" ")
# discard headers
# change conditions if need
if line.find("教員名") is not -1 or len(terms) < 5 or line is "":
continue
# read body
map.append({
'date': terms[0],
'weeks': terms[1],
'jigen': terms[2],
'gakka': terms[3],
'gakunen': terms[4],
'old': terms[5],
'new': terms[7].replace("\n","") if 7 < len(terms) else "空きコマ"
})
return map
if __name__ == "__main__":
# arg check
parser = argparse.ArgumentParser()
parser.add_argument('--cache',help='Using cache, not download original pdf')
parser.add_argument('--filter',help='[1E|2E|2C etc...]')
args = parser.parse_args()
# execute
if args.cache is not None:
download()
pre_parse()
data = parse()
# use filter
if args.filter is not None:
data = filter1(args.filter[0], args.filter[1], data)
if len(data) is 0:
print "No data."
for item in data:
print item['date'] + item['weeks'] + item['jigen'] + " " + item['gakunen'] + item['gakka'] + " " + item['old'] + " -> " + item['new']
|
Python
| 0
|
@@ -77,16 +77,33 @@
rgparse%0A
+import datetime%0A%0A
%0A# Const
@@ -445,16 +445,128 @@
rn let%0A%0A
+def get_date():%0A today = datetime.date.today()%0A return str(today.monnth+1) + %22%E6%9C%88%22 + str(today.day) + %22%E6%97%A5%22%0A%0A%0A
def filt
@@ -771,24 +771,112 @@
nen, map) %0A%0A
+def filter_today(map):%0A return filter(lambda item:item%5B'date'%5D is get_date(), map) %0A%0A
def parse():
@@ -1666,16 +1666,64 @@
c...%5D')%0A
+ parser.add_argument('--date', help='today')%0A
args
@@ -1964,21 +1964,96 @@
, data)%0A
-
%0A
+ if args.date is %22today%22:%0A date = filter_today(map)%0A%0A # print%0A
if l
|
34bd4dec6bc60ff676874c13cb993a8123bd0ddc
|
handle the exception of an invalid bitly url
|
main.py
|
main.py
|
#!/usr/bin/python
import urllib
import urllib2
import json
import settings as s
class ConsoleBitly:
def shorten(self,req):
url="http://api.bitly.com/v3/shorten?login="+s.bitly_username+"&apiKey="+s.bitly_apikey+"&longUrl="+req
print "Please wait... \n"
response=urllib2.urlopen(url)
a = json.loads(response.read())
print "\nShortened URL is: \033[1;36m"+a['data']['url']+"\033[1;m\n"
def expand(self,req):
url="http://api.bitly.com/v3/expand?login="+s.bitly_username+"&apiKey="+s.bitly_apikey+"&shortUrl="+req
print "Please wait... \n"
response=urllib2.urlopen(url)
a = json.loads(response.read())
print "\nExpanded URL is: \033[1;36m"+a['data']['expand'][0]['long_url']+"\033[1;m\n"
c=ConsoleBitly()
req=raw_input("Enter the URL to be shortened: ")
c.expand(req)
|
Python
| 0.000149
|
@@ -407,32 +407,40 @@
pand(self,req):%0A
+%09%09try:%0A%09
%09%09url=%22http://ap
@@ -521,32 +521,33 @@
&shortUrl=%22+req%0A
+%09
%09%09print %22Please
@@ -552,32 +552,33 @@
e wait... %5Cn%22%0A%09%09
+%09
response=urllib2
@@ -583,32 +583,33 @@
b2.urlopen(url)%0A
+%09
%09%09a = json.loads
@@ -618,32 +618,33 @@
esponse.read())%0A
+%09
%09%09print %22%5CnExpan
@@ -714,16 +714,143 @@
3%5B1;m%5Cn%22
+%0A%09%09except:%0A%09%09%09print %22%5C033%5B1;31mThe provided url might not be of a bit.ly domain OR shortened version does not exist!%5C033%5B1;m%5Cn%22
%0A%0Ac=Cons
|
b57e12c4e01559ce5bcb1588b14758429ad552df
|
Revert "fix: error instance to pytest"
|
tests/test_envconfig.py
|
tests/test_envconfig.py
|
import pytest
@pytest.mark.parametrize("attribute, value", [
('ATTRIBUTE_STR', 'default_str'),
('ATTRIBUTE_INT', 1),
('ATTRIBUTE_FLOAT', 1.5),
('ATTRIBUTE_BOOL', True),
])
def test_get_attributes(config, attribute, value):
assert getattr(config, attribute) == value
def test_set_existing_attribute(config, sentinel):
config.ATTRIBUTE_STR = sentinel
assert config.ATTRIBUTE_STR == sentinel
def test_set_existing_attribute_gets_overridden(config, mock_env, sentinel):
mock_env({'ATTRIBUTE_INT': '1'})
config.ATTRIBUTE_INT = sentinel
assert config.ATTRIBUTE_INT == 1
def test_set_new_attribute_gets_overridden(config, mock_env, sentinel):
mock_env({'ATTRIBUTE_NEW': 'hello attr'})
config.ATTRIBUTE_NEW = sentinel
assert config.ATTRIBUTE_NEW == 'hello attr'
def test_no_attribute(config):
assert not hasattr(config, 'MISSING_ATTRIBUTE')
def test_add_attribute(config, sentinel):
config.NEW_ATTRIBUTE = sentinel
assert config.NEW_ATTRIBUTE == sentinel
@pytest.mark.parametrize("attribute, value_type, new_value_in, new_value_out", [
("ATTRIBUTE_STR", str, 'new value', 'new value'),
("ATTRIBUTE_INT", int, '12345', 12345),
("ATTRIBUTE_FLOAT", float, '3.14', 3.14),
("ATTRIBUTE_BOOL", bool, 'yes', True),
])
def test_env_override(config, mock_env, attribute, value_type, new_value_in, new_value_out):
mock_env({attribute: new_value_in})
assert getattr(config, attribute) == new_value_out
assert type(getattr(config, attribute)) == value_type
def test_cant_parse(config, mock_env):
mock_env({'ATTRIBUTE_INT': 'string'})
with pytest.raises(AttributeError()):
print(config.ATTRIBUTE_INT)
|
Python
| 0
|
@@ -1659,10 +1659,8 @@
rror
-()
):%0A
|
86b1574c6a3c379d104433f4b57eca8c65e454fe
|
fix prefix
|
main.py
|
main.py
|
# coding=utf-8
from base64 import b64decode, b64encode
from os import environ
import urllib
from zlib import decompress, MAX_WBITS
from bs4 import BeautifulSoup
from flask import Flask, request, jsonify
from google.appengine.api import urlfetch
from requests import Session
from re import compile as re_compile
app = Flask(__name__)
app.config['DEBUG'] = True
dr_code = re_compile(ur"^[0-9]*[dDдД]?[0-9]*[rRрР][0-9]*$")
try:
from bot_token import BOT_TOKEN
except ImportError:
BOT_TOKEN = environ["TOKEN"]
SESSIONS = {}
URL = "https://api.telegram.org/bot%s/" % BOT_TOKEN
MyURL = "https://dzzzr-bot.appspot.com"
class DozoR(object):
def __init__(self, chat_id):
self.chat_id = chat_id
self.url = ""
self.prefix = ""
self.browser = Session()
def set_dzzzr(self, arguments):
try:
arguments = arguments.split()
if len(arguments) > 2:
self.url, captain, pin, login, password = arguments[:5]
else:
raise ValueError
self.prefix = arguments[6] if len(arguments) > 5 else ""
except ValueError:
return {
'chat_id': self.chat_id,
'text': "Usage: \n"
"/set_dzzzr url captain pin login password [prefix]"
}
else:
self.browser.headers.update({'referer': self.url})
self.browser.auth = (captain, pin)
login_page = self.browser.post(
self.url,
data={'login': login,
'password': password,
'action': "auth", 'notags': ''})
if login_page.status_code != 200:
return {
'chat_id': self.chat_id,
'text': "Not authorized"
}
else:
return {
'chat_id': self.chat_id,
'text': "Welcome %s" % login
}
def not_found(self, _):
return {
'chat_id': self.chat_id,
'text': "Command not found. Try /help"
}
def start(self, _):
return {'chat_id': self.chat_id, 'text': "I am awake!"}
def about(self, _):
return {
'chat_id': self.chat_id,
'text': "Hey!\n"
"My author is @m_messiah."
"You can find this nickname at:"
"\t+ Telegram"
"\t+ Twitter"
"\t+ Instagram"
"\t+ VK"
"\t+ GitHub (m-messiah)"
}
def base64(self, arguments):
response = {'chat_id': self.chat_id}
try:
response['text'] = b64decode(arguments.encode("utf8"))
assert len(response['text'])
except:
response['text'] = b64encode(arguments.encode("utf8"))
finally:
return response
def handle(self, text, reply_id=None):
if text[0] == '/':
command, _, arguments = text.partition(" ")
app.logger.debug("REQUEST\t%s\t%s\t'%s'",
self.chat_id,
command.encode("utf8"),
arguments.encode("utf8"))
if command == "/set_dzzzr":
#if str(sender['id']) == "3798371":
try:
return self.set_dzzzr(arguments)
except Exception as e:
return {'chat_id': self.chat_id,
'text': "Incorrect format (%s)" % e}
else:
return getattr(self, command[1:], self.not_found)(arguments)
else:
response = self.code(text, reply_id)
if response:
return response
def code(self, text, reply_id):
def send(browser, url, code):
if url == "":
return code + u" - сначала надо войти в движок"
answer = browser.post(url, data={'action': "entcod",
'cod': code})
if not answer:
return code + u" - Нет ответа. Проверьте вручную."
answer = BeautifulSoup(
decompress(answer.content, 16 + MAX_WBITS)
.decode("cp1251", "ignore"),
'html.parser'
)
message = answer.find(class_="sysmsg")
return code + " - " + (message.string if message and message.string
else u"нет ответа.")
response = {'chat_id': self.chat_id}
if reply_id:
response['reply_to_message_id'] = reply_id
codes = text.split()
result = []
for code in codes:
if dr_code.match(code):
code = code.upper().translate({ord(u'Д'): u'D',
ord(u'Р'): u'R'})
if "D" not in code:
code = self.prefix + code
result.append(send(self.browser, self.url, code))
if len(result):
response['text'] = u"\n".join(result).encode("utf8")
return response
else:
if u" бот" in text[-5:]:
response['text'] = u"хуебот".encode("utf8")
return response
if u"Привет" in text:
response['text'] = u"Привет!".encode("utf8")
return response
return None
def error():
return 'Hello World! I am DR bot (https://telegram.me/DzzzzR_bot)'
def send_reply(response):
app.logger.debug("SENT\t%s", response)
payload = urllib.urlencode(response)
if 'sticker' in response:
urlfetch.fetch(url=URL + "sendSticker",
payload=payload,
method=urlfetch.POST)
elif 'text' in response:
if response['text'] == '':
return
o = urlfetch.fetch(URL + "sendMessage",
payload=payload,
method=urlfetch.POST)
app.logger.debug(str(o.content))
@app.route('/', methods=['POST', 'GET'])
def index():
if request.method == 'GET':
return error()
else:
if 'Content-Type' not in request.headers:
return error()
if request.headers['Content-Type'] != 'application/json':
return error()
app.logger.debug("Request: %s", request)
try:
update = request.json
message = update['message']
sender = message['chat']
text = message.get('text')
if text:
app.logger.debug("MESSAGE FROM\t%s",
sender['username'] if 'username' in sender
else sender['id'])
if sender['id'] not in SESSIONS:
SESSIONS[sender['id']] = DozoR(sender['id'])
response = SESSIONS[sender['id']].handle(text)
if response:
send_reply(response)
return jsonify(result="OK", text="Accepted")
except Exception as e:
app.logger.warning(str(e))
return jsonify(result="Fail", text=str(e))
@app.errorhandler(404)
def page_not_found(e):
"""Return a custom 404 error."""
return 'Sorry, nothing at this URL.', 404
|
Python
| 0.000075
|
@@ -909,17 +909,17 @@
ents) %3E
-2
+4
:%0A
@@ -1072,17 +1072,17 @@
guments%5B
-6
+5
%5D if len
|
22675199efd1ee80304ed31a108505d84341d5ab
|
fix tests
|
tests/test_genomeops.py
|
tests/test_genomeops.py
|
import pandas as pd
import bioframe
import numpy as np
from io import StringIO
import os.path as op
import pytest
testdir = op.realpath(op.dirname(__file__))
### todo: test make_chromarms(chromsizes, mids, binsize=None, suffixes=("p", "q")):
def test_binnify():
chromsizes = bioframe.read_chromsizes(testdir+"/test_data/test.chrom.sizes")
assert len(chromsizes) == 2
assert len(bioframe.binnify(chromsizes, int(np.max(chromsizes.values)))) == len(
chromsizes
)
assert len(bioframe.binnify(chromsizes, int(np.min(chromsizes.values)))) == (
len(chromsizes) + 1
)
assert len(bioframe.binnify(chromsizes, 1)) == np.sum(chromsizes.values)
def test_digest():
pytest.importorskip("Bio")
fasta_records = bioframe.load_fasta(testdir+"/test_data/test.fa")
assert len(fasta_records) == 2
### no HindIII sites in the test.fa fasta records, so shouldn't change shape[0]
assert bioframe.digest(fasta_records, "HindIII").shape == (2, 3)
### one DpnII site on chrTEST2, shape[0] should increase by one
assert bioframe.digest(fasta_records, "DpnII").shape == (3, 3)
### DpnII site is on chrTEST2 position 3, first interval of chrTEST2 should end at 3
assert bioframe.digest(fasta_records, "DpnII").iloc[1].end == 3
def test_frac_mapped():
pytest.importorskip("pysam")
chromsizes = bioframe.read_chromsizes(testdir+"/test_data/test.chrom.sizes")
fasta_records = bioframe.load_fasta(testdir+"/test_data/test.fa")
unmapped = np.array([1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0])
assert (
unmapped
== bioframe.frac_mapped(
bioframe.binnify(chromsizes, 1), fasta_records, return_input=False
).values
).all()
unmapped = np.array([0.8, 0.8, 0])
assert (
unmapped
== bioframe.frac_mapped(
bioframe.binnify(chromsizes, 5), fasta_records, return_input=False
).values
).all()
unmapped = np.array([0.8, 4 / 7])
assert (
unmapped
== bioframe.frac_mapped(
bioframe.binnify(chromsizes, 7), fasta_records, return_input=False
).values
).all()
def test_frac_gc():
pytest.importorskip("pysam")
chromsizes = bioframe.read_chromsizes(testdir+"/test_data/test.chrom.sizes")
fasta_records = bioframe.load_fasta(testdir+"/test_data/test.fa")
unmapped_bp = (
0
== bioframe.frac_mapped(
bioframe.binnify(chromsizes, 1), fasta_records, return_input=False
).values
)
assert np.isnan(
bioframe.frac_gc(
bioframe.binnify(chromsizes, 1),
fasta_records,
return_input=False,
mapped_only=True,
).values[unmapped_bp]
).all()
## mapped_only=True should ignore N or return np.nan if interval only contains N
np.testing.assert_equal(
np.array([0.5, 0.5, np.nan]),
bioframe.frac_gc(
bioframe.binnify(chromsizes, 5),
fasta_records,
return_input=False,
mapped_only=True,
).values,
)
assert (
np.array([0.5, 0.5])
== bioframe.frac_gc(
bioframe.binnify(chromsizes, 7),
fasta_records,
return_input=False,
mapped_only=True,
).values
).all()
## mapped_only=False should count N as zero
assert (
np.array([0.4, 0.4, 0])
== bioframe.frac_gc(
bioframe.binnify(chromsizes, 5),
fasta_records,
return_input=False,
mapped_only=False,
).values
).all()
assert (
np.array([0.4, 2 / 7])
== bioframe.frac_gc(
bioframe.binnify(chromsizes, 7),
fasta_records,
return_input=False,
mapped_only=False,
).values
).all()
### todo: test frac_gene_coverage(bintable, mrna):
### currently broken
|
Python
| 0.000001
|
@@ -335,24 +335,45 @@
chrom.sizes%22
+, filter_chroms=False
)%0A assert
|
e392fa449150d91dcd07de00c4b9f8133d66e97f
|
convert a genbank file to a ppt file
|
genbank_to_ppt/genbank_to_ppt.py
|
genbank_to_ppt/genbank_to_ppt.py
|
"""
Convert a genbank file to a .ppt file
This is a simple genbank to tbl converter using BioPython
"""
import os
import sys
import binascii
import gzip
import re
from Bio import SeqIO
def is_gzip(gbkf):
"""
Is the file compressed?
:param gbkf:
:return: true if compressed else false
"""
with open(gbkf, 'rb') as i:
return binascii.hexlify(i.read(2)) == b'1f8b'
def feat_to_text(feat, qual):
if qual in feat.qualifiers:
return " ".join(feat.qualifiers[qual])
return "-"
def convert_genbank(gbkf, printout=False, verbose=False):
"""
Convert the genbank file to a table with the same columns of the ppt file
:param gbkf: the genbank input file
:param printout: print the table
:param verbose: more output
:return: the table
"""
res = []
if is_gzip(gbkf):
handle = gzip.open(gbkf, 'rt')
else:
handle = open(gbkf, 'r')
gire = re.compile('GI:(\d+)')
cogre = re.compile('(COG\S+)')
for seq in SeqIO.parse(handle, "genbank"):
if verbose:
sys.stderr.write(f"Parsing {seq.id}\n")
for feat in seq.features:
if feat.type != "CDS":
continue
gi = "-"
if gire.match(feat_to_text(feat, 'db_xref')):
gi = gire.match(feat_to_text(feat, 'db_xref'))[1]
cog = "-"
if cogre.match(feat_to_text(feat, 'product')):
cog = cogre.match(feat_to_text(feat, 'product'))[1]
if 'gene' in feat.qualifiers:
gene = " ".join(feat.qualifiers)
thisres = [
f"{feat.location.start}..{feat.location.end}",
"+" if feat.strand >= 0 else "-",
(feat.length / 3) - 1,
gi,
feat_to_text(feat, 'gene'),
feat_to_text(feat, 'locus_tag'),
cog,
feat_to_text(feat, 'product')
]
if printout:
print("\t".join(thisres))
res.append(thisres)
return res
|
Python
| 0.00152
|
@@ -1748,20 +1748,22 @@
+(len
(feat.
-length
+seq)
/ 3
|
484b0d1d764a413f54f9e5f6f99eca84e6a947cd
|
Make rocket threads daemonized. Ignore tickets and sessions
|
main.py
|
main.py
|
# -*- coding: utf-8 -*-
import sys
import socket
import logging
import traceback
from select import select
from . import SERVER_NAME
from .worker import get_method
class Rocket:
def __init__(self,
app_info,
method='test',
bind_addr = ('127.0.0.1', 8000),
max_threads = 0,
min_threads = 10,
timeout = 10):
self.address = bind_addr[0]
self.port = bind_addr[1]
self._worker = get_method(method)
self._worker.app_info = app_info
self._worker.stopServer = False
self._worker.min_threads = min_threads
self._worker.max_threads = max_threads
self._worker.timeout = timeout
self._worker.threads.update([self._worker() for k in range(min_threads)])
def start(self):
for thread in self._worker.threads:
thread.start()
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if not self.socket:
logging.error("Failed to get socket.")
raise socket.error
try:
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except:
msg = "Cannot share socket. Using {0}:{1} exclusively."
logging.warning(msg.format(self.address, self.port))
try:
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
except:
msg = "Cannot set TCP_NODELAY, things might run a little slower"
logging.warning(msg)
try:
self.socket.bind((self.address,int(self.port)))
except:
msg = "Socket {0}:{1} in use by other process and it won't share."
logging.error(msg)
sys.exit(1)
self.socket.listen(socket.SOMAXCONN)
try:
while not self._worker.stopServer:
try:
if select([self.socket], [], [], 1.0)[0]:
self._worker.queue.put(self.socket.accept())
except KeyboardInterrupt:
return self.stop()
except Exception:
logging.warn(str(traceback.format_exc()))
continue
except:
logging.error(str(traceback.format_exc()))
return self.stop()
def stop(self):
logging.info("Stopping Server")
break_loop = 10
for t in range(len(self._worker.threads)):
self._worker.queue.put((None,None))
while len(self._worker.threads) and break_loop != 0:
try:
if 'client_socket' in self._worker.threads:
logging.debug("Shutting down client on thread")
self._worker.threads.client_socket.shutdown(socket.SHUT_RDWR)
else:
logging.warning("'client' not in thread")
break_loop -= 1
except:
logging.warning(traceback.format_exc())
break_loop -= 1
|
Python
| 0
|
@@ -500,16 +500,20 @@
worker =
+ W =
get_met
@@ -533,28 +533,17 @@
-self._worker
+W
.app_inf
@@ -563,28 +563,17 @@
-self._worker
+W
.stopSer
@@ -592,28 +592,17 @@
-self._worker
+W
.min_thr
@@ -628,28 +628,17 @@
-self._worker
+W
.max_thr
@@ -664,28 +664,17 @@
-self._worker
+W
.timeout
@@ -696,49 +696,26 @@
-self._worker.threads.update(%5Bself._worker
+W.threads = set(%5BW
() f
@@ -801,32 +801,65 @@
worker.threads:%0A
+ thread.daemon = True%0A
thre
@@ -2384,16 +2384,41 @@
oop = 10
+%0A W = self._worker
%0A%0A
@@ -2434,36 +2434,25 @@
n range(len(
-self._worker
+W
.threads)):%0A
@@ -2459,36 +2459,25 @@
-self._worker
+W
.queue.put((
@@ -2507,28 +2507,17 @@
ile len(
-self._worker
+W
.threads
@@ -2590,36 +2590,25 @@
_socket' in
-self._worker
+W
.threads:%0A
@@ -2693,28 +2693,17 @@
-self._worker
+W
.threads
@@ -2794,22 +2794,20 @@
logging.
-warnin
+debu
g(%22'clie
@@ -2914,16 +2914,78 @@
warning(
+'Failed to stop thread: %5Cn'%0A +
tracebac
|
f5ffdefed84c7ddc6dbb4ea897e9f476b5b4d245
|
Add squares to table.
|
main.py
|
main.py
|
class Square:
def __init__(self, coords):
pass
def add_mark(self, player):
pass
class Line:
def __init__(self, params):
pass
def squares(self):
pass
def win(self):
pass
def not_winnable(self):
pass
class TTT_Table:
def __init__(self, base, power, players):
self.base = base
self.power = power
self.players = players
self.turn = self.players[0]
def add_squares_recursive(self):
pass
def list_lines(self):
pass
def win(self):
pass
def add_mark(self, player):
pass
class Player:
def __init__(self, name, mark)
self.name = name
self.mark = mark
|
Python
| 0.000005
|
@@ -331,16 +331,85 @@
= power%0A
+%09%09self.squares = %7B%7D%0A%09%09self.add_squares_recursive(self.power - 1, %5B%5D)%0A
%09%09self.p
@@ -485,33 +485,234 @@
cursive(self
-):%0A%09%09pass
+, powerleft, list):%0A%09%09for i in range(0, self.power):%0A%09%09%09if powerleft == 0:%0A%09%09%09%09self.squares%5B''.join(list + %5Bstr(i)%5D)%5D = Square(list + %5Bi%5D)%0A%09%09%09else:%0A%09%09%09%09self.add_squares_recursive(powerleft - 1, list + %5Bstr(i)%5D)
%0A%09%09%0A%09def lis
@@ -846,16 +846,17 @@
e, mark)
+:
%0A%09%09self.
@@ -888,8 +888,57 @@
mark%0A%09%0A
+table = TTT_Table(4, 4, %5B1%5D)%0Aprint(table.squares)
|
f082a6839cb3d8586c7949951035003dbce1d14b
|
Rename some tests to be more explicit
|
tests/test_paragraph.py
|
tests/test_paragraph.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from lxml import etree
from . import xhtml2odt
class ParagraphElements(unittest.TestCase):
def test_p1(self):
html = '<html xmlns="http://www.w3.org/1999/xhtml"><p>Test</p></html>'
odt = xhtml2odt(html)
print odt
assert str(odt) == """<?xml version="1.0" encoding="utf-8"?>
<text:p xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" text:style-name="Text_20_body">Test</text:p>
"""
def test_p_inside_ul(self):
html = '<html xmlns="http://www.w3.org/1999/xhtml"><p><ul><li>Test</li></ul></p></html>'
odt = xhtml2odt(html)
print odt
assert str(odt) == """<?xml version="1.0" encoding="utf-8"?>
<text:list xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" text:style-name="List_20_1">
<text:list-item>
<text:p text:style-name="list-item-bullet">Test</text:p>
</text:list-item>
</text:list>
"""
def test_p_inside_ol(self):
html = '<html xmlns="http://www.w3.org/1999/xhtml"><p><ol><li>Test</li></ol></p></html>'
odt = xhtml2odt(html)
print odt
assert str(odt) == """<?xml version="1.0" encoding="utf-8"?>
<text:list xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" text:style-name="Numbering_20_1">
<text:list-item>
<text:p text:style-name="list-item-number">Test</text:p>
</text:list-item>
</text:list>
"""
def test_p_inside_blockquote(self):
html = '<html xmlns="http://www.w3.org/1999/xhtml"><p><blockquote><p>Test</p></blockquote></p></html>'
odt = xhtml2odt(html)
print odt
assert str(odt) == """<?xml version="1.0" encoding="utf-8"?>
<text:p xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" text:style-name="Quotations">Test</text:p>
"""
def test_p_inside_pre(self):
html = '<html xmlns="http://www.w3.org/1999/xhtml"><p><pre>Test</pre></p></html>'
odt = xhtml2odt(html)
print odt
assert str(odt) == """<?xml version="1.0" encoding="utf-8"?>
<text:p xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" text:style-name="Preformatted_20_Text">Test</text:p>
"""
def test_p_center1(self):
"""<p> tag: with text-align: center (space)"""
html = '<html xmlns="http://www.w3.org/1999/xhtml"><p style="text-align: center">Test</p></html>'
odt = xhtml2odt(html)
print odt
assert str(odt) == """<?xml version="1.0" encoding="utf-8"?>
<text:p xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" text:style-name="center">Test</text:p>
"""
def test_p_center2(self):
"""<p> tag: with text-align:center (no space)"""
html = '<html xmlns="http://www.w3.org/1999/xhtml"><p style="text-align:center">Test</p></html>'
odt = xhtml2odt(html)
print odt
assert str(odt) == """<?xml version="1.0" encoding="utf-8"?>
<text:p xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" text:style-name="center">Test</text:p>
"""
if __name__ == '__main__':
unittest.main()
|
Python
| 0.000528
|
@@ -501,22 +501,26 @@
test_p_
-inside
+containing
_ul(self
@@ -969,22 +969,26 @@
test_p_
-inside
+containing
_ol(self
@@ -1442,22 +1442,26 @@
test_p_
-inside
+containing
_blockqu
@@ -1834,14 +1834,18 @@
t_p_
-inside
+containing
_pre
|
44795b29dbeac606e2110ac676c20d2eb7f3edf9
|
add patches
|
custom/icds/tests/test_aww_no_submissions.py
|
custom/icds/tests/test_aww_no_submissions.py
|
from __future__ import absolute_import
from __future__ import unicode_literals
from datetime import datetime, timedelta
from django.test import TestCase
import mock
from corehq.apps.domain.shortcuts import create_domain
from corehq.apps.locations.tests.util import make_loc, setup_location_types
from corehq.apps.users.models import CommCareUser
from corehq.warehouse.models import ApplicationDim, ApplicationStatusFact, Batch, UserDim
from custom.icds.messaging.custom_content import run_indicator_for_user
from custom.icds.messaging.indicators import AWWSubmissionPerformanceIndicator
@mock.patch('custom.icds.messaging.indicators.get_warehouse_latest_modified_date', return_value=datetime.utcnow())
class TestAWWSubmissionPerformanceIndicator(TestCase):
domain = 'domain'
@classmethod
def setUpClass(cls):
super(TestAWWSubmissionPerformanceIndicator, cls).setUpClass()
cls.domain_obj = create_domain(cls.domain)
def make_user(name, location):
user = CommCareUser.create(cls.domain, name, 'password')
user.set_location(location)
return user
cls.loc_types = setup_location_types(cls.domain, ['awc'])
cls.loc = make_loc('awc', type='awc', domain=cls.domain)
cls.user = make_user('user', cls.loc)
cls.user_sans_app_status = make_user('user_sans_app_status', cls.loc)
cls.batch = Batch.objects.create(
start_datetime=datetime.now(),
end_datetime=datetime.now(),
completed_on=datetime.now(),
dag_slug='batch',
)
cls.app_dim = ApplicationDim.objects.create(
batch=cls.batch,
domain=cls.domain,
application_id=100007,
name='icds-cas',
deleted=False,
)
cls.user_dim = UserDim.objects.create(
batch=cls.batch,
user_id=cls.user.get_id,
username=cls.user.username,
user_type=cls.user._get_user_type(),
doc_type=cls.user.doc_type,
date_joined=datetime.utcnow() - timedelta(days=5000),
deleted=False,
)
cls.app_fact = ApplicationStatusFact.objects.create(
batch=cls.batch,
app_dim=cls.app_dim,
user_dim=cls.user_dim,
domain=cls.domain,
last_form_submission_date=None,
)
@classmethod
def tearDownClass(cls):
cls.domain_obj.delete()
super(TestAWWSubmissionPerformanceIndicator, cls).tearDownClass()
# warehouse entities are cleaned up by db transaction rollback
@property
def now(self):
return datetime.utcnow()
def test_form_sent_today(self):
self.app_fact.last_form_submission_date = self.now
self.app_fact.save()
messages = run_indicator_for_user(self.user, AWWSubmissionPerformanceIndicator, language_code='en')
self.assertEqual(len(messages), 0)
def test_form_sent_just_under_seven_days_ago(self):
self.app_fact.last_form_submission_date = self.now - timedelta(days=6, hours=23)
self.app_fact.save()
messages = run_indicator_for_user(self.user, AWWSubmissionPerformanceIndicator, language_code='en')
self.assertEqual(len(messages), 0)
def test_form_sent_eight_days_ago(self):
self.app_fact.last_form_submission_date = self.now - timedelta(days=8)
self.app_fact.save()
messages = run_indicator_for_user(self.user, AWWSubmissionPerformanceIndicator, language_code='en')
self.assertEqual(len(messages), 1)
self.assertIn('one week', messages[0])
def test_form_sent_thirty_days_ago(self):
self.app_fact.last_form_submission_date = self.now - timedelta(days=29, hours=23)
self.app_fact.save()
messages = run_indicator_for_user(self.user, AWWSubmissionPerformanceIndicator, language_code='en')
self.assertEqual(len(messages), 1)
self.assertIn('one week', messages[0])
def test_form_sent_thirty_one_days_ago(self):
self.app_fact.last_form_submission_date = self.now - timedelta(days=31)
self.app_fact.save()
messages = run_indicator_for_user(self.user, AWWSubmissionPerformanceIndicator, language_code='en')
self.assertEqual(len(messages), 1)
self.assertIn('one month', messages[0])
def test_no_last_form_submission(self):
self.app_fact.last_form_submission_date = None
self.app_fact.save()
messages = run_indicator_for_user(self.user, AWWSubmissionPerformanceIndicator, language_code='en')
self.assertEqual(len(messages), 1)
self.assertIn('one month', messages[0])
def test_no_app_status_fact(self):
messages = run_indicator_for_user(
self.user_sans_app_status,
AWWSubmissionPerformanceIndicator,
language_code='en',
)
self.assertEqual(len(messages), 1)
self.assertIn('one month', messages[0])
|
Python
| 0.000001
|
@@ -2698,27 +2698,34 @@
t_today(self
+, patch
):%0A
-
self
@@ -2997,32 +2997,39 @@
en_days_ago(self
+, patch
):%0A self.
@@ -3319,32 +3319,39 @@
ht_days_ago(self
+, patch
):%0A self.
@@ -3679,32 +3679,39 @@
ty_days_ago(self
+, patch
):%0A self.
@@ -4058,24 +4058,31 @@
ays_ago(self
+, patch
):%0A s
@@ -4418,24 +4418,31 @@
mission(self
+, patch
):%0A s
@@ -4708,32 +4708,32 @@
, messages%5B0%5D)%0A%0A
-
def test_no_
@@ -4748,24 +4748,31 @@
us_fact(self
+, patch
):%0A m
|
a28eedba060934d498ac38e8704022dc38c43758
|
Add stringio from six
|
tests/test_utilities.py
|
tests/test_utilities.py
|
from subprocess import Popen, PIPE
from StringIO import StringIO
import sys
class Capturing(list):
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._stringio = StringIO()
return self
def __exit__(self, *args):
self.extend(self._stringio.getvalue().splitlines())
sys.stdout = self._stdout
class Capturing_err(list):
def __enter__(self):
self._stderr = sys.stderr
sys.stderr = self._stringio = StringIO()
return self
def __exit__(self, *args):
self.extend(self._stringio.getvalue().splitlines())
sys.stderr = self._stderr
def terminal(command):
return Popen(command, stdout=PIPE, stderr=PIPE).communicate()
|
Python
| 0.999564
|
@@ -33,24 +33,19 @@
PE%0Afrom
-StringIO
+six
import
|
75b628453463a4199468b9f45dc80c22725c2b93
|
remove unised import
|
tests/testapp/models.py
|
tests/testapp/models.py
|
# coding=utf-8
from __future__ import absolute_import, unicode_literals
from django.db import models
from model_utils import FieldTracker
from tests.testapp.constants import ModelState
from tximmutability.models import MutableModel
from tximmutability.rule import MutabilityRule
class AbstractImmutableModel(MutableModel):
name = models.CharField(
null=False, max_length=50, default='Immutable Model'
)
state = models.CharField(max_length=50, default=ModelState.IMMUTABLE_STATE)
@staticmethod
def get_mutability_rule(**kwargs):
field = kwargs.pop('field', None)
field_name = 'state' if field is None else field
return MutabilityRule(
field_name, values=(ModelState.MUTABLE_STATE,), **kwargs
)
class Meta:
abstract = True
def saved_value(self, field):
# self.refresh_from_db()
hints = {'instance': self}
db_instance_qs = (
self.__class__._base_manager.db_manager(hints=hints)
.filter(pk=self.pk)
.only(field)
)
return getattr(db_instance_qs.get(), 'state')
class BaseImmutableModel(AbstractImmutableModel):
description = models.CharField(null=True, max_length=250)
mutability_rules = (
AbstractImmutableModel.get_mutability_rule(
exclude_fields=('description',),
error_message='Instance can not be %(action)s, immutable status',
),
)
class ImmutableModelAllowDelete(AbstractImmutableModel):
mutability_rules = (
AbstractImmutableModel.get_mutability_rule(exclude_on_delete=True),
)
class ImmutableModelAllowUpdate(AbstractImmutableModel):
mutability_rules = (
AbstractImmutableModel.get_mutability_rule(exclude_on_update=True),
)
class ImmutableRelationModel(AbstractImmutableModel):
related_field = models.ForeignKey(
'BaseImmutableModel', on_delete=models.CASCADE, null=True, blank=True
)
mutability_rules = (
AbstractImmutableModel.get_mutability_rule(
field='related_field__state'
),
)
class ImmutableMultiForwardRelModel(AbstractImmutableModel):
related_field = models.ForeignKey(
'ModelWithRelation', on_delete=models.CASCADE, null=True, blank=True
)
mutability_rules = (
AbstractImmutableModel.get_mutability_rule(
field='related_field__related_field__state'
),
)
class ImmutableReverseRelationModel(AbstractImmutableModel):
related_field = models.ForeignKey(
'ImmutableMultiReverseRelModel',
on_delete=models.CASCADE,
null=True,
blank=True,
)
mutability_rules = (
AbstractImmutableModel.get_mutability_rule(
field='modelwithrelation__state'
),
)
class ImmutableMultiReverseRelModel(AbstractImmutableModel):
mutability_rules = (
AbstractImmutableModel.get_mutability_rule(
field='immutablereverserelationmodel__' 'modelwithrelation__state'
),
)
class ImmutableMultiMixRelModel(AbstractImmutableModel):
related_field = models.ForeignKey(
'BaseImmutableModel', on_delete=models.CASCADE, null=True, blank=True
)
mutability_rules = (
AbstractImmutableModel.get_mutability_rule(
field='related_field__immutablerelationmodel__state'
),
AbstractImmutableModel.get_mutability_rule(
field='modelwithrelation__related_field__state'
),
)
class ModelWithRelation(AbstractImmutableModel):
related_field = models.ForeignKey(
'ImmutableReverseRelationModel',
on_delete=models.CASCADE,
null=True,
blank=True,
)
related_field2 = models.ForeignKey(
'ImmutableMultiMixRelModel',
on_delete=models.CASCADE,
null=True,
blank=True,
)
|
Python
| 0.000006
|
@@ -98,45 +98,8 @@
dels
-%0Afrom model_utils import FieldTracker
%0A%0Afr
|
603d0dbb3ce2911b62f3274e68b93812da9acf2d
|
Remove SuperOnline and UyduNet DNS addresses
|
main.py
|
main.py
|
# -*- coding: utf-8 -*-
"""
main.py
Jan 14, 2014
Copyright (C) 2014 Barış Şencan
"""
import os
import redis
from flask import Flask, render_template, url_for
from flask.ext.compress import Compress
app = Flask(__name__)
# Enable gzip compression.
Compress(app)
# Static file loading helper.
app.jinja_env.globals['static'] = (
lambda filename: url_for('static', filename=filename))
# Redis configuration.
redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379')
redis = redis.from_url(redis_url)
# DNS list (plot twist: it's actually a dictionary).
dns_list = {
'Google': ('8.8.8.8', '8.8.4.4'),
'OpenDNS': ('208.67.222.222', '208.67.220.220'),
'TTNet': ('195.175.39.40', '195.175.39.39'),
'SuperOnline': ('213.74.0.1', '213.74.1.1'),
'UyduNet': ('62.248.80.161', '62.248.80.162')
}
@app.route('/')
def home():
status_for = dict()
# Fetch information from database.
for server in dns_list:
try:
status_for[server] = redis.get(server)
except:
status_for[server] = 'unknown'
return render_template('home.html', dns_list=dns_list, status_for=status_for)
|
Python
| 0
|
@@ -69,12 +69,12 @@
Bar
-%C4%B1%C5%9F %C5%9E
+is S
enca
@@ -716,113 +716,12 @@
39')
-,%0A 'SuperOnline': ('213.74.0.1', '213.74.1.1'),%0A 'UyduNet': ('62.248.80.161', '62.248.80.162')
%0A%7D%0A%0A
-%0A
@app
@@ -748,33 +748,8 @@
():%0A
- status_for = dict()%0A%0A
@@ -781,17 +781,57 @@
database
-.
+ and render page.%0A status_for = dict()
%0A for
@@ -974,17 +974,16 @@
nknown'%0A
-%0A
retu
|
3788876762107acf272ae91198f7f98e85de3349
|
Add cache pruning function
|
main.py
|
main.py
|
import hashlib
import models
import os
import os.path
def init():
models.db.connect()
models.db.create_tables([models.Entry])
def digest(file_path):
h = hashlib.sha1()
file = open(file_path, 'rb')
buf = file.read(8192)
while len(buf) > 0:
h.update(buf)
buf = file.read(8192)
return h.hexdigest()
def traverse(path):
path = os.path.abspath(path)
for (dir_path, dirs, files) in os.walk(path):
buf = []
for file_name in sorted(files):
if file_name.startswith('.'):
continue
file_path = os.path.join(dir_path, file_name)
entry = {
'path': file_path,
'size': os.path.getsize(file_path),
'last_modified': os.path.getmtime(file_path),
'hash_str': digest(file_path)
}
buf.append(entry)
if len(buf) >= 256:
print('Writing chunks until', file_name)
models.Entry.insert_many(buf).execute()
buf.clear()
if buf:
# Clear out remaining buffer
models.Entry.insert_many(buf).execute()
def get_duplicates():
from models import Entry
from peewee import fn, SQL
return (Entry
.select(Entry.hash_str, fn.COUNT(Entry.hash_str).alias('occurrence'))
.group_by(Entry.hash_str)
.having(SQL('occurrence') > 1))
def check_correctness():
from models import Entry
size_miss, time_miss, count = 0, 0, 0
for hash_entry in get_duplicates():
entries = Entry.select().where(Entry.hash_str == hash_entry.hash_str)
size, last_modified, path = None, None, None
for entry in entries:
if size:
if entry.size != size:
print('Size mismatch:', hash_entry.hash_str, entry.size, size, entry.path)
size_miss += 1
elif entry.last_modified != last_modified:
if abs(entry.last_modified - last_modified) < 5:
continue
print('Time mismatch:', hash_entry.hash_str, entry.last_modified, last_modified, path, entry.path)
time_miss += 1
else:
size, last_modified, path = entry.size, entry.last_modified, entry.path
count += 1
print('Mismatches: size {}, time {} of total {} duplicates'.format(size_miss, time_miss, count))
def query_file(path):
from datetime import datetime
print('Size', os.path.getsize(path))
print('Ctime', datetime.fromtimestamp(os.path.getctime(path)))
print('Mtime', datetime.fromtimestamp(os.path.getmtime(path)))
print('Atime', datetime.fromtimestamp(os.path.getatime(path)))
def move_duplicates(target_dir):
from models import Entry
count = 0
for hash_entry in get_duplicates():
hash_str = hash_entry.hash_str
entries = (Entry
.select()
.where(Entry.hash_str == hash_str)
.order_by(Entry.last_modified, Entry.id)
.offset(1))
for entry in entries:
new_path = os.path.join(target_dir, '{}_{}'.format(hash_str, os.path.basename(entry.path)))
print('Rename', entry.path, 'to', new_path)
os.rename(entry.path, new_path)
count += 1
print('Moved', count, 'duplicate files')
|
Python
| 0.000001
|
@@ -3377,8 +3377,254 @@
files')%0A
+%0Adef prune():%0A from models import Entry%0A count = 0%0A for entry in Entry.select():%0A if not os.path.exists(entry.path):%0A entry.delete_instance()%0A count += 1%0A print(count, 'non-existent file entries cleared')%0A
|
9c7660fd63bc1c48a0533e867c7d18faf9d90c03
|
Make use thru uwsgi easier
|
main.py
|
main.py
|
#!/usr/bin/env python
from morss import main
if __name__ == '__main__':
main()
|
Python
| 0
|
@@ -37,16 +37,44 @@
ort main
+, cgi_wrapper as application
%0A%0Aif __n
|
27cbdd93f2c5c723776b932d66a56699f9267b8d
|
Use single quotes instead of double quotes
|
main.py
|
main.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import re
import sys
from html.parser import HTMLParser
import urllib3
import taglib
class MyHTMLParser(HTMLParser):
ignore_tags = {"ul", "dl", "dd"}
def __init__(self, target_ol_count = 1):
self.target_ol_count = target_ol_count
self.ol_count = 1
self.in_ol = False
self.in_li = False
self.skip_depth = 0
self.titles = []
self.title_str = ""
super(MyHTMLParser, self).__init__()
def handle_starttag(self, tag, attrs):
# Wait till given count
if self.ol_count != self.target_ol_count:
return
if tag == "ol":
self.in_ol = True
elif tag == "li" and self.in_ol and self.skip_depth == 0:
self.in_li = True
elif tag in self.ignore_tags:
self.skip_depth += 1
def handle_endtag(self, tag):
if tag == "ol":
self.in_ol = False
self.ol_count += 1
# Wait till given count
elif self.ol_count != self.target_ol_count:
return
elif tag == "li" and self.in_li and self.skip_depth == 0:
self.in_li = False
self.add_title(self.title_str) # Add title to list
self.title_str = "" # Reset title
elif tag in self.ignore_tags:
self.skip_depth -= 1
def handle_data(self, data):
# Skipping irrelevant tags?
if self.skip_depth > 0:
return
# Nth <ol> tag that we're looking for?
if self.ol_count != self.target_ol_count:
return
# Empty?
data = data.rstrip()
if not data:
return
# Concatenate string of partial title (e.g. when there is a href)
if self.in_li:
self.title_str += data
def add_title(self, title):
# Empty?
if not title:
return
# Remove [TIME] e.g. "Title [3:35]" => "Title"
title = re.sub("\s*\[.*?\]\s*$", "", title)
self.titles.append(title)
def get_titles(url, ol_count = 1):
http = urllib3.PoolManager()
response = http.request('GET', url)
parser = MyHTMLParser(ol_count)
parser.feed(response.data.decode('utf-8'))
return parser.titles
def set_track_titles(titles, files, artist):
n = min(len(titles), len(files)) # Whichever's shorter
for i in range(n):
f = taglib.File(files[i])
if artist:
f.tags['ARTIST'] = artist
f.tags['TITLE'] = titles[i]
digits = len(str(len(titles)))
f.tags['TRACKNUMBER'] = ['%0*d/%d' % (digits, i, len(titles))]
retval = f.save()
if len(retval) != 0:
print('Something went wrong while saving {0}'.format(files[i]))
else:
print('Saved tags to {0}'.format(files[i]))
argparser = argparse.ArgumentParser()
argparser.add_argument("--ol-count", type=int, default=1, metavar="N",
help="use Nth <ol> tag as the list of track titles")
argparser.add_argument("--artist", help="album artist")
argparser.add_argument("url")
argparser.add_argument("files", nargs='+', help="files to write the tags to")
args = argparser.parse_args()
url = args.url
ol_count = args.ol_count
files = args.files
artist = args.artist
# print(get_titles(url, ol_count))
titles = get_titles(url, ol_count)
set_track_titles(titles, files, artist)
|
Python
| 0
|
@@ -199,24 +199,24 @@
= %7B
-%22ul%22, %22dl%22, %22dd%22
+'ul', 'dl', 'dd'
%7D%0A%0A
@@ -465,18 +465,18 @@
e_str =
-%22%22
+''
%0A
@@ -669,36 +669,36 @@
if tag ==
-%22ol%22
+'ol'
:%0A se
@@ -725,36 +725,36 @@
elif tag ==
-%22li%22
+'li'
and self.in_ol
@@ -937,12 +937,12 @@
==
-%22ol%22
+'ol'
:%0A
@@ -1130,12 +1130,12 @@
==
-%22li%22
+'li'
and
@@ -1298,18 +1298,18 @@
e_str =
-%22%22
+''
@@ -1979,17 +1979,17 @@
E%5D e.g.
-%22
+'
Title %5B3
@@ -1996,20 +1996,20 @@
:35%5D
-%22
+'
=%3E
-%22
+'
Title
-%22
+'
%0A
@@ -2028,17 +2028,17 @@
re.sub(
-%22
+'
%5Cs*%5C%5B.*?
@@ -2047,13 +2047,13 @@
%5Cs*$
-%22, %22%22
+', ''
, ti
@@ -2947,17 +2947,17 @@
rgument(
-%22
+'
--ol-cou
@@ -2958,17 +2958,17 @@
ol-count
-%22
+'
, type=
@@ -2995,11 +2995,11 @@
var=
-%22N%22
+'N'
,%0A
@@ -3009,17 +3009,17 @@
help=
-%22
+'
use Nth
@@ -3054,17 +3054,17 @@
k titles
-%22
+'
)%0Aargpar
@@ -3084,17 +3084,17 @@
ent(
-%22
+'
--artist
%22, h
@@ -3093,17 +3093,17 @@
tist
-%22
+'
, help=
-%22
+'
albu
@@ -3110,17 +3110,17 @@
m artist
-%22
+'
)%0Aargpar
@@ -3140,13 +3140,13 @@
ent(
-%22url%22
+'url'
)%0Aar
@@ -3170,15 +3170,15 @@
ent(
-%22
+'
files
-%22
+'
, na
@@ -3191,17 +3191,17 @@
', help=
-%22
+'
files to
@@ -3222,9 +3222,9 @@
s to
-%22
+'
)%0A%0Aa
|
52306859616973bcb6a14b436551506381979f71
|
edit variable name
|
main.py
|
main.py
|
#!/usr/bin/env python
# -*- coding=UTF-8 -*-
from os import path
from datetime import datetime
import logging
import sqlite3
import sys
import requests
from bs4 import BeautifulSoup
from config import EMAIL, PASSWORD, DEVICE
reload(sys)
if hasattr(sys, 'setdefaultencoding'):
sys.setdefaultencoding('UTF-8')
db = sqlite3.connect(sys.path[0], 'main.db')
cursor = db.cursor()
session = requests.session()
session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:28.0) Gecko/20100101 Firefox/28.0'})
def get_hidden_form_data(form):
ret = dict()
for i in form.findAll('input', type='hidden'):
ret[i['name']] = i['value']
return ret
def login(email, password):
logging.info('Login...')
LOGIN_URL = 'https://www.amazon.com/ap/signin?_encoding=UTF8&openid.assoc_handle=usflex&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.mode=checkid_setup&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.ns.pape=http%3A%2F%2Fspecs.openid.net%2Fextensions%2Fpape%2F1.0&openid.pape.max_auth_age=0&openid.return_to=https%3A%2F%2Fwww.amazon.com%2Fgp%2Fyourstore%2Fhome%3Fie%3DUTF8%26ref_%3Dgno_signin'
LOGIN_POST_URL = 'https://www.amazon.com/ap/signin'
login_page = BeautifulSoup(session.get(LOGIN_URL).text)
form = login_page.find('form', id='ap_signin_form')
data = get_hidden_form_data(form)
data.update({'email': email, 'password': password})
session.post(LOGIN_POST_URL, data)
def get_contents():
URL = 'https://www.amazon.com/gp/digital/fiona/manage/features/order-history/ajax/queryPdocs.html'
req = session.post(URL, {'offset': 0, 'count': 15,
'contentType': 'Personal Document', 'queryToken': 0, 'isAjax': 1})
return [{'category': i['category'], 'contentName': i['asin']}
for i in req.json()['data']['items']]
def deliver_content(content):
URL = 'https://www.amazon.com/gp/digital/fiona/content-download/fiona-ajax.html/ref=kinw_myk_ro_send'
content.update({'isAjax': '1', 'deviceID': DEVICE})
req = session.post(URL, content)
assert req.json()['data'] == 1
def deliver_all(contents):
logging.info('Delivering...')
def contentInDB(content):
try:
cursor.execute('select * from content where name = "%s"' % content)
except sqlite3.OperationalError:
cursor.execute('create table content (name text)')
return False
else:
return False if cursor.fetchone() is None else True
contents = filter(lambda x: not contentInDB(x['contentName']), contents)
for content in contents:
try:
logging.info('delivering ' + content['contentName'])
deliver_content(content)
except:
logging.error('Error, ignore')
pass
else:
logging.info('Done. Save to db.')
cursor.execute('insert into content values ("%s")' % content['contentName'])
db.commit()
if __name__ == '__main__':
logging.basicConfig(filename=path.join(sys.path[0], 'main.log'),
level='INFO',
format='%(asctime)s [%(levelname)s] %(message)s')
login(EMAIL, PASSWORD)
deliver_all(get_contents())
|
Python
| 0.000004
|
@@ -39,16 +39,57 @@
-8 -*-%0A%0A
+import logging%0Aimport sqlite3%0Aimport sys%0A
from os
@@ -133,49 +133,8 @@
time
-%0Aimport logging%0Aimport sqlite3%0Aimport sys
%0A%0Aim
@@ -331,16 +331,26 @@
connect(
+path.join(
sys.path
@@ -364,16 +364,17 @@
ain.db')
+)
%0Acursor
@@ -389,22 +389,16 @@
sor()%0A%0As
-ession
= reque
@@ -412,22 +412,16 @@
sion()%0As
-ession
.headers
@@ -738,25 +738,25 @@
.')%0A
-LOGIN_URL
+login_url
= 'http
@@ -1270,30 +1270,30 @@
in'%0A
-LOGIN_POST_URL
+login_post_url
= 'http
@@ -1358,28 +1358,22 @@
up(s
-ession.get(LOGIN_URL
+.get(login_url
).te
@@ -1535,34 +1535,28 @@
s
-ession.post(LOGIN_POST_URL
+.post(login_post_url
, da
@@ -1684,36 +1684,28 @@
.html'%0A r
-eq
= s
-ession
.post(URL, %7B
@@ -1895,18 +1895,16 @@
r i in r
-eq
.json()%5B
@@ -2123,20 +2123,12 @@
r
-eq
= s
-ession
.pos
@@ -2155,18 +2155,16 @@
assert r
-eq
.json()%5B
|
b3e61d648be5c5d28cfe3a7ef69f918c2a2c33a1
|
optimize the logic of mail
|
main.py
|
main.py
|
# -*- coding: utf-8 -*-
import mail
import simplejson
import urllib2
import time
from config import *
def moniter(m, send_to, high, low):
req = urllib2.Request("https://data.btcchina.com/data/ticker")
opener = urllib2.build_opener()
last_sent = 0
while True:
try:
f = opener.open(req)
data = simplejson.load(f)
except:
time.sleep(3)
continue
price = float(data['ticker']['last'])
if price > high or price < low:
for i in range(3):
try:
if time.time() - last_sent > 5 * 60:
m.send(send_to, "BTC Ticker Warning",
"the price now is " + str(price))
last_sent = time.time()
except:
continue
break
print "Price: ¥%s Buy: ¥%s Sell: ¥%s" % (data['ticker']['last'],
data['ticker']['buy'], data['ticker']['sell'])
time.sleep(3)
if __name__ == "__main__":
m = mail.Mail(account, smtp_addr, account, password)
moniter(m, send_to, high, low)
|
Python
| 0.999999
|
@@ -16,16 +16,18 @@
tf-8 -*-
+
%0Aimport
@@ -80,29 +80,8 @@
ime%0A
-from config import *%0A
%0A%0Ade
@@ -491,68 +491,8 @@
ow:%0A
- for i in range(3):%0A try:%0A
@@ -536,24 +536,41 @@
5 * 60:%0A
+ try:%0A
@@ -614,18 +614,18 @@
arning%22,
-%0A
+%0A
@@ -677,24 +677,59 @@
price))%0A
+ print %22sent email%22%0A
@@ -774,32 +774,45 @@
except
+ Exception, e
:%0A
@@ -821,38 +821,15 @@
-continue%0A break
+print e
%0A%0A
@@ -990,17 +990,24 @@
leep(3)%0A
-%0A
+
%0Aif __na
|
8e9c04dda00dc565a9a07c37fb43ccb4c5d03969
|
remove the useless processing for external url.
|
flask_navigation/item.py
|
flask_navigation/item.py
|
import collections
from flask import url_for, request
from .utils import freeze_dict
class Item(object):
"""The navigation item object.
:param label: the display label of this navigation item.
:param endpoint: the unique name of this navigation item.
If this item point to a internal url, this parameter
should be acceptable for ``url_for`` which will generate
the target url.
:param args: optional. If this parameter be provided, it will be passed to
the ``url_for`` with ``endpoint`` together.
Maybe this arguments need to be decided in the Flask app
context, then this parameter could be a function to delay the
execution.
:param url: optional. If this parameter be provided, the target url of
this navigation will be it. The ``endpoint`` and ``args`` will
not been used to generate url.
The ``endpoint`` is the identity name of this navigation item. It will be
unique in whole application. In mostly situation, it should be a endpoint
name of a Flask view function.
"""
def __init__(self, label, endpoint, args=None, url=None):
self.label = label
self.endpoint = endpoint
self._args = args
self._url = url
@property
def args(self):
"""The arguments which will be passed to ``url_for``.
:type: :class:`dict`
"""
if self._args is None:
return {}
if callable(self._args):
return dict(self._args())
return dict(self._args)
@property
def url(self):
"""The final url of this navigation item.
By default, the value is generated by the :attr:`self.endpoint` and
:attr:`self.args`.
.. note::
The :attr:`url` property require the app context without a provided
config value :const:`SERVER_NAME`, because of :func:`flask.url_for`.
:type: :class:`str`
"""
if self._url is None:
return url_for(self.endpoint, **self.args)
return self._url
@property
def is_active(self):
"""``True`` if the item should be presented as active, and ``False``
always if the request context is not bound.
"""
return request and self.is_current
@property
def is_internal(self):
"""``True`` if the target url is internal of current app."""
return self._url is None
@property
def is_current(self):
"""``True`` if current request has same endpoint with the item.
The property should be used in a bound request context, or the
:exception:`RuntimeError` may be raised.
"""
if self.is_internal:
has_same_endpoint = (request.endpoint == self.endpoint)
has_same_args = (request.view_args == self.args)
return has_same_endpoint and has_same_args # matches the endpoint
else:
return self._url == request.url # matches the whole url
@property
def ident(self):
"""The identity of this item.
:type: :class:`~flask.ext.navigation.Navigation.ItemReference`
"""
return ItemReference(self.endpoint, self.args)
class ItemCollection(collections.MutableSequence,
collections.Iterable):
"""The collection of navigation items.
This collection is a mutable sequence. All items have order index, and
could be found by its endpoint name. e.g.::
c = ItemCollection()
c.append(Item(endpoint='doge'))
print(c['doge']) # output: Item(endpoint='doge')
print(c[0]) # output: Item(endpoint='doge')
print(c) # output: ItemCollection([Item(endpoint='doge')])
print(len(c)) # output: 1
c.append(Item(endpoint='lumpy', args={'num': 4}))
print(c[1]) # output: Item(endpoint='lumpy', args={'num': 4})
assert c['lumpy', {'num': 4}] is c[1]
"""
def __init__(self, iterable=None):
#: the item collection
self._items = []
#: the mapping collection of endpoint -> item
self._items_mapping = {}
#: initial extending
self.extend(iterable or [])
def __repr__(self):
return 'ItemCollection(%r)' % self._items
def __getitem__(self, index):
if isinstance(index, int):
return self._items[index]
if isinstance(index, tuple):
endpoint, args = index
else:
endpoint, args = index, {}
ident = ItemReference(endpoint, args)
return self._items_mapping[ident]
def __setitem__(self, index, item):
# remove the old reference
old_item = self._items[index]
del self._items_mapping[old_item.ident]
self._items[index] = item
self._items_mapping[item.ident] = item
def __delitem__(self, index):
item = self[index]
del self._items[index]
del self._items_mapping[item.ident]
def __len__(self):
return len(self._items)
def __iter__(self):
return iter(self._items)
def insert(self, index, item):
self._items.insert(index, item)
self._items_mapping[item.ident] = item
class ItemReference(collections.namedtuple('ItemReference', 'endpoint args')):
"""The identity tuple of navigation item.
:param endpoint: the endpoint of view function.
:type endpoint: ``str``
:param args: the arguments of view function.
:type args: ``dict``
"""
def __new__(cls, endpoint, args=()):
if isinstance(args, dict):
args = freeze_dict(args)
return super(cls, ItemReference).__new__(cls, endpoint, args)
|
Python
| 0
|
@@ -2064,28 +2064,27 @@
if self.
-_url is None
+is_internal
:%0A
@@ -2353,16 +2353,21 @@
return
+bool(
request
@@ -2385,16 +2385,17 @@
_current
+)
%0A%0A @p
@@ -2780,32 +2780,36 @@
%22%22%22%0A if
+not
self.is_internal
@@ -2806,32 +2806,86 @@
s_internal:%0A
+ return False # always false for external url%0A
has_same
@@ -2936,28 +2936,24 @@
nt)%0A
-
has_same_arg
@@ -2985,28 +2985,24 @@
self.args)%0A
-
retu
@@ -3067,91 +3067,8 @@
oint
-%0A else:%0A return self._url == request.url # matches the whole url
%0A%0A
|
6b6bbe079a6b68ac82f4caa11473b5b005824715
|
Update crop_geotiff.py
|
geobeam/examples/crop_geotiff.py
|
geobeam/examples/crop_geotiff.py
|
# Copyright 2021 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
"""
Example pipeline that loads a cropland type raster dataset into
Bigquery.
"""
def run(pipeline_args, known_args):
"""
Run the pipeline. Invoked by the Beam runner.
"""
import apache_beam as beam
from apache_beam.io.gcp.internal.clients import bigquery as beam_bigquery
from apache_beam.options.pipeline_options import PipelineOptions
from geobeam.io import GeotiffSource
from geobeam.fn import format_record
pipeline_options = PipelineOptions([
'--experiments', 'use_beam_bq_sink'
] + pipeline_args)
with beam.Pipeline(options=pipeline_options) as p:
logging.info('Will be inserting column: {}'.format(known_args.band_column))
(p
| beam.io.Read(GeotiffSource(known_args.gcs_url,
band_number=known_args.band_number,
centroid_only=known_args.centroid_only,
merge_blocks=known_args.merge_blocks))
| 'FormatRecords' >> beam.Map(format_record, known_args.band_column, 'int')
| 'WriteToBigQuery' >> beam.io.WriteToBigQuery(
beam_bigquery.TableReference(
datasetId=known_args.dataset,
tableId=known_args.table),
method=beam.io.WriteToBigQuery.Method.FILE_LOADS,
write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE,
create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED))
if __name__ == '__main__':
import logging
import argparse
logging.getLogger().setLevel(logging.INFO)
parser = argparse.ArgumentParser()
parser.add_argument('--gcs_url')
parser.add_argument('--dataset')
parser.add_argument('--table')
parser.add_argument('--band_column')
parser.add_argument('--band_number', type=int, default=1)
parser.add_argument('--skip_nodata', type=bool, default=True)
parser.add_argument('--centroid_only', type=bool, default=False)
parser.add_argument('--in_epsg', type=int, default=None)
parser.add_argument('--merge_blocks', type=int, default=1)
known_args, pipeline_args = parser.parse_known_args()
run(pipeline_args, known_args)
|
Python
| 0.000001
|
@@ -652,16 +652,242 @@
y.%0A%22%22%22%0A%0A
+def elev_to_centimeters(element):%0A %22%22%22%0A Convert the floating-point to store%0A as INT64 in order to support clustering on this value column (croptype).%0A %22%22%22%0A%0A value, geom = element%0A%0A return (int(value), geom)%0A%0A
%0Adef run
@@ -1732,16 +1732,80 @@
locks))%0A
+ %7C 'ElevToCentimeters' %3E%3E beam.Map(elev_to_centimeters)%0A
|
3cff942af436f16aab2078e6aeedd3073f4a5522
|
Add Flask-Mail, and null user loader
|
flask_roots/extension.py
|
flask_roots/extension.py
|
from __future__ import absolute_import
import os
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.images import Images
# from flask.ext.mail import Mail
from flask.ext.login import LoginManager
from flask.ext.acl import AuthManager
class Roots(object):
def __init__(self, app):
self.extensions = {}
self.init_app(app)
def init_app(self, app):
# Establish two-way links.
self.app = app
app.roots = self
app.extensions['roots'] = self
from .config import setup_config
setup_config(app)
from .logs import setup_logs
setup_logs(app)
from .session import setup_session
setup_session(app)
self.extensions['login_manager'] = LoginManager(app)
self.extensions['auth'] = AuthManager(app)
from .mako import MakoTemplates
self.extensions['mako'] = MakoTemplates(app)
self.extensions['images'] = Images(app)
self.extensions['db'] = db = SQLAlchemy(app)
db.metadata.bind = db.engine # WTF do I need to do this for?!
from .routing import setup_routing
setup_routing(app)
from .errors import setup_errors
setup_errors(app)
|
Python
| 0.000001
|
@@ -124,18 +124,16 @@
Images%0A
-#
from fla
@@ -742,16 +742,24 @@
ager'%5D =
+ login =
LoginMa
@@ -765,24 +765,72 @@
anager(app)%0A
+ login.user_callback = lambda uid: None%0A%0A
self
@@ -1136,16 +1136,61 @@
for?!%0A%0A
+ self.extensions%5B'mail'%5D = Mail(app)%0A%0A
|
18897bf535b4885b9dfbf0a014c92656e8ed74b7
|
Update main to return properly formatted data
|
main.py
|
main.py
|
import telegram
import tornado.ioloop
import tornado.web
from tornado.options import define, options
from goodreads_api import get_book_details_by_name, BookNotFound
from settings import TELEGRAM_ACCESS_TOKEN, WEBHOOK_URL
define("port", default=5000, help="run on the given port", type=int)
bot = telegram.Bot(token=TELEGRAM_ACCESS_TOKEN)
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.write('wink, wink')
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write('wink, wink')
def post(self):
data = tornado.escape.json_decode(self.request.body)
try:
message_id = data['message']['message_id']
chat_id = data['message']['chat']['id']
text = data['message']['text']
chat_type = data['message']['chat']['type']
if not chat_type == 'group':
return
response = parse_command(text=text)
bot.sendMessage(reply_to_message_id=message_id,
chat_id=chat_id, text=response)
except KeyError:
pass
except telegram.error.TelegramError:
print(data)
return
class WebHookHandler(tornado.web.RequestHandler):
def get(self):
# one time only operation
response = bot.setWebhook(WEBHOOK_URL)
if not response:
return self.write('Setting up webhook has failed')
return self.write('Webhook has been successfully set')
def parse_command(text):
# The telegram usually sends the whole text as something like:
# '/ping hello' or '/ping@botname hello'
command, argument = text.split(' ', 1)
if command == '/book' or command == '/book@goodreadsbot':
return get_book_details(book_name=argument)
def get_book_details(book_name):
try:
book_data = get_book_details_by_name(book_name)
except BookNotFound:
return "I couldn't find the book, can you be more precise?"
def make_app():
return tornado.web.Application([
(r'/', IndexHandler),
(r'/duh', MainHandler),
(r'/setwebhook', WebHookHandler)
])
if __name__ == "__main__":
tornado.options.parse_command_line()
app = make_app()
app.listen(options.port)
tornado.ioloop.IOLoop.current().start()
|
Python
| 0
|
@@ -160,16 +160,58 @@
otFound%0A
+from utils import get_formatted_book_data%0A
from set
@@ -1840,16 +1840,45 @@
gument)%0A
+ return 'Invalid command'%0A
%0A%0Adef ge
@@ -1967,16 +1967,86 @@
ook_name
+=book_name)%0A return get_formatted_book_data(book_data=book_data
)%0A ex
|
f9aa61fa326f9737e2af971a420da9c0652612ae
|
revise BaseDoctype to add generic generation method
|
tldp/doctypes/common.py
|
tldp/doctypes/common.py
|
#! /usr/bin/python
from __future__ import absolute_import, division, print_function
import os
from ..utils import logger
class SignatureChecker(object):
@classmethod
def signatureLocation(cls, f):
f.seek(0)
buf = f.read(1024).lower()
for sig in cls.signatures:
try:
sindex = buf.index(sig.lower())
logger.debug("Found signature %s in %s at %s; doctype %s.",
sig, f.name, sindex, cls)
return sindex
except ValueError:
logger.debug("Signature %s not found in %s for type %s",
sig, f.name, cls.__name__)
return None
class BaseDoctype(object):
def __init__(self, *args, **kwargs):
self.source = kwargs.get('source')
self.output = kwargs.get('output')
self.platform = kwargs.get('platform')
self.logdir = os.path.join(self.output.dirname, 'logs')
if os.path.exists(self.logdir):
logger.warning("Found existing logs directory: %s", self.logdir)
else:
os.mkdir(self.logdir)
def generate(self):
os.chdir(self.output.dirname)
self.output.clear()
self.platform_check()
self.create_htmls()
self.create_pdf()
self.create_txt()
self.create_html()
#
# -- end of file
|
Python
| 0
|
@@ -1193,32 +1193,42 @@
irname)%0A
+vector = %5B
self.output.clea
@@ -1227,20 +1227,31 @@
put.clea
-r()%0A
+n(),%0A
@@ -1271,25 +1271,31 @@
_check()
-%0A
+,%0A
self.cre
@@ -1278,32 +1278,37 @@
),%0A
+
self.create_html
@@ -1310,17 +1310,28 @@
_htmls()
+,
%0A
+
@@ -1347,25 +1347,30 @@
te_pdf()
-%0A
+,%0A
self.cre
@@ -1353,32 +1353,38 @@
(),%0A
+
self.create_txt(
@@ -1384,17 +1384,28 @@
te_txt()
+,
%0A
+
@@ -1422,16 +1422,176 @@
e_html()
+,%0A %5D%0A result = all(vector)%0A logger.info(%22%25s generation of all documents %25s%22, self.source.stem, result)%0A return all(vector)
%0A%0A#%0A# --
|
577ebb6d4dc037bc912aa11d525ca4f2f09e7940
|
set default schema to defm
|
db/log.py
|
db/log.py
|
from sqlalchemy.orm import sessionmaker
from forecast import util
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy import MetaData
from pysandag.database import get_connection_string
import os
def new_run(name='runs'):
Base = declarative_base()
table_name = name
class Run(Base):
__tablename__ = table_name
__table_args__ = {'schema': 'defm'}
# define columns for the table
id = Column(Integer, primary_key=True)
base_rate_version = Column(Integer)
birth_rate_version = Column(Integer)
death_rate_version = Column(Integer)
migration_rate_version = Column(Integer)
householder_rate_version = Column(Integer)
db_dir = 'results/'
if not os.path.exists(db_dir):
os.makedirs(db_dir)
engine = create_engine(get_connection_string("model_config.yml", 'output_database'))
if not engine.has_table(table_name):
Base.metadata.create_all(engine)
db_session = sessionmaker(bind=engine)
session = db_session()
# Rate versions from yml file
rate_versions = util.yaml_to_dict('model_config.yml', 'rate_versions')
# Insert versions in database
model_run = Run(
base_rate_version=rate_versions['population'],
birth_rate_version=rate_versions['birth'],
death_rate_version=rate_versions['death'],
migration_rate_version=rate_versions['migration'],
householder_rate_version=rate_versions['householder'])
session.add(model_run)
session.commit()
run_id = model_run.id
return run_id
def insert_run(db_name,model_run_id,df_results,table_name):
engine = create_engine(get_connection_string("model_config.yml", 'output_database'))
# Insert prediction in the population table
df_results['run_id'] = model_run_id # foreign key to run log table
df_results.to_sql(name=table_name, con=engine, schema='defm', if_exists = 'append', index=True)
df_results = df_results.drop('run_id', 1) # remove run_id
|
Python
| 0.000006
|
@@ -803,24 +803,65 @@
n(Integer)%0A%0A
+ #metadata = MetaData(schema=%22defm%22)%0A%0A
db_dir =
@@ -872,16 +872,16 @@
sults/'%0A
-
if n
@@ -1021,25 +1021,173 @@
_database'))
-%0A
+.execution_options(%0A schema_translate_map=%7B%0A None: %22defm%22, # no schema name -%3E %22defm%22%0A %7D)%0A Base.metadata.schema = 'defm'
%0A if not
@@ -1213,16 +1213,30 @@
ble_name
+,schema='defm'
):%0A
|
d8085d288323eb6530115ea9e56ee4795cb65877
|
Move spurious prints in config.py to use logging
|
salt/config.py
|
salt/config.py
|
'''
All salt configuration loading and defaults should be in this module
'''
# Import python modules
import os
import tempfile
import socket
import sys
# import third party libs
import yaml
try:
yaml.Loader = yaml.CLoader
yaml.Dumper = yaml.CDumper
except:
pass
# Import salt libs
import salt.crypt
import salt.loader
import salt.utils
def load_config(opts, path, env_var):
'''
Attempts to update ``opts`` dict by parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if not path or not os.path.isfile(path):
path = os.environ.get(env_var, path)
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = "%s.template" % path
if os.path.isfile(template):
with open(path, 'w') as out:
with open(template, 'r') as f:
f.readline() # skip first line
out.write(f.read())
if os.path.isfile(path):
try:
conf_opts = yaml.safe_load(open(path, 'r'))
if conf_opts is None:
# The config file is empty and the yaml.load returned None
conf_opts = {}
else:
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
conf_opts['id'] = str(conf_opts['id'])
opts.update(conf_opts)
opts['conf_file'] = path
except Exception, e:
print 'Error parsing configuration file: {0} - {1}'.format(path, e)
else:
print 'Missing configuration file: {0}'.format(path)
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
for path_option in path_options:
if path_option in opts:
opts[path_option] = os.path.normpath(
os.sep.join([opts['root_dir'], opts[path_option]]))
def minion_config(path):
'''
Reads in the minion configuration file and sets up special options
'''
opts = {'master': 'salt',
'master_port': '4506',
'user': 'root',
'root_dir': '/',
'pki_dir': '/etc/salt/pki',
'id': socket.getfqdn(),
'cachedir': '/var/cache/salt',
'cache_jobs': False,
'conf_file': path,
'renderer': 'yaml_jinja',
'failhard': False,
'autoload_dynamic_modules': True,
'disable_modules': [],
'disable_returners': [],
'module_dirs': [],
'returner_dirs': [],
'states_dirs': [],
'render_dirs': [],
'clean_dynamic_modules': True,
'open_mode': False,
'multiprocessing': True,
'sub_timeout': 60,
'log_file': '/var/log/salt/minion',
'log_level': 'warning',
'log_granular_levels': {},
'test': False,
'cython_enable': False,
'state_verbose': False,
'acceptance_wait_time': 10,
}
load_config(opts, path, 'SALT_MINION_CONFIG')
opts['master_ip'] = dns_check(opts['master'])
opts['master_uri'] = 'tcp://' + opts['master_ip'] + ':'\
+ str(opts['master_port'])
# Enabling open mode requires that the value be set to True, and nothing
# else!
opts['open_mode'] = opts['open_mode'] is True
# set up the extension_modules location from the cachedir
opts['extension_modules'] = os.path.join(opts['cachedir'], 'extmods')
opts['grains'] = salt.loader.grains(opts)
# Prepend root_dir to other paths
prepend_root_dir(opts, ['pki_dir', 'cachedir', 'log_file'])
return opts
def master_config(path):
'''
Reads in the master configuration file and sets up default options
'''
opts = {'interface': '0.0.0.0',
'publish_port': '4505',
'user': 'root',
'worker_threads': 5,
'sock_dir': os.path.join(tempfile.gettempdir(), '.salt-unix'),
'ret_port': '4506',
'keep_jobs': 24,
'root_dir': '/',
'pki_dir': '/etc/salt/pki',
'cachedir': '/var/cache/salt',
'file_roots': {
'base': ['/srv/salt'],
},
'file_buffer_size': 1048576,
'hash_type': 'md5',
'conf_file': path,
'open_mode': False,
'auto_accept': False,
'renderer': 'yaml_jinja',
'failhard': False,
'state_top': 'top.sls',
'order_masters': False,
'log_file': '/var/log/salt/master',
'log_level': 'warning',
'log_granular_levels': {},
'cluster_masters': [],
'cluster_mode': 'paranoid',
'serial': 'msgpack',
'nodegroups': {},
}
load_config(opts, path, 'SALT_MASTER_CONFIG')
opts['aes'] = salt.crypt.Crypticle.generate_key_string()
# Prepend root_dir to other paths
prepend_root_dir(opts, ['pki_dir', 'cachedir', 'log_file', 'sock_dir'])
# Enabling open mode requires that the value be set to True, and nothing
# else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
return opts
def dns_check(addr):
'''
Verify that the passed address is valid and return the ipv4 addr if it is
a hostname
'''
try:
socket.inet_aton(addr)
# is a valid ip addr
except socket.error:
# Not a valid ip addr, check if it is an available hostname
try:
addr = socket.gethostbyname(addr)
except socket.gaierror:
# Woah, this addr is totally bogus, die!!!
err = ('The master address {0} could not be validated, please '
'check that the specified master in the minion config '
'file is correct\n')
err = err.format(addr)
sys.stderr.write(err)
sys.exit(42)
return addr
|
Python
| 0
|
@@ -112,24 +112,19 @@
%0Aimport
-tempfile
+sys
%0Aimport
@@ -137,19 +137,39 @@
%0Aimport
-sys
+logging%0Aimport tempfile
%0A%0A# impo
@@ -361,16 +361,51 @@
.utils%0A%0A
+log = logging.getLogger(__name__)%0A%0A
%0Adef loa
@@ -1633,21 +1633,21 @@
-print
+msg =
'Error
@@ -1684,16 +1684,41 @@
%7D - %7B1%7D'
+%0A log.warn(msg
.format(
@@ -1725,16 +1725,17 @@
path, e)
+)
%0A els
@@ -1749,14 +1749,18 @@
-print
+log.debug(
'Mis
@@ -1801,16 +1801,17 @@
at(path)
+)
%0A%0A%0Adef p
|
7c5dad065fc3cb391609c9dd9a8d1b3effc197b1
|
fix typo
|
paths/recursive_total_path.py
|
paths/recursive_total_path.py
|
import cProfile
def numberOfPaths(nXm_matrix):
"""
Returns the total number of paths from the top left
to the bottom right by moving right and down in a 2D array
of size n x m. Where cells can only contain `1` or `0` while
real paths can only contain `1`.
"""
hight = len(nXm_matrix)
width = len(nXm_matrix[0])
def calculate(matrix, matrix_h, matrix_w, next_h, next_w, last_value=0):
"""
Local calculation recursive function.
"""
# Stop condition 1
if matrix[next_h][next_w] == 0:
return last_value
# Stop condition 2
if next_h == matrix_h and next_w == matrix_w:
return last_value + 1
# Move right
if next_w < matrix_w:
last_value = calculate(matrix, matrix_h, matrix_w,
next_h, next_w + 1, last_value)
# Move down
if next_h < matrix_h:
last_value = calculate(matrix, matrix_h, matrix_w,
next_h + 1, next_w, last_value)
# Final Result
return last_value
count = calculate(nXm_matrix, hight-1, width-1, 0, 0)
return count
def run_test():
"""
Test function.
"""
d2_matrix = [
[1,1,1,1,1,1],
[1,1,0,1,1,1],
[1,1,1,0,1,1],
[1,1,0,1,1,1],
[1,1,1,1,0,1],
]
count = numberOfPaths(d2_matrix)
print "---------------------"
print "Total Number of Paths = {}\n".format(count)
if __name__ == "__main__":
"""
Run the code and profile it.
"""
cProfile.run('run_test()')
|
Python
| 0.999991
|
@@ -1027,31 +1027,8 @@
e)%0A%0A
- # Final Result%0A
|
b0d0c9b67c0faa583c216687544a544ed7fde631
|
Fix up syntax in the minion
|
salt/minion.py
|
salt/minion.py
|
'''
Routines to set up a minion
'''
# Import python libs
import os
import distutils.sysconfig
# Import zeromq libs
import zmq
# Import salt libs
import salt.crypt
import salt.utils
import salt.modules
# To set up a minion:
# 1, Read in the configuration
# 2. Generate the function mapping dict
# 3. Authenticate with the master
# 4. Store the aes key
# 5. connect to the publisher
# 6. handle publications
class Minion(object):
'''
This class instanciates a minion, runs connections for a minion, and loads
all of the functions into the minion
'''
def __init__(self, opts):
'''
Pass in the options dict
'''
self.opts = opts
self.functions = self.__load_functions()
self.authenticate()
def __load_functions(self):
'''
Parses through the modules in the modules directory and loads up all of
the functions.
'''
# This is going to need some work to clean it up and expand
# functionality, right now it just loads up all callable objects in the
# modules package
mods = {}
functions = {}
for mod in dir(salt.modules):
if not mod.startswith('_'):
module = getattr(salt.modules, mod)
for attr in dir(module):
if not attr.startswith('_'):
if callable(getattr(module, attr)):
functions{mod + '.' + attr: getattr(module, attr)}
print functions
return functions
def _handle_payload(self, payload):
'''
Takes a payload from the master publisher and does whatever the
master wants done.
'''
pass
def authenticate(self):
'''
Authenticate with the master, this method breaks the functional
pardigmn, it will update the master information from a fesh sign in,
signing in can occur as often as needed to keep up with the revolving
master aes key.
'''
auth = salt.crypt.Auth(self.opts)
creds = auth.sign_in()
self.aes = creds['aes']
self.publish_port = creds['publish_port']
def tune_in(self):
'''
Lock onto the publisher. This is the main event loop for the minion
'''
master_pub = 'tcp://' + self.opts['master'] + ':'\
+ str(self.publish_port)
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect(master_pub)
while True:
payload = socket.recv()
self._handle_payload(payload)
|
Python
| 0.999989
|
@@ -33,66 +33,8 @@
'''%0A
-# Import python libs%0Aimport os%0Aimport distutils.sysconfig%0A
# Im
@@ -1028,26 +1028,8 @@
age%0A
- mods = %7B%7D%0A
@@ -1364,17 +1364,17 @@
unctions
-%7B
+%5B
mod + '.
@@ -1381,17 +1381,19 @@
' + attr
-:
+%5D =
getattr
@@ -1406,17 +1406,16 @@
e, attr)
-%7D
%0A
|
a6fdca8d13ece3df9e676a3efdc38ad1c48fd390
|
Add shuffle template tag. Refs #10197 and #10198
|
ella/ellaexports/templatetags/ellaexports.py
|
ella/ellaexports/templatetags/ellaexports.py
|
# -*- coding: utf-8 -*-
import hashlib
from datetime import datetime
from httplib import urlsplit
from django.conf import settings
from django import template
from django.utils.feedgenerator import rfc2822_date
from ella.ellaexports.conf import ellaexports_settings
register = template.Library()
DOUBLE_RENDER = getattr(settings, 'DOUBLE_RENDER', False)
class PublishableFullUrlNode(template.Node):
def __init__(self, var_name):
self.var_name = var_name
def render(self, context):
publishable = template.Variable(self.var_name).resolve(context)
return publishable.get_absolute_url(domain=True)
@register.tag
def publishable_full_url(parser, token):
tokens = token.split_contents()
if len(tokens) != 2:
raise AttributeError('publishable_full_url takes one argument (variable containing publishable object).')
var_name = tokens[1]
return PublishableFullUrlNode(var_name)
class AtomIdNode(template.Node):
def __init__(self, var_name, hashed_output):
self.var_name = var_name
self.hashed_output = hashed_output
def render(self, context):
"""
Example output: tag:zena.cz,2004-05-27:/12/10245
2004-05-27 ... publication date
12 ... content type
10245 ... publishable ID
If self.hashed_output is set, whole tag is hashed by SHA1.
"""
publishable = template.Variable(self.var_name).resolve(context)
if publishable.publish_from:
pub_date = publishable.publish_from.strftime('%Y-%m-%d')
else:
pub_date = '1970-01-01'
url = publishable.get_absolute_url(domain=True)
url_splitted = urlsplit(url)
out = 'tag:%s,%s:/%d/%d' % (
url_splitted.netloc,
pub_date,
publishable.content_type_id,
publishable.pk
)
if self.hashed_output:
h = hashlib.sha1(out)
out = h.hexdigest()
return out
@register.tag
def get_atom_id(parser, token):
"""
Gets Atom ID for Publishable object.
Example:
{% get_atom_id publishable_object_template_variable %} # outputs Atom ID value
{% get_atom_id publishable_object_template_variable hashed %} # outputs hashed Atom ID value
"""
hashed = False
tokens = token.split_contents()
if len(tokens) not in (2, 3,):
raise AttributeError('get_atom_id takes one or two arguments (variable containing publishable object, [hashed]).')
if len(tokens) == 3:
if tokens[2].lower() == 'hashed':
hashed = True
var_name = tokens[1]
return AtomIdNode(var_name, hashed)
class FeedStrftimeNode(template.Node):
def __init__(self, var_name, formatstring):
self.var_name = var_name
self.formatstring = formatstring
def render(self, context):
if self.var_name == 'None':
variable = datetime.now()
else:
variable = template.Variable(self.var_name).resolve(context)
if type(variable) != datetime:
raise AttributeError('Given variable is not datetime object. %s' % variable)
formatstring = ellaexports_settings.FEED_DATETIME_FORMAT
if self.formatstring:
formatstring = self.formatstring
return variable.strftime(str(formatstring))
@register.tag
def feed_strftime(parser, token):
"""
Gets datetime formated by custom format string.
"""
formatstring = None
tokens = token.split_contents()
if len(tokens) not in (2, 3,):
raise AttributeError('get_atom_id takes one or two arguments (variable containing publishable object, [hashed]).')
if len(tokens) == 3:
formatstring = tokens[2]
if formatstring[0] in ('\'', '"',):
formatstring = formatstring[1:]
if formatstring[-1] in ('\'', '"',):
formatstring = formatstring[:-1]
var_name = tokens[1]
return FeedStrftimeNode(var_name, formatstring)
@register.filter
def feed_replace_datetime_czech(value):
EN2CZ_MONTHS = {
'January': u'leden',
'February': u'únor',
'March': u'březen',
'April': u'duben',
'May': u'květen',
'June': u'červen',
'July': u'červenec',
'August': u'srpen',
'September': u'září',
'October': u'říjen',
'November': u'listopad',
'December': u'prosinec',
}
EN2CZ_WEEKDAYS = {
'Monday': u'pondělí',
'Tuesday': u'úterý',
'Wednesday': u'středa',
'Thursday': u'čtvrtek',
'Friday': u'pátek',
'Saturday': u'sobota',
'Sunday': u'neděle',
}
out = value
first_pass = ''
for en, cz in EN2CZ_MONTHS.items():
if value.find(en) > -1:
first_pass = value.replace(en, cz)
break
for en, cz in EN2CZ_WEEKDAYS.items():
if first_pass.find(en) > -1:
out = first_pass.replace(en, cz)
break
return out
register.filter(rfc2822_date)
|
Python
| 0
|
@@ -32,16 +32,30 @@
hashlib%0A
+import random%0A
from dat
@@ -4998,16 +4998,124 @@
rn out%0A%0A
+@register.filter%0Adef shuffle(value):%0A result = list(value)%0A random.shuffle(result)%0A return result%0A%0A
register
|
981e458db0f0e7b331f60f1b77106a0e484b3ded
|
Correct the spelling on exclude of Community level
|
pycon/sponsorship/forms.py
|
pycon/sponsorship/forms.py
|
import re
from django import forms
from django.contrib.admin.widgets import AdminFileWidget
from django.forms.models import inlineformset_factory, BaseInlineFormSet
from django.utils.translation import ugettext_lazy as _
from multi_email_field.forms import MultiEmailField
from pycon.sponsorship.models import Sponsor, SponsorBenefit, SponsorLevel
def strip(text):
return u' '.join(text.strip().split())
class SponsorDetailsForm(forms.ModelForm):
contact_emails = MultiEmailField(
help_text=_(u"Please enter one email address per line.")
)
class Meta:
model = Sponsor
fields = ["name",
"contact_name",
"contact_emails",
"contact_phone",
"contact_address",
"external_url",
"display_url",
"twitter_username",
"web_description",
"web_logo",
]
widgets = {
'web_description': forms.widgets.Textarea(attrs={'cols': 40, 'rows': 5}),
}
class SponsorApplicationForm(SponsorDetailsForm):
class Meta(SponsorDetailsForm.Meta):
fields = SponsorDetailsForm.Meta.fields + [
"level",
"wants_table",
"wants_booth",
"small_entity_discount",
]
help_texts = {
'web_description': strip(
u"""
Your description can be up to 100 words long.
"""
),
}
def __init__(self, *args, **kwargs):
self.user = kwargs.pop("user")
kwargs.update({
"initial": {
"contact_name": self.user.get_full_name(),
"contact_emails": [self.user.email],
}
})
super(SponsorApplicationForm, self).__init__(*args, **kwargs)
# TODO: there should be a way to turn off each level as it
# fills, instead of having to edit code. Plus, this should
# really be a radio button, where the unavailable ones stay
# visible but grayed out with "Full" or "Out" next to them.
self.fields['level'].queryset = (
SponsorLevel.objects
.exclude(name='Open Source and Community')
# .exclude(name='Financial Aid Sponsor')
# .exclude(name='Media')
# .exclude(name='Patron')
# .exclude(name='Silver')
# .exclude(name='Gold')
# .exclude(name='Platinum')
# .exclude(name='Diamond')
# .exclude(name='Keystone')
)
def clean_web_description(self):
value = self.cleaned_data['web_description']
word_count = len(re.findall(r"[-\w']+", value.lower()))
if word_count > 100:
raise forms.ValidationError(
_(u"Your description is {} words long;"
" please reduce it to 100 or less.".format(word_count))
)
return value
def save(self, commit=True):
obj = super(SponsorApplicationForm, self).save(commit=False)
obj.applicant = self.user
if commit:
obj.save()
return obj
class SponsorBenefitsInlineFormSet(BaseInlineFormSet):
def _construct_form(self, i, **kwargs):
form = super(SponsorBenefitsInlineFormSet, self)._construct_form(i, **kwargs)
# only include the relevant data fields for this benefit type
fields = form.instance.data_fields()
form.fields = dict((k, v) for (k, v) in form.fields.items() if k in fields + ["id"])
for field in fields:
# don't need a label, the form template will label it with the benefit name
form.fields[field].label = ""
# provide word limit as help_text
if form.instance.benefit.type in ["text", "richtext"] and form.instance.max_words:
form.fields[field].help_text = u"maximum %s words" % form.instance.max_words
# use admin file widget that shows currently uploaded file
if field == "upload":
form.fields[field].widget = AdminFileWidget()
return form
SponsorBenefitsFormSet = inlineformset_factory(
Sponsor, SponsorBenefit,
formset=SponsorBenefitsInlineFormSet,
can_delete=False, extra=0,
fields=["text", "upload"]
)
class SponsorEmailForm(forms.Form):
from_ = forms.EmailField(widget=forms.TextInput(attrs={'class': 'fullwidth-input'}))
cc = forms.CharField(help_text=_(u"(comma-separated addresses)"),
required=False,
widget=forms.TextInput(attrs={'class': 'fullwidth-input'}))
bcc = forms.CharField(help_text=_(u"(comma-separated addresses)"),
required=False,
widget=forms.TextInput(attrs={'class': 'fullwidth-input'}))
subject = forms.CharField(widget=forms.TextInput(attrs={'class': 'fullwidth-input'}))
body = forms.CharField(widget=forms.Textarea(attrs={'class': 'fullwidth-textarea'}))
sample_subject = forms.CharField(
required=False,
widget=forms.TextInput(attrs={
'class': 'fullwidth-input',
'readonly': True,
'style': 'background-color: #ddd',
}),
)
sample_body = forms.CharField(
help_text=_(u"""
You can keep editing the body and hitting Send
until you love how this preview looks.
Then, press Send one final time!
"""),
required=False,
widget=forms.Textarea(attrs={
'class': 'fullwidth-textarea',
'readonly': True,
'style': 'background-color: #ddd',
}),
)
|
Python
| 0.999999
|
@@ -2253,20 +2253,24 @@
Source
-and
+Project/
Communit
|
feb1857ac556cca08513bb35599191ee9b46e174
|
Use the new name of the library module.
|
pycurl/examples/sfquery.py
|
pycurl/examples/sfquery.py
|
#! /usr/bin/env python
# -*- coding: iso-8859-1 -*-
# vi:ts=4:et
#
# sfquery -- Source Forge query script using the ClientCGI high-level interface
#
# Retrieves a SourceForge XML export object for a given project.
# Specify the *numeric* project ID. the user name, and the password,
# as arguments. If you have a valid ~/.netrc entry for sourceforge.net,
# you can just give the project ID.
#
# By Eric S. Raymond, August 2002. All rites reversed.
import os, sys, netrc
import pycurl
assert sys.version[:3] >= "2.2", "requires Python 2.2 or better"
class SourceForgeUserSession(pycurl.CurlCGI):
# SourceForge-specific methods. Sensitive to changes in site design.
def login(self, name, password):
"Establish a login session."
self.post("account/login.php", (("form_loginname", name),
("form_pw", password),
("return_to", ""),
("stay_in_ssl", "1"),
("login", "Login With SSL")))
def logout(self):
"Log out of SourceForge."
self.get("account/logout.php")
def fetch_xml(self, numid):
self.get("export/xml_export.php?group_id=%s" % numid)
if __name__ == "__main__":
if len(sys.argv) == 1:
print "Usage: %s <project id> <name> <password>" % sys.argv[0]
sys.exit(1)
project_id = sys.argv[1]
# Try to grab authenticators out of your .netrc
try:
auth = netrc.netrc().authenticators("sourceforge.net")
name, account, password = auth
except:
name = sys.argv[2]
password = sys.argv[3]
session = SourceForgeUserSession("https://sourceforge.net/")
session.set_verbosity(0)
session.login(name, password)
# Login could fail.
if session.answered("Invalid Password or User Name"):
sys.stderr.write("Login/password not accepted (%d bytes)\n" % len(session.response))
sys.exit(1)
# We'll see this if we get the right thing.
elif session.answered("Personal Page For: " + name):
session.fetch_xml(project_id)
sys.stdout.write(session.response)
session.logout()
sys.exit(0)
# Or maybe SourceForge has changed its site design so our check strings
# are no longer valid.
else:
sys.stderr.write("Unexpected page (%d bytes)\n"%len(session.response))
sys.exit(1)
|
Python
| 0
|
@@ -472,18 +472,16 @@
%0Aimport
-py
curl%0A%0Aas
@@ -573,18 +573,16 @@
Session(
-py
curl.Cur
|
03f05240145741fe1027c864a9047a2bf77c5161
|
Fix e-d-addresses + boto 2.0 incompatibility
|
euca2ools/commands/euca/describeaddresses.py
|
euca2ools/commands/euca/describeaddresses.py
|
# Software License Agreement (BSD License)
#
# Copyright (c) 2009-2011, Eucalyptus Systems, Inc.
# All rights reserved.
#
# Redistribution and use of this software 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 list of conditions and the
# following disclaimer.
#
# Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the
# following disclaimer in the documentation and/or other
# materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Author: Neil Soman neil@eucalyptus.com
# Mitch Garnaat mgarnaat@eucalyptus.com
import euca2ools.commands.eucacommand
from boto.roboto.param import Param
class DescribeAddresses(euca2ools.commands.eucacommand.EucaCommand):
APIVersion = '2011-01-01'
Description = 'Shows information about addresses.'
Args = [Param(name='ip', ptype='string',
cardinality='+', optional=True)]
Filters = [Param(name='instance-id', ptype='string',
doc='Instance the address is associated with (if any).'),
Param(name='public-ip', ptype='string',
doc='The elastic IP address.')]
def display_addresses(self, addresses):
for address in addresses:
domain = address.domain or 'standard'
address_string = '%s\t%s\t%s' % (address.public_ip,
address.instance_id,
domain)
print 'ADDRESS\t%s' % address_string
def main(self):
conn = self.make_connection_cli()
return self.make_request_cli(conn, 'get_all_addresses',
addresses=self.ip)
def main_cli(self):
addresses = self.main()
self.display_addresses(addresses)
|
Python
| 0.000442
|
@@ -2082,20 +2082,16 @@
ess.')%5D%0A
-
%0A def
@@ -2186,22 +2186,46 @@
n =
+getattr(
address
-.
+, '
domain
+', 'standard')
or
@@ -2749,10 +2749,8 @@
resses)%0A
-%0A%0A
|
f4bedfed9a7324574695c065f8a1b7132d5f4708
|
update ftbfs logic
|
ethel/commands/build.py
|
ethel/commands/build.py
|
from ethel.runners.sbuild import sbuild
from ethel.utils import upload
import glob
import os
# target package firehose
def run(dsc, package, job, firehose):
suite = job['suite']
arch = job['arch']
info, out, ftbfs = sbuild(dsc, suite, arch)
changes = "{source}*{arch}.changes".format(
source=package['source'],
arch=arch
)
changes = list(glob.glob(changes))
if changes == [] and not ftbfs:
print(out)
raise Exception("Um. No changes but no FTBFS.")
changes = changes[0]
if os.path.exists(changes):
upload(changes, job['_id'])
return (info, out, ftbfs)
|
Python
| 0
|
@@ -517,61 +517,50 @@
-changes = changes%5B0%5D%0A%0A if os.path.exists(changes):
+if not ftbfs:%0A changes = changes%5B0%5D
%0A
|
6fb8d542e29b29569c0d124e533a3f9fbf4f81e9
|
make archive_forms task work with excel as it was
|
corehq/apps/data_interfaces/utils.py
|
corehq/apps/data_interfaces/utils.py
|
from django.utils.translation import ugettext as _
from couchdbkit import ResourceNotFound
from corehq.apps.casegroups.models import CommCareCaseGroup
from corehq.apps.hqcase.utils import get_case_by_identifier
from couchforms.models import XFormInstance
from dimagi.utils.couch.database import iter_docs
from soil import DownloadBase
def add_cases_to_case_group(domain, case_group_id, uploaded_data):
response = {
'errors': [],
'success': [],
}
try:
case_group = CommCareCaseGroup.get(case_group_id)
except ResourceNotFound:
response['errors'].append(_("The case group was not found."))
return response
for row in uploaded_data:
identifier = row.get('case_identifier')
case = None
if identifier is not None:
case = get_case_by_identifier(domain, str(identifier))
if not case:
response['errors'].append(_("Could not find case with identifier '%s'." % identifier))
elif case.doc_type != 'CommCareCase':
response['errors'].append(_("It looks like the case with identifier '%s' is deleted" % identifier))
elif case._id in case_group.cases:
response['errors'].append(_("A case with identifier %s already exists in this group." % identifier))
else:
case_group.cases.append(case._id)
response['success'].append(_("Case with identifier '%s' has been added to this group." % identifier))
if response['success']:
case_group.save()
return response
def archive_forms_old(domain, user, uploaded_data):
form_ids = [row.get('form_id') for row in uploaded_data]
return archive_or_restore_forms(domain, user, form_ids, 'archive')
def archive_or_restore_forms(domain, user, form_ids, archive_or_restore, task=None):
# todo convert this to Async friendly view
response = {
'errors': [],
'success': [],
}
missing_forms = set(form_ids)
success_count = 0
if task:
DownloadBase.set_progress(task, 0, len(form_ids))
for xform_doc in iter_docs(XFormInstance.get_db(), form_ids):
xform = XFormInstance.wrap(xform_doc)
missing_forms.discard(xform['_id'])
if xform['domain'] != domain:
response['errors'].append(_(u"XFORM {form_id} does not belong to domain {domain}").format(
form_id=xform['_id'], domain=xform['domain']))
continue
xform_string = _(u"XFORM {form_id} for domain {domain} by user '{username}'").format(
form_id=xform['_id'],
domain=xform['domain'],
username=user.username)
try:
if archive_or_restore.is_archive_mode():
xform.archive(user=user.username)
message = _(u"Successfully archived {form}").format(form=xform_string)
else:
xform.unarchive(user=user.username)
message = _(u"Successfully unarchived {form}").format(form=xform_string)
response['success'].append(message)
success_count = success_count + 1
except Exception as e:
response['errors'].append(_(u"Could not archive {form}: {error}").format(
form=xform_string, error=e))
if task:
DownloadBase.set_progress(task, success_count, len(form_ids))
for missing_form_id in missing_forms:
response['errors'].append(
_(u"Could not find XForm {form_id}").format(form_id=missing_form_id))
response["success_count_msg"] = _("{success_msg} {count} form(s)".format(
success_msg=archive_or_restore.success_text,
count=success_count))
return {"messages": response}
|
Python
| 0
|
@@ -1591,24 +1591,58 @@
aded_data):%0A
+ # used by excel archive forms%0A
form_ids
@@ -1759,16 +1759,33 @@
archive'
+, from_excel=True
)%0A%0A%0Adef
@@ -1866,57 +1866,28 @@
None
-):%0A # todo convert this to Async friendly view
+, from_excel=False):
%0A
@@ -3532,24 +3532,68 @@
_form_id))%0A%0A
+ if from_excel:%0A return response%0A%0A
response
|
026f7d8c07d5ec4e307caa692c66a04653565f52
|
修复 notebook js 函数未转换的 bug
|
pyecharts/render/engine.py
|
pyecharts/render/engine.py
|
# coding=utf-8
import re
from jinja2 import Environment
from pyecharts.commons.types import Any, Optional
from ..commons.utils import write_utf8_html_file
from ..datasets import EXTRA, FILENAMES
from ..globals import CurrentConfig
class RenderEngine:
def __init__(self, env: Optional[Environment] = None):
self.env = env or CurrentConfig.GLOBAL_ENV
@staticmethod
def generate_js_link(chart: Any) -> Any:
if not chart.js_host:
chart.js_host = CurrentConfig.ONLINE_HOST
links = []
for dep in chart.js_dependencies.items:
# TODO: if?
if dep in FILENAMES:
f, ext = FILENAMES[dep]
links.append("{}{}.{}".format(chart.js_host, f, ext))
else:
for url, files in EXTRA.items():
if dep in files:
f, ext = files[dep]
links.append("{}{}.{}".format(url, f, ext))
break
chart.dependencies = links
return chart
def render_chart_to_file(self, template_name: str, chart: Any, path: str):
"""
Render a chart or page to local html files.
:param chart: A Chart or Page object
:param path: The destination file which the html code write to
:param template_name: The name of template file.
"""
tpl = self.env.get_template(template_name)
html = tpl.render(chart=self.generate_js_link(chart))
html = re.sub(r'\\n|\\t|"?__-o-__"?', "", html)
write_utf8_html_file(path, html)
def render_chart_to_notebook(self, template_name, **kwargs) -> str:
tpl = self.env.get_template(template_name)
return tpl.render(**kwargs)
|
Python
| 0
|
@@ -1715,22 +1715,22 @@
-return
+html =
tpl.ren
@@ -1743,8 +1743,84 @@
kwargs)%0A
+ html = re.sub(r'%5C%5Cn%7C%5C%5Ct%7C%22?__-o-__%22?', %22%22, html)%0A return html%0A
|
4682a44436d3267877c50735aca3f0f9f36672cc
|
Add more specific error message when deleting too many items at import
|
events/importer/sync.py
|
events/importer/sync.py
|
import logging
# Per module logger
logger = logging.getLogger(__name__)
class ModelSyncher(object):
def __init__(self, queryset, generate_obj_id,
delete_func=None, check_deleted_func=None, allow_deleting_func=None):
d = {}
self.generate_obj_id = generate_obj_id
self.delete_func = delete_func
self.check_deleted_func = check_deleted_func
self.allow_deleting_func = allow_deleting_func
# Generate a list of all objects
for obj in queryset:
d[generate_obj_id(obj)] = obj
# this only resets the initial queryset, objects outside it may still have _found or _changed True
obj._found = False
obj._changed = False
self.obj_dict = d
def mark(self, obj):
if getattr(obj, '_found', False):
raise Exception("Object %s already marked" % obj)
obj_id = self.generate_obj_id(obj)
if obj_id not in self.obj_dict:
self.obj_dict[obj_id] = obj
else:
obj = self.obj_dict[obj_id]
obj._found = True
def get(self, obj_id):
return self.obj_dict.get(obj_id, None)
def finish(self, force=False):
delete_list = []
for obj_id, obj in self.obj_dict.items():
if obj._found:
# We have to reset _found so we don't mark or match the same object across several synchers.
# Only relevant if consecutive synchers get different querysets;
# then the marked object might come from outside the initial syncher queryset.
# That results in spurious _found values in both found and non-found objects.
obj._found = False
obj._changed = False
continue
if self.check_deleted_func is not None and self.check_deleted_func(obj):
continue
delete_list.append(obj)
if len(delete_list) > 5 and len(delete_list) > len(self.obj_dict) * 0.2 and not force:
raise Exception("Attempting to delete more than 20% of total items")
for obj in delete_list:
if self.allow_deleting_func:
if not self.allow_deleting_func(obj):
raise Exception("Deleting %s not allowed by the importer" % str(obj))
if self.delete_func:
deleted = self.delete_func(obj)
else:
obj.delete()
deleted = True
if deleted:
logger.info("Deleting object %s" % obj)
|
Python
| 0
|
@@ -2048,16 +2048,17 @@
ception(
+f
%22Attempt
@@ -2075,30 +2075,65 @@
ete
-more than 20%25
+%7Blen(delete_list)%7D out
of
+a
total
+ of %7Blen(self.obj_dict)%7D
ite
|
c5d224818903ccad9624ac4cb3449af82faa55f9
|
fix typo
|
floyd/main.py
|
floyd/main.py
|
import click
import sys
from distutils.version import LooseVersion
import floyd
from floyd.cli.utils import get_cli_version
from floyd.cli.auth import login, logout
from floyd.cli.data import data
from floyd.cli.experiment import clone, delete, info, init, logs, output, status, stop
from floyd.cli.run import run, restart
from floyd.cli.version import upgrade, version
from floyd.client.version import VersionClient
from floyd.log import configure_logger
@click.group()
@click.option('-h', '--host', default='https://www.floydhub.com', help='Floyd server endpoint')
@click.option('-v', '--verbose', count=True, help='Turn on debug logging')
def cli(host, verbose):
"""
Floyd CLI interacts with FloydHub server and executes your commands.
More help is available under each command listed below.
"""
import raven
raven.Client(
dsn='https://d8669005bd2b4b1ba6387ec57e1ce660:1d25ce33fcdb4864b9fd4f0c97689a98@sentry.io/226940',
release=get_cli_version(),
environment='prod',
processors=('raven.processors.SanitizePasswordsProcessr',))
floyd.floyd_host = host
configure_logger(verbose)
check_cli_version()
def check_cli_version():
"""
Check if the current cli version satisfies the server requirements
"""
server_version = VersionClient().get_cli_version()
current_version = get_cli_version()
if LooseVersion(current_version) < LooseVersion(server_version.min_version):
print("""
Your version of CLI (%s) is no longer compatible with server.""" % current_version)
if click.confirm('Do you want to upgrade to version %s now?' % server_version.latest_version):
from floyd.cli.version import pip_upgrade
pip_upgrade()
sys.exit(0)
else:
print("""Your can manually run:
pip install -U floyd-cli
to upgrade to the latest version (%s))""" % server_version.latest_version)
sys.exit(0)
elif LooseVersion(current_version) < LooseVersion(server_version.latest_version):
print("""
New version of CLI (%s) is now available. To upgrade run:
pip install -U floyd-cli
""" % server_version.latest_version)
def add_commands(cli):
cli.add_command(clone)
cli.add_command(data)
cli.add_command(delete)
cli.add_command(info)
cli.add_command(init)
cli.add_command(login)
cli.add_command(logout)
cli.add_command(logs)
cli.add_command(output)
cli.add_command(status)
cli.add_command(stop)
cli.add_command(restart)
cli.add_command(run)
cli.add_command(upgrade)
cli.add_command(version)
add_commands(cli)
|
Python
| 0.999991
|
@@ -1077,16 +1077,17 @@
sProcess
+o
r',))%0A%0A
|
41d3298eb716ad813a82f56fbfb2771373338c09
|
Make this test pass by checking for 61 which is what OS X uses as connection refused, apparently
|
greentest/test__socket_errors.py
|
greentest/test__socket_errors.py
|
# Copyright (c) 2008-2009 AG Projects
# Author: Denis Bilenko
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import unittest
from eventlet import api
if hasattr(api._threadlocal, 'hub'):
from eventlet.green import socket
else:
import socket
class TestSocketErrors(unittest.TestCase):
def test_connection_refused(self):
s = socket.socket()
try:
s.connect(('127.0.0.1', 81))
except socket.error, ex:
code, text = ex.args
assert code == 111, (code, text)
assert 'refused' in text.lower(), (code, text)
if __name__=='__main__':
unittest.main()
|
Python
| 0
|
@@ -1518,14 +1518,20 @@
ode
-== 111
+in %5B111, 61%5D
, (c
|
e25ff765e423511da57f04c96227d2ca69e7c149
|
Update focal_loss.py
|
focal_loss.py
|
focal_loss.py
|
from keras import backend as K
'''
Compatible with tensorflow backend
'''
def focal_loss(gamma=2., alpha=.25):
def focal_loss_fixed(y_true, y_pred):
pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))
pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))
return -K.sum(alpha * K.pow(1. - pt_1, gamma) * K.log(pt_1))-K.sum((1-alpha) * K.pow( pt_0, gamma) * K.log(1. - pt_0))
return focal_loss_fixed
|
Python
| 0
|
@@ -308,19 +308,20 @@
turn -K.
-sum
+mean
(alpha *
@@ -363,18 +363,23 @@
_1))
--K.sum((1-
+ - K.mean((1 -
alph
@@ -389,17 +389,16 @@
* K.pow(
-
pt_0, ga
|
c626e6a39b239e78c45dadf8b8c4479b6d75da04
|
Use UUID values for survey multi-option fields
|
indico/modules/events/surveys/fields/simple.py
|
indico/modules/events/surveys/fields/simple.py
|
# This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico 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.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from wtforms.fields import IntegerField, BooleanField, StringField, SelectField, TextAreaField
from wtforms.validators import NumberRange, Optional, ValidationError, Length, DataRequired
from indico.modules.events.surveys.fields.base import SurveyField, FieldConfigForm
from indico.util.i18n import _
from indico.web.forms.fields import IndicoRadioField, MultipleItemsField, IndicoSelectMultipleCheckboxField
from indico.web.forms.validators import HiddenUnless
from indico.web.forms.widgets import SwitchWidget
class TextConfigForm(FieldConfigForm):
max_length = IntegerField(_('Max length'), [Optional(), NumberRange(min=1)])
multiline = BooleanField(_('Multiline'), widget=SwitchWidget(),
description=_("If the field should be rendered as a textarea instead of a single-line "
"text field."))
class TextField(SurveyField):
name = 'text'
friendly_name = _('Text')
config_form = TextConfigForm
@property
def wtf_field_class(self):
return TextAreaField if self.question.field_data.get('multiline') else StringField
@property
def validators(self):
max_length = self.question.field_data.get('max_length')
return [Length(max=max_length)] if max_length else None
class NumberConfigForm(FieldConfigForm):
min_value = IntegerField(_('Min value'), [Optional()])
max_value = IntegerField(_('Max value'), [Optional()])
def _validate_min_max_value(self, field):
if (self.min_value.data is not None and self.max_value.data is not None and
self.min_value.data >= self.max_value.data):
raise ValidationError(_('The min value must be less than the max value.'))
validate_min_value = _validate_min_max_value
validate_max_value = _validate_min_max_value
class NumberField(SurveyField):
name = 'number'
friendly_name = _('Number')
config_form = NumberConfigForm
wtf_field_class = IntegerField
@property
def validators(self):
min_value = self.question.field_data.get('min_value')
max_value = self.question.field_data.get('max_value')
return [NumberRange(min=min_value, max=max_value)]
class BoolField(SurveyField):
name = 'bool'
friendly_name = _('Yes/No')
def create_wtf_field(self):
return self._make_wtforms_field(BooleanField, widget=SwitchWidget())
class SingleChoiceConfigForm(FieldConfigForm):
display_type = IndicoRadioField(_('Display type'), [DataRequired()],
description=_('Show the question either as radio button or select'),
choices=[('radio', _('Show as radio button')),
('select', _('Show as select field'))],
default='radio')
radio_display_type = IndicoRadioField(_('Arrangment of available options'),
[HiddenUnless('display_type', 'radio')],
choices=[('vertical', _('Vertical alignment')),
('horizontal', _('Horizontal alignment'))])
options = MultipleItemsField(_('Options'), [DataRequired()],
fields=[('option', _('Option'))], unique_field='option',
description=_('Specify options available for selection by user'))
class SingleChoiceField(SurveyField):
name = 'single_choice'
friendly_name = _('Single Choice')
config_form = SingleChoiceConfigForm
def create_wtf_field(self):
field_options = {}
if self.question.field_data['display_type'] == 'select':
field_class = SelectField
else:
field_class = IndicoRadioField
field_options['orientation'] = self.question.field_data['radio_display_type']
options = [x['option'] for x in self.question.field_data['options']]
choices = zip(options, options)
return self._make_wtforms_field(field_class, choices=choices, **field_options)
class MultiSelectConfigForm(FieldConfigForm):
options = MultipleItemsField(_('Options'), [DataRequired()], fields=[('option', _('Option'))],
unique_field='option',
description=_('Specify choices available for selection by user'))
class MultiSelectField(SurveyField):
name = 'multiselect'
friendly_name = _('Select multiple')
config_form = MultiSelectConfigForm
def create_wtf_field(self):
options = [x['option'] for x in self.question.field_data['options']]
choices = zip(options, options)
return self._make_wtforms_field(IndicoSelectMultipleCheckboxField, choices=choices)
|
Python
| 0
|
@@ -4113,32 +4113,49 @@
_field='option',
+ uuid_field='id',
%0A
@@ -4199,47 +4199,44 @@
ify
-options available for selection by user
+the answers the user can choose from
'))%0A
@@ -4696,35 +4696,45 @@
e'%5D%0A
-options = %5B
+choices = %5B(x%5B'id'%5D,
x%5B'option'%5D
@@ -4724,32 +4724,33 @@
d'%5D, x%5B'option'%5D
+)
for x in self.q
@@ -4784,48 +4784,8 @@
'%5D%5D%0A
- choices = zip(options, options)%0A
@@ -5069,16 +5069,33 @@
option',
+ uuid_field='id',
%0A
@@ -5147,47 +5147,39 @@
ify
-choices available for selection by user
+the answers the user can select
'))%0A
@@ -5368,19 +5368,29 @@
-options = %5B
+choices = %5B(x%5B'id'%5D,
x%5B'o
@@ -5396,16 +5396,17 @@
option'%5D
+)
for x i
@@ -5448,48 +5448,8 @@
'%5D%5D%0A
- choices = zip(options, options)%0A
|
6b992aa75c0f553ca5066cda269e93d4f63ea4a5
|
Optimize banned host validation test
|
corehq/util/tests/test_validation.py
|
corehq/util/tests/test_validation.py
|
from corehq.util.validation import is_url_or_host_banned
from django.test import TestCase
def inclusive_range(start, stop):
return range(start, stop + 1)
class ValidationTestCase(TestCase):
def testBannedHosts(self):
self.assertTrue(is_url_or_host_banned('anything.commcarehq.org'))
for i in inclusive_range(0, 255):
for j in inclusive_range(0, 255):
for k in inclusive_range(0, 255):
self.assertTrue(is_url_or_host_banned('10.%s.%s.%s' % (i, j, k)))
for i in inclusive_range(16, 31):
for j in inclusive_range(0, 255):
for k in inclusive_range(0, 255):
self.assertTrue(is_url_or_host_banned('172.%s.%s.%s' % (i, j, k)))
for i in inclusive_range(0, 255):
for j in inclusive_range(0, 255):
self.assertTrue(is_url_or_host_banned('192.168.%s.%s' % (i, j)))
self.assertTrue(is_url_or_host_banned('127.0.0.1'))
self.assertTrue(is_url_or_host_banned('localhost'))
self.assertFalse(is_url_or_host_banned('dimagi.com'))
|
Python
| 0
|
@@ -1,12 +1,39 @@
+from random import sample%0A%0A
from corehq.
@@ -115,21 +115,17 @@
se%0A%0A
-%0A
def
-inclusiv
+sampl
e_ra
@@ -150,15 +150,85 @@
-return
+yield start%0A num_samples = min(8, stop - start)%0A for middle in sample(x
rang
@@ -238,19 +238,70 @@
tart
+ + 1
, stop
- + 1)
+), num_samples):%0A yield middle%0A yield stop
%0A%0A%0Ac
@@ -455,32 +455,29 @@
for i in
-inclusiv
+sampl
e_range(0, 2
@@ -498,32 +498,29 @@
for j in
-inclusiv
+sampl
e_range(0, 2
@@ -545,32 +545,29 @@
for k in
-inclusiv
+sampl
e_range(0, 2
@@ -671,32 +671,29 @@
for i in
-inclusiv
+sampl
e_range(16,
@@ -714,32 +714,29 @@
for j in
-inclusiv
+sampl
e_range(0, 2
@@ -761,32 +761,29 @@
for k in
-inclusiv
+sampl
e_range(0, 2
@@ -888,32 +888,29 @@
for i in
-inclusiv
+sampl
e_range(0, 2
@@ -939,16 +939,13 @@
in
-inclusiv
+sampl
e_ra
|
99c14c2156ed1d087594e2640af7ec8d888ba4ae
|
Update to v17.1.19
|
make.py
|
make.py
|
#!/usr/bin/env python
import logging
import os
import shutil
import tempfile
import zipfile
try:
from urllib.parse import urljoin
from urllib.request import urlretrieve
except ImportError:
from urllib import urlretrieve
from urlparse import urljoin
import yaml
from PIL import Image
logging.basicConfig(level=logging.INFO)
DIST_DIR = 'emojis'
AWS_ICON_DOWNLOAD_URL = 'https://media.amazonwebservices.com/AWS-Design/Arch-Center/16.2.22_Update/AWS_Simple_Icons_EPS-SVG_v16.2.22.zip'
BASE_URL = 'https://raw.githubusercontent.com/Surgo/aws_emojipacks/master/'
IGNORED_SERVICE_GROUPS = ('General', 'SDK')
ALLOW_CHILD_SERVICES = ('Kinesis', )
REPLACE_NAMES = {
'ImportExportSnowball': 'Snowball',
'ElasticLoadBalancing': 'ELB',
}
IGNORED_NAMES = (
'DatabaseMigrationService',
'Kinesis-enabledapp',
'snapshot',
'volume',
)
def cleanup_dist_dir(dist_dir):
if os.path.exists(dist_dir):
shutil.rmtree(dist_dir)
os.mkdir(dist_dir)
def download_icons(icons_url, dist_path):
dist_path, headers = urlretrieve(icons_url, filename=dist_path)
logging.info("Download to: %s", dist_path)
return dist_path
def get_friendly_name_from_filename(path):
filename = os.path.basename(path)
friendly_name, _ = os.path.splitext(filename)
_, friendly_name = friendly_name.split('_', 1)
friendly_name = friendly_name.replace('Amazon', '').replace('AWS', '')
name_parts = friendly_name.split('_')
if len(name_parts) >= 2:
if name_parts[0] not in ALLOW_CHILD_SERVICES:
return None
friendly_name = name_parts[-1]
if friendly_name in REPLACE_NAMES:
friendly_name = REPLACE_NAMES[friendly_name]
if friendly_name in IGNORED_NAMES:
return None
return friendly_name.lower()
def get_images_from_archive_file(archived_filename):
with zipfile.ZipFile(archived_filename, 'r') as archived_file:
for path in archived_file.namelist():
path_parts = path.split(os.sep)
if len(path_parts) != 3:
continue
base, group, filename = path_parts
if not filename.endswith('.png'):
continue
if group in IGNORED_SERVICE_GROUPS:
continue
friendly_name = get_friendly_name_from_filename(filename)
if not friendly_name:
continue
with archived_file.open(path) as image_file:
yield Image.open(image_file), friendly_name
def emojinize_image(image):
image.thumbnail((128, 128), Image.ANTIALIAS)
return image
def download_and_save_icons(dist_dir):
saved_icons = dict()
temp_dir = tempfile.gettempdir()
temp_path = download_icons(AWS_ICON_DOWNLOAD_URL, os.path.join(temp_dir, 'icons.zip'))
for image, friendly_name in get_images_from_archive_file(temp_path):
emoji_icon = emojinize_image(image)
dist_path = os.path.join(
dist_dir,
'{name}.{ext}'.format(name=friendly_name, ext='png'),
)
emoji_icon.save(dist_path, 'PNG', optimize=True)
logging.info("Save emoji: %s", dist_path)
saved_icons[friendly_name] = dist_path
return saved_icons
def generate_emojipacks_yaml_data(base_url, saved_icons, prefix=None):
emoji_data = []
for friendly_name, dist_path in saved_icons.items():
emoji_data.append(
dict(
name=prefix and '{prefix}-{name}'.format(prefix=prefix, name=friendly_name) or friendly_name,
src=urljoin(base_url, dist_path),
),
)
return dict(
title="aws service icons",
emojis=emoji_data,
)
if __name__ == '__main__':
cleanup_dist_dir(DIST_DIR)
saved_icons = download_and_save_icons(DIST_DIR)
for prefix in (None, 'aws'):
emojipacks_yaml_data = generate_emojipacks_yaml_data(BASE_URL, saved_icons, prefix=prefix)
yaml_filename = '{prefix}-emojipacks.yml'.format(prefix=prefix or 'noprefix')
with (open(yaml_filename, 'w')) as yaml_file:
yaml.dump(emojipacks_yaml_data, yaml_file, default_flow_style=False)
logging.info("Save yaml: %s", yaml_filename)
|
Python
| 0
|
@@ -443,22 +443,22 @@
Center/1
-6.2.22
+7.1.19
_Update/
@@ -488,14 +488,14 @@
G_v1
-6.2.22
+7.1.19
.zip
|
f006136d805989330ba7c496c3113b80518d7f4a
|
Fix a small stuff
|
functional_tests/test_jahia2wp.py
|
functional_tests/test_jahia2wp.py
|
"""(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2017"""
import os
import pytest
from settings import DOCKER_IP, OPENSHIFT_ENV, TEST_SITE, SRC_DIR_PATH
from utils import Utils
from wordpress import WPUser
from wordpress.generator import MockedWPGenerator
SCRIPT_FILE = os.path.join(SRC_DIR_PATH, 'jahia2wp.py')
SITE_URL_SPECIFIC = "http://{0}/{1}".format(DOCKER_IP, TEST_SITE)
UNIT_NAME = "idevelop"
@pytest.fixture(scope="module")
def setup():
wp_env = OPENSHIFT_ENV
wp_url = SITE_URL_SPECIFIC
unit_name = UNIT_NAME
wp_generator = MockedWPGenerator(wp_env, wp_url, unit_name)
if wp_generator.wp_config.is_installed:
wp_generator.clean()
class TestCommandLine:
# ORDER matters
def test_check_one_fails(self, setup):
assert not Utils.run_command('python %s check %s %s'
% (SCRIPT_FILE, OPENSHIFT_ENV, SITE_URL_SPECIFIC))
def test_clean_one_fails(self):
assert not Utils.run_command('python %s clean %s %s'
% (SCRIPT_FILE, OPENSHIFT_ENV, SITE_URL_SPECIFIC))
def test_generate_one_success(self):
expected = "Successfully created new WordPress site at {}".format(SITE_URL_SPECIFIC)
assert Utils.run_command('python %s generate %s %s'
% (SCRIPT_FILE, OPENSHIFT_ENV, SITE_URL_SPECIFIC)) == expected
def test_backup_full(self):
expected = "Successfully backed-up WordPress site for {}".format(SITE_URL_SPECIFIC)
assert Utils.run_command('python %s backup %s %s'
% (SCRIPT_FILE, OPENSHIFT_ENV, SITE_URL_SPECIFIC)) == expected
def test_backup_incremental(self):
expected = "Successfully backed-up WordPress site for {}".format(SITE_URL_SPECIFIC)
assert Utils.run_command('python %s backup %s %s --backup-type=inc'
% (SCRIPT_FILE, OPENSHIFT_ENV, SITE_URL_SPECIFIC)) == expected
def test_list_plugins(self):
expected = "Plugin list for site '"
assert Utils.run_command('python %s list-plugins %s %s'
% (SCRIPT_FILE, OPENSHIFT_ENV, SITE_URL_SPECIFIC)).startswith(expected)
def test_generate_one_fails(self):
assert not Utils.run_command('python %s generate %s %s'
% (SCRIPT_FILE, OPENSHIFT_ENV, SITE_URL_SPECIFIC))
def test_check_one_success(self):
expected = "WordPress site valid and accessible at {}".format(SITE_URL_SPECIFIC)
assert Utils.run_command('python %s check %s %s'
% (SCRIPT_FILE, OPENSHIFT_ENV, SITE_URL_SPECIFIC)) == expected
def test_wp_version(self):
expected = Utils.get_mandatory_env(key="WP_VERSION")
# we do the check only if a specific version was given
# (e.g. "4.9"), because "latest" will depend on when
# the test is run
if expected != "latest":
assert Utils.run_command('python %s version %s %s'
% (SCRIPT_FILE, OPENSHIFT_ENV, SITE_URL_SPECIFIC)) == expected
def test_wp_admins(self):
user = WPUser(
Utils.get_mandatory_env(key="WP_ADMIN_USER"),
Utils.get_mandatory_env(key="WP_ADMIN_EMAIL"),
role='administrator')
expected = repr(user)
assert Utils.run_command('python %s admins %s %s'
% (SCRIPT_FILE, OPENSHIFT_ENV, SITE_URL_SPECIFIC)) == expected
def test_inventory(self):
version = Utils.run_command('python %s version %s %s' % (SCRIPT_FILE, OPENSHIFT_ENV, SITE_URL_SPECIFIC))
expected_lines = [
"path;valid;url;version;db_name;db_user;admins",
"/srv/{0}/{1}/htdocs/{2};ok;{3};{4};wp_".format(
OPENSHIFT_ENV, DOCKER_IP, TEST_SITE, SITE_URL_SPECIFIC, version),
]
output = Utils.run_command(
'python {0} inventory {1} /srv/{1}/{2}'.format(
SCRIPT_FILE, OPENSHIFT_ENV, DOCKER_IP))
for expected_line in expected_lines:
assert expected_line in output
def test_clean_one(self):
assert Utils.run_command('python %s clean %s %s'
% (SCRIPT_FILE, OPENSHIFT_ENV, SITE_URL_SPECIFIC))
|
Python
| 0.999426
|
@@ -416,31 +416,8 @@
ITE)
-%0AUNIT_NAME = %22idevelop%22
%0A%0A@p
@@ -521,34 +521,8 @@
FIC%0A
- unit_name = UNIT_NAME%0A
@@ -574,17 +574,18 @@
rl,
-unit_name
+%22idevelop%22
)%0A
|
a4b7be1a8c6d44c272ce25acf9513054d6bee4ad
|
Fix in listports to work with windows
|
python_loader/listports.py
|
python_loader/listports.py
|
"""BlinkyTape Python communication library.
This code assumes stock serialLoop() in the firmware.
Commands are issued in 3-byte blocks, with pixel data
encoded in RGB triplets in range 0-254, sent sequentially
and a triplet ending with a 255 causes the accumulated pixel
data to display (a show command).
Note that with the stock firmware changing the maximum brightness
over serial communication is impossible.
"""
from serial.tools import list_ports
import re
import platform
def listPorts():
allPorts = list_ports.comports()
ports = []
# Regular expression that identifies the serial port to use
# for OS/X:
if platform.system() == 'Darwin':
match = '/dev/cu\.usb*'
# For Linux:
elif platform.system() == 'Linux':
match = '/dev/ttyACM*'
# TODO: Windows ?
else:
match = "*"
for port in allPorts:
# If the port name is acceptable, add it to the list
if re.match(match, port[0]) != None:
ports.append(port[0])
return ports
# Example code
if __name__ == "__main__":
print listPorts()
|
Python
| 0
|
@@ -853,11 +853,11 @@
h =
-%22*%22
+'.'
%0A%0A
|
c1ad95ee4680836fc359ee636a2252925a41b3a9
|
fix raw_id_fields on admin. closes #33
|
knowledge/admin.py
|
knowledge/admin.py
|
from django.contrib import admin
from knowledge.models import Question, Response, Category
class CategoryAdmin(admin.ModelAdmin):
list_display = [f.name for f in Category._meta.fields]
prepopulated_fields = {'slug': ('title', )}
admin.site.register(Category, CategoryAdmin)
class QuestionAdmin(admin.ModelAdmin):
list_display = [f.name for f in Question._meta.fields]
list_select_related = True
admin.site.register(Question, QuestionAdmin)
class ResponseAdmin(admin.ModelAdmin):
list_display = [f.name for f in Response._meta.fields]
list_select_related = True
admin.site.register(Response, ResponseAdmin)
|
Python
| 0.000001
|
@@ -401,32 +401,61 @@
_related = True%0A
+ raw_id_fields = %5B'user'%5D%0A
admin.site.regis
@@ -614,16 +614,57 @@
= True%0A
+ raw_id_fields = %5B'user', 'question'%5D%0A
admin.si
|
4c052b2429d7b48768f51cef0627e7a1772909b3
|
Fix import
|
dbaas/workflow/steps/tests/test_base_step.py
|
dbaas/workflow/steps/tests/test_base_step.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import logging
from django.test import TestCase
from ..base import BaseStep
LOG = logging.getLogger(__name__)
class BaseStepTestCase(TestCase):
def setUp(self):
self.base_step = BaseStep()
def test_has_do_method(self):
self.assertTrue(hasattr(self.base_step, 'do'))
def test_has_undo_method(self):
self.assertTrue(hasattr(self.base_step, 'undo'))
def test_do_requires_workflow_dict(self):
try:
self.base_step.do()
except TypeError:
exception = True
self.assertTrue(exception)
def test_undo_requires_workflow_dict(self):
try:
self.base_step.undo()
except TypeError:
exception = True
self.assertTrue(exception)
|
Python
| 0.000002
|
@@ -129,16 +129,21 @@
%0Afrom ..
+util.
base imp
|
b70e34d399b171b3d8e0731206dde54f8d029379
|
Add uuid to import
|
casstest/casstest.py
|
casstest/casstest.py
|
# -*- coding: utf-8 -*-
import os
from cassandra.io.libevreactor import LibevConnection
from cassandra.cluster import Cluster
seed = os.environ.get('SEED', '127.0.0.1')
port = int(os.environ.get('PORT', '9042'))
keyspace = os.environ.get('KEYSPACE', 'test')
def test_read(session, user_id, age):
read_query = 'SELECT name, age, user_id FROM users'
rows = session.execute(read_query)
for row in rows:
assert(row.name == "John O'Reilly")
assert(row.age == age)
assert(row.user_id == user_id)
def main():
print('Connecting to seed {0} on port {1}'.format(seed, port))
cluster = Cluster([seed], port=port)
cluster.connection_class = LibevConnection
print('Using keyspace {0}'.format(keyspace))
session = cluster.connect(keyspace)
user_id = uuid.uuid1()
create_query = """
INSERT INTO users (name, age, user_id)
VALUES (%s, %s, %s)
""", ("John O'Reilly", 42, user_id)
session.execute(create_query)
test_read(session, user_id, 42)
update_query = 'UPDATE users SET age = 84'
session.execute(update_query)
test_read(session, user_id, 84)
delete_query = 'DELETE name, age, user_id FROM users'
session.execute(delete_query)
if __name__ == '__main__':
main()
|
Python
| 0
|
@@ -27,16 +27,28 @@
port os%0A
+import uuid%0A
from cas
|
050e7de57d0a7c1298c6801373fe1f58c856d1ea
|
fix pep8
|
khmer/utils.py
|
khmer/utils.py
|
from __future__ import print_function, unicode_literals
#
# This file is part of khmer, https://github.com/dib-lab/khmer/, and is
# Copyright (C) Michigan State University, 2009-2015. It is licensed under
# the three-clause BSD license; see LICENSE.
# Contact: khmer-project@idyll.org
#
# Convenience functions for performing common argument-checking tasks in
# scripts.
def print_error(msg):
"""Print the given message to 'stderr'."""
import sys
print(msg, file=sys.stderr)
def _split_left_right(name):
"""Split record name at the first whitespace and return both parts.
RHS is set to an empty string if not present.
"""
parts = name.split(None, 1)
lhs, rhs = [parts[0], parts[1] if len(parts) > 1 else '']
return lhs, rhs
def check_is_pair(record1, record2):
"""Check if the two sequence records belong to the same fragment.
In an matching pair the records are left and right pairs
of each other, respectively. Returns True or False as appropriate.
Handles both Casava formats: seq/1 and seq/2, and 'seq::... 1::...'
and 'seq::... 2::...'.
Also handles the default format of the SRA toolkit's fastq-dump:
'Accession seq/1'
"""
if hasattr(record1, 'quality') or hasattr(record2, 'quality'):
if not (hasattr(record1, 'quality') and hasattr(record2, 'quality')):
raise ValueError("both records must be same type (FASTA or FASTQ)")
lhs1, rhs1 = _split_left_right(record1.name)
lhs2, rhs2 = _split_left_right(record2.name)
# handle 'name/1'
if lhs1.endswith('/1') and lhs2.endswith('/2'):
subpart1 = lhs1.split('/', 1)[0]
subpart2 = lhs2.split('/', 1)[0]
if subpart1 and subpart1 == subpart2:
return True
# handle '@name 1:rst'
elif lhs1 == lhs2 and rhs1.startswith('1:') and rhs2.startswith('2:'):
return True
# handle @name seq/1
elif lhs1 == lhs2 and rhs1.endswith('/1') and rhs2.endswith('/2'):
subpart1 = rhs1.split('/', 1)[0]
subpart2 = rhs2.split('/', 1)[0]
if subpart1 and subpart1 == subpart2:
return True
return False
def check_is_left(name):
"""Check if the name belongs to a 'left' sequence (/1).
Returns True or False.
Handles both Casava formats: seq/1 and 'seq::... 1::...'
"""
lhs, rhs = _split_left_right(name)
if lhs.endswith('/1'): # handle 'name/1'
return True
elif rhs.startswith('1:'): # handle '@name 1:rst'
return True
elif rhs.endswith('/1'): # handles '@name seq/1'
return True
return False
def check_is_right(name):
"""Check if the name belongs to a 'right' sequence (/2).
Returns True or False.
Handles both Casava formats: seq/2 and 'seq::... 2::...'
"""
lhs, rhs = _split_left_right(name)
if lhs.endswith('/2'): # handle 'name/2'
return True
elif rhs.startswith('2:'): # handle '@name 2:rst'
return True
elif rhs.endswith('/2'): # handles '@name seq/2'
return True
return False
def broken_paired_reader(screed_iter, min_length=None,
force_single=False, require_paired=False):
"""Read pairs from a stream.
A generator that yields singletons and pairs from a stream of FASTA/FASTQ
records (yielded by 'screed_iter'). Yields (n, is_pair, r1, r2) where
'r2' is None if is_pair is False.
The input stream can be fully single-ended reads, interleaved paired-end
reads, or paired-end reads with orphans, a.k.a. "broken paired".
Usage::
for n, is_pair, read1, read2 in broken_paired_reader(...):
...
Note that 'n' behaves like enumerate() and starts at 0, but tracks
the number of records read from the input stream, so is
incremented by 2 for a pair of reads.
If 'min_length' is set, all reads under this length are ignored (even
if they are pairs).
If 'force_single' is True, all reads are returned as singletons.
"""
record = None
prev_record = None
n = 0
if force_single and require_paired:
raise ValueError("force_single and require_paired cannot both be set!")
# handle the majority of the stream.
for record in screed_iter:
# ignore short reads
if min_length and len(record.sequence) < min_length:
record = None
continue
if prev_record:
if check_is_pair(prev_record, record) and not force_single:
yield n, True, prev_record, record # it's a pair!
n += 2
record = None
else: # orphan.
if require_paired:
raise ValueError("Unpaired reads when require_paired"
" is set!")
yield n, False, prev_record, None
n += 1
prev_record = record
record = None
# handle the last record, if it exists (i.e. last two records not a pair)
if prev_record:
if require_paired:
raise ValueError("Unpaired reads when require_paired is set!")
yield n, False, prev_record, None
def write_record(record, fileobj):
"""Write sequence record to 'fileobj' in FASTA/FASTQ format."""
if hasattr(record, 'quality'):
recstr = '@{name}\n{sequence}\n+\n{quality}\n'.format(
name=record.name,
sequence=record.sequence,
quality=record.quality)
else:
recstr = '>{name}\n{sequence}\n'.format(
name=record.name,
sequence=record.sequence)
try:
fileobj.write(bytes(recstr, 'utf-8'))
except TypeError:
fileobj.write(recstr)
def write_record_pair(read1, read2, fileobj):
"""Write a pair of sequence records to 'fileobj' in FASTA/FASTQ format."""
if hasattr(read1, 'quality'):
assert hasattr(read2, 'quality')
write_record(read1, fileobj)
write_record(read2, fileobj)
# vim: set ft=python ts=4 sts=4 sw=4 et tw=79:
|
Python
| 0.000001
|
@@ -1171,17 +1171,16 @@
tq-dump:
-
%0A 'Ac
|
eb4bd0931cee9ee1e9d3fdd3ae4d4742032fc16e
|
fix pplot example for uneven grids
|
examples/ensemble/plot_partial_dependence.py
|
examples/ensemble/plot_partial_dependence.py
|
"""
========================
Partial Dependence Plots
========================
Partial dependence plots show the dependence between the target function [2]_
and a set of 'target' features, marginalizing over the
values of all other features (the complement features). Due to the limits
of human perception the size of the target feature set must be small (usually,
one or two) thus the target features are usually chosen among the most
important features
(see :attr:`~sklearn.ensemble.GradientBoostingRegressor.feature_importances_`).
This example shows how to obtain partial dependence plots from a
:class:`~sklearn.ensemble.GradientBoostingRegressor` trained on the California
housing dataset. The example is taken from [1]_.
The plot shows four one-way and one two-way partial dependence plots.
The target variables for the one-way PDP are:
median income (`MedInc`), avg. occupants per household (`AvgOccup`),
median house age (`HouseAge`), and avg. rooms per household (`AveRooms`).
We can clearly see that the median house price shows a linear relationship
with the median income (top left) and that the house price drops when the
avg. occupants per household increases (top middle).
The top right plot shows that the house age in a district does not have
a strong influence on the (median) house price; so does the average rooms
per household.
The tick marks on the x-axis represent the deciles of the feature values
in the training data.
Partial dependence plots with two target features enable us to visualize
interactions among them. The two-way partial dependence plot shows the
dependence of median house price on joint values of house age and avg.
occupants per household. We can clearly see an interaction between the
two features:
For an avg. occupancy greater than two, the house price is nearly independent
of the house age, whereas for values less than two there is a strong dependence
on age.
.. [1] T. Hastie, R. Tibshirani and J. Friedman,
"Elements of Statistical Learning Ed. 2", Springer, 2009.
.. [2] For classification you can think of it as the regression score before
the link function.
"""
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from six.moves.urllib.error import HTTPError
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.ensemble.partial_dependence import plot_partial_dependence
from sklearn.ensemble.partial_dependence import partial_dependence
from sklearn.datasets.california_housing import fetch_california_housing
def main():
cal_housing = fetch_california_housing()
# split 80/20 train-test
X_train, X_test, y_train, y_test = train_test_split(cal_housing.data,
cal_housing.target,
test_size=0.2,
random_state=1)
names = cal_housing.feature_names
print('_' * 80)
print("Training GBRT...")
clf = GradientBoostingRegressor(n_estimators=100, max_depth=4,
learning_rate=0.1, loss='huber',
random_state=1)
clf.fit(X_train, y_train)
print("done.")
print('_' * 80)
print('Convenience plot with ``partial_dependence_plots``')
print
features = [0, 5, 1, 2, (5, 1)]
fig, axs = plot_partial_dependence(clf, X_train, features,
feature_names=names,
n_jobs=3, grid_resolution=50)
fig.suptitle('Partial dependence of house value on nonlocation features\n'
'for the California housing dataset')
plt.subplots_adjust(top=0.9) # tight_layout causes overlap with suptitle
print('_' * 80)
print('Custom 3d plot via ``partial_dependence``')
print
fig = plt.figure()
target_feature = (1, 5)
pdp, (x_axis, y_axis) = partial_dependence(clf, target_feature,
X=X_train, grid_resolution=50)
XX, YY = np.meshgrid(x_axis, y_axis)
Z = pdp.T.reshape(XX.shape).T
ax = Axes3D(fig)
surf = ax.plot_surface(XX, YY, Z, rstride=1, cstride=1, cmap=plt.cm.BuPu)
ax.set_xlabel(names[target_feature[0]])
ax.set_ylabel(names[target_feature[1]])
ax.set_zlabel('Partial dependence')
# pretty init view
ax.view_init(elev=22, azim=122)
plt.colorbar(surf)
plt.suptitle('Partial dependence of house value on median age and '
'average occupancy')
plt.subplots_adjust(top=0.9)
plt.show()
# Needed on Windows because plot_partial_dependence uses multiprocessing
if __name__ == '__main__':
main()
|
Python
| 0.000001
|
@@ -3994,32 +3994,20 @@
pdp,
-(x_axis, y_axis)
+axes
= parti
@@ -4041,28 +4041,16 @@
eature,%0A
-
@@ -4136,22 +4136,24 @@
rid(
-x_axis, y_axis
+axes%5B0%5D, axes%5B1%5D
)%0A
@@ -4161,18 +4161,19 @@
Z = pdp
-.T
+%5B0%5D
.reshape
@@ -4177,16 +4177,32 @@
ape(
-XX.shape
+list(map(np.size, axes))
).T%0A
|
e140b67659c3183ac4e1bc4c35dc7bd7ec60f3d2
|
remove <br>
|
gaeupload/handler_web.py
|
gaeupload/handler_web.py
|
# handler_web.py
#
#
""" web request handler. """
import time
import logging
starttime = time.time()
#logging.debug('start time: %s' % time.ctime(time.time()))
## gozerlib imports
from gozerlib.utils.generic import fromenc, toenc, getversion
from gozerlib.utils.xmpp import stripped
from gozerlib.plugins import plugs
from gozerlib.config import cfg
from gozerlib.utils.exception import handle_exception
from gozerlib.boot import boot, getcmndtable, getpluginlist
from gozerlib.persist import Persist
from gozerlib.errors import NoSuchCommand
from gozerlib.utils.log import setloglevel
## gaelib import
from gozerlib.gae.web.bot import WebBot
from gozerlib.gae.web.event import WebEvent
from gozerlib.gae.utils.auth import checkuser
from gozerlib.gae.utils.web import commandbox, start, closer, loginurl, logouturl
## google imports
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.api import users as gusers
## simplejson import
from simplejson import loads
## basic imports
import wsgiref.handlers
import sys
import time
import types
import os
import logging
## init
logging.info(getversion('GAE WEB'))
boot()
## define
bot = WebBot(name='webbot')
## classes
class DispatchHandler(webapp.RequestHandler):
""" the bots web command dispatcher. """
def get(self):
""" show basic page. """
global starttime
if starttime:
self.response.starttime = starttime
starttime = 0
else:
self.response.starttime = time.time()
event = WebEvent(bot=bot).parse(self.response, self.request)
event.cbtype = "WEB"
(userhost, user, u, nick) = checkuser(self.response, self.request, event)
#logging.warn("web_handler - in")
login = loginurl(self.response)
logout = logouturl(self.response)
self.response.out.write('<br>')
if not user:
start(self.response, {'appname': cfg['appname'] , 'plugins': getpluginlist() , 'who': 'login', 'loginurl': login, 'logouturl': logout, 'onload': 'void(0);'})
else:
start(self.response, {'appname': cfg['appname'] , 'plugins': getpluginlist() , 'who': userhost, 'loginurl': login, 'logouturl': logout, 'onload': 'void(0);'})
self.response.out.write('<br><div class="body"><i>"enter a command in the box above."</i><br></div>')
#closer(self.response)
#logging.warn("web_handler - out")
def post(self):
""" this is where the command get disaptched. """
global starttime
if starttime:
self.response.starttime = starttime
starttime = 0
else:
self.response.starttime = time.time()
logging.debug("web - incoming - %s" % self.request.remote_addr)
login = loginurl(self.response)
logout = logouturl(self.response)
event = WebEvent(bot=bot).parse(self.response, self.request)
event.cbtype = "WEB"
if not event.user:
start(self.response, {'appname': cfg['appname'] , 'plugins': getpluginlist() , 'who': 'login', 'loginurl': login, 'logouturl': logout, 'onload': 'putFocus(0,0);'})
else:
start(self.response, {'appname': cfg['appname'] , 'plugins': getpluginlist() , 'who': event.userhost, 'loginurl': login, 'logouturl': logout, 'onload': 'putFocus(0,0);'})
try:
bot.doevent(event)
self.response.out.write('</div>')
except NoSuchCommand:
self.response.out.write("sorry no %s command found." % event.usercmnd)
except Exception, ex:
handle_exception(event)
closer(self.response)
class FeedListHandler(webapp.RequestHandler):
""" the bots web command dispatcher. """
def get(self):
""" show basic page. """
global starttime
from waveplugs.hubbub import HubbubWatcher
watcher = HubbubWatcher('hubbub')
feeds = watcher.getall()
for feed in feeds.values():
self.response.out.write("%s %s<br>\n" % (feed.data.name, feed.data.url))
## the application
application = webapp.WSGIApplication([('/', DispatchHandler),
('/dispatch', DispatchHandler),
('/dispatch/', DispatchHandler),
('/feeds', FeedListHandler),
('/feeds/', FeedListHandler)],
debug=True)
## main
def main():
global bot
global application
run_wsgi_app(application)
if __name__ == "__main__":
main()
|
Python
| 0
|
@@ -1431,32 +1431,73 @@
basic page. %22%22%22%0A
+ logging.warn(%22web_handler - in%22)%0A
global s
@@ -1497,32 +1497,32 @@
lobal starttime%0A
-
%0A if star
@@ -1852,50 +1852,8 @@
nt)%0A
- #logging.warn(%22web_handler - in%22)%0A
@@ -1933,48 +1933,8 @@
nse)
-%0A self.response.out.write('%3Cbr%3E')
%0A%0A
@@ -2426,17 +2426,58 @@
-#
+self.response.out.write('%3C/div%3E')%0A
closer(s
@@ -2498,17 +2498,16 @@
-#
logging.
@@ -2613,16 +2613,88 @@
d. %22%22%22%0A%0A
+ logging.debug(%22web - incoming - %25s%22 %25 self.request.remote_addr)%0A
@@ -2876,80 +2876,8 @@
()%0A%0A
- logging.debug(%22web - incoming - %25s%22 %25 self.request.remote_addr)%0A
|
85680ed5792456a109583830bcbfbc30ef3b62c4
|
Complete 'About Lambdas' koans
|
jesusmtnez/python/koans/koans/about_lambdas.py
|
jesusmtnez/python/koans/koans/about_lambdas.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based slightly on the lambdas section of AboutBlocks in the Ruby Koans
#
from runner.koan import *
class AboutLambdas(Koan):
def test_lambdas_can_be_assigned_to_variables_and_called_explicitly(self):
add_one = lambda n: n + 1
self.assertEqual(__, add_one(10))
# ------------------------------------------------------------------
def make_order(self, order):
return lambda qty: str(qty) + " " + order + "s"
def test_accessing_lambda_via_assignment(self):
sausages = self.make_order('sausage')
eggs = self.make_order('egg')
self.assertEqual(__, sausages(3))
self.assertEqual(__, eggs(2))
def test_accessing_lambda_without_assignment(self):
self.assertEqual(__, self.make_order('spam')(39823))
|
Python
| 0.001766
|
@@ -309,18 +309,18 @@
rtEqual(
-__
+11
, add_on
@@ -653,18 +653,28 @@
rtEqual(
-__
+'3 sausages'
, sausag
@@ -705,18 +705,24 @@
rtEqual(
-__
+'2 eggs'
, eggs(2
@@ -810,10 +810,21 @@
ual(
-__
+'39823 spams'
, se
|
d9719a20d4ee433aaab27a648888966d1ce0163b
|
Implement inversion counting with global variable
|
count-inversions/count_inversions.py
|
count-inversions/count_inversions.py
|
from random import randint
import sys
def sort_and_count(arr):
n = len(arr)
if n == 1:
return arr
else:
first_half = arr[:n/2]
second_half = arr[n/2:]
return merge_and_count_split(sort_and_count(first_half), sort_and_count(second_half))
def merge_and_count_split(arr1, arr2):
i, j = 0, 0
result = []
while 1:
if i == len(arr1):
result.extend(arr2[j:])
break
if j == len(arr2):
result.extend(arr1[i:])
break
if (arr1[i] < arr2[j]):
result.append(arr1[i])
i += 1
else:
result.append(arr2[j])
j += 1
return result
def main(arr_len):
test_arr = [randint(0,arr_len) for n in range(arr_len)]
return sort_and_count(test_arr)
if __name__ == '__main__':
try:
arr_len = int(sys.argv[1])
except (IndexError, ValueError):
print 'Format: python merge-sort.py <array-length>'
print main(arr_len)
|
Python
| 0.000059
|
@@ -32,16 +32,27 @@
rt sys%0A%0A
+count = 0%0A%0A
def sort
@@ -321,16 +321,30 @@
ult = %5B%5D
+%0A%09global count
%0A%0A%09while
@@ -477,16 +477,17 @@
rr1%5Bi%5D %3C
+=
arr2%5Bj%5D
@@ -559,16 +559,42 @@
rr2%5Bj%5D)%0A
+%09%09%09count += len(arr1) - i%0A
%09%09%09j +=
@@ -632,16 +632,17 @@
_len):%0A%09
+#
test_arr
@@ -689,16 +689,68 @@
r_len)%5D%0A
+%09test_arr = %5B1,6,3,4,8,2,5,0,3,6,5,4,7,2,2,5,6,8,1%5D%0A
%09return
@@ -927,22 +927,16 @@
gth%3E'%0A%0A%09
-print
main(arr
@@ -928,20 +928,34 @@
th%3E'%0A%0A%09main(arr_len)
+%0A%09print count%0A
|
9b49f1f1b87394a54ddbad595a51c104254ec334
|
Fix the explicit check for http. Thanks to Ed Marshall for the bug report.
|
kong/models.py
|
kong/models.py
|
from django.db import models
from django.template import Template, Context
from django.db.models import permalink
from django.contrib.localflavor.us import models as USmodels
import datetime
#(HACK) http://code.djangoproject.com/ticket/897
class ManyToManyField_NoSyncdb(models.ManyToManyField):
def __init__(self, *args, **kwargs):
super(ManyToManyField_NoSyncdb, self).__init__(*args, **kwargs)
self.creates_table = False
class Client(models.Model):
name = models.CharField(max_length=100, blank=True)
slug = models.SlugField(blank=True)
phone = USmodels.PhoneNumberField(blank=True)
email = models.EmailField(blank=True)
contact = models.CharField(max_length=100, blank=True)
def __unicode__(self):
if self.name:
return self.name
else:
return self.slug
class Site(models.Model):
name = models.CharField(max_length=80, blank=True)
slug = models.SlugField()
type = models.ForeignKey('Type', related_name='sites')
client = models.ForeignKey(Client, related_name='sites', blank=True, null=True)
settings = models.CharField(max_length=80)
pythonpath = models.CharField(max_length=255,
default="/home/code.django-1.0")
#aliases = models.ForeignKey('Alias')
is_live = models.BooleanField(default=False)
def __unicode__(self):
return "%s: %s" % (self.slug, self.settings)
@permalink
def get_absolute_url(self):
return ('kong_site_detail', [self.slug])
@property
def url(self):
curr_site = self.hostedsite.servername
if curr_site.find('http://') == -1:
curr_site = "http://%s" % curr_site
return curr_site
@property
def tests(self):
return Test.objects.filter(sites=self) | Test.objects.filter(types=self.type)
class HostedSite(Site):
servername = models.CharField(max_length=100, default='example.com',
help_text='This is the address of your actual site')
on_servers = models.ManyToManyField('Server', null=True, blank=True, related_name="sites")
maxclients = models.IntegerField(default=30, null=True, blank=True)
wsgi_processes = models.IntegerField(default=5, null=True, blank=True)
wsgi_max_requests = models.IntegerField(default=500, null=True, blank=True)
serveradmin = models.CharField(max_length=100, null=True, blank=True)
mediaserver = models.CharField(max_length=100, null=True, blank=True)
def __unicode__(self):
return self.servername
class Server(models.Model):
name = models.CharField(max_length=80, blank=True)
slug = models.SlugField()
#(HACK) http://code.djangoproject.com/ticket/897
clients = ManyToManyField_NoSyncdb('HostedSite', db_table='kong_hostedsite_on_servers')
hostname = models.CharField(max_length=100)
internalip = models.IPAddressField(null=True, blank=True)
externalip = models.IPAddressField(null=True, blank=True)
def __unicode__(self):
return self.hostname
@permalink
def get_absolute_url(self):
return ('kong_server_detail', [self.slug])
class Type(models.Model):
name = models.CharField(max_length=40)
slug = models.SlugField(blank=True)
def __unicode__(self):
return self.name
def all_sites(self):
return self.sites.all()
class Test(models.Model):
name = models.CharField(max_length=250)
slug = models.SlugField(blank=True)
sites = models.ManyToManyField(Site, blank=True, null=True, related_name='tests')
types = models.ManyToManyField(Type, blank=True, null=True, related_name='tests')
body = models.TextField()
def __unicode__(self):
return self.name
def render(self, site):
return Template(self.body).render(Context({'site': site})).encode()
@permalink
def get_absolute_url(self):
return ('kong_testresults_detail', [self.slug])
class TestResult(models.Model):
test = models.ForeignKey(Test, related_name='test_results')
site = models.ForeignKey(Site, related_name='test_results')
run_date = models.DateTimeField(default=datetime.datetime.now)
duration = models.IntegerField(null=True)
succeeded = models.BooleanField()
content = models.TextField()
class Meta:
ordering = ('-run_date',)
def __unicode__(self):
return "%s for %s" % (self.test, self.site)
@permalink
def get_absolute_url(self):
return ('kong_testresults_detail', [self.slug])
###### Not Currently used
class Alias(models.Model):
site = models.ForeignKey(HostedSite, related_name="aliases")
url = models.CharField(max_length=100)
def __unicode__(self):
return self.url
class DeployTarget(models.Model):
name = models.CharField(max_length=250)
slug = models.SlugField(blank=True)
is_active = models.BooleanField()
last_deployed = models.DateTimeField()
servers = models.ManyToManyField(Server)
def __unicode__(self):
return self.name
|
Python
| 0
|
@@ -183,16 +183,32 @@
datetime
+%0Aimport urlparse
%0A%0A#(HACK
@@ -1637,40 +1637,51 @@
if
-curr_site.find('http://') == -1:
+urlparse.urlsplit(curr_site).scheme == '':
%0A
|
dc4258e13beb5fafa56ecb447af90b9dc4206f27
|
fix crash in debug log output
|
kraken/blla.py
|
kraken/blla.py
|
# -*- coding: utf-8 -*-
#
# Copyright 2019 Benjamin Kiessling
#
# 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 or 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.
"""
kraken.blla
~~~~~~~~~~~~~~
Trainable baseline layout analysis tools for kraken
"""
import torch
import logging
import numpy as np
import pkg_resources
import torch.nn.functional as F
import torchvision.transforms as tf
from typing import Optional, Dict, Callable
from kraken.lib import vgsl, dataset
from kraken.lib.util import pil2array, is_bitonal, get_im_str
from kraken.lib.exceptions import KrakenInputException
from kraken.lib.segmentation import (polygonal_reading_order,
vectorize_lines, vectorize_regions,
scale_polygonal_lines,
calculate_polygonal_environment,
scale_regions)
__all__ = ['segment']
logger = logging.getLogger(__name__)
def segment(im,
text_direction: str = 'horizontal-lr',
mask: Optional[np.array] = None,
reading_order_fn: Callable = polygonal_reading_order,
model=None,
device: str = 'cpu'):
"""
Segments a page into text lines using the baseline segmenter.
Segments a page into text lines and returns the polyline formed by each
baseline and their estimated environment.
Args:
im (PIL.Image): An RGB image.
text_direction (str): Ignored by the segmenter but kept for
serialization.
mask (PIL.Image): A bi-level mask image of the same size as `im` where
0-valued regions are ignored for segmentation
purposes. Disables column detection.
reading_order_fn (function): Function to determine the reading order.
Has to accept a list of tuples (baselines,
polygon) and a text direction (`lr` or
`rl`).
model (vgsl.TorchVGSLModel): A TorchVGSLModel containing a segmentation
model. If none is given a default model
will be loaded.
device (str or torch.Device): The target device to run the neural
network on.
Returns:
{'text_direction': '$dir',
'type': 'baseline',
'lines': [
{'baseline': [[x0, y0], [x1, y1], ..., [x_n, y_n]], 'boundary': [[x0, y0, x1, y1], ... [x_m, y_m]]},
{'baseline': [[x0, ...]], 'boundary': [[x0, ...]]}
]
'regions': [
{'region': [[x0, y0], [x1, y1], ..., [x_n, y_n]], 'type': 'image'},
{'region': [[x0, ...]], 'type': 'text'}
]
}: A dictionary containing the text direction and under the key 'lines'
a list of reading order sorted baselines (polylines) and their
respective polygonal boundaries. The last and first point of each
boundary polygon is connected.
Raises:
KrakenInputException if the input image is not binarized or the text
direction is invalid.
"""
im_str = get_im_str(im)
logger.info(f'Segmenting {im_str}')
if model is None:
logger.info('No segmentation model given. Loading default model.')
model = vgsl.TorchVGSLModel.load_model(pkg_resources.resource_filename(__name__, 'blla.mlmodel'))
if model.one_channel_mode == '1' and not is_bitonal(im):
logger.warning('Running binary model on non-binary input image '
'(mode {}). This will result in severely degraded '
'performance'.format(im.mode))
model.eval()
model.to(device)
if mask:
if mask.mode != '1' and not is_bitonal(mask):
logger.error('Mask is not bitonal')
raise KrakenInputException('Mask is not bitonal')
mask = mask.convert('1')
if mask.size != im.size:
logger.error('Mask size {mask.size} doesn\'t match image size {im.size}')
raise KrakenInputException('Mask size {mask.size} doesn\'t match image size {im.size}')
logger.info('Masking enabled in segmenter.')
mask = pil2array(mask)
batch, channels, height, width = model.input
transforms = dataset.generate_input_transforms(batch, height, width, channels, 0, valid_norm=False)
res_tf = tf.Compose(transforms.transforms[:3])
scal_im = res_tf(im).convert('L')
with torch.no_grad():
logger.debug('Running network forward pass')
o, _ = model.nn(transforms(im).unsqueeze(0).to(device))
logger.debug('Upsampling network output')
o = F.interpolate(o, size=scal_im.size[::-1])
o = o.squeeze().cpu().numpy()
scale = np.divide(im.size, o.shape[:0:-1])
# postprocessing
cls_map = model.user_metadata['class_mapping']
st_sep = cls_map['aux']['_start_separator']
end_sep = cls_map['aux']['_end_separator']
logger.info('Vectorizing baselines')
baselines = []
regions = {}
for bl_type, idx in cls_map['baselines'].items():
logger.debug(f'Vectorizing lines of type {bl_type}')
baselines.extend([(bl_type,x) for x in vectorize_lines(o[(st_sep, end_sep, idx), :, :])])
logger.info('Vectorizing regions')
for region_type, idx in cls_map['regions'].items():
logger.debug(f'Vectorizing lines of type {bl_type}')
regions[region_type] = vectorize_regions(o[idx])
logger.debug('Polygonizing lines')
lines = list(filter(lambda x: x[2] is not None, zip([x[0] for x in baselines],
[x[1] for x in baselines],
calculate_polygonal_environment(scal_im, [x[1] for x in baselines]))))
logger.debug('Scaling vectorized lines')
sc = scale_polygonal_lines([x[1:] for x in lines], scale)
lines = list(zip([x[0] for x in lines], [x[0] for x in sc], [x[1] for x in sc]))
logger.debug('Scaling vectorized regions')
for reg_id, regs in regions.items():
regions[reg_id] = scale_regions(regs, scale)
logger.debug('Reordering baselines')
order_regs = []
for regs in regions.values():
order_regs.extend(regs)
lines = reading_order_fn(lines=lines, regions=order_regs, text_direction=text_direction[-2:])
if 'class_mapping' in model.user_metadata and len(model.user_metadata['class_mapping']['baselines']) > 1:
script_detection = True
else:
script_detection = False
return {'text_direction': text_direction,
'type': 'baselines',
'lines': [{'script': bl_type, 'baseline': bl, 'boundary': pl} for bl_type, bl, pl in lines],
'regions': regions,
'script_detection': script_detection}
|
Python
| 0.000001
|
@@ -5900,36 +5900,38 @@
g(f'Vectorizing
-line
+region
s of type %7Bbl_ty
@@ -5917,34 +5917,38 @@
egions of type %7B
-bl
+region
_type%7D')%0A
|
17dceb0d66ac72547c6de6153d79d9bcd5dd9926
|
put _id and properties in the right places
|
gdcdatamodel/mappings/mappings.py
|
gdcdatamodel/mappings/mappings.py
|
from gdcdatamodel import node_avsc_json
from mapped_entities import (
file_tree, file_traversal,
participant_tree, participant_traversal,
annotation_tree, annotation_traversal,
ONE_TO_MANY, ONE_TO_ONE, annotation_tree
)
def _get_es_type(_type):
if 'long' in _type or 'int' in _type:
return 'long'
else:
return 'string'
def _munge_properties(source):
a = [n['fields'] for n in node_avsc_json if n['name'] == source]
if not a:
return
fields = [b['type'] for b in a[0] if b['name'] == 'properties']
fields[0][0]['fields'].append({
'name': '{}_id'.format(source),
'type': 'string'
})
return {b['name']: {
'type': _get_es_type(b['type']),
'index': 'not_analyzed'
} for b in fields[0][0]['fields']}
def _walk_tree(tree, mapping):
for k, v in [(k, v) for k, v in tree.items() if k != 'corr']:
corr, name = v['corr']
mapping[name] = {'properties': _munge_properties(k)}
_walk_tree(tree[k], mapping[name])
return mapping
def get_file_es_mapping(include_participant=True):
files = _walk_tree(file_tree, _munge_properties("file"))
files["_id"] = {"path": "file_id"}
if include_participant:
files['participant'] = get_participant_es_mapping(False)
files["participant"]["type"] = "nested"
return files
def get_participant_es_mapping(include_file=True):
participant = _walk_tree(participant_tree, _munge_properties("participant"))
participant["_id"] = {"path": "participant_id"}
if include_file:
participant['files'] = get_file_es_mapping(True)
participant["files"]["type"] = "nested"
return participant
def get_annotation_es_mapping(include_file=True):
annotation = _walk_tree(annotation_tree, _munge_properties("annotation"))
annotation["_id"] = {"path": "annotation_id"}
if include_file:
annotation['files'] = get_file_es_mapping(False)
annotation["files"]["type"] = "nested"
return annotation
|
Python
| 0.000001
|
@@ -1115,16 +1115,71 @@
files =
+ %7B%22_id%22: %7B%22path%22: %22file_id%22%7D%7D%0A files%5B%22properties%22%5D =
_walk_t
@@ -1224,47 +1224,8 @@
%22))%0A
- files%5B%22_id%22%5D = %7B%22path%22: %22file_id%22%7D%0A
@@ -1262,16 +1262,30 @@
files%5B
+%22properties%22%5D%5B
'partici
@@ -1342,16 +1342,30 @@
files%5B%22
+properties%22%5D%5B%22
particip
@@ -1476,16 +1476,77 @@
cipant =
+ %7B%22_id%22: %7B%22path%22: %22file_id%22%7D%7D%0A participant%5B%22properties%22%5D =
_walk_t
@@ -1605,60 +1605,8 @@
%22))%0A
- participant%5B%22_id%22%5D = %7B%22path%22: %22participant_id%22%7D%0A
@@ -1642,16 +1642,30 @@
icipant%5B
+%22properties%22%5D%5B
'files'%5D
@@ -1714,16 +1714,30 @@
cipant%5B%22
+properties%22%5D%5B%22
files%22%5D%5B
|
fd6cddb6ec94bc579eb1156d6d89ce95ffc62038
|
Create a field to store the display name for a package
|
crate/web/packages/search_indexes.py
|
crate/web/packages/search_indexes.py
|
from django.utils.translation import ugettext_noop as _
from haystack import indexes
from crate.web.packages.models import Package
from crate.web.search.indexes import PackageCelerySearchIndex
LICENSES = {
"GNU General Public License (GPL)": "GPL",
"GNU Library or Lesser General Public License (LGPL)": "LGPL",
"GNU Affero General Public License v3": "Affero GPL",
"Apache Software License": "Apache License",
"ISC License (ISCL)": "ISC License",
"Other/Proprietary License": _("Other/Proprietary"),
}
class PackageIndex(PackageCelerySearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
name = indexes.CharField(model_attr="name", boost=1.5)
summary = indexes.CharField(null=True)
description = indexes.CharField(null=True)
author = indexes.CharField(null=True)
maintainer = indexes.CharField(null=True)
downloads = indexes.IntegerField(model_attr="downloads", indexed=False)
url = indexes.CharField(model_attr="get_absolute_url", indexed=False)
operating_systems = indexes.MultiValueField(null=True, faceted=True, facet_class=indexes.FacetMultiValueField)
licenses = indexes.MultiValueField(null=True, faceted=True, facet_class=indexes.FacetMultiValueField)
implementations = indexes.MultiValueField(null=True, faceted=True, facet_class=indexes.FacetMultiValueField)
python_versions = indexes.MultiValueField(null=True, faceted=True, facet_class=indexes.FacetMultiValueField)
versions = indexes.MultiValueField(null=True)
release_count = indexes.IntegerField(default=0)
def get_model(self):
return Package
def prepare(self, obj):
data = super(PackageIndex, self).prepare(obj)
# For ES, because it doesn't tokenize on ``_``, which causes problems
# on lots of searches.
if '_' in data['name']:
data['name'] += ' ' + data['name'].replace('_', '-')
if obj.latest:
data["summary"] = obj.latest.summary
data["author"] = obj.latest.author if obj.latest.author else None
data["maintainer"] = obj.latest.maintainer if obj.latest.maintainer else None
data["description"] = obj.latest.description if obj.latest.description else None
operating_systems = []
licenses = []
implementations = []
python_versions = []
for classifier in obj.latest.classifiers.all():
if classifier.trove.startswith("License ::"):
# We Have a License for This Project
licenses.append(classifier.trove.rsplit("::", 1)[1].strip())
elif classifier.trove.startswith("Operating System ::"):
operating_systems.append(classifier.trove.rsplit("::", 1)[1].strip())
elif classifier.trove.startswith("Programming Language :: Python :: Implementation ::"):
implementations.append(classifier.trove.rsplit("::", 1)[1].strip())
elif classifier.trove.startswith("Programming Language :: Python ::"):
if classifier.trove == "Programming Language :: Python :: 2 :: Only":
python_versions.append("2.x")
elif classifier.trove.startswith("Programming Language :: Python :: 2"):
python_versions.append("2.x")
elif classifier.trove.startswith("Programming Language :: Python :: 3"):
python_versions.append("3.x")
else:
python_versions.append(classifier.trove.rsplit("::", 1)[1].strip())
if not licenses:
licenses = [_("Unknown")]
licenses = [x for x in licenses if x not in ["OSI Approved"]]
licenses = [LICENSES.get(x, x) for x in licenses]
data["licenses"] = licenses
if not operating_systems:
operating_systems = [_("Unknown")]
data["operating_systems"] = operating_systems
if not implementations:
implementations = [_("Unknown")]
data["implementations"] = implementations
if not python_versions:
python_versions = [_("Unknown")]
data["python_versions"] = python_versions
# Pack in all the versions in decending order.
releases = obj.releases.all().order_by("-order")
data["versions"] = [release.version for release in releases if release.version]
data["release_count"] = releases.count()
# We want to scale the boost for this document based on how many downloads have
# been recorded for this package.
# @@@ Might want to actually tier these values instead of percentage them.
# Cap out downloads at 100k
capped_downloads = min(data["downloads"], 10000)
boost = capped_downloads / 10000.0
data["_boost"] = 1.0 + boost
return data
|
Python
| 0.000001
|
@@ -712,16 +712,87 @@
st=1.5)%0A
+ display_name = indexes.CharField(model_attr=%22name%22, indexed=False)%0A
summ
|
36b2ca696bf6955d54ade1f917a1caea59b2d2d1
|
update version to 0.7.4
|
dlstats/version.py
|
dlstats/version.py
|
VERSION = (0, 7, 3)
def version_str():
if len(VERSION) == 3:
return "%s.%s.%s" % VERSION
elif len(VERSION) == 4:
return "%s.%s.%s-%s" % VERSION
else:
raise IndexError("Incorrect format for the VERSION tuple")
|
Python
| 0.000001
|
@@ -10,17 +10,17 @@
(0, 7,
-3
+4
)%0A%0Adef v
|
e6f87d1b35a2a9a20d05ceecee1b1ad113e5bff2
|
remove everyday
|
server/mostlikelink/apis.py
|
server/mostlikelink/apis.py
|
# coding=utf-8
from . import app, login_manager, csrf
from flask import json,jsonify,json_available, request
from flask.ext.login import login_required, login_user, logout_user,current_user
from mongoengine import errors
import models
import utils
@csrf.exempt
@app.route('/api/user/current_user', methods=['POST'])
@login_required
def api_get_current_user():
req = request.json
print req
return jsonify(email=current_user.email,
blog_id=current_user.blog_id
)
@csrf.exempt
@app.route('/api/link/add', methods=['POST'])
@login_required
def api_add_link():
req = request.get_json()
print req
title = req['title']
url = req['url']
user = models.User.objects(id=current_user.id).first()
if user is None:
print 'user not exist : ' + str(current_user.id)
return jsonify(succeed=False,
reason='User not exist')
search_links = models.LinkPost.objects(user=user, url=url)
if len(search_links) > 0:
print 'url exist'
return jsonify(succeed=False,
reason='URL exist'
)
link = models.LinkPost()
link.title = title
link.user = user
link.tags = []
link.url = url
link.color = utils.random_color()
try:
link.save()
except Exception, err:
print 'link save error : '+ err.message
return jsonify(succeed=False,
reason='Link save failed')
click_event = models.ClickEvent()
click_event.user = user
click_event.link = link
try:
click_event.save()
except Exception, ex:
print 'click event save : ' + ex.message
return jsonify(succeed=True)
@csrf.exempt
@app.route('/api/link/update', methods=['POST'])
@login_required
def api_update_link():
req = request.get_json()
print req
url = req['url']
title = req['title']
tags = list(set(req['tags'].replace(',', ' ').split(' ')))
tags = [tag.strip() for tag in tags if tag.strip()]
user = models.User.objects(id=current_user.id).first()
if user is None:
return jsonify(succeed=False,
reason='User not exist')
link = models.LinkPost.objects(user=user, url=url).first()
if link is None:
return jsonify(succeed=False,
reason='URL not exist'
)
tags_data = []
for tag in tags:
try:
cur_tag = models.Tag.objects(user=user, name=tag).first()
if cur_tag is None:
cur_tag = models.Tag()
cur_tag.name = tag
cur_tag.user = user
cur_tag.color = utils.random_color()
cur_tag.save()
tags_data.append(cur_tag)
except Exception, e:
print 'update tag error :', e.message
return jsonify(succeed=False,
reason='Update tags failed'
)
link.title = title
link.tags = tags_data
try:
link.save()
except Exception, e:
print 'link save error : ', e.message
return jsonify(succeed=False,
reason='Update link failed'
)
return jsonify(succeed=True)
@csrf.exempt
@app.route('/api/link/info', methods=['POST'])
@login_required
def api_link_info():
req = request.get_json()
print req
url = req['url']
user = models.User.objects(id=current_user.id).first()
if user is None:
return jsonify(succeed=False,
reason='User not exist')
# if exist , update
link = models.LinkPost.objects(user=user, url=url).first()
if link is None:
return jsonify(succeed=False,
reason='URL not exist'
)
tag_names = [tag.name for tag in link.tags]
tag_string = " ".join(tag_names)
return jsonify(succeed=True,
title=link.title,
tags=tag_string
)
@csrf.exempt
@app.route('/api/link/remove', methods=['POST'])
@login_required
def api_remove_link():
req = request.get_json()
print req
url = req['url']
user = models.User.objects(id=current_user.id).first()
if user is None:
return jsonify(succeed=False,
reason='User not exist')
link = models.LinkPost.objects(url=url).first()
if link is None:
return jsonify(succeed=True,
reason='Link not exist')
try:
link.delete()
return jsonify(succeed=True)
except:
return jsonify(succeed=False,
reason='Delete error')
@csrf.exempt
@app.route('/api/tags/recommend', methods=['GET'])
@login_required
def api_tags_recommend():
user = models.User.objects(id=current_user.id).first()
if user is None:
return jsonify(succeed=False,
reason='User not exist')
tags = models.Tag.objects(user=user)
tag_list = [tag.name for tag in tags]
rec_tags=[
u':top',
u'everyday',
]
print tag_list + rec_tags
return utils.json_response({
'succeed': True,
'tags': list(set(tag_list + rec_tags))
})
|
Python
| 0.000007
|
@@ -5102,29 +5102,8 @@
p',%0A
- u'everyday',%0A
|
cee7b86489a8737767ddcb4b4d1853ab7fb10e86
|
Add SettingInstance::state property
|
UM/Settings/SettingInstance.py
|
UM/Settings/SettingInstance.py
|
# Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Signal import Signal, signalemitter
from UM.Logger import Logger
from . import SettingRelation
from . import Validator
## Encapsulates all state of a setting.
#
#
@signalemitter
class SettingInstance:
## Constructor.
#
# \param definition The SettingDefinition object this is an instance of.
# \param container The container of this instance. Needed for relation handling.
def __init__(self, definition, container, *args, **kwargs):
if container is None:
raise ValueError("Cannot create a setting instance without a container")
super().__init__(*args, **kwargs)
self._definition = definition
self._container = container
self._visible = True
self._validator = None
self.__property_values = {}
def __getattr__(self, name):
if name in self.__property_values:
return self.__property_values[name]
raise AttributeError("'SettingInstance' object has no attribute '{0}'".format(name))
def setProperty(self, name, value):
if self._definition.hasProperty(name):
if self._definition.isReadOnlyProperty(name):
Logger.log("e", "Tried to set property %s which is a read-only property", name)
return
if name not in self.__property_values or value != self.__property_values[name]:
Logger.log("d", "Set property %s of instance %s", name, self)
self.__property_values[name] = value
if name == "value":
self._update()
self.propertyChanged.emit(self, name)
else:
raise AttributeError("No property {0} defined".format(name))
def updateProperty(self, name):
if not self._definition.hasProperty(name):
Logger.log("e", "Trying to update unknown property %s", name)
return
Logger.log("d", "Update property %s of instance %s", name, self)
try:
function = getattr(self._definition, name)
except AttributeError:
return
result = function(self._container)
if name not in self.__property_values or result != self.__property_values[name]:
self.__property_values[name] = function(self._container)
if name == "value":
self._update()
self.propertyChanged.emit(self, name)
## Emitted whenever a property of this instance changes.
#
# \param instance The instance that reported the property change (usually self).
# \param property The name of the property that changed.
propertyChanged = Signal()
## The SettingDefintion this instance maintains state for.
@property
def definition(self):
return self._definition
## The container of this instance.
@property
def container(self):
return self._container
## Get the state of validation of this instance.
@property
def validationState(self):
if self._validator:
return self._validator.getValidationState()
return Validator.ValidatorState.Unknown
## Emitted whenever this instance's validationState property changes.
#
# \param instance The instance that reported the validationState change.
validationStateChanged = Signal()
def __repr__(self):
return "<SettingInstance (0x{0:x}) definition={1} container={2}>".format(id(self), self._definition, self._container)
## protected:
def _update(self):
property_names = self._definition.getPropertyNames()
property_names.remove("value") # Move "value" to the front of the list so we always update that first.
property_names.insert(0, "value")
for property_name in property_names:
if self._definition.isReadOnlyProperty(property_name):
continue
for relation in filter(lambda r: r.role == property_name, self._definition.relations):
if relation.type == SettingRelation.RelationType.RequiresTarget:
continue
instance = self._container.getInstance(relation.target.key)
if not instance:
instance = SettingInstance(relation.target, self._container)
self._container.addInstance(instance)
instance.updateProperty(property_name)
|
Python
| 0.000001
|
@@ -93,16 +93,29 @@
igher.%0A%0A
+import enum%0A%0A
from UM.
@@ -235,16 +235,409 @@
idator%0A%0A
+%0A## The state of the instance%0A#%0A# This enum describes which state the instance is in. The state describes%0A# how the instance got its value.%0Aclass InstanceState(enum.IntEnum):%0A Default = 1 ## Default state, no value has been set.%0A Calculated = 2 ## Value is the result of calculations in a SettingFunction object.%0A User = 3 ## Value is the result of direct user interaction.%0A%0A%0A
## Enca
@@ -1263,16 +1263,61 @@
= None%0A%0A
+ self._state = InstanceState.Default%0A%0A
@@ -2117,32 +2117,135 @@
self._update()%0A%0A
+ self._state = InstanceState.User%0A self.stateChanged.emit(self)%0A%0A
@@ -3002,32 +3002,133 @@
self._update()%0A%0A
+ self._state = InstanceState.Calculated%0A self.stateChanged.emit(self)%0A%0A
self
@@ -4092,16 +4092,106 @@
gnal()%0A%0A
+ @property%0A def state(self):%0A return self._state%0A%0A stateChanged = Signal()
%0A%0A de
|
bca4bb08fbfffe27214803429ad63f7800f36428
|
Update demo.py to show different stock codes
|
demo.py
|
demo.py
|
#!/usr/bin/python3
# -*- encoding: utf-8 -*-
from indexes import *
import global_data
def main(stock='000001', date=global_data.NEWEST_TRADE_DATE, p_MA=5, p_MACD=(12,26,9),
p_RSI=6, p_KDJ=(9,3), p_MTM=(12,6), p_CCI=14):
"""
Example
stock: str, '000001',
date: str, '2017-08-18',
p_MA: int, 5
p_MACD: tuple, (12,26,9)
p_RSI: int, 6
p_KDJ: tuple, (9,3)
p_MTM: tuple, (12,6)
p_CCI: int, 14
"""
rsi = RSI(stock)
ma = MA(stock)
macd = MACD(stock)
mtm = MTM(stock)
kdj = KDJ(stock)
cci = CCI(stock)
global_data.add_data(stock) # download data to database
print('Demo for ', stock, date)
print('MA%s' % str(p_MA), ma.get_ma(date, p_MA))
print('MACD%s' % str(p_MACD), macd.get_macd(date, *p_MACD))
print('RSI%s' % str(p_RSI), rsi.get_rsi(date, p_RSI))
print('KDJ%s' % str(p_KDJ), kdj.get_kdj(date, *p_KDJ))
print('MTM%s' % str(p_MTM), mtm.get_mtm(date, *p_MTM))
print('CCI%s' % str(p_CCI), cci.get_cci(date, p_CCI))
# global_data.save_database(global_data.DB_FILE)
if __name__ == '__main__':
main()
|
Python
| 0
|
@@ -1144,10 +1144,51 @@
main(
+stock='000001')%0A main(stock='HK.00700'
)%0A
|
709b2153dfd5e6deecd1bf6c36bf74224081c880
|
Update demo.py to automatically download model
|
demo.py
|
demo.py
|
import os
import cv2
import dlib
import numpy as np
import argparse
from wide_resnet import WideResNet
def get_args():
parser = argparse.ArgumentParser(description="This script detects faces from web cam input, "
"and estimates age and gender for the detected faces.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--weight_file", type=str, default=None,
help="path to weight file (e.g. weights.18-4.06.hdf5)")
parser.add_argument("--depth", type=int, default=16,
help="depth of network")
parser.add_argument("--width", type=int, default=8,
help="width of network")
args = parser.parse_args()
return args
def draw_label(image, point, label, font=cv2.FONT_HERSHEY_SIMPLEX,
font_scale=1, thickness=2):
size = cv2.getTextSize(label, font, font_scale, thickness)[0]
x, y = point
cv2.rectangle(image, (x, y - size[1]), (x + size[0], y), (255, 0, 0), cv2.FILLED)
cv2.putText(image, label, point, font, font_scale, (255, 255, 255), thickness)
def main():
args = get_args()
depth = args.depth
k = args.width
weight_file = args.weight_file
if not weight_file:
weight_file = os.path.join("pretrained_models", "weights.18-4.06.hdf5")
# for face detection
detector = dlib.get_frontal_face_detector()
# load model and weights
img_size = 64
model = WideResNet(img_size, depth=depth, k=k)()
model.load_weights(weight_file)
# capture video
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
while True:
# get video frame
ret, img = cap.read()
if not ret:
print("error: failed to capture image")
return -1
input_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img_h, img_w, _ = np.shape(input_img)
# detect faces using dlib detector
detected = detector(input_img, 1)
faces = np.empty((len(detected), img_size, img_size, 3))
for i, d in enumerate(detected):
x1, y1, x2, y2, w, h = d.left(), d.top(), d.right() + 1, d.bottom() + 1, d.width(), d.height()
xw1 = max(int(x1 - 0.4 * w), 0)
yw1 = max(int(y1 - 0.4 * h), 0)
xw2 = min(int(x2 + 0.4 * w), img_w - 1)
yw2 = min(int(y2 + 0.4 * h), img_h - 1)
cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0, 0), 2)
# cv2.rectangle(img, (xw1, yw1), (xw2, yw2), (255, 0, 0), 2)
faces[i,:,:,:] = cv2.resize(img[yw1:yw2 + 1, xw1:xw2 + 1, :], (img_size, img_size))
if len(detected) > 0:
# predict ages and genders of the detected faces
results = model.predict(faces)
predicted_genders = results[0]
ages = np.arange(0, 101).reshape(101, 1)
predicted_ages = results[1].dot(ages).flatten()
# draw results
for i, d in enumerate(detected):
label = "{}, {}".format(int(predicted_ages[i]),
"F" if predicted_genders[i][0] > 0.5 else "M")
draw_label(img, (d.left(), d.top()), label)
cv2.imshow("result", img)
key = cv2.waitKey(30)
if key == 27:
break
if __name__ == '__main__':
main()
|
Python
| 0
|
@@ -96,16 +96,195 @@
eResNet%0A
+from keras.utils.data_utils import get_file%0A%0Apretrained_model = %22https://www.dropbox.com/s/rf8hgoev8uqjv3z/weights.18-4.06.hdf5?dl=1%22%0Amodhash = '89f56a39a78454e96379348bddd78c0d'%0A
%0A%0Adef ge
@@ -1498,24 +1498,25 @@
le:%0A
+#
weight_file
@@ -1574,16 +1574,131 @@
6.hdf5%22)
+%0A weight_file = get_file(%22weights.18-4.06.hdf5%22, pretrained_model, cache_subdir=%22models%22, file_hash=modhash)
%0A%0A #
|
f92f8c38c8b85469d58d338328659056350c7801
|
correct comment
|
crossbeam-channel/benchmarks/plot.py
|
crossbeam-channel/benchmarks/plot.py
|
#!/usr/bin/env python3
import random
import sys
import matplotlib.pyplot as plt
def read_data(files):
results = []
for f in files:
with open(f) as f:
for line in f.readlines():
test, lang, impl, secs, _ = line.split()
splt = test.split('_')
results.append((splt[0], '_'.join(splt[1:]), lang, impl, float(secs)))
return results
def get_runs(results, prefix):
runs = set()
for pre, test, lang, impl, secs in results:
if pre == prefix:
runs.add(test)
result = list(runs)
result.sort()
return result
def find(s, x):
for i in range(len(s)):
if s[i] == x:
return i
return None
color_set = {
'aqua': '#00ffff',
'azure': '#f0ffff',
'beige': '#f5f5dc',
'black': '#000000',
'blue': '#0000ff',
'brown': '#a52a2a',
'cyan': '#00ffff',
'darkblue': '#00008b',
'darkcyan': '#008b8b',
'darkgrey': '#a9a9a9',
'darkgreen': '#006400',
'darkkhaki': '#bdb76b',
'darkmagenta': '#8b008b',
'darkolivegreen': '#556b2f',
'darkorange': '#ff8c00',
'darkorchid': '#9932cc',
'darkred': '#8b0000',
'darksalmon': '#e9967a',
'darkviolet': '#9400d3',
'fuchsia': '#ff00ff',
'gold': '#ffd700',
'green': '#008000',
'indigo': '#4b0082',
'khaki': '#f0e68c',
'lightblue': '#add8e6',
'lightcyan': '#e0ffff',
'lightgreen': '#90ee90',
'lightgrey': '#d3d3d3',
'lightpink': '#ffb6c1',
'lightyellow': '#ffffe0',
'lime': '#00ff00',
'magenta': '#ff00ff',
'maroon': '#800000',
'navy': '#000080',
'olive': '#808000',
'orange': '#ffa500',
'pink': '#ffc0cb',
'purple': '#800080',
'red': '#ff0000',
}
saved_color = {}
def get_color(name):
if name not in saved_color:
color = color_set.popitem()
saved_color[name] = color
return saved_color[name][1]
def plot(results, fig, subplot, title, prefix):
runs = get_runs(results, prefix)
ys = [len(runs) * (i + 1) for i in range(len(runs))]
ax = fig.add_subplot(subplot)
ax.set_title(title)
ax.set_yticks(ys)
ax.set_yticklabels(runs)
ax.tick_params(which='major', length=0)
ax.set_xlabel('seconds')
scores = {}
for pre, test, lang, impl, secs in results:
if pre == prefix:
name = impl if lang == 'Rust' else impl + f' ({lang})'
if name not in scores:
scores[name] = [0] * len(runs)
scores[name][find(runs, test)] = secs
opts = dict(height=0.8, align='center')
x_max = max(max(scores.values(), key=lambda x: max(x)))
for i, (name, score) in enumerate(scores.items()):
yy = [y + i - len(runs) // 2 + 0.2 for y in ys]
ax.barh(yy, score, color=get_color(name), **opts)
for xxx, yyy in zip(score, yy):
if xxx:
ax.text(min(x_max - len(name) * 0.018 * x_max, xxx), yyy - 0.25, name, fontsize=9)
def plot_all(results, descriptions, labels):
fig = plt.figure(figsize=(10, 10))
# TODO support more number subplots
subplot = [221, 222, 223, 224]
for p, d, l in zip(subplot, descriptions, labels):
plot(results, fig, p, d, l)
plt.subplots_adjust(
top=0.95,
bottom=0.05,
left=0.1,
right=0.95,
wspace=0.3,
hspace=0.2,
)
plt.savefig('plot.png')
# plt.show()
def main():
results = read_data(sys.argv[1:])
descriptions = [
'Bounded channel of capacity 0',
'Bounded channel of capacity 1',
'Bounded channel of capacity N',
'Unbounded channel',
]
labels = ['bounded0', 'bounded1', 'bounded', 'unbounded']
plot_all(results, descriptions, labels)
if __name__ == '__main__':
main()
|
Python
| 0.000005
|
@@ -3092,15 +3092,8 @@
ore
-number
subp
|
6c56f6d2f031c2cfe0dcb2fd7c875a8ee3d19625
|
Make IndentTag a proper tag.
|
scope/scope.py
|
scope/scope.py
|
#
# template.py
#
# Copyright (c) 2013 Luis Garcia.
# This source file is subject to terms of the MIT License. (See accompanying file LICENSE)
#
"""Library for code templates serialization."""
import itertools
class Scope:
"""Offer utilities to work with scope-based code templates."""
def serialize(self, template):
"""Serialize the provided template according to the language specifications."""
context = SerializerContext()
template.serialize(context)
return context.output
def flatten(self, template):
"""Creates a 'flat' version of the template. It process special s to create a simple structure for the template."""
return _flatten(template)
class SerializerContext:
"""Context object for the output generator."""
def __init__(self):
self._output = ''
self._indentation = 0
def write(self, str):
"""Print provided string to the output."""
self._output += ' ' * self._indentation + str + '\n'
def new_line(self):
"""Add a new blank line."""
self._output += '\n'
def indent(self):
"""Increase line indentation."""
self._indentation += 1
def unindent(self):
"""Decrease line indentation."""
self._indentation -= 1
def serialize(self, object):
"""Serialize object and print it to the output."""
if isinstance(object, str):
self.write(object)
else:
object.serialize(self)
@property
def indentation(self):
"""Current indentation, in units for the serializer."""
return self._indentation
@property
def output(self):
"""Output of the serializer."""
return self._output
class TagBase:
"""Base class for scope-based template tags."""
def __init__(self):
self._children = []
def __repr__(self):
return '{0} {1}'.format(self.__class__.__name__, self.__dict__)
def __eq__(self, other):
return self.__dict__ == other.__dict__
def set_arguments(self):
"""Method called for defining arguments for the object. Should be implemented by subclasses."""
pass
def serialize(self, context):
"""Method called for serializing object. Should be implemented by subclasses."""
pass
@property
def children(self):
"""List of elements assigned to the tag."""
return self._children
@children.setter
def children(self, children):
self._children = children
return self
class Tag:
"""Handler for tag implementations."""
def __init__(self, class_):
self._class = class_
def __call__(self, ** args):
return _TagImpl(self._class)(** args)
def __getitem__(self, children):
return _TagImpl(self._class)[children]
def _flatten(self):
return _flatten(_TagImpl(self._class))
def _list(self):
return _list(_TagImpl(self._class))
class IndentTag(TagBase):
def serialize(self, context):
context.indent()
for child in self.children:
context.serialize(child)
context.unindent()
#
# Implementation-detail
#
class _TagImpl:
def __init__(self, class_):
self._element = class_()
self._children = []
def __call__(self, ** args):
self._element.set_arguments(** args)
return self
def __getitem__(self, children):
if isinstance(children, tuple):
self._children = list(children)
else:
self._children = [children]
return self
def serialize(self, context):
return _flatten(self).serialize(context)
def _list(self):
return [self]
def _flatten(self):
source = itertools.chain(* list(_list(t) for t in self._children))
items = [_flatten(e) for e in source]
if len(items) > 0:
self._element.children = items
return self._element
class _ForEachTag:
def __init__(self, enumerable, function):
self._enumerable = enumerable
self._function = function
def _list(self):
return itertools.chain(* list(_list(self._function(e)) for e in self._enumerable))
class _SpanTagImpl:
def __init__(self):
self._children = []
def __getitem__(self, children):
if isinstance(children, tuple):
self._children = list(children)
else:
self._children = [children]
return self
def _list(self):
return itertools.chain(* list(_list(e) for e in self._children))
class _SpanTag:
def __init__(self):
self._children = []
def __getitem__(self, children):
return _SpanTagImpl()[children]
def _list(self):
return _SpanTagImpl()._list()
def _flatten(value):
if isinstance(value, str):
return value
else:
return value._flatten()
def _list(value):
if isinstance(value, str):
return [value]
else:
return value._list()
#
# Helper tags
#
def for_each(elements, function):
"""Allows to generate a tag for each items in an enumarable."""
return _ForEachTag(elements, function)
"""Indent elements in the block."""
indent = IndentTag()
"""Group elements. These will be appended to the parent."""
span = _SpanTag()
|
Python
| 0.000077
|
@@ -4581,16 +4581,20 @@
ndent =
+Tag(
IndentTa
@@ -4594,17 +4594,16 @@
ndentTag
-(
)%0A%0A%22%22%22Gr
|
d1ac527fb1d7cefba9b66577d16351950fc09647
|
Add note about new logging feature in example plugin.
|
plugins/callbacks/log_plays.py
|
plugins/callbacks/log_plays.py
|
# (C) 2012, Michael DeHaan, <michael.dehaan@gmail.com>
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible 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.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import os
import time
import json
TIME_FORMAT="%b %d %Y %H:%M:%S"
MSG_FORMAT="%(now)s - %(category)s - %(data)s\n\n"
if not os.path.exists("/var/log/ansible/hosts"):
os.makedirs("/var/log/ansible/hosts")
def log(host, category, data):
if type(data) == dict:
if 'verbose_override' in data:
# avoid logging extraneous data from facts
data = 'omitted'
else:
data = data.copy()
invocation = data.pop('invocation', None)
data = json.dumps(data)
if invocation is not None:
data = json.dumps(invocation) + " => %s " % data
path = os.path.join("/var/log/ansible/hosts", host)
now = time.strftime(TIME_FORMAT, time.localtime())
fd = open(path, "a")
fd.write(MSG_FORMAT % dict(now=now, category=category, data=data))
fd.close()
class CallbackModule(object):
"""
logs playbook results, per host, in /var/log/ansible/hosts
"""
def on_any(self, *args, **kwargs):
pass
def runner_on_failed(self, host, res, ignore_errors=False):
log(host, 'FAILED', res)
def runner_on_ok(self, host, res):
log(host, 'OK', res)
def runner_on_error(self, host, msg):
log(host, 'ERROR', msg)
def runner_on_skipped(self, host, item=None):
log(host, 'SKIPPED', '...')
def runner_on_unreachable(self, host, res):
log(host, 'UNREACHABLE', res)
def runner_on_no_hosts(self):
pass
def runner_on_async_poll(self, host, res, jid, clock):
pass
def runner_on_async_ok(self, host, res, jid):
pass
def runner_on_async_failed(self, host, res, jid):
log(host, 'ASYNC_FAILED', res)
def playbook_on_start(self):
pass
def playbook_on_notify(self, host, handler):
pass
def playbook_on_task_start(self, name, is_conditional):
pass
def playbook_on_vars_prompt(self, varname, private=True, prompt=None, encrypt=None, confirm=False, salt_size=None, salt=None, default=None):
pass
def playbook_on_setup(self):
pass
def playbook_on_import_for_host(self, host, imported_file):
log(host, 'IMPORTED', imported_file)
def playbook_on_not_import_for_host(self, host, missing_file):
log(host, 'NOTIMPORTED', missing_file)
def playbook_on_play_start(self, pattern):
pass
def playbook_on_stats(self, stats):
pass
|
Python
| 0
|
@@ -737,16 +737,306 @@
t json%0A%0A
+# NOTE: in Ansible 1.2 or later general logging is available without%0A# this plugin, just set ANSIBLE_LOG_PATH as an environment variable%0A# or log_path in the DEFAULTS section of your ansible configuration%0A# file. This callback is an example of per hosts logging for those%0A# that want it.%0A%0A
TIME_FOR
|
e169adc40ccdc0ea3821ac9d6603591a6330fe9c
|
update test_jobs.py for lobster
|
custodian/lobster/tests/test_jobs.py
|
custodian/lobster/tests/test_jobs.py
|
import os
import shutil
import unittest
from monty.os import cd
from monty.tempfile import ScratchDir
from custodian.lobster.jobs import LobsterJob
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
test_files_lobster2 = os.path.join(MODULE_DIR, "../../../test_files/lobster/lobsterins")
test_files_lobster3 = os.path.join(MODULE_DIR, "../../../test_files/lobster/vasp_lobster_output")
VASP_OUTPUT_FILES = [
"OUTCAR",
"vasprun.xml",
"CHG",
"CHGCAR",
"CONTCAR",
"INCAR",
"KPOINTS",
"POSCAR",
"POTCAR",
"DOSCAR",
"EIGENVAL",
"IBZKPT",
"OSZICAR",
"PCDAT",
"PROCAR",
"REPORT",
"WAVECAR",
"XDATCAR",
]
LOBSTERINPUT_FILES = ["lobsterin"]
LOBSTER_FILES = [
"lobsterin",
"lobsterin.orig",
"lobsterout",
"CHARGE.lobster",
"COHPCAR.lobster",
"COOPCAR.lobster",
"DOSCAR.lobster",
"GROSSPOP.lobster",
"ICOHPLIST.lobster",
"ICOOPLIST.lobster",
"lobster.out",
"projectionData.lobster",
"MadelungEnergies.lobster",
"SitePotentials.lobster",
"bandOverlaps.lobster",
"ICOBILIST.lobster",
"COBICAR.lobster"
]
FW_FILES = [
'custodian.json',
'FW.json',
'FW_submit.script'
]
class LobsterJobTest(unittest.TestCase):
"""Similar to VaspJobTest. Omit test of run."""
def test_to_from_dict(self):
v = LobsterJob(lobster_cmd="hello")
v2 = LobsterJob.from_dict(v.as_dict())
self.assertEqual(type(v2), type(v))
self.assertEqual(v2.lobster_cmd, "hello")
def test_setup(self):
with cd(test_files_lobster2):
with ScratchDir(".", copy_from_current_on_enter=True):
# check if backup is done correctly
v = LobsterJob("hello", backup=True)
v.setup()
self.assertTrue(os.path.exists("lobsterin.orig"))
# check if backup id done correctly
with ScratchDir(".", copy_from_current_on_enter=True):
v = LobsterJob("hello", backup=False)
v.setup()
self.assertFalse(os.path.exists("lobsterin.orig"))
def test_postprocess(self):
# test gzipped and zipping of additional files
with cd(os.path.join(test_files_lobster3)):
with ScratchDir(".", copy_from_current_on_enter=True):
shutil.copy("lobsterin", "lobsterin.orig")
v = LobsterJob("hello", gzipped=True, add_files_to_gzip=VASP_OUTPUT_FILES)
v.postprocess()
for file in (VASP_OUTPUT_FILES+LOBSTER_FILES+FW_FILES):
filegz = file+".gz"
self.assertTrue(os.path.exists(filegz))
with ScratchDir(".", copy_from_current_on_enter=True):
shutil.copy("lobsterin", "lobsterin.orig")
v = LobsterJob("hello", gzipped=False, add_files_to_gzip=VASP_OUTPUT_FILES)
v.postprocess()
for file in (VASP_OUTPUT_FILES+LOBSTER_FILES+FW_FILES):
self.assertTrue(os.path.exists(file))
if __name__ == "__main__":
unittest.main()
|
Python
| 0.000001
|
@@ -2776,20 +2776,16 @@
gz))%0D%0A%0D%0A
-%0D%0A%0D%0A
|
b5c8821026e877e014bd3755af07c4e0213644dd
|
Add ability to open default settings for viewing
|
misc.py
|
misc.py
|
import sublime_plugin
import sublime
import webbrowser
import os
from . import PluginLogger
from .lib.sdk import SDK
_logger = PluginLogger(__name__)
class OpenBrowser(sublime_plugin.WindowCommand):
"""Opens API reference in default browser.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, url):
webbrowser.open_new_tab(url)
class OpenDartEditor(sublime_plugin.TextCommand):
"""Opens the Dart Editor.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit):
sdk = SDK()
sdk.start_editor()
class OpenDartSettings(sublime_plugin.WindowCommand):
"""Opens Dart settings files.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@property
def user_file(self):
return os.path.join(sublime.packages_path(),
'User/Dart.sublime-settings')
def run(self, kind='user'):
if kind != 'user':
sublime.status_message('Dart: Not supported settings kind: {0}'
.format(kind))
_logger.error('Not supported settings kind: %s', kind)
return
if not os.path.exists(self.user_file):
_logger.debug('Creating user settings file at: %s',
self.user_file)
with open(self.user_file, 'w') as f:
f.write('{\n\t\n}')
try:
self.window.open_file(self.user_file)
except OSError as e:
_logger.error('Unexpected error while trying to open %s',
self.user_file)
_logger.error(e)
_logger.error('=' * 80)
|
Python
| 0
|
@@ -733,16 +733,280 @@
s files.
+%0A%0A Default settings (that is, Packages/Dart/Support/Dart.sublime-settings)%0A are displayed as a read-only view not meant for editing.%0A%0A User settings (that is, Packages/User/Dart.sublime-settings) are opened%0A as a regular view and are meant for editing.
%0A %22%22%22
@@ -1253,31 +1253,105 @@
def
-run(self, kind='
+open_default(self):%0A %22%22%22Prints the default settings for Dart to a read-only view. The
user
-'):
%0A
@@ -1359,133 +1359,954 @@
-if kind != 'user':%0A sublime.status_message('Dart: Not supported settings kind: %7B0%7D'%0A .format(kind))
+should not edit their settings here, but use the 'user' file instead.%0A %22%22%22%0A setts = sublime.load_resource(%0A 'Packages/Dart/Support/Dart.sublime-settings')%0A%0A v = self.window.new_file()%0A v.run_command('append', %7B%22characters%22: setts.replace('%5Cr', '')%7D)%0A v.set_name('Dart Settings %E2%80%93 Default (read-only)')%0A # TODO(guillermooo): ST should detect that this is a JSON file by%0A # looking at the extension, but it isn't the case. Check with%0A # Sublime HQ. For now, set the syntax manually.%0A v.set_syntax_file('Packages/JavaScript/JSON.tmLanguage')%0A v.set_scratch(True)%0A v.set_read_only(True)%0A%0A def run(self, kind='user'):%0A %22%22%22%0A @kind: Any of (user, default).%0A %22%22%22%0A if kind == 'default':%0A _logger.debug('Opening default settings for viewing only.')%0A self.open_default()%0A return%0A%0A if kind != 'user':
%0A
@@ -2333,12 +2333,10 @@
or('
-Not
+Un
supp
@@ -2350,20 +2350,20 @@
ettings
-kind
+type
: %25s', k
|
68e69188e412d30cb6e269b8b350cea743d9cfa7
|
Allow passing extra environment files when scaling nodes
|
tripleo_common/scale.py
|
tripleo_common/scale.py
|
# Copyright 2015 Red Hat, Inc.
# All Rights Reserved.
#
# 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 or 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.
import logging
import os
import shutil
from heatclient.common import template_utils
from tripleo_common import libutils
from tuskarclient.common import utils as tuskarutils
LOG = logging.getLogger(__name__)
TEMPLATE_NAME = 'overcloud-without-mergepy.yaml'
REGISTRY_NAME = "overcloud-resource-registry-puppet.yaml"
class ScaleManager(object):
def __init__(self, heatclient, stack_id, tuskarclient=None, plan_id=None,
tht_dir=None):
self.tuskarclient = tuskarclient
self.heatclient = heatclient
self.stack_id = stack_id
self.tht_dir = tht_dir
if self.tuskarclient:
self.plan = tuskarutils.find_resource(self.tuskarclient.plans,
plan_id)
def scaleup(self, role, num):
LOG.debug('updating role %s count to %d', role, num)
param_name = '{0}::count'.format(role)
param = next(x for x in self.plan.parameters if
x['name'] == param_name)
if num < int(param['value']):
raise ValueError("Role %s has already %s nodes, can't set lower "
"value" % (role, param['value']))
self.plan = self.tuskarclient.plans.patch(
self.plan.uuid,
[{'name': param_name, 'value': str(num)}])
self._update_stack()
def scaledown(self, instances):
resources = self.heatclient.resources.list(self.stack_id,
nested_depth=5)
resources_by_role = {}
instance_list = list(instances)
for res in resources:
try:
instance_list.remove(res.physical_resource_id)
except ValueError:
continue
stack_name, stack_id = next(
x['href'] for x in res.links if
x['rel'] == 'stack').rsplit('/', 2)[1:]
# get resource to remove from resource group (it's parent resource
# of nova server)
role_resource = next(x for x in resources if
x.physical_resource_id == stack_id)
# get tuskar role name from resource_type,
# resource_type is in format like "Tuskar::Compute-1"
role = role_resource.resource_type.rsplit('::', 1)[-1]
if role not in resources_by_role:
resources_by_role[role] = []
resources_by_role[role].append(role_resource)
if instance_list:
raise ValueError(
"Couldn't find following instances in stack %s: %s" %
(self.stack_id, ','.join(instance_list)))
# decrease count for each role (or resource group) and set removal
# policy for each resource group
if self.tuskarclient:
stack_params = self._get_removal_params_from_plan(
resources_by_role)
else:
stack_params = self._get_removal_params_from_heat(
resources_by_role)
self._update_stack(parameters=stack_params)
def _update_stack(self, parameters={}):
if self.tuskarclient:
self.tht_dir = libutils.save_templates(
self.tuskarclient.plans.templates(self.plan.uuid))
tpl_name = 'plan.yaml'
env_name = 'environment.yaml'
else:
tpl_name = TEMPLATE_NAME
env_name = REGISTRY_NAME
try:
tpl_files, template = template_utils.get_template_contents(
template_file=os.path.join(self.tht_dir, tpl_name))
env_files, env = (
template_utils.process_multiple_environments_and_files(
env_paths=[os.path.join(self.tht_dir, env_name)]))
fields = {
'existing': True,
'stack_id': self.stack_id,
'template': template,
'files': dict(list(tpl_files.items()) +
list(env_files.items())),
'environment': env,
'parameters': parameters
}
LOG.debug('stack update params: %s', fields)
self.heatclient.stacks.update(**fields)
finally:
if self.tuskarclient:
if LOG.isEnabledFor(logging.DEBUG):
LOG.debug("Tuskar templates saved in %s", self.tht_dir)
else:
shutil.rmtree(self.tht_dir)
def _get_removal_params_from_plan(self, resources_by_role):
patch_params = []
stack_params = {}
for role, role_resources in resources_by_role.items():
param_name = "{0}::count".format(role)
old_count = next(x['value'] for x in self.plan.parameters if
x['name'] == param_name)
count = max(int(old_count) - len(role_resources), 0)
patch_params.append({'name': param_name, 'value': str(count)})
# add instance resource names into removal_policies
# so heat knows which instances should be removed
removal_param = "{0}::removal_policies".format(role)
stack_params[removal_param] = [{
'resource_list': [r.resource_name for r in role_resources]
}]
LOG.debug('updating plan %s: %s', self.plan.uuid, patch_params)
self.plan = self.tuskarclient.plans.patch(self.plan.uuid, patch_params)
return stack_params
def _get_removal_params_from_heat(self, resources_by_role):
stack_params = {}
stack = self.heatclient.stacks.get(self.stack_id)
for role, role_resources in resources_by_role.items():
param_name = "{0}Count".format(role)
old_count = next(v for k, v in stack.parameters.iteritems() if
k == param_name)
count = max(int(old_count) - len(role_resources), 0)
stack_params[param_name] = str(count)
# add instance resource names into removal_policies
# so heat knows which instances should be removed
removal_param = "{0}RemovalPolicies".format(role)
stack_params[removal_param] = [{
'resource_list': [r.resource_name for r in role_resources]
}]
return stack_params
|
Python
| 0.000007
|
@@ -1047,16 +1047,40 @@
dir=None
+, environment_files=None
):%0A
@@ -1216,16 +1216,67 @@
tht_dir%0A
+ self.environment_files = environment_files%0A
@@ -4251,16 +4251,175 @@
_name))%0A
+ env_paths = %5Bos.path.join(self.tht_dir, env_name)%5D%0A if self.environment_files:%0A env_paths.extend(self.environment_files)%0A
@@ -4441,16 +4441,16 @@
env = (%0A
-
@@ -4547,46 +4547,17 @@
ths=
-%5Bos.path.join(self.tht_dir, env_name)%5D
+env_paths
))%0A
|
28c40453c23b3ae64ab720a5510b377ba1dc5702
|
make the sum between the process and the children process.
|
tsuru/plugins/statsd.py
|
tsuru/plugins/statsd.py
|
# Copyright 2014 tsuru-circus authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import socket
from zmq.eventloop import ioloop
from circus.plugins import CircusPlugin
from circus.util import human2bytes
from tsuru import common
class StatsdEmitter(CircusPlugin):
name = 'statsd'
default_app_name = "app"
def __init__(self, endpoint, pubsub_endpoint, check_delay, ssh_server,
**config):
super(StatsdEmitter, self).__init__(endpoint, pubsub_endpoint,
check_delay, ssh_server=ssh_server)
self.app = config.get('application_name', self.default_app_name)
apprc = "/home/application/apprc"
envs = common.load_envs(apprc)
app_name = envs.get("TSURU_APPNAME")
host_name = socket.gethostname()
# tsuru.app.host
self.prefix = 'tsuru.{}.{}'.format(app_name, host_name)
# initialize statsd
from circus.plugins.statsd import StatsdClient
host = envs.get("STATSD_HOST") or config.get('host', 'localhost')
port = envs.get("STATSD_PORT") or config.get('port', '8125')
self.statsd = StatsdClient(
host=host,
port=int(port),
prefix=self.prefix,
sample_rate=float(config.get('sample_rate', '1.0'))
)
def handle_recv(self, data):
watcher_name, action, msg = self.split_data(data)
self.statsd.increment('{}.{}'.format(watcher_name, action))
def stop(self):
self.statsd.stop()
super(StatsdEmitter, self).stop()
class BaseObserver(StatsdEmitter):
def __init__(self, *args, **config):
super(BaseObserver, self).__init__(*args, **config)
self.loop_rate = float(config.get("loop_rate", 60)) # in seconds
def handle_init(self):
self.period = ioloop.PeriodicCallback(self.look_after,
self.loop_rate * 1000, self.loop)
self.period.start()
def handle_stop(self):
self.period.stop()
self.statsd.stop()
def handle_recv(self, data):
pass
def look_after(self):
raise NotImplementedError()
class Stats(BaseObserver):
name = 'stats'
def look_after(self):
info = self.call("stats")
if info["status"] == "error":
self.statsd.increment("_stats.error")
return
for name, stats in info['infos'].items():
if name.startswith("plugin:"):
# ignore plugins
continue
cpus = []
mems = []
mem_infos = []
for sub_name, sub_info in stats.items():
if isinstance(sub_info, dict):
cpus.append(sub_info['cpu'])
mems.append(sub_info['mem'])
mem_infos.append(human2bytes(sub_info['mem_info1']))
elif sub_name == "spawn_count":
# spawn_count info is in the same level as processes
# dict infos, so if spawn_count is given, take it and
# continue
self.statsd.gauge("{}.spawn_count".format(name),
sub_info)
self.statsd.gauge("{}.watchers_num".format(name), len(cpus))
if not cpus:
# if there are only dead processes, we have an empty list
# and we can't measure it
continue
self.statsd.gauge("{}.cpu_max".format(name), max(cpus))
self.statsd.gauge("{}.cpu_sum".format(name), sum(cpus))
self.statsd.gauge("{}.mem_pct_max".format(name), max(mems))
self.statsd.gauge("{}.mem_pct_sum".format(name), sum(mems))
self.statsd.gauge("{}.mem_max".format(name), max(mem_infos))
self.statsd.gauge("{}.mem_sum".format(name), sum(mem_infos))
|
Python
| 0
|
@@ -2823,82 +2823,300 @@
cpu
-s.append(sub_info%5B'cpu'%5D)%0A mems.append(sub_info%5B'mem'%5D)
+ = %5Bsub_info%5B'cpu'%5D%5D%0A mem = %5Bsub_info%5B'mem'%5D%5D%0A%0A for p in sub_info%5B'children'%5D:%0A cpu.append(p%5B'cpu'%5D)%0A mem.append(p%5B'mem'%5D)%0A%0A cpus.append(sum(cpu))%0A mems.append(sum(mem))%0A
%0A
|
6aa22782ce8a077d63be11be9a59c3fbbde0e700
|
Clean up command line a bit.
|
tuneharvest/commands.py
|
tuneharvest/commands.py
|
import argparse
import sys
from tuneharvest.sources.console import from_console
from tuneharvest.sources.slack import from_slack
from tuneharvest.sinks.console import to_console
from tuneharvest.sinks.youtube import to_youtube
from tuneharvest.filters import Masseuse
parser = argparse.ArgumentParser(
'tuneharvest',
description='Can harvest youtube music links from a slack conversation for posting in a youtube playlist.'
)
subparsers = parser.add_subparsers()
from_parser = subparsers.add_parser('from', help='Read music links from a location')
from_subparsers = from_parser.add_subparsers()
from_console_parser = from_subparsers.add_parser('console', help='Read links line by line from stdin')
from_console_parser.set_defaults(action=from_console)
from_console_parser.add_argument(
'--format', '-F', default='{media}',
help='Format to read from console'
)
from_slack_parser = from_subparsers.add_parser('slack', help='Read links based on a slack search')
from_slack_parser.set_defaults(action=from_slack)
from_slack_parser.add_argument(
'--token', '-t', default='keys/token-from-slack.txt',
help='Slack API token or filename containing API token'
)
from_slack_parser.add_argument(
'--query', '-q', default='has:link',
help='Slack search query'
)
from_slack_parser.add_argument(
'--direction', '-D', default='desc', choices=('asc', 'desc'),
help='Slack sort direction'
)
from_slack_parser.add_argument(
'--limit', '-L', default=None, type=int,
help='Max number of items to find'
)
to_parser = subparsers.add_parser('to', help='Write music links to a location')
to_subparsers = to_parser.add_subparsers()
to_console_parser = to_subparsers.add_parser('console', help='Write links found to stdout')
to_console_parser.set_defaults(action=to_console)
to_console_parser.add_argument(
'--format', '-F', default='{media}',
help='Format to write to console'
)
to_console_parser.add_argument(
'--limit', '-L', default=None, type=int,
help='Max items to print'
)
to_youtube_parser = to_subparsers.add_parser('youtube', help='Update a youtube playlist')
to_youtube_parser.set_defaults(action=to_youtube)
to_youtube_parser.add_argument(
'--secrets', '-S', default='keys/secrets-to-youtube.json',
help='JSON client secrets file'
)
to_youtube_parser.add_argument(
'--title', '-T', default=None,
help='Title of youtube playlist'
)
to_youtube_parser.add_argument(
'--id', '-I', default=None,
help='Youtube playlist ID to modify'
)
to_youtube_parser.add_argument(
'--privacy', default='unlisted', choices=('private', 'public', 'unlisted'),
help='Privacy setting of new youtube playlist'
)
to_youtube_parser.add_argument(
'--limit', '-L', default=200, type=int,
help='Max number of items in playlist'
)
to_youtube_parser.add_argument(
'--reverse', action='store_true',
help='Whether to reverse link order'
)
to_youtube_parser.add_argument(
'-v', '--verbose', action='count', default=0,
help='Verbosity'
)
def main(argv=None):
argv = (argv or sys.argv)[1:]
commands = list()
prev = 1
for i in range(prev+1, len(argv)):
if sys.argv[i] in ('from', 'to'):
commands.append(sys.argv[prev:i])
prev = i
commands.append(sys.argv[prev:])
if not commands[-1]:
parser.parse_args()
raise RuntimeError('At least one `from` or `to` command is required.')
sources = list()
sink = None
for command in commands:
if command[0] == 'from':
sources.append(command)
elif sink is None:
sink = command
else:
raise RuntimeError('We only support one sink at a time currently')
if not sources:
sources.append('from console'.split())
if not sink:
sink = 'to console'.split()
source_args = [parser.parse_args(source) for source in sources]
sink_args = parser.parse_args(sink)
massage = Masseuse().massage
iter_source_links = (massage(link) for args in source_args for link in args.action(args))
sink_args.action(sink_args, iter_source_links)
if __name__ == '__main__':
main()
|
Python
| 0
|
@@ -264,16 +264,134 @@
seuse%0A%0A%0A
+import pkg_resources%0Atry:%0A VERSION = pkg_resources.require(%22tuneharvest%22)%5B0%5D.version%0Aexcept:%0A VERSION = 'DEV'%0A%0A%0A
parser =
@@ -420,27 +420,8 @@
er(%0A
- 'tuneharvest',%0A
@@ -436,20 +436,18 @@
ion=
-'Can h
+('H
arvest
+s
you
@@ -488,16 +488,38 @@
ersation
+' +%0A '
for pos
@@ -544,18 +544,244 @@
playlist
-.'
+%5Cn' +%0A ' Version %7B%7D').format(VERSION),%0A formatter_class=argparse.RawDescriptionHelpFormatter%0A)%0Aparser.add_argument(%0A '--version', action='store_true',%0A help='Print version (%7B%7D) and exit'.format(VERSION)
%0A)%0A%0Asubp
@@ -3675,16 +3675,23 @@
%0A
+ args =
parser.
@@ -3703,16 +3703,105 @@
_args()%0A
+ if args.version:%0A print(VERSION)%0A return%0A else:%0A
|
d99aebe4ded6f8b8663ca32a191c6c39e58b1517
|
bump version
|
kuyruk/__init__.py
|
kuyruk/__init__.py
|
from __future__ import absolute_import
import logging
from kuyruk.kuyruk import Kuyruk
from kuyruk.worker import Worker
from kuyruk.task import Task
from kuyruk.config import Config
__version__ = '0.14.4'
try:
# not available in python 2.6
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
# Add NullHandler to prevent logging warnings on startup
null_handler = NullHandler()
logging.getLogger('kuyruk').addHandler(null_handler)
logging.getLogger('pika').addHandler(null_handler)
|
Python
| 0
|
@@ -197,17 +197,17 @@
= '0.14.
-4
+5
'%0A%0Atry:%0A
|
336020466c48538921497a93db2ffa2ab2909eab
|
Drop prefetch tags in case_list, due not used
|
poradnia/cases/views/cases.py
|
poradnia/cases/views/cases.py
|
from __future__ import absolute_import
from django.shortcuts import get_object_or_404, redirect
from django.contrib import messages
from django.utils.translation import ugettext as _
from django.views.generic import UpdateView, TemplateView
from django_filters.views import FilterView
from braces.views import UserFormKwargsMixin, LoginRequiredMixin
from users.views import PermissionMixin
from letters.forms import AddLetterForm
from events.forms import EventForm
from letters.helpers import AttachmentFormSet
from records.models import Record
from ..models import Case
from ..forms import CaseForm, CaseGroupPermissionForm
from ..filters import StaffCaseFilter, UserCaseFilter
class CaseDetailView(LoginRequiredMixin, TemplateView): # TODO: Use django.views.generic.DetailView
template_name = 'cases/case_detail.html'
def get_context_data(self, **kwargs):
context = super(CaseDetailView, self).get_context_data(**kwargs)
context = {}
qs = (Case.objects.prefetch_related('tags').
select_related('created_by').
select_related('triggered').
select_related('modified_by'))
case = get_object_or_404(qs, pk=self.kwargs['pk'])
case.view_perm_check(self.request.user)
# Readed.update(user=request.user, case=case)
context['object'] = case
context['forms'] = {}
context['forms']['letter'] = {'title': _('Letter'),
'form': AddLetterForm(user=self.request.user, case=case),
'formset': AttachmentFormSet(instance=None)}
if self.request.user.is_staff:
context['forms']['event'] = {'title': _('Event'),
'form': EventForm(user=self.request.user, case=case)}
qs = (Record.objects.filter(case=case).
select_related('letter__created_by', 'letter', 'letter__modified_by').
select_related('event__created_by', 'event', 'event__modified_by').
select_related('event__alarm', ).
prefetch_related('letter__attachment_set', 'letter__created_by__avatar_set'))
if not self.request.user.is_staff:
qs = qs.for_user(self.request.user)
context['record_list'] = qs.all()
context['casegroup_form'] = CaseGroupPermissionForm(case=case, user=self.request.user)
return context
class CaseListView(PermissionMixin, FilterView):
model = Case
paginate_by = 25
@property
def filterset_class(self):
return StaffCaseFilter if self.request.user.is_staff else UserCaseFilter
def get_queryset(self, *args, **kwargs): # TODO: Mixins
qs = super(CaseListView, self).get_queryset(*args, **kwargs)
return qs.select_related('client').prefetch_related('tags')
def get_context_data(self, **kwargs):
context = super(CaseListView, self).get_context_data(**kwargs)
context['statuses'] = Case.STATUS
return context
class CaseUpdateView(UserFormKwargsMixin, UpdateView):
form_class = CaseForm
template_name = 'cases/case_form.html'
model = Case
def get_object(self):
obj = super(CaseUpdateView, self).get_object()
obj.perm_check(self.request.user, 'can_change_case')
return obj
def form_valid(self, form):
obj = form.save()
messages.success(self.request, _('Successful updated "%(object)s".') % {'object': obj})
return redirect(obj)
|
Python
| 0
|
@@ -988,33 +988,8 @@
cts.
-prefetch_related('tags').
%0A
|
8650f7380976671553db28e11ac145ac3b4b9d20
|
Update production.py
|
poradnia/config/production.py
|
poradnia/config/production.py
|
# -*- coding: utf-8 -*-
'''
Production Configurations
'''
from .common import * # noqa
# SECRET KEY
SECRET_KEY = env.str('DJANGO_SECRET_KEY')
# END SECRET KEY
# SITE CONFIGURATION
# Hosts/domain names that are valid for this site
# See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ["*"]
# END SITE CONFIGURATION
# EMAIL
EMAIL_BACKEND = env.email_url(default='consolemail://')
DEFAULT_FROM_EMAIL = env.str('DJANGO_DEFAULT_FROM_EMAIL',
'poradnia <noreply@porady.siecobywatelska.pl>')
EMAIL_HOST = env('DJANGO_EMAIL_HOST')
EMAIL_HOST_PASSWORD = env('DJANGO_EMAIL_HOST_PASSWORD')
EMAIL_HOST_USER = env('DJANGO_EMAIL_HOST_USER')
EMAIL_PORT = env.int('DJANGO_EMAIL_PORT')
EMAIL_SUBJECT_PREFIX = env('DJANGO_EMAIL_SUBJECT_PREFIX', default='[poradnia] ')
EMAIL_USE_TLS = env.bool('DJANGO_EMAIL_USE_TLS', defualt=True)
SERVER_EMAIL = EMAIL_HOST_USER
# END EMAIL
# TEMPLATE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
TEMPLATE_LOADERS = (
('django.template.loaders.cached.Loader', (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)),
)
# END TEMPLATE CONFIGURATION
# Your production stuff: Below this line define 3rd party libary settings
# Ustaw wartość twojego DSN
RAVEN_CONFIG = {
'dsn': env.str('RAVEN_DSN', 'http://example.com'),
}
INSTALLED_APPS += ('raven.contrib.django.raven_compat',)
MIDDLEWARE_CLASSES = (
"raven.contrib.django.raven_compat.middleware.Sentry404CatchMiddleware",
) + MIDDLEWARE_CLASSES
CACHES = {
'default': env.cache(),
}
|
Python
| 0.000001
|
@@ -466,17 +466,16 @@
_EMAIL',
-
%0A
@@ -556,24 +556,28 @@
L_HOST = env
+.str
('DJANGO_EMA
@@ -607,24 +607,28 @@
SSWORD = env
+.str
('DJANGO_EMA
@@ -663,24 +663,28 @@
T_USER = env
+.str
('DJANGO_EMA
@@ -766,16 +766,20 @@
IX = env
+.str
('DJANGO
@@ -802,24 +802,16 @@
REFIX',
-default=
'%5Bporadn
@@ -870,16 +870,8 @@
S',
-defualt=
True
|
475df103dc2fd29fa3426893923ebe87177c07bd
|
Remove unnecessary ord() (str/bytes)
|
pox/lib/packet/packet_base.py
|
pox/lib/packet/packet_base.py
|
# Copyright 2011 James McCauley
# Copyright 2008 (C) Nicira, 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:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
# This file is derived from the packet library in NOX, which was
# developed by Nicira, Inc.
import logging
lg = logging.getLogger('packet')
from pox.lib.util import initHelper
class packet_base (object):
"""
TODO: This description is somewhat outdated and should be fixed.
Base class for packets.
Classes that perform packet manipulation (parsing and contruction)
should derive from this class.
The general layout of such a subclass is as follows:
class foo (packet_base):
def __init__(data=None, prev=None):
packet_base.__init__(self)
# data: is the data for the packet as a "bytes" object.
# prev: is a pointer to the previous header
# which is expected to be of type packet_base
self.parsed = False
self.prev = prev
# define field variables here
self.bar = 0
if arr != None:
self.data = data # Phasing out?
self.parse(data)
def parse(self, data):
# parse packet here and set member variables
self.parsed = True # signal that packet was succesfully parsed
def hdr(self, payload):
# return fields as a string
return struct.pack('!I',self.bar)
def __str__(self):
# optionally convert to human readable string
"""
def __init__ (self):
self.next = None
self.prev = None
self.parsed = False
self.raw = None
def _init (self, kw):
if 'payload' in kw:
self.set_payload(kw['payload'])
del kw['payload']
initHelper(self, kw)
def msg(self, *args):
""" Shortcut for logging """
#TODO: Remove?
lg.info(*args)
def err(self, *args):
""" Shortcut for logging """
#TODO: Remove?
lg.error(*args)
def warn(self, *args):
""" Shortcut for logging """
#TODO: Remove?
lg.warning(*args)
def __bool__(self):
return self.parsed is True
def __len__(self):
return len(self.pack())
def __str__(self):
if hasattr(self, "_to_str"):
try:
return self._to_str()
except Exception as e:
#import traceback
#traceback.print_exc()
lg.debug("str(%s): %s" % (self.__class__.__name__, e))
return "[%s:Bad representation]" % (self.__class__.__name__,)
return "[%s l:%i%s]" % (self.__class__.__name__, len(self),
"" if self.next else " *")
def dump(self):
p = self
m = []
while p is not None:
if not isinstance(p, packet_base):
if isinstance(p, bytes):
if len(p) == 0:
m.append("[0 bytes]")
break
s = ''
for t in range(min(len(p), 5)):
s += "%02x " % (ord(p[t]),)
if len(p) > 5: s += "..."
s = s.rstrip()
m.append("[%s bytes: " % (len(p),) + s + "]")
break
try:
l = len(p)
m.append("[%s l:%i]" % (p.__class__.__name__, l))
except:
m.append("[%s]" % (p.__class__.__name__,))
break
m.append(str(p))
p = p.next
return "".join(m)
def find(self, proto):
"""
Find the specified protocol layer based on its class type or name.
"""
if not isinstance(proto, str):
proto = proto.__name__
if self.__class__.__name__ == proto and self.parsed:
return self
else:
if self.next and isinstance(self.next, packet_base):
return self.next.find(proto)
else:
return None
@property
def payload (self):
"""
The packet payload property.
Reading this property is generally the same as the "next" field.
Setting this generally sets this packet's "next" field, as well as
setting the new payload's "prev" field to point back to its new
container (the same as the set_payload() method).
"""
return self.next
@payload.setter
def payload (self, new_payload):
self.set_payload(new_payload)
def set_payload(self, payload):
'''
Set the packet payload. Expects bytes or a packet_base subclass.
'''
if isinstance(payload, packet_base):
self.next = payload
payload.prev = self
elif type(payload) == bytes:
self.next = payload
else:
raise TypeError("payload must be bytes or packet subclass")
def parse(self, raw):
'''Override me with packet parsing code'''
raise NotImplementedError("parse() not implemented")
def pre_hdr(self):
'''Override to prepare before payload is packed'''
pass
def hdr(self, payload):
'''Override me to return packet headers'''
raise NotImplementedError("hdr() not implemented")
@classmethod
def unpack (cls, raw, prev=None):
return cls(raw=raw, prev=prev)
def pack(self):
'''Convert header and payload to bytes'''
if self.parsed is False and self.raw is not None and self.next is None:
return self.raw
self.pre_hdr()
if self.next == None:
return self.hdr(b'')
elif isinstance(self.next, packet_base):
rest = self.next.pack()
elif isinstance(self.next, str):
rest = self.next.encode()
else:
rest = self.next
return self.hdr(rest) + rest
|
Python
| 0.000002
|
@@ -3519,18 +3519,13 @@
%22 %25
-(ord
(p%5Bt%5D
-)
,)%0A
|
25c94638d2b63e749c2deef2c64fa27b587ce5de
|
fix directory and job name lameness
|
gscripts/rnaseq/sailfish_index.py
|
gscripts/rnaseq/sailfish_index.py
|
#!/usr/bin/env python
__author__ = 'olga'
from gscripts.qtools import Submitter
import argparse
class CommandLine(object):
"""
Check out the argparse documentation for more awesome things you can do!
https://docs.python.org/2/library/argparse.html
"""
def __init__(self, inOpts=None):
self.parser = parser = argparse.ArgumentParser(
description='Generate a sailfish transcriptome index from fasta '
'files')
parser.add_argument('-f', '--fasta', required=True,
type=str, action='store',
help='Fasta files of the transcripts (+spikeins '
'if you please) you want to index using '
'STAR.')
parser.add_argument('-k', '--kmer-size', required=True, type=int,
action='store',
help='Size of the k-mers hashed from the '
'transcriptome')
parser.add_argument('-o', '--out-dir', required=False, type=str,
action='store',
help='Where you want to save the index. Defaults '
'to {fasta_file}_sailfish_index_k{kmer_size}')
parser.add_argument('-n', '--job-name', default='sailfish_index',
action='store', type=str,
help='The name of the submitted job in the queue')
parser.add_argument('-p', '--num-processors', required=False,
type=int, action='store', default=8,
help='Number of processors to use. Default is 8 ('
'easier to find a half-free node than a '
'fully free node)')
parser.add_argument('--out-sh', required=False, type=str,
action='store',
help='Name of the file that is submitted to '
'the PBS queue. Defaults to {job_name}.sh')
parser.add_argument('--do-not-submit', required=False,
action='store_true', default=False,
help='Flag to not actually submit the job but '
'just write the sh file (for testing)')
if inOpts is None:
self.args = vars(self.parser.parse_args())
else:
self.args = vars(self.parser.parse_args(inOpts))
def do_usage_and_die(self, str):
'''
If a critical error is encountered, where it is suspected that the
program is not being called with consistent parameters or data, this
method will write out an error string (str), then terminate execution
of the program.
'''
import sys
print >> sys.stderr, str
self.parser.print_usage()
return 2
# Class: Usage
class Usage(Exception):
'''
Used to signal a Usage error, evoking a usage statement and eventual
exit when raised
'''
def __init__(self, msg):
self.msg = msg
class SailfishIndex(object):
def __init__(self, fasta, kmer_size, job_name='sailfish_index',
num_processors=8,
out_sh=None, out_dir=None, submit=False):
if num_processors > 16:
raise ValueError('At most 16 processors can be specified, '
'but you '
'asked for {}'.format(num_processors))
if kmer_size > 31:
raise ValueError('Maximum kmer size is 31 due to memory '
'limitations but "{}" was specified'.format(
kmer_size))
if out_dir is None:
out_dir = '{}_sailfish_index_k{}'.format(fasta,
kmer_size)
else:
out_dir = out_dir
if out_sh is None:
out_sh = job_name + '.sh'
else:
out_sh = out_sh
command = 'sailfish quant --index {0} --threads {1} --transcripts ' \
'' \
'{2} --out {3}'.format(kmer_size,
num_processors,
fasta,
out_dir)
sub = Submitter(queue_type='PBS', sh_filename=out_sh,
commands=[command], job_name=job_name,
nodes=1, ppn=num_processors,
queue='home',
walltime='0:30:00')
sub.write_sh(submit=submit)
if __name__ == '__main__':
cl = CommandLine()
try:
job_name = '_'.join([cl.args['job_name'], 'sailfish_index'])
out_sh = name = job_name + '.sh' if cl.args['out_sh'] is None \
else cl.args['out_sh']
submit = not cl.args['do_not_submit']
directory = cl.args['directory']
SailfishIndex(cl.args['fasta'], cl.args['kmer_size'],
cl.args['job_name'],
num_processors=cl.args['num_processors'],
out_sh=cl.args['out_sh'], out_dir=cl.args['out_dir'],
submit=submit)
except Usage, err:
cl.do_usage_and_die()
|
Python
| 0
|
@@ -4738,24 +4738,25 @@
try:%0A
+%0A
job_name
@@ -4751,102 +4751,36 @@
-job_name = '_'.join(%5Bcl.args%5B'job_name'%5D, 'sailfish_index'%5D)%0A%0A out_sh = name = job_name
+out_sh = cl.args%5B'job_name'%5D
+ '
@@ -4899,49 +4899,8 @@
it'%5D
-%0A directory = cl.args%5B'directory'%5D
%0A%0A
|
bf5c124192378358ba92e9707beae50ba39778ce
|
rename learn_rate -> learning_rate
|
examples/ensemble/plot_partial_dependence.py
|
examples/ensemble/plot_partial_dependence.py
|
"""
========================
Partial Dependence Plots
========================
Partial dependence plots show the dependence between the target function [1]_
and a set of 'target' features, marginalizing over the
values of all other features (the complement features). Due to the limits
of human perception the size of the target feature set must be small (usually,
one or two) thus the target features are usually choosen among the most
important features (see :meth:`ensemble.GradientBoostingRegressor.feature_importances_`).
This example shows how to obtain partial dependence plots from a
:class:`ensemble.GradientBoostingRegressor` trained on the California
housing dataset. The example is taken from [HTF2009]_.
The first plot shows four one-dimensional partial dependence plots. The target
variables are: median income (`MedInc`), avg. occupants per household (`AvgOccup`),
median house age (`HouseAge`), and avg. rooms per household (`AveRooms`).
We can clearly see that the median house price shows a linear relationship with the
median income (top left) and that the house price drops when the avg. occupants
per household increases (top right).
The lower left plot shows that the house age in a district does not have
a strong influence on the (median) house price.
The red tick marks on the x-axis represent the deciles of the feature values
in the trainig data.
Partial dependence plots with two target features enable us to visualize
interactions among them. The two-variable partial dependence plot shows the
dependence of median house price on joint values of house age and avg.
occupants per household. We can clearly see an interaction between the
two features:
For an avg. occupancy greather than two, the house price is nearly independent
of the house age, whereas for values less than two there is a strong dependence
on age.
.. [HTF2009] T. Hastie, R. Tibshirani and J. Friedman, "Elements of Statistical Learning Ed. 2", Springer, 2009.
.. [1] For classification you can think of it as the regression score before the link function.
"""
print __doc__
import numpy as np
import pylab as pl
import matplotlib
from mpl_toolkits.mplot3d import Axes3D
from scipy.stats.mstats import mquantiles
from sklearn.cross_validation import train_test_split
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.ensemble import gradient_boosting
from sklearn.datasets.cal_housing import fetch_cal_housing
# fetch California housing dataset
cal_housing = fetch_cal_housing()
# split 80/20 train-test
X_train, X_test, y_train, y_test = train_test_split(cal_housing.data,
cal_housing.target,
test_size=0.2,
random_state=1)
names = cal_housing.feature_names
print('_' * 80)
print("Training GBRT...")
clf = GradientBoostingRegressor(n_estimators=800, max_depth=4,
learn_rate=0.1, loss='huber',
random_state=1)
clf.fit(X_train, y_train)
print("fin.")
print('_' * 80)
print('One-way partial dependence plots')
print
pl.figure()
sub_plots = []
for i, fx in enumerate([0, 5, 1, 2]):
name = names[fx]
target_feature = np.array([fx], dtype=np.int32)
ax = pl.subplot(2, 2, i + 1)
# plot partial dependence
pdp, (axis,) = gradient_boosting.partial_dependence(clf, target_feature,
X=X_train)
ax.plot(axis, pdp.ravel(), 'g-')
# plot data deciles
deciles = mquantiles(X_train[:, fx], prob=np.arange(0.1, 1.0, 0.1))
trans = matplotlib.transforms.blended_transform_factory(ax.transData,
ax.transAxes)
ax.vlines(deciles, 0.0, 0.05, transform=trans, color='red')
pl.xlabel(name)
pl.ylabel('Partial Dependence')
sub_plots.append(ax)
# set common ylim
y_min = min((ax.get_ylim()[0] for ax in sub_plots))
y_max = max((ax.get_ylim()[1] for ax in sub_plots))
for ax in sub_plots:
ax.set_ylim((y_min, y_max))
pl.tight_layout()
print('_' * 80)
print('Two-way partial dependence plot')
print
fig = pl.figure()
target_feature = np.array([1, 5], dtype=np.int32)
pdp, (x_axis, y_axis) = gradient_boosting.partial_dependence(clf,
target_feature,
X=X_train,
grid_resolution=50)
XX, YY = np.meshgrid(x_axis, y_axis)
Z = pdp.T.reshape(XX.shape).T
ax = Axes3D(fig)
surf = ax.plot_surface(XX, YY, Z, rstride=1, cstride=1, cmap=pl.cm.BuPu)
ax.set_xlabel(names[target_feature[0]])
ax.set_ylabel(names[target_feature[1]])
ax.set_zlabel('Partial dependence')
# pretty init view
ax.view_init(elev=22, azim=122)
pl.colorbar(surf)
|
Python
| 0.00004
|
@@ -2978,16 +2978,19 @@
learn
+ing
_rate=0.
|
a73451272d832ac22e6afcff0bf3fbe416328b65
|
use correct file?
|
cicada/publishers.py
|
cicada/publishers.py
|
import logging
import os
import stat
import subprocess
class PublishArtifact(object):
"""
Publish console ouput
artifct is relative to workspace directory
href/linktext is made for future linking
"""
def __init__(self, artifact, destination, href, linktext):
self.artifact = artifact
self.destination = destination
self.href = href
self.linktext = linktext
def link(self):
return (self.href, self.linktext)
def run(self, workspace, project, jobname, start):
destdir = os.path.join(self.destination, project, jobname, str(start));
if not os.path.exists(destdir):
os.makedirs(destdir)
sourcedir = os.path.join(workspace, self.artifact)
# create empty file if it doesnt exist
# this works for files and directories
if not os.path.exists(sourcedir):
subprocess.call(['touch', '-a', sourcedir])
regular = False
if (stat.S_ISREG(os.stat(sourcedir).st_mode)):
regular = True
destdir = os.path.join(destdir, self.destination)
logging.info('%s is %s file', sourcedir, str(regular))
if regular:
logging.info('Copying file %s to %s', sourcedir, destdir)
subprocess.call(['cp', sourcedir, destdir])
else:
logging.info('Copying directory %s to %s', sourcedir, destdir)
subprocess.call(['cp', '-r', sourcedir, destdir])
# portable? link to latest
latestdir = os.path.join(self.destination, project, jobname, 'latest');
subprocess.call(['rm', '-rf', latestdir])
subprocess.call(['ln', '-s', destdir, latestdir])
return destdir
|
Python
| 0.000001
|
@@ -644,24 +644,96 @@
s(destdir):%0A
+ logging.info(%22Making destination directory of %25s%22, destdir)%0A
@@ -745,32 +745,33 @@
kedirs(destdir)%0A
+%0A
sourcedi
@@ -1162,27 +1162,24 @@
r, self.
-destination
+artifact
)%0A%0A
@@ -1236,18 +1236,16 @@
gular))%0A
-%0A%0A
|
eaba29ee7ea2a02eef180531e7efaf4c3cfebf31
|
Check for subscript like DD1
|
lcapy/latex.py
|
lcapy/latex.py
|
import re
sub_super_pattern = re.compile(r"([_\^]){([\w]+)}")
class Latex(object):
words = ('in', 'out', 'ref', 'rms', 'load', 'source', 'avg',
'mean', 'peak', 'pp', 'min', 'max', 'src',
'cc', 'ee', 'dd', 'ss', 'ih', 'il', 'oh', 'ol')
def __init__(self, string):
self.str = string
def mathrm(self):
"""Place words in sub- or super-scripts inside a mathrm.
For example V_{rms} -> V_{\mathrm{rms}}"""
def foo(match):
fred = match.group(2)
if fred.lower() in self.words:
fred = r'{\mathrm{%s}}' % fred
else:
fred = r'{%s}' % fred
return match.group(1) + fred
return sub_super_pattern.sub(foo, self.str)
def __str__(self):
return self.mathrm()
def latex_str(string):
return Latex(string).__str__()
def format_label(s):
if s == '':
return s
# Pass math-mode labels verbatim.
if s[0] == '$' and s[-1] == '$':
return s
# With leading $ and no trailing $, e.g., v=$V1, try to
# automagically convert to LateX string, otherwise pass
# verbatim. Currently, this only converts words in sub- or
# super- scripts to roman. TODO, handle more cases.
if s[0] == '$' and s[-1] != '$':
return '$' + latex_str(s[1:]) + '$'
# If have + or ^ need to be in math-mode.
if '_' in s or '^' in s or '\\left' in s:
return '$' + latex_str(s) + '$'
return s
|
Python
| 0.000006
|
@@ -51,12 +51,24 @@
)%7B(%5B
-%5Cw%5D+
+a-zA-Z%5D+)(%5B0-9%5D*
)%7D%22)
@@ -536,27 +536,27 @@
-fre
+wor
d = match.gr
@@ -562,16 +562,59 @@
roup(2)%0A
+ suffix = word + match.group(3)%0A
@@ -633,19 +633,19 @@
if
-fre
+wor
d.lower(
@@ -673,28 +673,30 @@
-fred
+suffix
= r'%7B%5Cmathr
@@ -701,28 +701,30 @@
hrm%7B%25s%7D%7D' %25
-fred
+suffix
%0A
@@ -746,20 +746,22 @@
-fred
+suffix
= r'%7B%25s
@@ -765,20 +765,22 @@
%7B%25s%7D' %25
-fred
+suffix
%0A
@@ -812,12 +812,14 @@
) +
-fred
+suffix
%0A%0A
|
9cc013cc0fbff030be386ed3af5f6a826b97ca5f
|
make the module hook more robust
|
lib/spack/spack/hooks/module_file_generation.py
|
lib/spack/spack/hooks/module_file_generation.py
|
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import spack.modules
import spack.modules.common
import llnl.util.tty as tty
try:
enabled = spack.config.get('modules:enable')
except KeyError:
tty.debug('NO MODULE WRITTEN: list of enabled module files is empty')
enabled = []
def _for_each_enabled(spec, method_name):
"""Calls a method for each enabled module"""
for name in enabled:
generator = spack.modules.module_types[name](spec)
try:
getattr(generator, method_name)()
except RuntimeError as e:
msg = 'cannot perform the requested {0} operation on module files'
msg += ' [{1}]'
tty.warn(msg.format(method_name, str(e)))
post_install = lambda spec: _for_each_enabled(spec, 'write')
post_uninstall = lambda spec: _for_each_enabled(spec, 'remove')
|
Python
| 0.000001
|
@@ -191,16 +191,36 @@
R MIT)%0A%0A
+import spack.config%0A
import s
@@ -289,20 +289,107 @@
as tty%0A%0A
-try:
+%0Adef _for_each_enabled(spec, method_name):%0A %22%22%22Calls a method for each enabled module%22%22%22
%0A ena
@@ -434,25 +434,32 @@
e')%0A
-except KeyError:%0A
+ if not enabled:%0A
@@ -536,113 +536,19 @@
-enabled = %5B%5D%0A%0A%0Adef _for_each_enabled(spec, method_name):%0A %22%22%22Calls a method for each enabled module%22%22%22
+ return%0A
%0A
@@ -884,16 +884,20 @@
(e)))%0A%0A%0A
+def
post_ins
@@ -896,39 +896,35 @@
post_install
- = lambda spec:
+(spec):%0A
_for_each_e
@@ -945,16 +945,22 @@
write')%0A
+%0A%0Adef
post_uni
@@ -969,23 +969,19 @@
tall
- = lambda spec:
+(spec):%0A
_fo
|
5b1349c5322c47b10fb74efeecaace6ac5d41346
|
Add logging. (#7)
|
lambda_function.py
|
lambda_function.py
|
import json
import logging
import requests
import uuid
PARTICLE_CLOUD_API_ENDPOINT = 'https://api.particle.io'
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# Main function entrypoint, handles request routing.
def lambda_handler(event, context):
logger.info("Recieved event: {}".format(json.dumps(event)))
# The Smart Home API request namespace.
namespace = event['header']['namespace']
if namespace == 'Alexa.ConnectedHome.Discovery':
return handle_device_discovery(namespace)
if namespace == 'Alexa.ConnectedHome.Control':
if event['header']['name'] == 'TurnOnRequest':
return handle_turn_on_control(namespace, event['payload'])
if event['header']['name'] == 'HealthCheckRequest':
return handle_health_check(namespace, event['payload'])
def handle_device_discovery(namespace):
logger.info('Handling discovery event.')
headers = {
'messageId': str(uuid.uuid4()),
'name': 'DiscoverAppliancesResponse',
'namespace': namespace,
'payloadVersion': '2',
}
payload = {
'discoveredAppliances': [
{
'applianceId': '20003a000747343232363230',
'manufacturerName': 'Particle Industries, Inc.',
'modelName': 'Particle Photon',
'version': 'v1',
'friendlyName': 'gatekeeper',
'friendlyDescription': 'Gatekeeper connected via Particle Cloud',
'isReachable': True,
'actions': [
'turnOn'
],
'additionalApplianceDetails': {}
}
]
}
response = {
'header': headers,
'payload': payload,
}
logger.info("Returning discovery response: {}".format(json.dumps(response)))
return response
def handle_turn_on_control(namespace, payload):
logger.info('Handling control request.')
# The OAuth2 access token for access to the Particle Cloud API.
access_token = payload['accessToken']
# The Particle device ID.
device_id = payload['appliance']['applianceId']
# Call the `prime` function on the device.
url = PARTICLE_CLOUD_API_ENDPOINT + '/v1/devices/{}/prime'.format(device_id)
requests.post(url, headers={
'Authorization': 'Bearer ' + access_token,
})
headers = {
'messageId': str(uuid.uuid4()),
'name': 'TurnOnConfirmation',
'namespace': namespace,
'payloadVersion': '2',
}
response = {
'header': headers,
'payload': {},
}
logger.info("Returning control response: {}".format(json.dumps(response)))
return response
def handle_health_check(namespace):
logger.info('Handling health check request.')
headers = {
'messageId': str(uuid.uuid4()),
'name': 'TurnOnConfirmation',
'namespace': namespace,
'payloadVersion': '2',
}
payload = {
'description': 'Gatekeeper is probably online',
'isHealthy': True,
}
response = {
'header': headers,
'payload': payload,
}
logger.info("Returning health check response: {}".format(json.dumps(response)))
return response
|
Python
| 0
|
@@ -2275,16 +2275,27 @@
_id)%0A
+ response =
request
@@ -2375,16 +2375,93 @@
%7D)%0A%0A
+ logger.info(%22Response from Particle Cloud: %7B%7D%22.format(response.json()))%0A%0A
head
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.