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
|
|---|---|---|---|---|---|---|---|
9fa396ee3a13fd84cc27e692d2c5423250893d62
|
Set maximum select box size to 10.
|
src/abizeitung/views/student.py
|
src/abizeitung/views/student.py
|
# -*- coding: utf-8 -*-
from abizeitung.models import Teacher, StudentSurvey, Student, TeacherSurvey,\
StudentSurveyEntry, TeacherSurveyEntry
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.forms import Select, ValidationError
from django.forms.fields import ChoiceField
from django.forms.models import ModelForm
from django.shortcuts import render
from django.template.context import RequestContext
def validate_student(value):
if value == "-1":
return
if not Student.objects.filter(id=value).exists():
raise ValidationError(u"Ungültige Auswahl!")
def validate_teacher(value):
if value == "-1":
return
if not Teacher.objects.filter(id=value).exists():
raise ValidationError(u"Ungültige Auswahl")
class StudentEditForm(ModelForm):
class Meta:
model = Student
fields = ["test", "picture", "baby_picture"]
def __init__(self, *args, **kwargs):
super(StudentEditForm, self).__init__(*args, **kwargs)
self.instance = kwargs["instance"]
self.fields["test"].widget.attrs["class"] = "form-control"
self.student_choices = [(-1, u"Bitte jemanden auswählen."), ("42", "Test")]
for student in Student.objects.all():
self.student_choices.append((student.pk, student.fullname()))
self.teacher_choices = [(-1, u"Bitte jemanden auswählen.")]
for teacher in Teacher.objects.all():
self.teacher_choices.append((teacher.pk, teacher.fullname()))
kwargs = lambda survey: {
"label" : survey.question,
"widget" : Select(attrs={"class" : "selectpicker",
"data-live-search" : "true"}),
}
self.student_surveys = {}
for survey in StudentSurvey.objects.all():
initial = -1
entries = StudentSurveyEntry.objects.filter(student=self.instance, survey=survey)
if entries.exists():
initial = entries[0].choice.pk
field = ChoiceField(choices=self.student_choices, initial=initial, validators=[validate_student], **kwargs(survey))
name = "student_survey_%s" % survey.id
self.fields[name] = field
self.student_surveys[survey] = name
self.teacher_surveys = {}
for survey in TeacherSurvey.objects.all():
initial = -1
entries = TeacherSurveyEntry.objects.filter(student=self.instance, survey=survey)
if entries.exists():
initial = entries[0].choice.pk
field = ChoiceField(choices=self.teacher_choices, initial=initial, validators=[validate_teacher], **kwargs(survey))
name = "teacher_survey_%s" % survey.id
self.fields[name] = field
self.teacher_surveys[survey] = name
def clean(self):
super(StudentEditForm, self).clean()
self.survey2student = {}
for survey, name in self.student_surveys.items():
pk = self.cleaned_data.get(name, "-1")
if pk != "-1":
self.survey2student[survey] = Student.objects.get(pk=self.cleaned_data[name])
self.survey2teacher = {}
for survey, name in self.teacher_surveys.items():
pk = self.cleaned_data.get(name, "-1")
if pk != "-1":
self.survey2teacher[survey] = Teacher.objects.get(pk=self.cleaned_data[name])
return self.cleaned_data
def save_surveys(self):
used = set()
for entry in StudentSurveyEntry.objects.filter(student=self.instance):
if entry.survey in self.survey2student:
entry.choice = self.survey2student[entry.survey]
entry.save()
else:
entry.delete()
used.add(entry.survey)
for survey, choice in self.survey2student.items():
if not survey in used:
entry = StudentSurveyEntry()
entry.survey = survey
entry.student = self.instance
entry.choice = choice
entry.save()
used = set()
for entry in TeacherSurveyEntry.objects.filter(student=self.instance):
if entry.survey in self.survey2teacher:
entry.choice = self.survey2teacher[entry.survey]
entry.save()
else:
entry.delete()
used.add(entry.survey)
for survey, choice in self.survey2teacher.items():
if not survey in used:
entry = TeacherSurveyEntry()
entry.survey = survey
entry.student = self.instance
entry.choice = choice
entry.save()
@login_required
def edit(request):
context = {}
form = StudentEditForm(request.POST or None, files=request.FILES or None,
instance=Student.objects.get(user=request.user))
if request.method == "POST":
if form.is_valid():
form.save()
form.save_surveys()
else:
messages.error(request, "Konnte Daten nicht speichern!")
context["form"] = form
context["student"] = Student.objects.get(user=request.user)
return render(request, "student/edit.html", context, context_instance=RequestContext(request))
|
Python
| 0
|
@@ -1777,16 +1777,73 @@
: %22true%22
+,%0A %22data-size%22 : %2210%22
%7D),%0A
|
b83576644d5aacd4ab841a03ff228796ff1b1b67
|
change name
|
coolTestly/__openerp__.py
|
coolTestly/__openerp__.py
|
{
"name": "testly",
"author": "Ju",
"version": "1.0",
"category": "Generic Modules/Sales & Purchases",
"depends": [
"purchase",
],
"demo": [],
"data": [
],
"installable": True
}
|
Python
| 0.000147
|
@@ -8,17 +8,21 @@
name%22: %22
-t
+coolT
estly%22,%0A
@@ -222,8 +222,9 @@
: True%0A%7D
+%0A
|
f844b95e7cb034985f1d284a41789d1e427b0f74
|
Update env_detect.py
|
device/src/env_detect.py
|
device/src/env_detect.py
|
#!/usr/bin/env python
#Weather station.
#detect environment information from several sensors:
#water leverl, air humity, raining, air temperature, light sensitivity.
#Air temperature&humity sensor: DHT11.
#Add dht.py in micropython/stmhal/modules, refer to esp8266
#Compile the DHT in firmware, then use DHT lib in application.
#Raining, same to soil moisture.
#Raining ? DO value: 0
from pyb import Pin
p_in = Pin('Y12', Pin.IN, Pin.PULL_UP)
p_in.value
adc = pyb.ADC(Pin('Y11')) # create an analog object from a pin
adc = pyb.ADC(pyb.Pin.board.Y11)
val = adc.read() # read an analog value
#-----------------------------------------#
#Light intensity sensor(GY-30) <--> I2C(1)
#SDA <--> X10
#SCL <--> X9
#VCC
#GND
#ADO(ADDR/address ?)
from pyb import I2C
i2c = I2C(1) # create on bus 1
i2c = I2C(1, I2C.MASTER) # create and init as a master
i2c.init(I2C.MASTER, baudrate=20000) # init as a master
i2c.init(I2C.SLAVE, addr=0x23) # init as a slave with given address(GY-30 address is 0x23)
i2c.deinit() # turn off the peripheral
i2c.init(I2C.MASTER)
|
Python
| 0.000001
|
@@ -1135,8 +1135,130 @@
MASTER)%0A
+i2c.send('123', 0x23) # send 3 bytes to slave with address 0x23%0Ai2c.send(b'456', addr=0x23) # keyword for address%0A
|
ce948b49fbd4f3e8012b6d351bbf53db32172474
|
fix repeated import of CascadeRPNHead (#8578)
|
mmdet/models/dense_heads/__init__.py
|
mmdet/models/dense_heads/__init__.py
|
# Copyright (c) OpenMMLab. All rights reserved.
from .anchor_free_head import AnchorFreeHead
from .anchor_head import AnchorHead
from .atss_head import ATSSHead
from .autoassign_head import AutoAssignHead
from .cascade_rpn_head import CascadeRPNHead, StageCascadeRPNHead
from .centernet_head import CenterNetHead
from .centripetal_head import CentripetalHead
from .corner_head import CornerHead
from .ddod_head import DDODHead
from .deformable_detr_head import DeformableDETRHead
from .detr_head import DETRHead
from .embedding_rpn_head import EmbeddingRPNHead
from .fcos_head import FCOSHead
from .fovea_head import FoveaHead
from .free_anchor_retina_head import FreeAnchorRetinaHead
from .fsaf_head import FSAFHead
from .ga_retina_head import GARetinaHead
from .ga_rpn_head import GARPNHead
from .gfl_head import GFLHead
from .guided_anchor_head import FeatureAdaption, GuidedAnchorHead
from .lad_head import LADHead
from .ld_head import LDHead
from .mask2former_head import Mask2FormerHead
from .maskformer_head import MaskFormerHead
from .nasfcos_head import NASFCOSHead
from .paa_head import PAAHead
from .pisa_retinanet_head import PISARetinaHead
from .pisa_ssd_head import PISASSDHead
from .reppoints_head import RepPointsHead
from .retina_head import RetinaHead
from .retina_sepbn_head import RetinaSepBNHead
from .rpn_head import RPNHead
from .sabl_retina_head import SABLRetinaHead
from .solo_head import DecoupledSOLOHead, DecoupledSOLOLightHead, SOLOHead
from .solov2_head import SOLOV2Head
from .ssd_head import SSDHead
from .tood_head import TOODHead
from .vfnet_head import VFNetHead
from .yolact_head import YOLACTHead, YOLACTProtonet, YOLACTSegmHead
from .yolo_head import YOLOV3Head
from .yolof_head import YOLOFHead
from .yolox_head import YOLOXHead
__all__ = [
'AnchorFreeHead', 'AnchorHead', 'GuidedAnchorHead', 'FeatureAdaption',
'RPNHead', 'GARPNHead', 'RetinaHead', 'RetinaSepBNHead', 'GARetinaHead',
'SSDHead', 'FCOSHead', 'RepPointsHead', 'FoveaHead',
'FreeAnchorRetinaHead', 'ATSSHead', 'FSAFHead', 'NASFCOSHead',
'PISARetinaHead', 'PISASSDHead', 'GFLHead', 'CornerHead', 'YOLACTHead',
'YOLACTSegmHead', 'YOLACTProtonet', 'YOLOV3Head', 'PAAHead',
'SABLRetinaHead', 'CentripetalHead', 'VFNetHead', 'StageCascadeRPNHead',
'CascadeRPNHead', 'EmbeddingRPNHead', 'LDHead', 'CascadeRPNHead',
'AutoAssignHead', 'DETRHead', 'YOLOFHead', 'DeformableDETRHead',
'SOLOHead', 'DecoupledSOLOHead', 'CenterNetHead', 'YOLOXHead',
'DecoupledSOLOLightHead', 'LADHead', 'TOODHead', 'MaskFormerHead',
'Mask2FormerHead', 'SOLOV2Head', 'DDODHead'
]
|
Python
| 0
|
@@ -2324,30 +2324,8 @@
ad',
- 'CascadeRPNHead',%0A
'Au
@@ -2338,16 +2338,20 @@
gnHead',
+%0A
'DETRHe
@@ -2389,20 +2389,16 @@
TRHead',
-%0A
'SOLOHe
@@ -2397,24 +2397,28 @@
'SOLOHead',
+%0A
'DecoupledS
|
5e7e60f8afb3ddeeec2714a9d11dd30a6ea3e52f
|
Add new calc_total_error tests
|
photutils/utils/tests/test_prepare_data.py
|
photutils/utils/tests/test_prepare_data.py
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
from numpy.testing import assert_allclose
from astropy.tests.helper import pytest
from .. import calc_total_error
SHAPE = (5, 5)
DATAVAL = 2.
DATA = np.ones(SHAPE) * DATAVAL
MASK = np.zeros_like(DATA, dtype=bool)
MASK[2, 2] = True
BKG_ERROR = np.ones(SHAPE)
EFFGAIN = np.ones(SHAPE) * DATAVAL
BACKGROUND = np.ones(SHAPE)
WRONG_SHAPE = np.ones((2, 2))
class TestCalculateTotalError(object):
def test_error_shape(self):
with pytest.raises(ValueError):
calc_total_error(DATA, WRONG_SHAPE, EFFGAIN)
def test_gain_shape(self):
with pytest.raises(ValueError):
calc_total_error(DATA, BKG_ERROR, WRONG_SHAPE)
@pytest.mark.parametrize('effective_gain', (0, -1))
def test_gain_le_zero(self, effective_gain):
with pytest.raises(ValueError):
calc_total_error(DATA, BKG_ERROR, effective_gain)
def test_gain_scalar(self):
error_tot = calc_total_error(DATA, BKG_ERROR, 2.)
assert_allclose(error_tot, np.sqrt(2.) * BKG_ERROR)
def test_gain_array(self):
error_tot = calc_total_error(DATA, BKG_ERROR, EFFGAIN)
assert_allclose(error_tot, np.sqrt(2.) * BKG_ERROR)
|
Python
| 0.000002
|
@@ -267,16 +267,42 @@
pytest%0A
+import astropy.units as u%0A
from ..
@@ -1358,28 +1358,1178 @@
t, np.sqrt(2.) * BKG_ERROR)%0A
+%0A def test_units(self):%0A units = u.electron / u.s%0A error_tot1 = calc_total_error(DATA * units, BKG_ERROR * units,%0A EFFGAIN * u.s)%0A assert error_tot1.unit == units%0A error_tot2 = calc_total_error(DATA, BKG_ERROR, EFFGAIN)%0A assert_allclose(error_tot1.value, error_tot2)%0A%0A def test_error_units(self):%0A units = u.electron / u.s%0A with pytest.raises(ValueError):%0A calc_total_error(DATA * units, BKG_ERROR * u.electron,%0A EFFGAIN * u.s)%0A%0A def test_effgain_units(self):%0A units = u.electron / u.s%0A with pytest.raises(u.UnitsError):%0A calc_total_error(DATA * units, BKG_ERROR * units, EFFGAIN * u.km)%0A%0A def test_missing_bkgerror_units(self):%0A units = u.electron / u.s%0A with pytest.raises(ValueError):%0A calc_total_error(DATA * units, BKG_ERROR, EFFGAIN * u.s)%0A%0A def test_missing_effgain_units(self):%0A units = u.electron / u.s%0A with pytest.raises(ValueError):%0A calc_total_error(DATA * units, BKG_ERROR * units,%0A EFFGAIN)%0A%0A
|
5dd6fa526eac5632f75d543342a7a5a45b866716
|
Update plantcv/plantcv/visualize/obj_size_ecdf.py
|
plantcv/plantcv/visualize/obj_size_ecdf.py
|
plantcv/plantcv/visualize/obj_size_ecdf.py
|
# Plot Empirical Cumulative Distribution Function for Object Size
import os
import cv2
import pandas as pd
from plantcv.plantcv import params
from plantcv.plantcv._debug import _debug
from statsmodels.distributions.empirical_distribution import ECDF
from plotnine import ggplot, aes, geom_point, labels, \
scale_color_manual, scale_x_log10
def obj_size_ecdf(mask, title=None):
""" Plot empirical cumulative distribution for object size based on binary
mask
Inputs:
mask = binary mask
title = a custom title for the plot (default=None)
Returns:
fig_ecdf = empirical cumulative distribution function plot
:param mask: numpy.ndarray
:param title: str
:return fig_ecdf: plotnine.ggplot.ggplot
"""
objects, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[-2:]
areas = [cv2.contourArea(cnt) for cnt in objects]
ecdf = ECDF(areas, side='right')
ecdf_df = pd.DataFrame({'object area': ecdf.x, 'cumulative probability': ecdf.y})
# create ecdf plot and apply log-scale for x-axis (areas)
fig_ecdf = (ggplot(data=ecdf_df, mapping=aes(x='object area', y='cumulative probability'))
+ geom_point(size=.1)
+ scale_x_log10())
if title is not None:
fig_ecdf = fig_ecdf + labels.ggtitle(title)
# Plot or print the ecdf
_debug(visual=fig_ecdf,
filename=os.path.join(params.debug_outdir, str(params.device) + '_area_ecdf.png'))
return fig_ecdf
|
Python
| 0
|
@@ -301,34 +301,8 @@
els,
- %5C%0A scale_color_manual,
sca
|
77eefbefcdc5c04d194924e11fa491a0c4c91c14
|
convert print statement to logger call
|
geopy/geocoders/bing.py
|
geopy/geocoders/bing.py
|
import xml.dom.minidom
from urllib import urlencode
from urllib2 import urlopen
from geopy.geocoders.base import Geocoder
class Bing(Geocoder):
"""Geocoder using the Bing Maps API."""
def __init__(self, api_key, format_string='%s', output_format='xml'):
"""Initialize a customized Bing geocoder with location-specific
address information and your Bing Maps API key.
``api_key`` should be a valid Bing Maps API key.
``format_string`` is a string containing '%s' where the string to
geocode should be interpolated before querying the geocoder.
For example: '%s, Mountain View, CA'. The default is just '%s'.
``output_format`` can currently only be 'xml'.
"""
self.api_key = api_key
self.format_string = format_string
self.output_format = output_format.lower()
self.url = "http://dev.virtualearth.net/REST/v1/Locations?%s"
def geocode(self, string, exactly_one=True):
params = {'addressLine': self.format_string % string,
'o': self.output_format,
'key': self.api_key
}
url = self.url % urlencode(params)
return self.geocode_url(url, exactly_one)
def geocode_url(self, url, exactly_one=True):
print "Fetching %s..." % url
page = urlopen(url)
parse = getattr(self, 'parse_' + self.output_format)
return parse(page, exactly_one)
def parse_xml(self, page, exactly_one=True):
"""Parse a location name, latitude, and longitude from an XML response.
"""
if not isinstance(page, basestring):
page = self._decode_page(page)
doc = xml.dom.minidom.parseString(page)
resources = doc.getElementsByTagName('Resources')
if exactly_one and len(resources) != 1:
raise ValueError("Didn't find exactly one resource! " \
"(Found %d.)" % len(resources))
def parse_resource(resource):
strip = ", \n"
address = self._get_first_text(resource, 'AddressLine', strip)
city = self._get_first_text(resource, 'Locality', strip)
state = self._get_first_text(resource, 'AdminDistrict', strip)
zip = self._get_first_text(resource, 'PostalCode', strip)
country = self._get_first_text(resource, 'CountryRegion', strip)
city_state = self._join_filter(", ", [city, state])
place = self._join_filter(" ", [city_state, zip])
location = self._join_filter(", ", [address, place, country])
latitude = self._get_first_text(resource, 'Latitude') or None
latitude = latitude and float(latitude)
longitude = self._get_first_text(resource, 'Longitude') or None
longitude = longitude and float(longitude)
return (location, (latitude, longitude))
if exactly_one:
return parse_resource(resources[0])
else:
return (parse_resource(resource) for resource in resources)
|
Python
| 0.999999
|
@@ -115,16 +115,46 @@
Geocoder
+%0Afrom geopy.util import logger
%0A%0Aclass
@@ -1322,14 +1322,21 @@
-print
+logger.debug(
%22Fet
@@ -1353,16 +1353,17 @@
.%22 %25 url
+)
%0A
|
ddf52f0a7c3ed2d276c32c9b60242449ce8bf272
|
convert print statement to logger call
|
geopy/geocoders/bing.py
|
geopy/geocoders/bing.py
|
import xml.dom.minidom
from urllib import urlencode
from urllib2 import urlopen
from geopy.geocoders.base import Geocoder
class Bing(Geocoder):
"""Geocoder using the Bing Maps API."""
def __init__(self, api_key, format_string='%s', output_format='xml'):
"""Initialize a customized Bing geocoder with location-specific
address information and your Bing Maps API key.
``api_key`` should be a valid Bing Maps API key.
``format_string`` is a string containing '%s' where the string to
geocode should be interpolated before querying the geocoder.
For example: '%s, Mountain View, CA'. The default is just '%s'.
``output_format`` can currently only be 'xml'.
"""
self.api_key = api_key
self.format_string = format_string
self.output_format = output_format.lower()
self.url = "http://dev.virtualearth.net/REST/v1/Locations?%s"
def geocode(self, string, exactly_one=True):
params = {'addressLine': self.format_string % string,
'o': self.output_format,
'key': self.api_key
}
url = self.url % urlencode(params)
return self.geocode_url(url, exactly_one)
def geocode_url(self, url, exactly_one=True):
print "Fetching %s..." % url
page = urlopen(url)
parse = getattr(self, 'parse_' + self.output_format)
return parse(page, exactly_one)
def parse_xml(self, page, exactly_one=True):
"""Parse a location name, latitude, and longitude from an XML response.
"""
if not isinstance(page, basestring):
page = self._decode_page(page)
doc = xml.dom.minidom.parseString(page)
resources = doc.getElementsByTagName('Resources')
if exactly_one and len(resources) != 1:
raise ValueError("Didn't find exactly one resource! " \
"(Found %d.)" % len(resources))
def parse_resource(resource):
strip = ", \n"
address = self._get_first_text(resource, 'AddressLine', strip)
city = self._get_first_text(resource, 'Locality', strip)
state = self._get_first_text(resource, 'AdminDistrict', strip)
zip = self._get_first_text(resource, 'PostalCode', strip)
country = self._get_first_text(resource, 'CountryRegion', strip)
city_state = self._join_filter(", ", [city, state])
place = self._join_filter(" ", [city_state, zip])
location = self._join_filter(", ", [address, place, country])
latitude = self._get_first_text(resource, 'Latitude') or None
latitude = latitude and float(latitude)
longitude = self._get_first_text(resource, 'Longitude') or None
longitude = longitude and float(longitude)
return (location, (latitude, longitude))
if exactly_one:
return parse_resource(resources[0])
else:
return (parse_resource(resource) for resource in resources)
|
Python
| 0.999999
|
@@ -115,16 +115,46 @@
Geocoder
+%0Afrom geopy.util import logger
%0A%0Aclass
@@ -1322,14 +1322,21 @@
-print
+logger.debug(
%22Fet
@@ -1353,16 +1353,17 @@
.%22 %25 url
+)
%0A
|
22fdc870e6807a946f3e01b3c08b2ea5552c7555
|
add end point for chamber member list
|
congress/members.py
|
congress/members.py
|
from .client import Client
from .utils import CURRENT_CONGRESS, check_chamber
class MembersClient(Client):
def get(self, member_id):
"Takes a bioguide_id, returns a legislator"
path = "members/{0}.json".format(member_id)
return self.fetch(path)
def filter(self, chamber, congress=CURRENT_CONGRESS, **kwargs):
"""
Takes a chamber and Congress,
OR state and district, returning a list of members
"""
check_chamber(chamber)
kwargs.update(chamber=chamber, congress=congress)
if 'state' in kwargs and 'district' in kwargs:
path = ("members/{chamber}/{state}/{district}/"
"current.json").format(**kwargs)
elif 'state' in kwargs:
path = ("members/{chamber}/{state}/"
"current.json").format(**kwargs)
else:
path = ("{congress}/{chamber}/"
"members.json").format(**kwargs)
return self.fetch(path, parse=lambda r: r['results'])
def bills(self, member_id, type='introduced'):
"Same as BillsClient.by_member"
path = "members/{0}/bills/{1}.json".format(member_id, type)
return self.fetch(path)
def new(self, **kwargs):
"Returns a list of new members"
path = "members/new.json"
return self.fetch(path)
def departing(self, chamber, congress=CURRENT_CONGRESS):
"Takes a chamber and congress and returns a list of departing members"
check_chamber(chamber)
path = "{0}/{1}/members/leaving.json".format(congress, chamber)
return self.fetch(path)
def compare(self, first, second, chamber, type='votes', congress=CURRENT_CONGRESS):
"""
See how often two members voted together in a given Congress.
Takes two member IDs, a chamber and a Congress number.
"""
check_chamber(chamber)
path = "members/{first}/{type}/{second}/{congress}/{chamber}.json"
path = path.format(first=first, second=second, type=type,
congress=congress, chamber=chamber)
return self.fetch(path)
def party(self):
"Get state party counts for the current Congress"
path = "states/members/party.json"
return self.fetch(path, parse=lambda r: r['results'])
|
Python
| 0
|
@@ -103,16 +103,257 @@
ient):%0A%0A
+ def list_chamber(self, chamber,congress=CURRENT_CONGRESS):%0A %22Takes a bioguide_id, returns a legislator%22%0A path = %22%7Bcongress%7D/%7Bchamber%7D/members.json%22.format(congress=congress,chamber=chamber)%0A return self.fetch(path)%0A%0A
def
|
6c05bf7400340d2797666e853dc813c5ff029055
|
Update settings for Heroku
|
connect/settings.py
|
connect/settings.py
|
import os
from django.utils.translation import ugettext_lazy as _
"""
Django settings for connect project.
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('CONNECT_SECRET_KEY',
'jj4ie+#b4h=ovjrma7ad*0vhuu8j4fi@8beksc-f+pa_co')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('CONNECT_DEBUG', 'on') == 'on'
TEMPLATE_DEBUG = DEBUG
# Allow all host headers
ALLOWED_HOSTS = os.environ.get('CONNECT_ALLOWED_HOSTS', 'localhost').split(',')
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Application definition
ADMINS = (
('Nicole Harris', 'n.harris@kabucreative.com.au'),
)
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.flatpages',
'django.contrib.humanize',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django_behave',
'django_gravatar',
'endless_pagination',
'parsley',
'django_boost',
'connect',
'connect_config',
'accounts',
'moderation',
'discover',
'bdd'
)
if DEBUG:
INSTALLED_APPS += (
'debug_toolbar',
'django_extensions',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.sites.middleware.CurrentSiteMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'connect.urls'
WSGI_APPLICATION = 'connect.wsgi.application'
# Testing
TEST_RUNNER = 'django_behave.runner.DjangoBehaveTestSuiteRunner'
# Pagination
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
)
ENDLESS_PAGINATION_PREVIOUS_LABEL = '<i class="fa fa-chevron-left"></i>'
ENDLESS_PAGINATION_NEXT_LABEL = '<i class="fa fa-chevron-right"></i>'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
# Parse database configuration from $DATABASE_URL, if it is set
if 'DATABASE_URL' in os.environ:
import dj_database_url
DATABASES = {'default': dj_database_url.config()}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ['CONNECT_DB_NAME'],
'USER': os.environ['CONNECT_DB_USER'],
'PASSWORD': os.environ['CONNECT_DB_PASSWORD'],
'HOST': os.environ['CONNECT_DB_HOST'],
'PORT': os.environ['CONNECT_DB_PORT'],
},
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
USE_I18N = True
USE_L10N = True
USE_TZ = True
TIME_ZONE = 'Australia/Melbourne'
LANGUAGE_CODE = 'en'
LANGUAGES = (
('en', _('English')),
)
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
# Static files (CSS, JavaScript, Images)
STATIC_ROOT = 'connect/static/'
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
# os.path.join(BASE_DIR, 'static'),
)
# Media files (user uploaded)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
# Gravatar Settings
GRAVATAR_DEFAULT_IMAGE = 'retro'
# Site Settings
SITE_ID = 1
SITE_URL = 'http://localhost:8000' #TODO: change for production
# Email
# Set 'from' email address for system emails
if DEBUG:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
else:
EMAIL_HOST = os.environ['CONNECT_EMAIL_HOST']
EMAIL_PORT = os.environ['CONNECT_EMAIL_PORT']
EMAIL_HOST_USER = os.environ['CONNECT_EMAIL_HOST_USER']
EMAIL_HOST_PASSWORD = os.environ['CONNECT_EMAIL_HOST_PASSWORD']
EMAIL_USE_TLS = os.environ['CONNECT_EMAIL_USE_TLS']
# Auth Settings
AUTH_USER_MODEL = 'accounts.CustomUser'
LOGIN_REDIRECT_URL = '/'
|
Python
| 0
|
@@ -539,17 +539,18 @@
BUG', 'o
-n
+ff
') == 'o
@@ -683,16 +683,17 @@
t(',')%0A%0A
+%0A
# Honor
@@ -4216,17 +4216,20 @@
'%0Aelse:%0A
-%09
+
EMAIL_HO
@@ -4270,56 +4270,12 @@
T'%5D%0A
-%09EMAIL_PORT = os.environ%5B'CONNECT_EMAIL_PORT'%5D%0A%09
+
EMAI
@@ -4326,17 +4326,20 @@
_USER'%5D%0A
-%09
+
EMAIL_HO
@@ -4398,45 +4398,33 @@
D'%5D%0A
-%09
+
EMAIL_
-USE_TLS = os.environ%5B'CONNECT_
+PORT = 587%0A
EMAI
@@ -4432,18 +4432,23 @@
_USE_TLS
-'%5D
+ = True
%0A%0A%0A# Aut
|
e08129c1c3f3df26a87beb04b54f388a8be1de55
|
Remove page outline when exporting ReST
|
contrib/wiki2rst.py
|
contrib/wiki2rst.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import codecs
import os.path
import re
import sys
from cStringIO import StringIO
from pkg_resources import resource_listdir, resource_string
from trac.loader import load_components
from trac.test import EnvironmentStub, Mock, MockPerm
from trac.util.text import printerr, printout
from trac.web.chrome import web_context
from trac.web.href import Href
from trac.wiki.formatter import format_to_html
from trac.wiki.model import WikiPage
try:
import html2rest
except ImportError:
printerr("The html2rest package must be installed.")
sys.exit(1)
class Parser(html2rest.Parser):
def __init__(self, writer=sys.stdout, encoding='utf8', relroot=None,
relpath=None):
html2rest.Parser.__init__(self, writer, encoding, relroot, relpath)
self.links = {}
def end_a(self):
if '#pending' in self.hrefs:
href = self.hrefs['#pending']
label = self.hrefs[href]
key = label.lower()
if key not in self.links:
self.links[key] = (label, href)
elif href != self.links[key][1]:
alt = label
while True:
alt += '*'
if alt not in self.links:
break
continue
self.data(alt[len(label):])
self.hrefs[href] = alt
self.links[alt] = (alt, href)
self.data('`_')
del self.hrefs['#pending']
def end_body(self):
self.end_p()
for label, href in self.links.itervalues():
if href[0] != '#':
self.writeline('.. _%s: %s' % (label, href))
self.end_p()
def wiki2rest(env, context, wiki):
text = re.sub('\r?\n', '\n', wiki.text)
text = re.sub(r'\[\[TracGuideToc\]\]\r?\n?', '', text)
html = format_to_html(env, context, text)
html = html.replace(u'<span class="icon">\u200b</span>', '')
html = re.sub(r'<em>\s*([^<]*?)\s*</em>', r'<em>\1</em>', html)
html = '<html><body>%s</body></html>' % html
writer = StringIO()
parser = Parser(writer, 'utf-8', None, None)
parser.feed(html)
parser.close()
rst = writer.getvalue().strip('\n')
rst = re.sub('\n{4,}', '\n\n\n', rst)
# sort links
rst = re.sub(r'(?:\n\.\. _[^\n]*)+\Z',
lambda m: '\n'.join(sorted(m.group(0).split('\n'),
key=lambda v: v.lower())),
rst)
if any(ord(c) > 0x7f for c in rst):
# Trac detects utf-8 using BOM
rst = '%s.. charset=utf-8\n\n%s' % (codecs.BOM_UTF8, rst)
return rst + '\n'
def main():
names = sorted(name for name in resource_listdir('trac.wiki',
'default-pages')
if not name.startswith('.'))
env = EnvironmentStub()
load_components(env)
with env.db_transaction:
for name in names:
wiki = WikiPage(env, name)
wiki.text = resource_string('trac.wiki', 'default-pages/' +
name).decode('utf-8')
if wiki.text:
wiki.save('trac', '')
else:
printout('%s: Skipped empty page' % name)
req = Mock(href=Href('/'), abs_href=Href('http://trac.edgewall.org/'),
perm=MockPerm(), chrome={})
for name in sys.argv[1:]:
name = os.path.basename(name)
wiki = WikiPage(env, name)
if not wiki.exists:
continue
context = web_context(req, wiki.resource, absurls=True)
rst = wiki2rest(env, context, wiki)
sys.stdout.write(rst)
if __name__ == '__main__':
main()
|
Python
| 0.000002
|
@@ -1870,32 +1870,100 @@
%5Cn?', '', text)%0A
+ text = re.sub(r'%5C%5B%5C%5BPageOutline%5C(%5B%5E%5C)%5D*%5C)%5C%5D%5C%5D%5Cr?%5Cn?', '', text)%0A
html = forma
|
21c8b67d1e8fb2f343a248d89999148ac44546c4
|
Remove unreachable return statement
|
gnocchi/storage/ceph.py
|
gnocchi/storage/ceph.py
|
# -*- encoding: utf-8 -*-
#
# Copyright © 2014 eNovance
#
# Authors: Mehdi Abaakouk <mehdi.abaakouk@enovance.com>
#
# 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 contextlib
import ctypes
import errno
import time
from oslo_config import cfg
from oslo_utils import importutils
from gnocchi import storage
from gnocchi.storage import _carbonara
# NOTE(sileht): rados module is not available on pypi
rados = importutils.try_import('rados')
OPTS = [
cfg.StrOpt('ceph_pool',
default='gnocchi',
help='Ceph pool name to use.'),
cfg.StrOpt('ceph_username',
default=None,
help='Ceph username (ie: client.admin).'),
cfg.StrOpt('ceph_keyring',
default=None,
help='Ceph keyring path.'),
cfg.StrOpt('ceph_conffile',
default='/etc/ceph/ceph.conf',
help='Ceph configuration file.'),
]
class CephStorage(_carbonara.CarbonaraBasedStorage):
def __init__(self, conf):
super(CephStorage, self).__init__(conf)
self.pool = conf.ceph_pool
options = {}
if conf.ceph_keyring:
options['keyring'] = conf.ceph_keyring
# NOTE(sileht): librados handles reconnection itself,
# by default if a call timeout (30sec), it raises
# a rados.Timeout exception, and librados
# still continues to reconnect on the next call
self.rados = rados.Rados(conffile=conf.ceph_conffile,
rados_id=conf.ceph_username,
conf=options)
self.rados.connect()
@contextlib.contextmanager
def _lock(self, metric, lock_name):
# NOTE(sileht): current stable python binding (0.80.X) doesn't
# have rados_lock_XXX method, so do ourself the call with ctypes
#
# https://github.com/ceph/ceph/commit/f5bf75fa4109b6449a88c7ffdce343cf4691a4f9
# When ^^ is released, we can drop this code and directly use:
# - ctx.lock_exclusive(name, 'lock', 'gnocchi')
# - ctx.unlock(name, 'lock', 'gnocchi')
name = self._get_object_name(metric, lock_name)
with self._get_ioctx() as ctx:
while True:
ret = rados.run_in_thread(
ctx.librados.rados_lock_exclusive,
(ctx.io, ctypes.c_char_p(name.encode('ascii')),
ctypes.c_char_p(b"lock"),
ctypes.c_char_p(b"gnocchi"),
ctypes.c_char_p(b""), None, ctypes.c_int8(0)))
if ret in [errno.EBUSY, errno.EEXIST]:
time.sleep(0.1)
elif ret < 0:
rados.make_ex(ret, "Error while getting lock of %s" % name)
else:
break
try:
yield
finally:
ret = rados.run_in_thread(
ctx.librados.rados_unlock,
(ctx.io, ctypes.c_char_p(name.encode('ascii')),
ctypes.c_char_p(b"lock"), ctypes.c_char_p(b"gnocchi")))
if ret < 0:
rados.make_ex(ret,
"Error while releasing lock of %s" % name)
def _get_ioctx(self):
return self.rados.open_ioctx(self.pool)
@staticmethod
def _get_object_name(metric, lock_name):
return str("gnocchi_%s_%s" % (metric.id, lock_name))
@staticmethod
def _object_exists(ioctx, name):
try:
size, mtime = ioctx.stat(name)
# NOTE(sileht): the object have been created by
# the lock code
return size > 0
except rados.ObjectNotFound:
return False
return True
def _create_metric_container(self, metric):
name = self._get_object_name(metric, 'container')
with self._get_ioctx() as ioctx:
if self._object_exists(ioctx, name):
raise storage.MetricAlreadyExists(metric)
else:
ioctx.write_full(name, "metric created")
def _store_metric_measures(self, metric, aggregation, data):
name = self._get_object_name(metric, aggregation)
with self._get_ioctx() as ioctx:
ioctx.write_full(name, data)
def delete_metric(self, metric):
with self._get_ioctx() as ioctx:
name = self._get_object_name(metric, 'container')
try:
ioctx.remove_object(name)
except rados.ObjectNotFound:
raise storage.MetricDoesNotExist(metric)
for aggregation in metric.archive_policy.aggregation_methods:
name = self._get_object_name(metric, aggregation)
try:
ioctx.remove_object(name)
except rados.ObjectNotFound:
pass
def _get_measures(self, metric, aggregation):
try:
with self._get_ioctx() as ioctx:
name = self._get_object_name(metric, aggregation)
offset = 0
content = b''
while True:
data = ioctx.read(name, offset=offset)
if not data:
break
content += data
offset += len(content)
if len(content) == 0:
# NOTE(sileht: the object have been created by
# the lock code
raise rados.ObjectNotFound
else:
return content
except rados.ObjectNotFound:
name = self._get_object_name(metric, 'container')
with self._get_ioctx() as ioctx:
if self._object_exists(ioctx, name):
raise storage.AggregationDoesNotExist(metric, aggregation)
else:
raise storage.MetricDoesNotExist(metric)
|
Python
| 0.999998
|
@@ -4225,28 +4225,8 @@
alse
-%0A return True
%0A%0A
|
e56df10f3e40b9287735f1295a0ed72e1525896f
|
change json to md RasaHQ/roadmap#280
|
examples/restaurantbot/bot.py
|
examples/restaurantbot/bot.py
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import logging
import warnings
from policy import RestaurantPolicy
from rasa_core import utils
from rasa_core.agent import Agent
from rasa_core.policies.memoization import MemoizationPolicy
logger = logging.getLogger(__name__)
class RestaurantAPI(object):
def search(self, info):
return "papi's pizza place"
def train_dialogue(domain_file="restaurant_domain.yml",
model_path="models/dialogue",
training_data_file="data/babi_stories.md"):
agent = Agent(domain_file,
policies=[MemoizationPolicy(max_history=3),
RestaurantPolicy()])
training_data = agent.load_data(training_data_file)
agent.train(
training_data,
epochs=400,
batch_size=100,
validation_split=0.2
)
agent.persist(model_path)
return agent
def train_nlu():
from rasa_nlu.training_data import load_data
from rasa_nlu import config
from rasa_nlu.model import Trainer
training_data = load_data('data/nlu_data.json')
trainer = Trainer(config.load("nlu_model_config.yml"))
trainer.train(training_data)
model_directory = trainer.persist('models/nlu/',
fixed_model_name="current")
return model_directory
if __name__ == '__main__':
utils.configure_colored_logging(loglevel="INFO")
parser = argparse.ArgumentParser(
description='starts the bot')
parser.add_argument(
'task',
choices=["train-nlu", "train-dialogue", "run"],
help="what the bot should do - e.g. run or train?")
task = parser.parse_args().task
# decide what to do based on first parameter of the script
if task == "train-nlu":
train_nlu()
elif task == "train-dialogue":
train_dialogue()
|
Python
| 0
|
@@ -1224,12 +1224,10 @@
ata.
-json
+md
')%0A
|
40316f4a2f1e973ba98a50592a54f21a2d5ac18e
|
Add the exceptions module to describe exceptions from external target
|
rapidtest/executors/exceptions.py
|
rapidtest/executors/exceptions.py
|
class ExternalExecutionTargetError(Exception):
pass
|
Python
| 0
|
@@ -1,56 +1,920 @@
-class ExternalExecutionTargetError(Exception):%0A pass
+from ..utils import Dictable%0A%0AMSG_CANNOT_GUESS_METHOD = '''cannot find the target method. You may specify operations as %5C%0Aarguments to Case if there are multiple methods to be called, or prepend all names of private %5C%0Amethods with underscores.'''%0A%0A%0Aclass ExternalError(Exception):%0A pass%0A%0Aclass ExternalEnvironmentError(ExternalError):%0A pass%0A%0Aclass ExternalRuntimeError(ExternalError):%0A pass%0A%0A%0Aclass ExternalException(Dictable):%0A def __init__(self, name, message=None, stack_trace=None, runtime=False):%0A self.name = name%0A self.message = message or ''%0A self.stack_trace = (stack_trace or '').rstrip()%0A self.runtime = runtime%0A%0A def to_exception(self):%0A Exc = type(self.name, (Exception,), %7B%7D)%0A msg = '%7B%7D%5Cn%7B%7D'.format(self.message, self.stack_trace)%0A Wrapper = ExternalRuntimeError if self.runtime else ExternalEnvironmentError%0A return Wrapper, Exc(msg)
%0A
|
dbbdc1f262f25e7c3f27db4e2ab8076b9de2ec4d
|
Fix undefined variable.
|
vxscreenshots/watch.py
|
vxscreenshots/watch.py
|
#! /usr/bin/env python
# -*- coding: UTF-8 -*-
import os
from os import makedirs
from os.path import isdir, dirname
import time
import logging
import boto3
import click
import sqlite3
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
from .config import read_config
config = read_config()
class S3Element(LoggingEventHandler):
def __init__(self, bucket, folder):
super(LoggingEventHandler, self).__init__()
self.folder = folder
self.bucket = bucket
self.url = ''
self.format_logging()
self.valid_ext = ['.png', '.jpg', '.gif', '.jpeg']
self.db = config.get('vxscreenshots.database')
if not isdir(dirname(self.db)):
makedirs(dirname(self.db))
self.logger.info('Cache dbname: %s' % self.db)
self.logger.info('Bucket name: %s' % self.bucket)
self.logger.info('Folder name: %s' % self.folder)
def format_logging(self, log_level='INFO'):
root = logging.getLogger()
if root.handlers:
for handler in root.handlers:
root.removeHandler(handler)
logging.basicConfig(format='%(asctime)s: %(name)s: %(levelname)s: %(message)s',
level=logging.INFO)
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.INFO)
def get_conn(self):
return self.conn.cursor()
def get_path(self, src_path):
return '{}/{}'.format(self.folder, src_path)
def get_url(self, fname):
return "http://{bucket}/{fname}".format(bucket=self.bucket,
fname=fname)
def init_db(self):
self.cursor.execute('''CREATE TABLE stock_images
(path text, url text, synced boolean)
''')
def db_insert_new(self, images):
self.cursor.executemany('INSERT INTO stock_images VALUES (?,?,?)',
images)
self.conn.commit()
def on_modified(self, event):
what = 'directory' if event.is_directory else 'file'
self.send_to_s3(what, event)
def send_to_s3(self, what, event):
self.logger.info("Screenshot was Modified %s: %s", what, event.src_path)
name, ext = os.path.splitext(event.src_path)
if what != 'directory' and \
os.path.isfile(event.src_path) and \
ext in self.valid_ext:
s3 = boto3.resource('s3')
data = open(event.src_path, 'rb')
fname = self.get_path(os.path.basename(data.name))
bucket = s3.Bucket(self.bucket)
bucket.put_object(Key=fname, Body=data, ACL='public-read',
ContentType='image/%s' % ext[1:])
self.url = self.get_url(fname)
self.logger.info("Screenshot was pushed to %s" % self.url)
self.conn = sqlite3.connect(self.db)
# Asume if running as a main script it is a dev mode
self.cursor = self.get_conn()
try:
self.init_db()
except Exception, e:
self.logger.warning(e)
try:
self.db_insert_new([(event.src_path, self.url, True)])
self.logger.warning('Inserted on db %s %s' % (event.src_path,
self.url))
except Exception, e:
self.logger.warning('I could not insert on cache %s' % e)
@click.option('--path', default=config.get('vxscreenshots.supervised'),
help='Path to be supervised')
@click.option('--bucket', default=config.get('vxscreenshots.bucket_name'),
help='Bucket where things will be saved to')
@click.option('--folder', default=config.get('vxscreenshots.folder'),
help='Inside the bucket how the folder will be named')
@click.command()
def cli(path, bucket, folder):
'''Watch a folder and push images automatically to amazon S3'''
event_handler = S3Element(bucket, folder)
msg = 'Sending to this bucket %s %s %s' % (bucket, folder, path)
event_handler.logger.info(msg)
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except IOError:
self.logger.info('A crazy file changed')
except KeyboardInterrupt:
observer.stop()
observer.join()
if __name__ == "__main__":
cli()
|
Python
| 0.000015
|
@@ -323,16 +323,17 @@
nfig()%0A%0A
+%0A
class S3
@@ -4363,36 +4363,45 @@
OError:%0A
-self
+event_handler
.logger.info('A
|
8d05da2ddb115f994c652e0e9d8a75b13a6269ee
|
add Shallow_water to list of noteboks to use jsanimate_widget in html version
|
make_html_on_master.py
|
make_html_on_master.py
|
"""
Convert notebooks listed in `chapters` into html files in the directory
`riemann_book_files`.
Run this code on the master branch with the latest set of notebooks,
adjusting the specification of `chapters` below first if you want to
process only a subset of the notebooks.
To post on the website, check out the `gh-pages` branch and then
cp -r build_html/* html/
and then git add, commit, and push to Github.
The files `build_html/*.ipynb` can be deleted, but copy over all the
subdirectories (`figures`, `exact_solvers`, etc.) in order for figures to
display in html files and links to Python code to work properly.
Note:
- The notebooks are first copied into the directory `build_html` and pre-processed
to use static_widgets (or jsanimation_widgets in certain notebooks),
and cross references to other notebooks have `.ipynb` replaced by `.html`
so the links work in the html files.
- The directories `utils`, `exact_solvers`, and `figures` are also copied
in before processing.
- The list `all_chapters` is used to replace cross-reference links
`chapter.ipynb` by `chapter.html`.
- The bibliography files `riemann.html` and riemann_bib.html` are
copied into `build_html`. These might need to be updated before
running this script (using make_html_bib.sh).
"""
import re
import subprocess
import os
all_chapters = ['Preface',
'Index',
'Introduction',
'Advection',
'Acoustics',
'Traffic_flow',
'Shallow_water',
'Shallow_tracer',
'Euler_equations',
'Approximate_solvers',
'Euler_approximate_solvers',
'Traffic_variable_speed',
'Nonlinear_elasticity',
'Euler_equations_TammannEOS',
'Nonconvex_scalar',
'Pressureless_flow',
'Kitchen_sink_problem']
chapters = all_chapters # which chapters to process
# test on a subset:
#chapters = ['Index','Introduction','Traffic_flow']
template_path = os.path.realpath('./html.tpl')
os.system('mkdir -p build_html') # for intermediate processing
# copy some things needed for processing
os.system('cp -r exact_solvers build_html/')
os.system('cp -r utils build_html/')
os.system('cp -r figures build_html/')
# Putting figures inside an img folder doesn't seem to be needed now:
#os.system('mkdir -p build_html/img') # for viewing images
#os.system('cp -r figures build_html/img/')
# Might need to update bibliography first with make_html_bib.sh
os.system('cp riemann.html build_html/') # bibliography
os.system('cp riemann_bib.html build_html/') # bibtex version of bibliography
os.chdir('build_html')
for i, chapter in enumerate(chapters):
filename = chapter + '.ipynb'
print("Processing %s" % filename)
input_filename = os.path.join('..',filename)
with open(input_filename, "r") as source:
lines = source.readlines()
output_filename = filename
html_filename = chapter+'.html'
with open(output_filename, "w") as output:
if chapter in ['Introduction','Nonconvex_scalar']:
widget = 'from utils.jsanimate_widgets import interact'
else:
widget = 'from utils.snapshot_widgets import interact'
for line in lines:
line = re.sub(r'from ipywidgets import interact', widget, line)
for j, chapter_name in enumerate(all_chapters):
line = re.sub(chapter_name+'.ipynb', chapter_name+'.html', line)
output.write(line)
args = ["jupyter", "nbconvert", "--to", "html", "--execute",
"--ExecutePreprocessor.kernel_name=python2",
"--output", html_filename,
"--template", template_path,
"--ExecutePreprocessor.timeout=60", output_filename]
subprocess.check_call(args)
os.chdir('..')
print("The html files can be found in build_html")
print("Open build_html/Index.html for the index")
if 0:
# Recommend doing this after switching to gh-pages branch:
os.system('mkdir -p html/figures')
os.system('cp build_html/img/figures/* html/figures/')
print("You may delete the directory build_html")
print("Open html/Index.html for the index")
|
Python
| 0
|
@@ -3076,16 +3076,32 @@
ction','
+Shallow_water','
Nonconve
|
07aca8e96d5e93edb684d0c4684ef8f837e8fc58
|
Use comment builder for dirhtml too
|
readthedocs/doc_builder/loader.py
|
readthedocs/doc_builder/loader.py
|
from django.utils.importlib import import_module
from django.conf import settings
# Managers
mkdocs = import_module(getattr(settings, 'MKDOCS_BACKEND', 'doc_builder.backends.mkdocs'))
sphinx = import_module(getattr(settings, 'SPHINX_BACKEND', 'doc_builder.backends.sphinx'))
loading = {
# Possible HTML Builders
'sphinx': sphinx.HtmlBuilderComments,
'sphinx_htmldir': sphinx.HtmlDirBuilder,
'sphinx_singlehtml': sphinx.SingleHtmlBuilder,
# Other Sphinx Builders
'sphinx_pdf': sphinx.PdfBuilder,
'sphinx_epub': sphinx.EpubBuilder,
'sphinx_search': sphinx.SearchBuilder,
'sphinx_singlehtmllocalmedia': sphinx.LocalMediaBuilder,
# Other markup
'mkdocs': mkdocs.MkdocsHTML,
'mkdocs_json': mkdocs.MkdocsJSON,
}
|
Python
| 0
|
@@ -392,24 +392,32 @@
mlDirBuilder
+Comments
,%0A 'sphin
|
75c1c739547130e588f0e6d33aa3d88e364f90ee
|
Fix error report path
|
watchtower/WatchMan.py
|
watchtower/WatchMan.py
|
'''
Copyright (c) 2015 Tim Savannah Under terms of the LGPLv2.
See LICENSE in the root directory for full terms.
WatchMan.py - Contains the main "runner" for WatchTower
'''
import os
import multiprocessing
import signal
import sys
import traceback
import time
from .Triggers import Trigger
DEFAULT_POLL_TIME = 5 # Default poll time, in second
DEFAULT_STOP_CHECK_INTERVAL = .25 # Interval to check if should continue. Sleeps in these increments up to pollTime.
SMALL_NUMBER = .0001 # A small number slightly greater than zero as the minimum time for poll/stop interval
class WatchMan(multiprocessing.Process):
'''
WatchMan - The main guard on duty. He/She watches a directory against a given list
of triggers, and performs the associated actions on the matched items.
'''
def __init__(self, rootDir, triggers, canMatchMultiple=False, pollTime=DEFAULT_POLL_TIME, stopCheckInterval=DEFAULT_STOP_CHECK_INTERVAL):
'''
__init__ - Create a WatchMan worker
@param rootDir <str> - A string path to the directory to watch
@param triggers list<watchtower.Trigger.Trigger> - list of Triggers to use on this directory
@param canMatchMultiple bool - If true, the items can be matched by multiple triggers. Use this if you want an item to be
handled multiple times, like overlapping data. Usually, and by default, this should be False.
@param pollTime <float> - Number of seconds to rest in between polling the directory. Defaults to DEFAULT_POLL_TIME
@param stopCheckInterval <float> - Number of seconds to sleep at one time; intervals of #pollTime. When time to sleep,
it sleeps in increments of this length, testing if a stop signal was received after each period.
Example: if poll time is 1s and stopCheckInterval is .25, it will sleep 4 times and check if the stop
signal was given after each sleep.
'''
multiprocessing.Process.__init__(self)
self.rootDir = rootDir
self.triggers = triggers
self.canMatchMultiple = canMatchMultiple
i = 0
for trigger in triggers:
if not isinstance(trigger, Trigger):
raise ValueError("Element %d, '%s' must implement watchtower.Trigger" %(i, str(trigger)))
i += 1
if rootDir.endswith('/'):
rootDir = rootDir[:-1]
if len(rootDir) == 0:
rootDir = '.'
if not os.path.isdir(rootDir):
raise ValueError('"%s" is not a valid directory, ' %(rootDir,))
self.rootDir = rootDir
self.stopCheckInterval = float(stopCheckInterval)
self.pollTime = float(pollTime)
if self.stopCheckInterval < SMALL_NUMBER:
raise ValueError('stopCheckInterval must be a positive number > %f' %(SMALL_NUMBER,) )
if self.pollTime < SMALL_NUMBER:
raise ValueError('pollTime must be a positive number > %f' %(SMALL_NUMBER,))
if self.pollTime < self.stopCheckInterval:
sys.stderr.write('Warning, given poll time %f exceeds the check interval of %f. Will be rounded up to check interval.\n' %(self.pollTime, self.stopCheckInterval))
self.pollTime = self.stopCheckInterval
self.keepGoing = True
def die(self, *args, **kwargs):
'''
die - Terminate this worker
@param args/kwargs - junk for signal handler
'''
if self.keepGoing is False:
return
self.keepGoing = False
signal.signal(signal.SIGTERM, signal.SIG_DFL)
signal.signal(signal.SIGINT, signal.SIG_DFL)
def cleanup(self):
pass
def run(self):
'''
run - start point of this process
'''
canMatchMultiple = self.canMatchMultiple # Make sure someone doesn't change this whilst executing..
# Connect to our signal handler
signal.signal(signal.SIGTERM, self.die)
signal.signal(signal.SIGINT, self.die)
while self.keepGoing is True:
# Get directory contents
try:
directoryContents = {x for x in os.listdir(self.rootDir) if x and os.path.isfile(self.rootDir + '/' + x)}
except Exception as e:
sys.stderr.write('Issue getting directory contents [%s]: \n' %(self.rootDir,))
sys.stderr.write(traceback.format_exc(sys.exc_info()) + '\n')
time.sleep(self.pollTime / 5)
continue
# Construct absolute paths
try:
directoryContentsAbsolute = {item : (self.rootDir + '/' + item) for item in directoryContents}
except SyntaxError: # Older python support
directoryContentsAbsolute = {}
for item in directoryContents:
directoryContentsAbsolute[item] = self.rootDir + '/' + item
remainingContents = directoryContents
if canMatchMultiple is True:
matchedThisIteration = set()
for trigger in self.triggers:
try:
matches = trigger.getFilenameMatches(remainingContents)
except Exception as e:
sys.stderr.write('Error getting matches on trigger %s [%s]\n%s\n' %
(trigger.getPatternStr(),
trigger.__class__.__name__,
traceback.format_exc(sys.exc_info())
)
)
continue
if canMatchMultiple is False:
remainingContents = remainingContents.difference(matches)
else:
matchedThisIteration = matchedThisIteration.union(matches)
namesAndData = {}
for match in matches:
try:
fullPath = directoryContentsAbsolute[match]
with open(fullPath, 'r') as f:
contents = f.read()
except Exception as e:
sys.stderr.write('Error reading file contents: %s\n%s\n' %(fullPath, traceback.format_exc(sys.exc_info())) )
continue
if contents.strip():
data = contents.split('\n')
if data[-1] == '':
data = data[:-1]
else:
data = []
namesAndData[match] = data
allMatches = namesAndData.keys()
for match in allMatches:
data = namesAndData[match]
try:
trigger.runAction(match, data)
except Exception as e:
# TODO: retries?
sys.stderr.write('Error handling action %s on %s. Data was: %s. Deleting task.\n%s\n' %(trigger.__class.__name__, match, str(data)), traceback.format_exc(sys.exc_info()))
# If multiple matches per round is allowed, don't remove here.
if self.canMatchMultiple is True:
continue
fullPath = directoryContentsAbsolute[match]
try:
os.remove(fullPath)
except Exception as e:
sys.stderr.write('Unable to remove completed task: %s\n' %(fullPath,))
# END for trigger
if self.canMatchMultiple is True:
for match in matchedThisIteration:
fullPath = directoryContentsAbsolute[match]
try:
os.remove(fullPath)
except Exception as e:
sys.stderr.write('Unable to remove completed task: %s\n' %(fullPath,))
timeSlept = 0.0
while timeSlept < self.pollTime:
time.sleep(self.stopCheckInterval)
timeSlept += self.stopCheckInterval
if self.keepGoing is False:
break
self.die()
sys.exit(0)
|
Python
| 0.000003
|
@@ -7038,16 +7038,18 @@
.__class
+__
.__name_
@@ -7067,17 +7067,16 @@
tr(data)
-)
, traceb
@@ -7106,16 +7106,17 @@
info()))
+)
%0A%0A
|
000e44df690a4a1a607224d5f53cc4feee7bcbc0
|
add tests for related objects.
|
reciprocity/chef_profile/tests.py
|
reciprocity/chef_profile/tests.py
|
"""Test ChefProfile model."""
from __future__ import unicode_literals
from django.conf import settings
from django.test import TestCase
from django.db.models import QuerySet, Manager
from .models import ChefProfile
import factory
USER_BATCH_SIZE = 20
class UserFactory(factory.django.DjangoModelFactory):
"""Factory for User model in tests."""
class Meta:
"""Establish User model as the product of this factory."""
model = settings.AUTH_USER_MODEL
django_get_or_create = ('username',)
first_name = factory.Faker('first_name')
last_name = factory.Faker('last_name')
email = factory.Faker('email')
username = factory.LazyAttribute(
lambda obj: ''.join((obj.first_name, obj.last_name)))
password = factory.PostGenerationMethodCall('set_password', 'secret')
class BuiltUserCase(TestCase):
"""Single user not saved to database, testing functionality of handlers."""
def setUp(self):
"""Set up user stub."""
self.user = UserFactory.build()
def test_user_not_saved(self):
"""Make sure set up user has not been saved yet."""
self.assertIsNone(self.user.id)
def test_init_chef_profile(self):
"""Test that ChefProfile created on save."""
profile = ChefProfile(user=self.user)
self.assertIs(profile, self.user.profile)
class SingleUserCase(TestCase):
"""Set up single user for tests."""
def setUp(self):
"""Create a user for testing."""
self.user = UserFactory.create()
class BasicUserProfileCase(SingleUserCase):
"""Basic test case for profile."""
def test_user_has_profile(self):
"""Test that newly created User has ChefProfile."""
self.assertTrue(self.user.profile)
def test_profile_pk(self):
"""Test that newly created User's profile has a primary key."""
self.assertIsInstance(self.user.profile.pk, int)
self.assertTrue(self.user.profile.pk)
def test_profile_is_active(self):
"""Test that profile of new User is active."""
self.assertTrue(self.user.profile.is_active)
def test_profile_active_manager(self):
"""Test that active attr is a Manager class."""
self.assertIsInstance(ChefProfile.active, Manager)
def test_profile_active_query(self):
"""Test that active manager can give a QuerySet."""
self.assertIsInstance(ChefProfile.active.all(), QuerySet)
def test_active_count(self):
"""Test that counting the active manager returns expected int."""
self.assertEqual(ChefProfile.active.count(), 1)
def test_about_me(self):
"""Test that User.profile.about_me can be added as expected."""
self.assertIsNone(self.user.profile.about_me)
self.user.profile.about_me = 'Here is something about me'
self.user.save()
self.assertEqual(self.user.profile.about_me, 'Here is something about me')
class ManyUsersCase(TestCase):
"""Test cases where many Users are registered."""
def setUp(self):
"""Add many Users to the test."""
self.user_batch = UserFactory.create_batch(USER_BATCH_SIZE)
def test_active_count(self):
"""Make sure that the active user count is the expected size."""
self.assertEqual(ChefProfile.active.count(), USER_BATCH_SIZE)
|
Python
| 0
|
@@ -176,16 +176,74 @@
Manager%0A
+from recipe.tests import RecipeFactory, IngredientFactory%0A
from .mo
@@ -266,16 +266,16 @@
Profile%0A
-
import f
@@ -1580,16 +1580,169 @@
reate()%0A
+ self.recipe = RecipeFactory.create()%0A self.ingredient1 = IngredientFactory.create()%0A self.ingredient2 = IngredientFactory.create()%0A
%0A%0Aclass
@@ -2801,17 +2801,17 @@
ount(),
-1
+2
)%0A%0A d
@@ -3131,24 +3131,978 @@
about me')%0A%0A
+ def test_favorites(self):%0A %22%22%22Ensure a user can have a favorite recipe.%22%22%22%0A self.assertNotIn(self.recipe, self.user.profile.favorites.all())%0A self.user.profile.favorites.add(self.recipe)%0A self.assertIn(self.recipe, self.user.profile.favorites.all())%0A%0A def test_liked_ingredient(self):%0A %22%22%22Test user can like a single ingredient.%22%22%22%0A self.user.profile.liked_ingredients.add(self.ingredient1)%0A self.assertIn(self.ingredient1, self.user.profile.liked_ingredients.all())%0A self.assertNotIn(self.ingredient2, self.user.profile.liked_ingredients.all())%0A%0A def test_disliked_ingredient(self):%0A %22%22%22Test that user can have disliked ingredients.%22%22%22%0A self.assertNotIn(self.ingredient2, self.user.profile.disliked_ingredients.all())%0A self.user.profile.disliked_ingredients.add(self.ingredient2)%0A self.assertIn(self.ingredient2, self.user.profile.disliked_ingredients.all())%0A
%0Aclass ManyU
@@ -4410,24 +4410,24 @@
ed size.%22%22%22%0A
-
self
@@ -4468,24 +4468,27 @@
unt(), USER_BATCH_SIZE)%0A
+%0A%0A%0A
|
5c22153b8b43e13266ea2b68a39bcf94b75ab993
|
Add get_timestra and get_entry_monitor_dir
|
creation/lib/cgWConsts.py
|
creation/lib/cgWConsts.py
|
####################################
#
# Keep all the constants used to
# create glidein entries in this
# module
#
# Author: Igor Sfiligoi
#
####################################
import time
import string
import os.path
start_time_tuple=time.localtime()
TIMESTR=(string.printable[start_time_tuple[0]-2000]+ #year, will work until ~2060
string.printable[start_time_tuple[1]]+ #month
string.printable[start_time_tuple[2]]+ #day
string.printable[start_time_tuple[3]]+ #hour
string.digits[start_time_tuple[4]/10]) #first minute digit
del start_time_tuple
# these two are in the submit dir, so they can be changed
PARAMS_FILE="params.cfg"
SUMMARY_SIGNATURE_FILE="signatures.sha1"
# these are in the stage dir, so they need to be renamed if changed
DESCRIPTION_FILE="description.%s.cfg"%TIMESTR
ATTRS_FILE="attributes.cfg"
CONSTS_FILE="constants.%s.cfg"%TIMESTR
FILE_LISTFILE="file_list.%s.lst"%TIMESTR
SCRIPT_LISTFILE="script_list.%s.lst"%TIMESTR
SUBSYSTEM_LISTFILE="subsystem_list.%s.lst"%TIMESTR
SIGNATURE_FILE="signature.%s.sha1"%TIMESTR
CONDOR_FILE="condor_bin.%s.tgz"%TIMESTR
CONDOR_DIR="condor"
CONDOR_ATTR="CONDOR_DIR"
VARS_FILE="condor_vars.%s.lst"%TIMESTR
CONDOR_STARTUP_FILE="condor_startup.sh"
# these are again in the submit dir
STARTUP_FILE="glidein_startup.sh"
GLIDEIN_FILE="glidein.descript"
JOB_DESCRIPT_FILE="job.descript"
SUBMIT_FILE="job.condor"
SUBMIT_WRAPPER="job_submit.sh"
XML_CONFIG_FILE="glideinWMS.xml"
###################################################
#
# These functions append constant parts to strings
#
###################################################
def get_entry_submit_dir(submit_dir,entry_name):
entry_submit_dir=os.path.join(submit_dir,"entry_"+entry_name)
return entry_submit_dir
def get_entry_stage_dir(stage_dir,entry_name):
entry_stage_dir=os.path.join(stage_dir,"entry_"+entry_name)
return entry_stage_dir
###########################################################
#
# CVS info
#
# $Id: cgWConsts.py,v 1.5 2007/11/27 20:29:27 sfiligoi Exp $
#
# Log:
# $Log: cgWConsts.py,v $
# Revision 1.5 2007/11/27 20:29:27 sfiligoi
# Fix typo
#
# Revision 1.4 2007/11/27 19:58:51 sfiligoi
# Move dicts initialization into cgWDictFile and entry subdir definition in cgWConsts
#
# Revision 1.3 2007/10/12 21:56:24 sfiligoi
# Add glideinWMS.cfg in the list of constants
#
# Revision 1.2 2007/10/12 21:02:24 sfiligoi
# Add missing import
#
# Revision 1.1 2007/10/12 20:20:26 sfiligoi
# Put constants into a dedicated module
#
#
###########################################################
|
Python
| 0.000001
|
@@ -215,16 +215,56 @@
s.path%0A%0A
+%0Adef get_timestr(when=time.time()):%0A
start_ti
@@ -291,17 +291,25 @@
ime(
-)%0ATIMESTR
+when)%0A timestr
=(st
@@ -380,32 +380,36 @@
~2060%0A
+
string.printable
@@ -444,32 +444,36 @@
#month%0A
+
+
string.printable
@@ -505,16 +505,20 @@
#day%0A
+
@@ -573,24 +573,28 @@
ur%0A
+
+
string.digit
@@ -650,29 +650,54 @@
it %0A
-del start_time_tuple%0A
+ return timestr%0A%0ATIMESTR=get_timestr()%0A
%0A# t
@@ -2018,16 +2018,163 @@
ge_dir%0A%0A
+def get_entry_monitor_dir(monitor_dir,entry_name):%0A entry_monitor_dir=os.path.join(monitor_dir,%22entry_%22+entry_name)%0A return entry_monitor_dir
%0A%0A%0A#####
@@ -2267,17 +2267,17 @@
.py,v 1.
-5
+6
2007/11
@@ -2278,26 +2278,26 @@
007/11/2
-7
+8
20:
-29:27
+51:48
sfiligo
@@ -2339,16 +2339,111 @@
.py,v $%0A
+# Revision 1.6 2007/11/28 20:51:48 sfiligoi%0A# Add get_timestra and get_entry_monitor_dir%0A#%0A
# Revis
|
853ebd17535e97c838de18bbc093ce854a7af2b8
|
Version bump
|
biodome.py
|
biodome.py
|
"""
biodome
=======
Controlled environments.
Copyright 2018 Caleb Hattingh
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 os
import logging
import ast
import typing
import functools
import contextlib
try:
# Python 3
from collections import UserDict # pragma: no cover
except ImportError: # pragma: no cover
# Python 2
from UserDict import IterableUserDict as UserDict # pragma: no cover
if typing.TYPE_CHECKING: # pragma: no cover
from typing import Callable, Any
__version__ = '2018.8.2'
logger = logging.getLogger(__name__)
def biodome(name, default=None, cast=None):
# type: (str, Any, Callable) -> Any
raw_value = os.environ.get(name)
if raw_value is None:
return default
if default is None and cast is None:
# No type information. Just pass through.
return raw_value
raw_value = raw_value.strip()
# Use the same type as default as the cast
type_ = cast or type(default)
if bool in (cast, type_):
return raw_value.lower() in (
'1', 'y', 'yes', 'on', 'active', 'activated', 'enabled', 'true',
't', 'ok', 'yeah',
)
try:
if type_ in (dict, list, set, tuple):
raw_value = ast.literal_eval(raw_value)
return (type(raw_value) == type_ and raw_value) or default
return type_(raw_value)
except:
logger.error(
'Env var %s: cast "%s" to type %s failed. The default will be'
'used.', name, raw_value, str(type_)
)
return default
class _Environ(UserDict):
def __init__(self, *args, **kwargs):
self.data = os.environ
def get(self, key, default=None, cast=None):
# type: (str, Any, Callable) -> Callable
return biodome(key, default, cast)
def get_callable(self, key, default=None, cast=None):
# type: (str, Any, Callable) -> Callable[[None], None]
return functools.partial(
self.get, key, default=default, cast=cast,
)
def __setitem__(self, key, value):
os.environ[key] = str(value)
environ = _Environ()
@contextlib.contextmanager
def env_change(name, value):
"""Context manager to temporarily change the value of an env var."""
# TODO: move this upstream to the biodome package
if name in environ:
old = environ[name]
def reset():
environ[name] = old
else:
def reset():
del environ[name]
try:
environ[name] = value
yield
finally:
reset()
|
Python
| 0.000001
|
@@ -1029,17 +1029,17 @@
'2018.8.
-2
+3
'%0Alogger
|
933dacc43a4d3db0ea134d374867e80e8144a539
|
Fix pairing syntax bug
|
mycroft/managers/identity_manager.py
|
mycroft/managers/identity_manager.py
|
# Copyright (c) 2017 Mycroft AI, Inc.
#
# This file is part of Mycroft Light
# (see https://github.com/MatthewScholefield/mycroft-light).
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this 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 json
from os.path import isfile
from time import time as get_time
from mycroft.managers.manager_plugin import ManagerPlugin
from mycroft.util import log
class IdentityManager(ManagerPlugin):
def __init__(self, rt):
super().__init__(rt)
if not rt.config['use_server']:
raise NotImplementedError('Server Disabled')
self.identity_file = rt.filesystem.path(rt.paths.identity)
self.uuid = self.access_token = self.refresh_token = ''
self.expiration = 0
self.load()
def is_expired(self):
return self.refresh_token and self.expiration <= get_time()
@staticmethod
def translate_from_server(data):
replacements = {
'accessToken': 'access',
'refreshToken': 'refresh',
'expiration': 'expires_at'
}
data['expiration'] += get_time()
return {k.get(replacements, k): v for k, v in data.items()}
def register(self, data):
"""Registers new login data from server"""
log.debug('REGISTERING TO:', data)
data = self.translate_from_server(data)
self.assign(data)
with open(self.identity_file, 'w') as f:
json.dump(data, f)
def assign(self, data):
"""Set identity from data"""
if not isinstance(data, dict):
log.error('Invalid Identity Data:', data)
return
try:
self.uuid = data['uuid']
self.access_token = data['access']
self.refresh_token = data['refresh']
self.expiration = data['expires_at']
except KeyError:
log.exception('Loading Identity')
def load(self):
"""Load identity from disk"""
if isfile(self.identity_file):
with open(self.identity_file) as f:
data = json.load(f)
self.assign(data)
|
Python
| 0.000001
|
@@ -1817,14 +1817,8 @@
rn %7B
-k.get(
repl
@@ -1825,16 +1825,22 @@
acements
+.get(k
, k): v
|
e78d621239d6e22f7c0baf3d507eb00f733c6c11
|
fix file encoding issue
|
docs/add_image_map.py
|
docs/add_image_map.py
|
# rst doesn't support image maps, so we'll add one after the html has been built
fileName = "_build/html/abmexample.html"
line = 'src="_images/abmexample.jpg" />'
lineWithMap = 'src="_images/abmexample.jpg" usemap="#image-map" />'
imageMap = """\n <map name="image-map">
<area target="" alt="" title="" href="models.html#trip-cbd-parking" coords="234,683,436,709" shape="rect">
<area target="" alt="" title="" href="models.html#trip-mode-choice" coords="438,670,235,646" shape="rect">
<area target="" alt="" title="" href="models.html#trip-scheduling" coords="235,607,434,630" shape="rect">
<area target="" alt="" title="" href="models.html#trip-destination-choice" coords="235,565,433,588" shape="rect">
<area target="" alt="" title="" href="models.html#trip-purpose" coords="236,524,436,550" shape="rect">
<area target="" alt="" title="" href="models.html#intermediate-stop-frequency" coords="5,481,663,505" shape="rect">
<area target="" alt="" title="" href="models.html#atwork-subtour-scheduling" coords="516,401,666,427" shape="rect">
<area target="" alt="" title="" href="models.html#atwork-subtour-destination" coords="517,361,667,385" shape="rect">
<area target="" alt="" title="" href="models.html#atwork-subtour-frequency" coords="515,243,667,265" shape="rect">
<area target="" alt="" title="" href="models.html#non-mandatory-tour-scheduling" coords="347,404,497,425" shape="rect">
<area target="" alt="" title="" href="models.html#non-mandatory-tour-destination-choice" coords="347,363,496,384" shape="rect">
<area target="" alt="" title="" href="models.html#non-mandatory-tour-frequency" coords="347,245,495,267" shape="rect">
<area target="" alt="" title="" href="models.html#joint-tour-scheduling" coords="175,402,327,424" shape="rect">
<area target="" alt="" title="" href="models.html#joint-tour-destination-choice" coords="175,361,326,386" shape="rect">
<area target="" alt="" title="" href="models.html#joint-tour-participation" coords="175,324,326,345" shape="rect">
<area target="" alt="" title="" href="models.html#joint-tour-composition" coords="176,282,326,307" shape="rect">
<area target="" alt="" title="" href="models.html#joint-tour-frequency" coords="176,243,327,266" shape="rect">
<area target="" alt="" title="" href="models.html#tour-mode" coords="5,442,667,464" shape="rect">
<area target="" alt="" title="" href="models.html#mandatory-tour-scheduling" coords="5,401,156,425" shape="rect">
<area target="" alt="" title="" href="models.html#mandatory-tour-frequency" coords="5,241,157,267" shape="rect">
<area target="" alt="" title="" href="models.html#cdap" coords="235,165,434,189" shape="rect">
<area target="" alt="" title="" href="models.html#free-parking-eligibility" coords="239,126,435,148" shape="rect">
<area target="" alt="" title="" href="models.html#auto-ownership" coords="237,86,433,109" shape="rect">
<area target="" alt="" title="" href="models.html#school-location" coords="237,43,435,67" shape="rect">
<area target="" alt="" title="" href="models.html#accessibility" coords="236,6,436,27" shape="rect">
</map>
""" # noqa
print("add image map to " + fileName)
with open(fileName, encoding="utf8") as file:
lines = file.readlines()
with open(fileName, 'w') as file:
for l in lines:
if line in l:
print("updated " + fileName)
file.writelines("%s" % l.replace(line, lineWithMap))
file.writelines("%s" % imageMap)
else:
file.writelines("%s" % l)
|
Python
| 0.000001
|
@@ -3239,25 +3239,8 @@
Name
-, encoding=%22utf8%22
) as
|
adb9b262167beecb30edc281e4ab10fc05b3e6da
|
optimize imports and add common exceptions
|
voting-server/app/errors.py
|
voting-server/app/errors.py
|
from flask import jsonify
from werkzeug.exceptions import HTTPException
from werkzeug.exceptions import default_exceptions
from app import app
def json_error(error):
response = jsonify(message = str(error))
response.status_code = error.code if isinstance(error, HTTPException) else 500
return response
for code in default_exceptions.keys():
app.register_error_handler(code, json_error)
|
Python
| 0
|
@@ -68,40 +68,9 @@
tion
-%0Afrom werkzeug.exceptions import
+,
def
@@ -368,8 +368,58 @@
_error)%0A
+app.register_error_handler(Exception, json_error)%0A
|
7d650f3ee367a8eac710893c1818aa08cccf7598
|
Add auth
|
bot/dao.py
|
bot/dao.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from pymongo import MongoClient, IndexModel
class DAO:
def __init__(self, *args, **kwargs):
#args -- tuple of anonymous arguments
#kwargs -- dictionary of named arguments
if kwargs.get('mongo') is None:
self.default_mongo_init()
else:
self.mongo = MongoClient(kwargs.get('mongo').get('host'), kwargs.get('mongo').get('port'))
self.mongo_db = self.mongo[kwargs.get('mongo').get('db')]
def default_mongo_init(self):
self.mongo = MongoClient('mongodb://localhost:27017/')
self.mongo_db = self.mongo['dark']
self.mongo_db['actress'].create_index('id', unique=True)
def update_one_feedback_by_id(self, id, ox, image):
collection = self.mongo_db['actress']
result = collection.update_one({"id": id}, {'$inc': {'count': 1}, '$push': {ox: image}}, upsert=True)
def update_one_works_by_id(self, id, no):
collection = self.mongo_db['actress']
result = collection.update_one({"id": id}, {'$push': {"works": no}}, upsert=True)
def find_one_works_by_id(self, id):
collection = self.mongo_db['actress']
return collection.find_one({"id": id}, {"works": True, "_id": False})
def update_one_info_by_actress(self, actress):
collection = self.mongo_db['actress']
result = collection.update_one({"id": actress.get("id")}, {'$set': {"id": actress.get("id"), "name": actress.get("name"), "img": actress.get("img")}}, upsert=True)
def find_one_actress_by_id(self, id):
collection = self.mongo_db['actress']
return collection.find_one({"id": id}, {"_id": False})
|
Python
| 0.000007
|
@@ -573,16 +573,34 @@
ngodb://
+username:password@
localhos
@@ -607,16 +607,20 @@
t:27017/
+dark
')%0A
|
4b8339b53f1b9dcd79f2a9060933713328a13b90
|
Mark dask-distributed tests on Windows as xfail (#1747)
|
xarray/tests/test_distributed.py
|
xarray/tests/test_distributed.py
|
import pytest
import xarray as xr
from xarray.core.pycompat import suppress
distributed = pytest.importorskip('distributed')
da = pytest.importorskip('dask.array')
import dask
from distributed.utils_test import cluster, loop, gen_cluster
from distributed.client import futures_of, wait
from xarray.tests.test_backends import create_tmp_file, ON_WINDOWS
from xarray.tests.test_dataset import create_test_data
from . import assert_allclose, has_scipy, has_netCDF4, has_h5netcdf
ENGINES = []
if has_scipy:
ENGINES.append('scipy')
if has_netCDF4:
ENGINES.append('netcdf4')
if has_h5netcdf:
ENGINES.append('h5netcdf')
@pytest.mark.parametrize('engine', ENGINES)
def test_dask_distributed_integration_test(loop, engine):
with cluster() as (s, _):
with distributed.Client(s['address'], loop=loop):
original = create_test_data()
with create_tmp_file(allow_cleanup_failure=ON_WINDOWS) as filename:
original.to_netcdf(filename, engine=engine)
with xr.open_dataset(filename, chunks=3, engine=engine) as restored:
assert isinstance(restored.var1.data, da.Array)
computed = restored.compute()
assert_allclose(original, computed)
@pytest.mark.skipif(distributed.__version__ <= '1.19.3',
reason='Need recent distributed version to clean up get')
@gen_cluster(client=True, timeout=None)
def test_async(c, s, a, b):
x = create_test_data()
assert not dask.is_dask_collection(x)
y = x.chunk({'dim2': 4}) + 10
assert dask.is_dask_collection(y)
assert dask.is_dask_collection(y.var1)
assert dask.is_dask_collection(y.var2)
z = y.persist()
assert str(z)
assert dask.is_dask_collection(z)
assert dask.is_dask_collection(z.var1)
assert dask.is_dask_collection(z.var2)
assert len(y.__dask_graph__()) > len(z.__dask_graph__())
assert not futures_of(y)
assert futures_of(z)
future = c.compute(z)
w = yield future
assert not dask.is_dask_collection(w)
assert_allclose(x + 10, w)
assert s.task_state
|
Python
| 0
|
@@ -1,12 +1,24 @@
+import sys%0A%0A
import pytes
@@ -633,24 +633,142 @@
5netcdf')%0A%0A%0A
+@pytest.mark.xfail(sys.platform == 'win32',%0A reason='https://github.com/pydata/xarray/issues/1738')%0A
@pytest.mark
|
6c3ff180c3bda17f1b6fdcf4500fdefdef9d713f
|
Fix copy & paste errors in setting I brought over from django-skel.
|
vsub/settings/production.py
|
vsub/settings/production.py
|
"""Settings used in the production environment."""
from memcacheify import memcacheify
from postgresify import postgresify
from base import *
## Email configuration
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-host
EMAIL_HOST = os.environ.get('EMAIL_HOST', 'smtp.gmail.com')
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-host-password
EMAIL_HOST_PASSWORD = environ.get('EMAIL_HOST_PASSWORD', '')
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-host-user
EMAIL_HOST_USER = environ.get('EMAIL_HOST_USER', 'your_email@example.com')
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-port
EMAIL_PORT = environ.get('EMAIL_PORT', 587)
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-subject-prefix
EMAIL_SUBJECT_PREFIX = '[%s] ' % SITE_NAME
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-use-tls
EMAIL_USE_TLS = True
# See: https://docs.djangoproject.com/en/dev/ref/settings/#server-email
SERVER_EMAIL = EMAIL_HOST_USER
## Database configuration
# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = postgresify()
## Cache configuration
# See: https://docs.djangoproject.com/en/dev/ref/settings/#caches
CACHES = memcacheify()
## Secret key configuration
# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
# Use the value set in the Heroku configuration.
SECRET_KEY = environ.get('SECRET_KEY', SECRET_KEY)
|
Python
| 0
|
@@ -530,16 +530,19 @@
SWORD =
+os.
environ.
@@ -572,16 +572,16 @@
D', '')%0A
-
%0A# See:
@@ -666,16 +666,19 @@
_USER =
+os.
environ.
@@ -797,16 +797,16 @@
il-port%0A
-
EMAIL_PO
@@ -810,16 +810,19 @@
_PORT =
+os.
environ.
@@ -1566,16 +1566,19 @@
T_KEY =
+os.
environ.
|
4fcdd2f4cea4899b3f7057f98b95fa7380682816
|
Add else: return to break out of loop when BACK is selected
|
cs251tk/webapp/web_cli.py
|
cs251tk/webapp/web_cli.py
|
import os
from ..common import chdir
from ..student import stash, pull, checkout_date
from ..student.markdownify.process_file import process_file
from PyInquirer import style_from_dict, Token, prompt
def check_student(student, spec, basedir):
files = []
if os.path.exists('{}/{}'.format(student, spec['assignment'])):
with chdir('{}/{}'.format(student, spec['assignment'])):
for file in spec['files']:
result = process_file(file['filename'],
steps=file['commands'],
options=file['options'],
spec=spec,
cwd=os.getcwd(),
supporting_dir=os.path.join(basedir, 'data', 'supporting'),
interact=False,
basedir=basedir,
spec_id=spec['assignment'],
skip_web_compile=False)
if 'web' in file['options']:
description = file['filename']
if result['missing']:
if 'optional' in file['options']:
description = '{} MISSING (OPTIONAL)'.format(file['filename'])
else:
description = '{} MISSING'.format(file['filename'])
files = files + [description]
else:
continue
return files
def ask_student(usernames):
style = style_from_dict({
Token.QuestionMark: '#959ee7 bold',
Token.Selected: '#959ee7',
Token.Pointer: '#959ee7 bold',
Token.Answer: '#959ee7 bold',
})
questions = [
{
'type': 'list',
'name': 'student',
'message': 'Choose student',
'choices': ['QUIT', 'LOG and QUIT', *usernames]
}
]
student = prompt(questions, style=style)
if not student:
return None
return student['student']
def ask_file(files, student, spec, basedir):
style = style_from_dict({
Token.QuestionMark: '#e3bd27 bold',
Token.Selected: '#e3bd27',
Token.Pointer: '#e3bd27 bold',
Token.Answer: '#e3bd27 bold',
})
while True:
questions = [
{
'type': 'list',
'name': 'file',
'message': 'Choose file',
'choices': ['BACK'] + files,
}
]
file = prompt(questions, style=style)
if file and file['file'] != 'BACK':
file_spec = {}
for f in spec['files']:
if f['filename'] == file['file']:
file_spec = f
break
if file_spec:
with chdir('{}/{}'.format(student, spec['assignment'])):
process_file(file_spec['filename'],
steps=file_spec['commands'],
options=file_spec['options'],
spec=spec,
cwd=os.getcwd(),
supporting_dir=os.path.join(basedir, 'data', 'supporting'),
interact=False,
basedir=basedir,
spec_id=spec['assignment'],
skip_web_compile=False)
def launch_cli(basedir, date, no_update, spec, usernames):
usernames = [
'{} NO SUBMISSION'.format(user)
if not os.path.exists('{}/{}'.format(user, spec['assignment']))
else user
for user in usernames
]
while True:
student = ask_student(usernames)
if not student or student == 'QUIT':
return False
elif student == 'LOG and QUIT':
return True
stash(student, no_update=no_update)
pull(student, no_update=no_update)
checkout_date(student, date=date)
files = check_student(student, spec, basedir)
if files:
ask_file(files, student, spec, basedir)
|
Python
| 0.000001
|
@@ -3526,16 +3526,49 @@
=False)%0A
+ else:%0A return%0A
%0A%0Adef la
|
c3b0d4b05314dc9fd51c790a86d30659d09c5250
|
Allow negative numbers in the GEOS string
|
wagtailgeowidget/helpers.py
|
wagtailgeowidget/helpers.py
|
import re
geos_ptrn = re.compile(
"^SRID=([0-9]{1,});POINT\(([0-9\.]{1,})\s([0-9\.]{1,})\)$"
)
def geosgeometry_str_to_struct(value):
'''
Parses a geosgeometry string into struct.
Example:
SRID=5432;POINT(12.0 13.0)
Returns:
>> [5432, 12.0, 13.0]
'''
result = geos_ptrn.match(value)
if not result:
return None
return {
'srid': result.group(1),
'x': result.group(2),
'y': result.group(3),
}
|
Python
| 0
|
@@ -59,16 +59,18 @@
POINT%5C((
+-?
%5B0-9%5C.%5D%7B
@@ -76,16 +76,18 @@
%7B1,%7D)%5Cs(
+-?
%5B0-9%5C.%5D%7B
|
d890d9410aa93966a7587f746378ddf13cd93395
|
use python tuple to push entry in queue
|
watchme/aosd_text_scroll.py
|
watchme/aosd_text_scroll.py
|
import sys
import aosd
import threading
import Queue
import time
import thread
import utils
class Aosd_conf(object):
line_space = 4
top_space = 0
geom_x_offset = 10
geom_y_offset = 10
shadow_color = 'black'
shadow_opacity = 255
shadow_x_offset = 1
shadow_y_offset = 1
fore_opacity = 255
font = "DejaVu Sans Mono"
font_size = 10
use_screen_width_percent = 50
use_screen_heigh_percent = 45
entry_timeout = 6
remove_keep_order = False
class Aosd_text_scroll_entry(object):
STATE_NEW = 0
STATE_SHOW = 1
def __init__(self, text, color, timeout=Aosd_conf.entry_timeout):
utils.init_from_args(self)
self.time_show = None
self.line_num = None
self._setup()
self.state = Aosd_text_scroll_entry.STATE_NEW
def show(self):
self.time_show = time.time()
self.osd.show()
self.osd.loop_once()
def move_to_line(self, line_num):
y = Aosd_conf.top_space + (line_num * (Aosd_conf.font_size + Aosd_conf.line_space))
self.osd.set_geometry(self.x, y, self.w, self.h)
self.osd.loop_once()
def _setup(self):
osd = aosd.AosdText()
osd.set_transparency(aosd.TRANSPARENCY_COMPOSITE)
if osd.get_transparency() != aosd.TRANSPARENCY_COMPOSITE:
osd.set_transparency(aosd.TRANSPARENCY_NONE)
osd.geom_x_offset = Aosd_conf.geom_x_offset
osd.geom_y_offset = Aosd_conf.geom_y_offset
osd.shadow_color = Aosd_conf.shadow_color
osd.shadow_opacity = Aosd_conf.shadow_opacity
osd.shadow_x_offset = Aosd_conf.shadow_x_offset
osd.shadow_y_offset = Aosd_conf.shadow_y_offset
osd.fore_color = self.color
osd.fore_opacity = Aosd_conf.fore_opacity
osd.set_font("%s %d" % (Aosd_conf.font, Aosd_conf.font_size))
osd.wrap = aosd.PANGO_WRAP_WORD_CHAR
osd.alignment = aosd.PANGO_ALIGN_LEFT
osd.set_layout_width(osd.get_screen_wrap_width())
osd.set_text(unicode(self.text, 'UTF-8', 'ignore'))
self.w, self.h = osd.get_text_size()
(screen_w, screen_h) = osd.get_screen_size()
self.x = screen_w - ((screen_w * Aosd_conf.use_screen_width_percent) / 100)
self.osd = osd
class Aosd_text_scroll(object):
def __init__(self):
utils.init_from_args(self)
self.osd = aosd.Aosd()
self.entries = list()
self.last_line = 0
self.todo_new = 0
def append(self, text, color, timeout=Aosd_conf.entry_timeout):
entry = Aosd_text_scroll_entry(text, color, timeout)
self.entries.append(entry)
self.todo_new += 1
def render(self):
(screen_w, screen_h) = self.osd.get_screen_size()
self.entries_max = ((screen_h * Aosd_conf.use_screen_heigh_percent) / 100) / (Aosd_conf.font_size + Aosd_conf.line_space)
self.time_render = time.time()
self._render_1_remove_old()
self._render_2_scroll_remaining()
self._render_3_append_new()
def _render_1_remove_old(self):
self.todo_scroll = 0
n = -1
to_remove = []
for entry in self.entries:
n += 1
if len(self.entries) < self.entries_max:
if entry.state != Aosd_text_scroll_entry.STATE_SHOW:
continue
if entry.time_show + entry.timeout > self.time_render:
continue
if entry == self.entries[-1]:
self.last_line = n
if Aosd_conf.remove_keep_order:
to_remove.append(entry)
else:
# Was originally a bug because removing items in a python list
# while iterating over it skips the next item
# However this gives a nice visual effect because only half of
# the lines disappear at each round
self.entries.remove(entry)
del entry
self.todo_scroll += 1
for rem in to_remove:
self.entries.remove(rem)
del rem
def _render_2_scroll_remaining(self):
if self.last_line < self.entries_max:
if self.todo_scroll == 0:
return
if len(self.entries) + self.todo_new < self.entries_max:
# do not scroll when not necessary
return
n = -1
for entry in self.entries:
n += 1
if entry.state != Aosd_text_scroll_entry.STATE_SHOW:
continue
entry.move_to_line(n)
self.last_line = n
self.todo_scroll = 0
def _render_3_append_new(self):
if self.todo_new == 0:
return
n = -1
for entry in self.entries:
n += 1
if entry.state != Aosd_text_scroll_entry.STATE_NEW:
continue
entry.move_to_line(self.last_line)
self.last_line += 1
entry.show()
entry.state = Aosd_text_scroll_entry.STATE_SHOW
self.todo_new = 0
class Aosd_text_scroll_thread(Aosd_text_scroll, threading.Thread):
def __init__(self, **kwargs):
Aosd_text_scroll.__init__(self, **kwargs)
threading.Thread.__init__(self)
self.queue = Queue.Queue()
def run(self): # Thread
while True:
try:
to_append = self.queue.get(True, 0.1) # XXX ugly timeout
except Queue.Empty:
pass
else:
if to_append[0] == "exit":
thread.exit()
Aosd_text_scroll.append(self, to_append[0], to_append[1], to_append[2])
Aosd_text_scroll.render(self)
def append(self, text, color, timeout=Aosd_conf.entry_timeout): # Aosd_text_scroll
to_append = [text, color, timeout]
self.queue.put_nowait(to_append)
def render(self): # Aosd_text_scroll
raise Exception("You should not call render on this class, it is already done inside the thread")
def exit(self):
self.append("exit", "now")
|
Python
| 0
|
@@ -5611,36 +5611,9 @@
lf,
-to_append%5B0%5D, to_append%5B1%5D,
+*
to_a
@@ -5621,11 +5621,8 @@
pend
-%5B2%5D
)%0A
@@ -5769,17 +5769,17 @@
ppend =
-%5B
+(
text, co
@@ -5790,17 +5790,17 @@
timeout
-%5D
+)
%0A
|
03ea21b744a1c499348a3d1b1ad87258efee1e33
|
add helpful StrictJsonObject object
|
dimagi/ext/jsonobject.py
|
dimagi/ext/jsonobject.py
|
from __future__ import absolute_import
import datetime
import decimal
from jsonobject.base_properties import AbstractDateProperty
from jsonobject import *
import re
from jsonobject.api import re_date, re_time, re_decimal
from dimagi.utils.dates import safe_strftime
from dimagi.utils.parsing import ISO_DATETIME_FORMAT
from django.conf import settings
OldJsonObject = JsonObject
OldDateTimeProperty = DateTimeProperty
HISTORICAL_DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
try:
# this isn't actually part of dimagi-utils
# but this is temporary and don't want to do a bigger reorg
from corehq.util.soft_assert import soft_assert
except ImportError:
def _assert(assertion, msg):
assert assertion, msg
else:
_assert = soft_assert('{}@{}'.format('droberts', 'dimagi.com'),
# should still fail in tests
fail_if_debug=settings.UNIT_TESTING)
class DateTimeProperty(AbstractDateProperty):
"""
Accepts and produces ISO8601 string in UTC (with the Z suffix)
Accepts with or without microseconds (must have all six digits if any)
Always produces with microseconds
(USec stands for microsecond)
"""
_type = datetime.datetime
def _wrap(self, value):
if '.' in value:
fmt = ISO_DATETIME_FORMAT
if len(value.split('.')[-1]) != 7:
raise ValueError(
'USecDateTimeProperty '
'must have 6 decimal places '
'or none at all: {}'.format(value)
)
else:
fmt = HISTORICAL_DATETIME_FORMAT
try:
result = datetime.datetime.strptime(value, fmt)
except ValueError as e:
raise ValueError(
'Invalid date/time {0!r} [{1}]'.format(value, e))
_assert(result.tzinfo is None,
"USecDateTimeProperty shouldn't ever return offset-aware!")
return result
def _unwrap(self, value):
_assert(value.tzinfo is None,
"Can't set a USecDateTimeProperty to an offset-aware datetime")
return value, safe_strftime(value, '%Y-%m-%dT%H:%M:%S.%fZ')
re_trans_datetime = re.compile("""
^
(\d{4}) # year
-
(0[1-9]|1[0-2]) # month
-
([12]\d|0[1-9]|3[01]) # day
T
([01]\d|2[0-3]) # hour
:
[0-5]\d # minute
:
[0-5]\d # second
(\.\d{6})? # millisecond (optional)
Z # timezone
$
""", re.VERBOSE)
# this is like jsonobject.api.re_datetime,
# but without the "time" part being optional
# i.e. I just removed (...)? surrounding the second two lines
re_loose_datetime = re.compile("""
^
(\d{4}) # year
\D?
(0[1-9]|1[0-2]) # month
\D?
([12]\d|0[1-9]|3[01]) # day
[ T]
([01]\d|2[0-3]) # hour
\D?
([0-5]\d) # minute
\D?
([0-5]\d)? # second
\D?
(\d{3,6})? # millisecond
([zZ]|([\+-])([01]\d|2[0-3])\D?([0-5]\d)?)? # timezone
$
""", re.VERBOSE)
class USecDateTimeMeta(object):
update_properties = {
datetime.datetime: DateTimeProperty,
}
string_conversions = (
(re_date, datetime.date),
(re_time, datetime.time),
(re_trans_datetime, datetime.datetime),
(re_decimal, decimal.Decimal),
)
class JsonObject(OldJsonObject):
Meta = USecDateTimeMeta
|
Python
| 0.004985
|
@@ -3360,8 +3360,84 @@
imeMeta%0A
+%0A%0Aclass StrictJsonObject(JsonObject):%0A _allow_dynamic_properties = False%0A
|
09e1a63ed487375b308465bfb24badffe361f182
|
change variable and function names
|
dusty/compiler/port_spec/__init__.py
|
dusty/compiler/port_spec/__init__.py
|
from dusty.constants import LOCALHOST
class ReusedHostFullAddress(Exception):
pass
class ReusedContainerPort(Exception):
pass
def _docker_compose_port_spec(host_forwarding_spec, host_port):
return {'in_container_port': str(host_forwarding_spec['container_port']),
'mapped_host_ip': LOCALHOST,
'mapped_host_port': str(host_port)}
def _virtualbox_port_spec(port):
return {'guest_ip': LOCALHOST,
'guest_port': str(port),
'host_ip': LOCALHOST,
'host_port': str(port)}
def _nginx_port_spec(host_forwarding_spec, port):
return {'proxied_ip': LOCALHOST,
'proxied_port': str(port),
'host_address': host_forwarding_spec['host_name'],
'host_port': str(host_forwarding_spec['host_port'])}
def _hosts_file_port_spec(host_forwarding_spec):
return {'forwarded_ip': LOCALHOST,
'host_address': host_forwarding_spec['host_name']}
def host_forwarding_spec_document(host_forwarding_spec, forwarding_port, container_ports, host_full_addresses, host_names):
""" Given a specific host_forwarding dictionary found in an dusty app spec, it will return the port_mappings for that
host_forwarding. Currently this will include docker_compose, virtualbox, nginx and hosts_file"""
port_spec = {'docker_compose': None, 'virtualbox': None, 'nginx': None, 'hosts_file': None}
container_port = host_forwarding_spec['container_port']
host_name = host_forwarding_spec['host_name']
host_full_address = '{}:{}'.format(host_name, host_forwarding_spec['host_port'])
if host_full_address in host_full_addresses:
raise ReusedHostFullAddress("{} has already been specified and used".format(host_full_address))
host_full_addresses.add(host_full_address)
if container_port in container_ports:
raise ReusedContainerPort("{} has already been specified and used".format(container_port))
container_ports.add(container_port)
port_spec['docker_compose'] = _docker_compose_port_spec(host_forwarding_spec, forwarding_port)
port_spec['virtualbox'] = _virtualbox_port_spec(forwarding_port)
port_spec['nginx'] = _nginx_port_spec(host_forwarding_spec, forwarding_port)
if host_name not in host_names:
port_spec['hosts_file'] = _hosts_file_port_spec(host_forwarding_spec)
host_names.add(host_name)
return port_spec
def port_spec_document(expanded_active_specs):
""" Given a dictionary containing the expanded dusty DAG specs this function will
return a dictionary containing the port mappings needed by downstream methods. Currently
this includes docker_compose, virtualbox, nginx and hosts_file."""
forwarding_port = 65000
port_spec = {'docker_compose':{}, 'virtualbox':[], 'nginx':[], 'hosts_file':[]}
host_full_addresses = set()
host_names = set()
# No matter the order of apps in expanded_active_specs, we want to produce a consistent
# port_spec with respect to the apps and the ports they are outputted on
for app_name in sorted(expanded_active_specs['apps'].keys()):
app_spec = expanded_active_specs['apps'][app_name]
if 'host_forwarding' not in app_spec:
continue
container_ports = set()
for host_forwarding_spec in app_spec['host_forwarding']:
host_forwarding_port_spec = host_forwarding_spec_document(host_forwarding_spec, forwarding_port, container_ports, host_full_addresses, host_names)
port_spec['docker_compose'][app_name] = host_forwarding_port_spec['docker_compose']
port_spec['virtualbox'].append(host_forwarding_port_spec['virtualbox'])
port_spec['nginx'].append(host_forwarding_port_spec['nginx'])
if host_forwarding_port_spec['hosts_file'] is not None:
port_spec['hosts_file'].append(host_forwarding_port_spec['hosts_file'])
forwarding_port += 1
return port_spec
|
Python
| 0.000002
|
@@ -962,37 +962,37 @@
_forwarding_
-spec_document
+port_mappings
(host_forwar
@@ -1294,36 +1294,40 @@
ile%22%22%22%0A port_
-spec
+mappings
= %7B'docker_comp
@@ -1972,36 +1972,40 @@
port)%0A%0A port_
-spec
+mappings
%5B'docker_compose
@@ -2075,36 +2075,40 @@
_port)%0A port_
-spec
+mappings
%5B'virtualbox'%5D =
@@ -2148,36 +2148,40 @@
_port)%0A port_
-spec
+mappings
%5B'nginx'%5D = _ngi
@@ -2273,36 +2273,40 @@
s:%0A port_
-spec
+mappings
%5B'hosts_file'%5D
@@ -2401,20 +2401,24 @@
rn port_
-spec
+mappings
%0A%0A%0Adef p
@@ -3391,29 +3391,29 @@
warding_
-spec_document
+port_mappings
(host_fo
|
9cb731c00bfc58c3a64b92fc3aa5140968fead43
|
update copyright
|
framework_agreement_sourcing/wizard/cost_estimate.py
|
framework_agreement_sourcing/wizard/cost_estimate.py
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Nicolas Bessi
# Copyright 2013 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm
from openerp.tools.translate import _
from .logistic_requisition_source import AGR_PROC
class logistic_requisition_cost_estimate(orm.TransientModel):
"""Add update of agreement price"""
_inherit = "logistic.requisition.cost.estimate"
def _prepare_cost_estimate_line(self, cr, uid, sourcing, context=None):
"""Override in order to update agreement source line
"""
res = super(logistic_requisition_cost_estimate,
self)._prepare_cost_estimate_line(cr, uid, sourcing,
context=context)
if sourcing.procurement_method == AGR_PROC:
res['type'] = 'make_to_order'
res['sale_flow'] = 'direct_delivery'
return res
def _link_po_lines_to_so_lines(self, cr, uid, so, sources, context=None):
"""Naive implementation to link all PO lines to SO lines.
For our actuall need we want to link all service line
to SO real product lines.
There should not be twice the same product on differents
Agreement PO line so this case in not handled
"""
so_lines = [x for x in so.order_line if x.product_id]
po_lines = set(x.purchase_line_id for x in sources
if x.purchase_line_id)
product_dict = dict((x.product_id.id, x.id) for x in so_lines
if x.product_id)
default = product_dict[product_dict.keys()[0]]
if not product_dict:
raise orm.except_orm(_('No stockable product in related PO'),
_('Please add one'))
for po_line in po_lines:
key = po_line.product_id.id if po_line.product_id else False
po_line.write(
{'sale_order_line_id': product_dict.get(key, default)})
def cost_estimate(self, cr, uid, ids, context=None):
"""Override to link PO to cost_estimate$
In a normal flow, when you chose a bid as the winning one, the bid is
dupplicated to generate the draft PO. On this action, it link the LRS
to the generated PO line.
In a tender flow, we don't dupplicate the bid, it's only a PO. The link
between the LRS and the PO line should then be created here.
This is for the drop shipping to work propely cause in that case, SO
and PO are linked together.
"""
so_model = self.pool['sale.order']
po_model = self.pool['purchase.order']
assert len(ids) == 1
wizard = self.browse(cr, uid, ids, context=context)
res = super(logistic_requisition_cost_estimate,
self).cost_estimate(cr, uid, ids, context=context)
so_id = res['res_id']
order = so_model.browse(cr, uid, so_id, context=context)
sources = []
for lrl in wizard.line_ids:
for source in lrl.source_ids:
if source.procurement_method == AGR_PROC:
sources.append(source)
po_ids = set(x.purchase_line_id.order_id.id for x in sources
if x.purchase_line_id)
if po_ids:
po_model.write(cr, uid, list(po_ids),
{'sale_id': so_id,
'sale_flow': 'direct_delivery'})
self._link_po_lines_to_so_lines(
cr, uid, order, sources, context=context)
return res
|
Python
| 0
|
@@ -144,16 +144,22 @@
ght 2013
+, 2014
Camptoc
|
9ad697081f62b63f966f998b6618bfb543717f4a
|
Allow to pass more attributes.
|
webapp/bootstrap/helpers.py
|
webapp/bootstrap/helpers.py
|
# -*- coding: utf-8 -*-
from byceps.blueprints.brand.models import Brand
from byceps.blueprints.orga.models import OrgaFlag, OrgaTeam, \
Membership as OrgaTeamMembership
from byceps.blueprints.party.models import Party
from byceps.blueprints.seating.models import Area as SeatingArea, \
Category as SeatingCategory, Point, Seat
from byceps.blueprints.snippet.models import Snippet, SnippetVersion, \
Mountpoint as SnippetMountpoint
from byceps.blueprints.terms.models import Version as TermsVersion
from byceps.blueprints.user.models import User
from byceps.blueprints.user_group.models import UserGroup
from .util import add_to_database
# -------------------------------------------------------------------- #
# brands
@add_to_database
def create_brand(id, title):
return Brand(id=id, title=title)
def get_brand(id):
return Brand.query.get(id)
# -------------------------------------------------------------------- #
# parties
@add_to_database
def create_party(**kwargs):
return Party(**kwargs)
def get_party(id):
return Party.query.get(id)
# -------------------------------------------------------------------- #
# users
@add_to_database
def create_user(screen_name, email_address, password, *, enabled=False):
user = User.create(screen_name, email_address, password)
user.enabled = enabled
return user
def get_user(screen_name):
return User.query.filter_by(screen_name=screen_name).one()
# -------------------------------------------------------------------- #
# orga teams
@add_to_database
def promote_orga(brand, user):
return OrgaFlag(brand=brand, user=user)
@add_to_database
def create_orga_team(id, title):
return OrgaTeam(id=id, title=title)
@add_to_database
def assign_user_to_orga_team(user, orga_team, party, *, duties=None):
membership = OrgaTeamMembership(orga_team=orga_team, party=party, user=user)
if duties:
membership.duties = duties
return membership
def get_orga_team(id):
return OrgaTeam.query.get(id)
# -------------------------------------------------------------------- #
# user groups
@add_to_database
def create_user_group(creator, title, description=None):
return UserGroup(creator, title, description)
# -------------------------------------------------------------------- #
# snippets
@add_to_database
def create_snippet(party, name):
return Snippet(party=party, name=name)
@add_to_database
def create_snippet_version(snippet, creator, title, body):
return SnippetVersion(snippet=snippet, creator=creator, title=title, body=body)
@add_to_database
def mount_snippet(snippet, endpoint_suffix, url_path):
return SnippetMountpoint(snippet=snippet, endpoint_suffix=endpoint_suffix, url_path=url_path)
# -------------------------------------------------------------------- #
# terms
@add_to_database
def create_terms_version(brand, creator, body):
return TermsVersion(brand=brand, creator=creator, body=body)
# -------------------------------------------------------------------- #
# seating
@add_to_database
def create_seating_area(party, slug, title):
return SeatingArea(party=party, slug=slug, title=title)
@add_to_database
def create_seat_category(party, title):
return SeatingCategory(party=party, title=title)
@add_to_database
def create_seat(area, coord_x, coord_y, category):
seat = Seat(area=area, category=category)
seat.coords = Point(x=coord_x, y=coord_y)
return seat
|
Python
| 0
|
@@ -3110,24 +3110,34 @@
slug, title
+, **kwargs
):%0A retur
@@ -3177,32 +3177,42 @@
lug, title=title
+, **kwargs
)%0A%0A%0A@add_to_data
|
7e45a26f86095ee2f6972e08697aa132e642636e
|
Test for types in __mul__
|
csympy/tests/test_arit.py
|
csympy/tests/test_arit.py
|
from csympy import Symbol, Integer
def test_arit1():
x = Symbol("x")
y = Symbol("y")
e = x + y
e = x * y
e = Integer(2)*x
e = 2*x
def test_arit2():
x = Symbol("x")
y = Symbol("y")
assert x+x == Integer(2) * x
assert x+x != Integer(3) * x
assert x+x == 2 * x
|
Python
| 0.000004
|
@@ -1,8 +1,39 @@
+from nose.tools import raises%0A%0A
from csy
@@ -324,12 +324,104 @@
+x == 2 * x%0A
+%0A@raises(TypeError)%0Adef test_arit3():%0A x = Symbol(%22x%22)%0A y = Symbol(%22y%22)%0A e = %22x%22*x%0A
|
852c62eef3d9beea43927f75b1a8aaa021ce25f9
|
Add a docstring to test helper
|
test/selenium/src/lib/test_helpers.py
|
test/selenium/src/lib/test_helpers.py
|
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: jernej@reciprocitylabs.com
# Maintained By: jernej@reciprocitylabs.com
"""
Utility classes for page objects used in tests.
Details:
Most of the tests require a sequence of primitive methods of the page
object. If the sequence repeats itself among tests, it should be shared in
this module.
"""
import uuid
from lib import base
from lib.constants.test import modal_create_new
from lib.constants.test import modal_custom_attribute
class HtmlParser(base.Test):
@staticmethod
def parse_text(text):
"""Simulates text parsed by html
Args:
text (str)
"""
return text.replace(" ", "").replace("\n", "")
class ModalNewProgramPage(base.Test):
"""Methods for simulating common user actions"""
@staticmethod
def enter_test_data(modal):
"""Fills out all fields in the lhn_modal
Args:
modal (lib.page.lhn_modal.new_program.EditProgramModal)
"""
unique_id = str(uuid.uuid4())
modal.enter_title(modal_create_new.Program.TITLE + unique_id)
modal.enter_description(
modal_create_new.Program.DESCRIPTION_SHORT + unique_id)
modal.enter_notes(
modal_create_new.Program.NOTES_SHORT + unique_id)
modal.enter_code(modal_create_new.Program.CODE + unique_id)
modal.filter_and_select_primary_contact("example")
modal.filter_and_select_secondary_contact("example")
modal.enter_program_url(
unique_id + modal_create_new.Program.PROGRAM_URL)
modal.enter_reference_url(
unique_id + modal_create_new.Program.REFERENCE_URL)
@staticmethod
def set_start_end_dates(modal, day_start, day_end):
"""
Sets the dates from the datepicker in the new program/edit modal.
Args:
modal (lib.page.lhn_modal.new_program.EditProgramModal)
day_start (int): for more info see
base.DatePicker.select_day_in_current_month
day_end (int): for more info see
base.DatePicker.select_day_in_current_month
"""
modal.enter_effective_date_start_month(day_start)
modal.enter_stop_date_end_month(day_end)
class ModalNewProgramCustomAttribute(base.Test):
@staticmethod
def enter_test_data(modal):
"""Fills out all fields in the lhn_modal
Args:
modal (lib.page.widget.custom_attribute.NewCustomAttributeModal)
"""
modal.enter_title(modal_custom_attribute.Program.TITLE)
modal.enter_inline_help(modal_custom_attribute.Program.INLINE_HELP)
modal.enter_placeholder(modal_custom_attribute.Program.PLACEHOLDER)
|
Python
| 0.000001
|
@@ -620,32 +620,116 @@
ser(base.Test):%0A
+ %22%22%22The HtmlParser class simulates what happens with (non-rich)text in HTML.%0A %22%22%22%0A
@staticmethod%0A
|
cfca983b909c4919d8478e81fca66bf01af80c74
|
Fix failing tests.
|
test/services/updater/test_updater.py
|
test/services/updater/test_updater.py
|
import os
import logging
import time
from threading import Semaphore, Thread, Event
from unittest.mock import patch, Mock
import git
from weavelib.messaging import Receiver, Sender
from weavelib.rpc import RPCClient
from weaveserver.core.services import ServiceManager
from weaveserver.services.updater.service import UpdaterService, UpdateScanner
from weaveserver.services.updater.service import Updater
AUTH = {
"auth1": {
"type": "SYSTEM",
"appid": "appmgr",
"package": "p",
},
"auth2": {
"appid": "appid2"
}
}
class TestUpdateScanner(object):
def setup_method(self):
self.update_check_freq_backup = UpdateScanner.UPDATE_CHECK_FREQ
UpdateScanner.UPDATE_CHECK_FREQ = 5
os.environ["USE_FAKE_REDIS"] = "TRUE"
self.service_manager = ServiceManager()
self.service_manager.apps = AUTH
self.service_manager.start_services(["messaging", "appmanager"])
def teardown_method(self):
del os.environ["USE_FAKE_REDIS"]
self.service_manager.stop()
def test_simple_update(self):
mock_repo = Mock()
mock_repo.needs_pull = Mock(return_value=False)
UpdateScanner.list_repos = lambda x, y: ["dir"]
UpdateScanner.get_repo = lambda x, y: mock_repo
started = Event()
service = UpdaterService("auth1", None)
service.before_service_start()
service.notify_start = started.set
Thread(target=service.on_service_start).start()
started.wait()
while service.get_status() != "No updates available.":
time.sleep(1)
mock_repo.asssert_called_with("dir")
mock_repo.needs_pull = Mock(return_value=True)
time.sleep(8)
assert service.get_status() == "Updates available."
service.on_service_stop()
def test_trigger_update_when_no_update(self):
UpdateScanner.UPDATE_CHECK_FREQ = 1000
mock_repo = Mock()
mock_repo.needs_pull = Mock(return_value=False)
UpdateScanner.list_repos = lambda x, y: ["dir"]
UpdateScanner.get_repo = lambda x, y: mock_repo
started = Event()
service = UpdaterService("auth1", None)
service.before_service_start()
service.notify_start = started.set
Thread(target=service.on_service_start).start()
started.wait()
service.update_status("dummy")
rpc = RPCClient(service.rpc.info_message)
rpc.start()
print("RPC:", rpc["perform_upgrade"](_block=True))
assert service.get_status() == "No updates available."
service.on_service_stop()
|
Python
| 0.000003
|
@@ -870,15 +870,21 @@
apps
- =
+.update(
AUTH
+)
%0A
|
9236d16b8013e3c71f57d43136be3b9640c56ee3
|
Fixed a Python 2.3 incompatibility.
|
django/test/testcases.py
|
django/test/testcases.py
|
import re, unittest
from urlparse import urlparse
from django.db import transaction
from django.core import management, mail
from django.db.models import get_apps
from django.test import _doctest as doctest
from django.test.client import Client
normalize_long_ints = lambda s: re.sub(r'(?<![\w])(\d+)L(?![\w])', '\\1', s)
class OutputChecker(doctest.OutputChecker):
def check_output(self, want, got, optionflags):
ok = doctest.OutputChecker.check_output(self, want, got, optionflags)
# Doctest does an exact string comparison of output, which means long
# integers aren't equal to normal integers ("22L" vs. "22"). The
# following code normalizes long integers so that they equal normal
# integers.
if not ok:
return normalize_long_ints(want) == normalize_long_ints(got)
return ok
class DocTestRunner(doctest.DocTestRunner):
def __init__(self, *args, **kwargs):
doctest.DocTestRunner.__init__(self, *args, **kwargs)
self.optionflags = doctest.ELLIPSIS
def report_unexpected_exception(self, out, test, example, exc_info):
doctest.DocTestRunner.report_unexpected_exception(self,out,test,example,exc_info)
# Rollback, in case of database errors. Otherwise they'd have
# side effects on other tests.
from django.db import transaction
transaction.rollback_unless_managed()
class TestCase(unittest.TestCase):
def _pre_setup(self):
"""Perform any pre-test setup. This includes:
* If the Test Case class has a 'fixtures' member, clearing the
database and installing the named fixtures at the start of each test.
* Clearing the mail test outbox.
"""
management.flush(verbosity=0, interactive=False)
if hasattr(self, 'fixtures'):
management.load_data(self.fixtures, verbosity=0)
mail.outbox = []
def __call__(self, result=None):
"""
Wrapper around default __call__ method to perform common Django test
set up. This means that user-defined Test Cases aren't required to
include a call to super().setUp().
"""
self.client = Client()
self._pre_setup()
super(TestCase, self).__call__(result)
def assertRedirects(self, response, expected_path, status_code=302, target_status_code=200):
"""Assert that a response redirected to a specific URL, and that the
redirect URL can be loaded.
"""
self.assertEqual(response.status_code, status_code,
"Response didn't redirect as expected: Response code was %d (expected %d)" %
(response.status_code, status_code))
scheme, netloc, path, params, query, fragment = urlparse(response['Location'])
self.assertEqual(path, expected_path,
"Response redirected to '%s', expected '%s'" % (path, expected_path))
redirect_response = self.client.get(path)
self.assertEqual(redirect_response.status_code, target_status_code,
"Couldn't retrieve redirection page '%s': response code was %d (expected %d)" %
(path, redirect_response.status_code, target_status_code))
def assertContains(self, response, text, count=None, status_code=200):
"""Assert that a response indicates that a page was retreived successfully,
(i.e., the HTTP status code was as expected), and that ``text`` occurs ``count``
times in the content of the response. If ``count`` is None, the count doesn't
matter - the assertion is true if the text occurs at least once in the response.
"""
self.assertEqual(response.status_code, status_code,
"Couldn't retrieve page: Response code was %d (expected %d)'" %
(response.status_code, status_code))
real_count = response.content.count(text)
if count is not None:
self.assertEqual(real_count, count,
"Found %d instances of '%s' in response (expected %d)" % (real_count, text, count))
else:
self.assertTrue(real_count != 0, "Couldn't find '%s' in response" % text)
def assertFormError(self, response, form, field, errors):
"Assert that a form used to render the response has a specific field error"
if not response.context:
self.fail('Response did not use any contexts to render the response')
# If there is a single context, put it into a list to simplify processing
if not isinstance(response.context, list):
contexts = [response.context]
else:
contexts = response.context
# If a single error string is provided, make it a list to simplify processing
if not isinstance(errors, list):
errors = [errors]
# Search all contexts for the error.
found_form = False
for i,context in enumerate(contexts):
if form in context:
found_form = True
for err in errors:
if field:
if field in context[form].errors:
self.failUnless(err in context[form].errors[field],
"The field '%s' on form '%s' in context %d does not contain the error '%s' (actual errors: %s)" %
(field, form, i, err, list(context[form].errors[field])))
elif field in context[form].fields:
self.fail("The field '%s' on form '%s' in context %d contains no errors" %
(field, form, i))
else:
self.fail("The form '%s' in context %d does not contain the field '%s'" % (form, i, field))
else:
self.failUnless(err in context[form].non_field_errors(),
"The form '%s' in context %d does not contain the non-field error '%s' (actual errors: %s)" %
(form, i, err, list(context[form].non_field_errors())))
if not found_form:
self.fail("The form '%s' was not used to render the response" % form)
def assertTemplateUsed(self, response, template_name):
"Assert that the template with the provided name was used in rendering the response"
if isinstance(response.template, list):
template_names = [t.name for t in response.template]
self.failUnless(template_name in template_names,
u"Template '%s' was not one of the templates used to render the response. Templates used: %s" %
(template_name, u', '.join(template_names)))
elif response.template:
self.assertEqual(template_name, response.template.name,
u"Template '%s' was not used to render the response. Actual template was '%s'" %
(template_name, response.template.name))
else:
self.fail('No templates used to render the response')
def assertTemplateNotUsed(self, response, template_name):
"Assert that the template with the provided name was NOT used in rendering the response"
if isinstance(response.template, list):
self.failIf(template_name in [t.name for t in response.template],
u"Template '%s' was used unexpectedly in rendering the response" % template_name)
elif response.template:
self.assertNotEqual(template_name, response.template.name,
u"Template '%s' was used unexpectedly in rendering the response" % template_name)
|
Python
| 0.999738
|
@@ -4185,18 +4185,18 @@
elf.
-assertTrue
+failUnless
(rea
|
665ece3f699d6a62be0d9c859532ae73e250d86f
|
Update __init__.py
|
wellapplication/__init__.py
|
wellapplication/__init__.py
|
# -*- coding: utf-8 -*-
__version__ = '0.2.24'
__author__ = 'Paul Inkenbrandt'
__name__ = 'wellapplication'
from transport import *
from usgs import *
from chem import WQP
from graphs import piper, fdc, gantt
import MannKendall
import avgMeths
|
Python
| 0.000072
|
@@ -176,16 +176,38 @@
rt WQP%0D%0A
+from mesopy import *%0D%0A
from gra
|
f5e459e369f1a00d3407f7993e427b676047da21
|
bump version
|
django_anger/__init__.py
|
django_anger/__init__.py
|
__version__ = "0.1-20130513.try3"
|
Python
| 0
|
@@ -15,16 +15,18 @@
%220.1
+.1
-2013051
3.tr
@@ -25,12 +25,7 @@
3051
-3.try3
+6
%22%0A
|
6185d7d348487a28655967f7e2c19e71bc11c67e
|
remove norm function references
|
version3/python/mpin.py
|
version3/python/mpin.py
|
#
# Python 3.7 Code to implement basic MPIN protocol API
# M.Scott August 2018
#
import hashlib
from XXX import ecp
from XXX import ecp2
from XXX import curve
from XXX import big
from XXX.ecp import *
from XXX.ecp2 import *
from XXX import pair
from XXX.fp12 import *
# hash ID to point on curve
def H(mpin_id):
r = curve.r
p = curve.p
h = hashlib.new(curve.SHA)
h.update(bytes(mpin_id, 'utf-8'))
x = big.from_bytes(h.digest())
x %= p
P = ECp()
while not P.set(x):
x = x + 1
# work out co-factor
nb = p.bit_length()
cf = 1
cf = cf << (nb + 4) // 2
cf += p
cf //= r
if cf != 1:
P = cf * P
return P
def random_generate():
FS = curve.EFS
s = big.rand(curve.r)
Z = big.to_bytes(s)
return Z
def get_server_secret(Z):
Q = ecp2.generator()
s = big.from_bytes(Z)
Q = s * Q
return Q.toBytes()
def get_client_secret(Z, ID):
P = H(ID)
s = big.from_bytes(Z)
P = s * P
return P.toBytes(False)
# subtract pin.ID from Secret key SK to create Token
def extract_pin(ID, PIN, SK):
P = H(ID)
P = -(PIN * P)
S = ECp()
if not S.fromBytes(SK):
return bytearray(0)
S.add(P)
# S.affine()
return S.toBytes(False)
# U=xH(ID)
def client_1(ID, X):
P = H(ID)
if X:
w = big.from_bytes(X)
else:
w = big.rand(curve.r)
X = big.to_bytes(w)
P = w * P
return (X, P.toBytes(False))
# reconstitute Client secret S from Token and PIN
# V=(x+y)S
def client_2(X, Y, ID, PIN, TK):
P = H(ID)
S = ECp()
if not S.fromBytes(TK):
return bytearray(0)
x = big.from_bytes(X)
y = big.from_bytes(Y)
x = (x + y) % curve.r
x = curve.r - x
S.add(PIN * P)
S = x * S
return S.toBytes(False)
# authenticate
def server(ID, Y, SS, U, V):
P = H(ID)
y = big.from_bytes(Y)
Q = ecp2.generator()
P = y * P
print("Got here")
sQ = ECp2()
if not sQ.fromBytes(SS):
return (False, Fp12(), Fp12())
TU = ECp()
if not TU.fromBytes(U):
return (False, bytearray(0), bytearray(0))
TV = ECp()
if not TV.fromBytes(V):
return (False, bytearray(0), bytearray(0))
TU.add(P)
# TU.affine()
r = pair.double_miller(Q, TV, sQ, TU)
r = pair.fexp(r)
if r.isone():
return (True, bytearray(0), bytearray(0))
# failed - diagnose it
E = r.toBytes()
r = pair.e(Q, TU)
F = r.toBytes()
return (False, E, F)
MAXPIN = 10000
TS = 10
TRAP = 200
def kangaroo(E, F):
FS = curve.EFS
e = Fp12()
e.fromBytes(E)
f = Fp12()
f.fromBytes(F)
# Pollards Kangaroos
t = f.copy()
distance = []
table = []
s = 1
for m in range(0, TS):
distance.append(s)
table.append(t.copy())
s *= 2
t.usqr()
t = Fp12.one()
# set trap
dn = 0
for j in range(0, TRAP):
i = t.a.a.a.int() % TS
t *= table[i]
dn += distance[i]
# release wild kangaroo
f = t.copy()
f.conj()
steps = 0
dm = 0
while dm - dn < MAXPIN:
steps = steps + 1
if steps > 4 * TRAP:
break
i = e.a.a.a.int() % TS
e *= table[i]
dm += distance[i]
if e == t:
res = dm - dn
break
if e == f:
res = dn - dm
break
if steps > 4 * TRAP or dm - dn >= MAXPIN:
res = 0
return res
def add_G1(A, B):
""" Add two points in G1: C = A + B """
A1 = ECp()
B1 = ECp()
if not A1.fromBytes(A):
return None
if not B1.fromBytes(B):
return None
A1.add(B1)
A1.norm()
return A1.toBytes(False)
def add_G2(A, B):
""" Add two points in G2: C = A + B """
A1 = ECp2()
B1 = ECp2()
if not A1.fromBytes(A):
return None
if not B1.fromBytes(B):
return None
A1.add(B1)
A1.norm()
return A1.toBytes()
|
Python
| 0.000001
|
@@ -1937,29 +1937,8 @@
* P%0A
- print(%22Got here%22)
%0A
@@ -2113,19 +2113,16 @@
ray(0))%0A
-
%0A TV
@@ -2208,20 +2208,16 @@
ray(0))%0A
-
%0A TU.
@@ -3646,38 +3646,24 @@
A1.add(B1)%0A
- A1.norm()%0A
return A
@@ -3890,22 +3890,8 @@
B1)%0A
- A1.norm()%0A
|
34db4460aa67fc9abfaaaf2c48a6ea7c5b801ff0
|
Fix for libtest for cpython 2.6 / jython / pypy
|
examples/libtest/imports/__init__.py
|
examples/libtest/imports/__init__.py
|
exec_order = []
class Imports(object):
exec_order = exec_order
def __init__(self):
self.v = 1
imports = Imports()
overrideme = "not overridden"
from . import cls as loccls
from .imports import cls as upcls
def conditional_func():
return "not overridden"
if True:
def conditional_func():
return "overridden"
|
Python
| 0.000001
|
@@ -190,38 +190,125 @@
cls%0A
-from .imports import cls as up
+%0A# This is not valid since Python 2.6!%0Atry:%0A from .imports import cls as upcls%0Aexcept ImportError:%0A upcls = loc
cls%0A
|
e354eba380c6df2f0a14e324da9cbe6467494ddc
|
add - ModelIORedis & build up interface.
|
versus/tools/modelIO.py
|
versus/tools/modelIO.py
|
"""
Class family for Model IO classes to handle read/write of learning models
"""
class ModelIO(object):
def __init__(self):
pass
def write(self):
raise NotImplementedError()
|
Python
| 0
|
@@ -76,16 +76,31 @@
ls%0A%22%22%22%0A%0A
+import redis%0A%0A%0A
class Mo
@@ -132,24 +132,34 @@
_init__(self
+, **kwargs
):%0A p
@@ -181,16 +181,23 @@
ite(self
+, model
):%0A
@@ -226,8 +226,687 @@
dError()
+%0A%0A def validate(self, model):%0A %22%22%22 Ensures that the model is valid. %22%22%22%0A pass%0A%0A def genkey(self, model):%0A %22%22%22 Generates a key from the model. Presumes model is valid. %22%22%22%0A return str(model)%0A%0A def package(self, model):%0A %22%22%22 Prepares the model for writing. %22%22%22%0A return model%0A%0A%0Aclass ModelIORedis(ModelIO):%0A %22%22%22 Performs IO to redis. %22%22%22%0A%0A def __init__(self, **kwargs):%0A super(ModelIORedis, self).__init__(**kwargs)%0A%0A def write(self, model):%0A%0A pool = redis.ConnectionPool(host='localhost', port=6379, db=0)%0A r = redis.Redis(connection_pool=pool)%0A%0A r.set(self.genkey(model), self.package(model))
|
c1135762c32526b3dc70c186ab97404ac27422e6
|
Handle missing plugin directory
|
repository.py
|
repository.py
|
import re
import os
import ttimer
import logging
import subprocess
import plugin
import static
class Repository():
def __init__(self, path):
self.ttl = static.ttl
self.path = path
self.system = static.system.lower()
self.logger = logging.getLogger('default')
self.load_plugins()
def pop_plugin(self, id):
i = 0
for p in self.plugins:
if p.id == id:
return self.plugins.pop(i)
i += 1
def get_plugin(self, id):
i = 0
for p in self.plugins:
if p.id == id:
return p
i += 1
return None
def get_plugins(self):
if hasattr(self, 'plugins'):
return self.plugins
return None
def start_plugins(self):
for p in self.plugins:
if not p.status(): p.start()
def reload_plugins(self):
old_ids = []
new_ids = []
# Build up lists with identifers before and after reload
for new in self.read_dir():
new_ids += [new]
for old in self.get_plugins():
old_ids += [old.id]
removed_plugins = set(old_ids) - set(new_ids)
added_plugins = set(new_ids) - set(old_ids)
# Stop threads for plugins that have been removed
for p in removed_plugins:
old_plugin = self.pop_plugin(p)
if old_plugin:
old_plugin.stop()
del old_plugin
# Add new plugins to list
for p in added_plugins:
self.logger.info('Adding ' + p + ' to polling list')
self.plugins += [plugin.Plugin(p, self.path, self.ttl)]
# Start stopped plugins
self.start_plugins()
def read_dir(self):
try:
files = os.listdir(self.path)
plugins = []
for file in files:
full_file_path = self.path + '/' + file
if os.path.isfile(full_file_path):
dotfile = re.compile('^\.')
anysystem = re.compile('-noarch\.[\w\d]+$')
cursystem = re.compile('-' + self.system + '\.[\w\d]+$')
# Skip dot-files
if dotfile.search(file):
self.logger.debug('Skipping dot-file: ' + file)
continue
# Add plugin to polling list if os or any match
if cursystem.search(file) or anysystem.search(file):
plugins += [file]
return plugins
except OSError as e:
self.logger.error('Failed to read directory \'' + self.path + '\': ' + e.strerror)
return None
def load_plugins(self):
files = self.read_dir()
self.plugins = []
for file in files:
try:
self.plugins += [plugin.Plugin(file, self.path, self.ttl)]
except plugin.PluginError as e:
self.logger.error(e)
self.logger.info('Loaded ' + str(len(self.plugins)) + ' plugins from ' + self.path)
return self.plugins
def config_load(self):
return # Do overrides to config values
def config_save(self):
return # Save runtime config to file
|
Python
| 0.000001
|
@@ -2221,16 +2221,29 @@
s = %5B%5D%0A%0A
+%09%09if files:%0A%09
%09%09for fi
@@ -2258,21 +2258,23 @@
les:%0A%09%09%09
+%09
try:%0A
+%09
%09%09%09%09self
@@ -2331,16 +2331,17 @@
tl)%5D%0A%09%09%09
+%09
except p
@@ -2364,16 +2364,17 @@
r as e:%0A
+%09
%09%09%09%09self
|
4b9da366b4169caf8802dcbbf20168512cc4e12e
|
Fix typo
|
ostrich/stages/stage_30_clone_osa.py
|
ostrich/stages/stage_30_clone_osa.py
|
# 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.
from ostrich import steps
from ostrich import utils
def _ansible_debug(r):
if r.complete['ansbile-debug'] == 'yes':
return 1
return 0
def get_steps(r):
"""Clone OSA."""
nextsteps = []
nextsteps.append(
steps.SimpleCommandStep(
'git-clone-osa',
('git clone %s/openstack/openstack-ansible '
'/opt/openstack-ansible'
% r.complete['git-mirror-openstack']),
**r.kwargs
)
)
nextsteps.append(
steps.KwargsStep(
'kwargs-osa',
r,
{
'cwd': '/opt/openstack-ansible',
'env': {
'ANSIBLE_ROLE_FETCH_MODE': 'git-clone',
'ANSIBLE_DEBUG': _ansible_debug(r),
'ANSIBLE_KEEP_REMOTE_FILES': '1'
}
},
**r.kwargs
)
)
if utils.is_ironic(r):
nextsteps.append(
steps.KwargsStep(
'kwargs-ironic',
r,
{
'env': {
'BOOTSTRAP_OPTS': 'nova_virt_type=ironic'
}
},
**r.kwargs
)
)
return nextsteps
|
Python
| 0.999999
|
@@ -641,10 +641,10 @@
'ans
-b
i
+b
le-d
|
62f137072aa26999ad30dda01fe2a736c3e00495
|
exclude in admin
|
django_typograf/admin.py
|
django_typograf/admin.py
|
from django.contrib import admin
from django_typograf.utils import get_typograf_field_name, get_typograf_hash_field_name
class TypografAdmin(admin.ModelAdmin):
""" Admin class for hide typograf fields from admin site """
def _exclude(self, obj=None):
""" Mark typograf fields as exclude """
exclude = ()
if obj:
exclude += tuple((get_typograf_field_name(field) for field in obj._meta.typografed_fields))
exclude += tuple((get_typograf_hash_field_name(field) for field in obj._meta.typografed_fields))
return exclude
def get_form(self, request, obj=None, **kwargs):
self.exclude = self.exclude or ()
self.exclude += self._exclude(obj)
return super().get_form(request, obj, **kwargs)
|
Python
| 0.00006
|
@@ -631,37 +631,32 @@
wargs):%0A
-self.
exclude = self.e
@@ -676,21 +676,16 @@
-self.
exclude
@@ -706,16 +706,61 @@
de(obj)%0A
+ kwargs.update(dict(exclude=exclude))%0A
|
1ba74fc225d71bc071827291d9942738ef56dd1f
|
Correct login view
|
apps/__init__.py
|
apps/__init__.py
|
# -*- coding: utf-8 -*-
from flask import Flask
from flask.ext.login import LoginManager
from .models import db, User
from .views import module
__all__ = ('create_app',)
def _init_db(app):
db.app = app
db.init_app(app)
def _init_jinja(app):
pass
def _init_login(app):
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.user_loader(User.get)
login_manager.login_view = '/login'
def create_app(name=None):
if name is None:
name = __name__
app = Flask(name)
app.config.from_object('config')
_init_db(app)
_init_jinja(app)
_init_login(app)
app.register_blueprint(module)
return app
|
Python
| 0.000001
|
@@ -422,19 +422,20 @@
iew = '/
-log
+sign
in'%0A%0A%0Ade
|
586418860c0441eaebadd0fe79989d6d9f90fa28
|
Fix for the component lookup error in vocabulary
|
src/bda/plone/productshop/vocabularies.py
|
src/bda/plone/productshop/vocabularies.py
|
from zope.interface import directlyProvides
from zope.schema.interfaces import IVocabularyFactory
from zope.schema.vocabulary import (
SimpleVocabulary,
SimpleTerm,
)
from zope.i18nmessageid import MessageFactory
from .utils import (
dotted_name,
available_variant_aspects,
)
#added by espen
from zope.component import getUtility
from plone.dexterity.interfaces import IDexterityFTI
from zope.component import ComponentLookupError
_ = MessageFactory('bda.plone.productshop')
def AvailableVariantAspectsVocabulary(context):
terms = list()
for definition in available_variant_aspects():
terms.append(SimpleTerm(value=dotted_name(definition.interface),
title=definition.title))
return SimpleVocabulary(terms)
directlyProvides(AvailableVariantAspectsVocabulary, IVocabularyFactory)
def RtfFieldsVocabulary(context):
try:
type = getUtility(IDexterityFTI, name='bda.plone.productshop.product')
fields = type.lookupSchema()
terms = [ SimpleTerm(value=pair, token=pair, title=pair) for pair in fields]
return SimpleVocabulary(terms)
except KeyError:
pass
finally:
pass
directlyProvides(RtfFieldsVocabulary, IVocabularyFactory)
|
Python
| 0
|
@@ -396,56 +396,8 @@
yFTI
-%0Afrom zope.component import ComponentLookupError
%0A%0A_
@@ -851,20 +851,22 @@
-type
+fields
= getUt
@@ -923,25 +923,52 @@
roduct')
-%0A
+.lookupSchema()%0A except:%0A
+
fields =
@@ -972,36 +972,28 @@
s =
-type.lookupSchema()%0A
+%5B'Datasheet', %5D%0A
-
term
@@ -1065,20 +1065,16 @@
fields%5D%0A
-
retu
@@ -1103,68 +1103,8 @@
rms)
-%0A except KeyError:%0A pass%0A finally:%0A pass
%0A%0Adi
|
3cade5788e55b124ce6c55350afb1beae4d3a5c3
|
Update __init__.py
|
examples/quickhowto2/app/__init__.py
|
examples/quickhowto2/app/__init__.py
|
import logging
from flask import Flask
from flask.ext.appbuilder import SQLA, AppBuilder
#from sqlalchemy.engine import Engine
#from sqlalchemy import event
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(name)s:%(message)s')
logging.getLogger().setLevel(logging.DEBUG)
app = Flask(__name__)
app.config.from_object('config')
db = SQLA(app)
appbuilder = AppBuilder(app, db.session)
"""
Only include this for SQLLite constraints
@event.listens_for(Engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()
"""
from app import views
|
Python
| 0.000072
|
@@ -382,16 +382,42 @@
.session
+, menu=Menu(reverse=False)
)%0A%0A%22%22%22%0AO
|
fb8e7ade2ca4ba01c9d6af2f169e3acc5f67613a
|
Enable CSRF_COOKIE_HTTPONLY = True
|
djangopeople/settings.py
|
djangopeople/settings.py
|
import dj_database_url
import os
from django.core.urlresolvers import reverse_lazy
from django.utils.six.moves.urllib import parse
OUR_ROOT = os.path.realpath(os.path.dirname(__file__))
DEBUG = bool(os.environ.get('DEBUG', False))
# OpenID settings
OPENID_REDIRECT_NEXT = reverse_lazy('openid_whatnext')
LOGIN_URL = reverse_lazy('login')
# Tagging settings
FORCE_LOWERCASE_TAGS = True
ADMINS = MANAGERS = ()
DATABASES = {'default': dj_database_url.config()}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be avilable on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
def gettext(s):
return s
LANGUAGES = (
('en', gettext('English')),
('cs', gettext('Czech')),
('ru', gettext('Russian')),
('fr', gettext('French')),
('es', gettext('Spanish')),
('he', gettext('Hebrew')),
('pt', gettext('Portuguese')),
('sk', gettext('Slovak')),
)
LOCALE_PATHS = (
os.path.join(OUR_ROOT, 'locale'),
)
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory where static media will be collected.
STATIC_ROOT = os.path.join(OUR_ROOT, 'static')
SECRET_KEY = os.environ['SECRET_KEY']
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
# Password used by the IRC bot for the API
API_PASSWORD = os.environ['API_PASSWORD']
TEMPLATES = [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'sekizai.context_processors.sekizai',
],
},
}]
if not DEBUG:
# Use the cached template loader.
del TEMPLATES[0]['APP_DIRS']
TEMPLATES[0]['OPTIONS']['loaders'] = (
('django.template.loaders.cached.Loader', (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)),
)
MIDDLEWARE_CLASSES = (
'django.middleware.security.SecurityMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'djangopeople.djangopeople.middleware.CanonicalDomainMiddleware',
'django.middleware.common.CommonMiddleware',
'djangopeople.djangopeople.middleware.RemoveWWW',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'djangopeople.django_openidconsumer.middleware.OpenIDMiddleware',
'django.contrib.admindocs.middleware.XViewMiddleware',
'djangopeople.djangopeople.middleware.NoDoubleSlashes',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
)
ROOT_URLCONF = 'djangopeople.urls'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.humanize',
'django.contrib.staticfiles',
'tagging',
'djangopeople.django_openidconsumer',
'djangopeople.django_openidauth',
'djangopeople.djangopeople',
'djangopeople.machinetags',
'password_reset',
'sekizai',
)
if 'SENTRY_DSN' in os.environ:
INSTALLED_APPS += (
'raven.contrib.django.raven_compat',
)
RAVEN_CONFIG = {'dsn': os.environ['SENTRY_DSN']}
GEONAMES_USERNAME = os.environ.get('GEONAMES_USERNAME', 'brutasse')
if 'CANONICAL_HOSTNAME' in os.environ:
CANONICAL_HOSTNAME = os.environ['CANONICAL_HOSTNAME']
ALLOWED_HOSTS = [CANONICAL_HOSTNAME]
SERVER_EMAIL = DEFAULT_FROM_EMAIL = os.environ['FROM_EMAIL']
SESSION_SERIALIZER = 'djangopeople.serializers.JSONSerializer'
X_FRAME_OPTIONS = 'DENY'
if DEBUG:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
else:
EMAIL_BACKEND = 'django_ses.SESBackend'
AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY']
AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_KEY']
AWS_STORAGE_BUCKET_NAME = os.environ['AWS_BUCKET_NAME']
AWS_QUERYSTRING_AUTH = False
STATICFILES_STORAGE = 'djangopeople.s3storage.S3HashedFilesStorage'
STATIC_URL = 'https://%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME
# Run the site over SSL
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
CSRF_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 2592000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
if 'REDISTOGO_URL' in os.environ:
redis_url = parse.urlparse(os.environ['REDISTOGO_URL'])
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION': '{0}:{1}'.format(redis_url.hostname, redis_url.port),
'OPTIONS': {
'DB': 0,
'PASSWORD': redis_url.password,
},
'VERSION': os.environ.get('CACHE_VERSION', 0),
},
}
try:
import debug_toolbar # noqa
except ImportError:
pass
else:
INSTALLED_APPS += (
'debug_toolbar',
)
|
Python
| 0.999765
|
@@ -5127,24 +5127,56 @@
ONLY = True%0A
+ CSRF_COOKIE_HTTPONLY = True%0A
CSRF_COO
|
aca0335593dbab772c806f8ac7ccde42cf4fd6f1
|
no mypy = happy mypy
|
paasta_tools/paasta_cluster_boost.py
|
paasta_tools/paasta_cluster_boost.py
|
#!/usr/bin/env python
# Copyright 2015-2016 Yelp 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.
import argparse
import logging
import sys
from paasta_tools.autoscaling import cluster_boost
from paasta_tools.utils import load_system_paasta_config
from paasta_tools.utils import paasta_print
log = logging.getLogger(__name__)
def parse_args():
"""Parses the command line arguments passed to this script"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-p', '--pool',
type=str,
default='default',
help="Name of the pool you want to increase the capacity. Default is 'default' pool.",
)
parser.add_argument(
'-b', '--boost',
type=float,
default=cluster_boost.DEFAULT_BOOST_FACTOR,
help="Boost factor to apply. Default is 1.5. A big failover should be 2, 3 is the max.",
)
parser.add_argument(
'-d', '--duration',
type=int,
default=cluster_boost.DEFAULT_BOOST_DURATION,
help="Duration of the capacity boost in minutes. Default is 40min.",
)
parser.add_argument(
'-f', '--force',
action='store_true',
dest='override',
help="Replace an existing boost. Default is false",
)
parser.add_argument(
'action',
choices=[
'set',
'status',
'clear',
],
help="You can view the status, set or clear a boost.",
)
parser.add_argument(
'-v', '--verbose',
action='count',
dest="verbose",
default=0,
help="Print out more output.",
)
return parser.parse_args()
def get_regions(pool: str) -> list:
""" Return the regions where we have slaves running for a given pool
"""
system_paasta_config = load_system_paasta_config()
expected_slave_attributes = system_paasta_config.get_expected_slave_attributes()
if expected_slave_attributes is None:
return []
regions = []
for slave in expected_slave_attributes:
slave_region = slave['datacenter']
if slave['pool'] == pool:
if slave_region not in regions:
regions.append(slave_region)
return regions
def paasta_cluster_boost():
""" Set, Get or clear a boost on a paasta cluster for a given pool in a given region
:returns: None
"""
system_config = load_system_paasta_config()
args = parse_args()
if args.verbose >= 2:
logging.basicConfig(level=logging.DEBUG)
elif args.verbose == 1:
logging.basicConfig(level=logging.INFO)
else:
logging.basicConfig(level=logging.WARNING)
action = args.action
pool = args.pool
if not system_config.get_cluster_boost_enabled():
paasta_print('ERROR: cluster_boost feature is not enabled.')
return False
regions = get_regions(pool)
if len(regions) == 0:
paasta_print('ERROR: no slaves found in pool {}'.format(pool))
return False
for region in regions:
if action == 'set':
if not cluster_boost.set_boost_factor(
region=region,
pool=pool,
factor=args.boost,
duration_minutes=args.duration,
override=args.override,
):
paasta_print('ERROR: Failed to set the boost for pool {}, region {}.'.format(pool, region))
return False
elif action == 'status':
paasta_print('Current boost value for pool: {}, region: {}: {}'.format(
pool, region, cluster_boost.get_boost_factor(
region=region, pool=pool,
),
))
elif action == 'clear':
if not cluster_boost.clear_boost(pool=pool, region=region):
paasta_print('ERROR: Failed to clear the boost for pool {}, region {}.')
return False
else:
raise NotImplementedError("Action: '%s' is not implemented." % action)
return False
if __name__ == '__main__':
if paasta_cluster_boost():
sys.exit(0)
sys.exit(1)
|
Python
| 0.999985
|
@@ -2176,16 +2176,8 @@
str)
- -%3E list
:%0A
|
33e9e7e279255c984a650e9bb2002faf4c8c66b1
|
fix prefix name (#3459)
|
PaddleSlim/classification/models/resnet.py
|
PaddleSlim/classification/models/resnet.py
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import paddle
import paddle.fluid as fluid
import math
from paddle.fluid.param_attr import ParamAttr
__all__ = ["ResNet", "ResNet34", "ResNet50", "ResNet101", "ResNet152"]
train_parameters = {
"input_size": [3, 224, 224],
"input_mean": [0.485, 0.456, 0.406],
"input_std": [0.229, 0.224, 0.225],
"learning_strategy": {
"name": "piecewise_decay",
"batch_size": 256,
"epochs": [10, 16, 30],
"steps": [0.1, 0.01, 0.001, 0.0001]
}
}
class ResNet():
def __init__(self, layers=50, prefix_name=''):
self.params = train_parameters
self.layers = layers
self.prefix_name = prefix_name
def net(self, input, class_dim=1000, conv1_name='conv1', fc_name=None):
layers = self.layers
prefix_name = self.prefix_name if self.prefix_name is '' else self.prefix_name + '_'
supported_layers = [34, 50, 101, 152]
assert layers in supported_layers, \
"supported layers are {} but input layer is {}".format(supported_layers, layers)
if layers == 34 or layers == 50:
depth = [3, 4, 6, 3]
elif layers == 101:
depth = [3, 4, 23, 3]
elif layers == 152:
depth = [3, 8, 36, 3]
num_filters = [64, 128, 256, 512]
# TODO(wanghaoshuang@baidu.com):
# fix name("conv1") conflict between student and teacher in distillation.
conv = self.conv_bn_layer(
input=input,
num_filters=64,
filter_size=7,
stride=2,
act='relu',
name=prefix_name + conv1_name)
conv = fluid.layers.pool2d(
input=conv,
pool_size=3,
pool_stride=2,
pool_padding=1,
pool_type='max')
for block in range(len(depth)):
for i in range(depth[block]):
if layers in [101, 152] and block == 2:
if i == 0:
conv_name = "res" + str(block + 2) + "a"
else:
conv_name = "res" + str(block + 2) + "b" + str(i)
else:
conv_name = "res" + str(block + 2) + chr(97 + i)
conv_name = prefix_name + conv_name
conv = self.bottleneck_block(
input=conv,
num_filters=num_filters[block],
stride=2 if i == 0 and block != 0 else 1,
name=conv_name)
pool = fluid.layers.pool2d(
input=conv, pool_size=7, pool_type='avg', global_pooling=True)
stdv = 1.0 / math.sqrt(pool.shape[1] * 1.0)
out = fluid.layers.fc(input=pool,
size=class_dim,
act='softmax',
name=prefix_name + fc_name,
param_attr=fluid.param_attr.ParamAttr(
initializer=fluid.initializer.Uniform(-stdv,
stdv)))
return out
def conv_bn_layer(self,
input,
num_filters,
filter_size,
stride=1,
groups=1,
act=None,
name=None):
conv = fluid.layers.conv2d(
input=input,
num_filters=num_filters,
filter_size=filter_size,
stride=stride,
padding=(filter_size - 1) // 2,
groups=groups,
act=None,
param_attr=ParamAttr(name=name + "_weights"),
bias_attr=False,
name=name + '.conv2d.output.1')
if self.prefix_name == '':
if name == "conv1":
bn_name = "bn_" + name
else:
bn_name = "bn" + name[3:]
else:
if name.split("_")[1] == "conv1":
bn_name = name.split("_", 1)[0] + "_bn_" + name.split("_", 1)[1]
else:
bn_name = name.split("_", 1)[0] + "_bn" + name.split("_",
1)[1][3:]
return fluid.layers.batch_norm(
input=conv,
act=act,
name=bn_name + '.output.1',
param_attr=ParamAttr(name=bn_name + '_scale'),
bias_attr=ParamAttr(bn_name + '_offset'),
moving_mean_name=bn_name + '_mean',
moving_variance_name=bn_name + '_variance', )
def shortcut(self, input, ch_out, stride, name):
ch_in = input.shape[1]
if ch_in != ch_out or stride != 1:
return self.conv_bn_layer(input, ch_out, 1, stride, name=name)
else:
return input
def bottleneck_block(self, input, num_filters, stride, name):
conv0 = self.conv_bn_layer(
input=input,
num_filters=num_filters,
filter_size=1,
act='relu',
name=name + "_branch2a")
conv1 = self.conv_bn_layer(
input=conv0,
num_filters=num_filters,
filter_size=3,
stride=stride,
act='relu',
name=name + "_branch2b")
conv2 = self.conv_bn_layer(
input=conv1,
num_filters=num_filters * 4,
filter_size=1,
act=None,
name=name + "_branch2c")
short = self.shortcut(
input, num_filters * 4, stride, name=name + "_branch1")
return fluid.layers.elementwise_add(
x=short, y=conv2, act='relu', name=name + ".add.output.5")
def ResNet34(prefix_name=''):
model = ResNet(layers=34, prefix_name=prefix_name)
return model
def ResNet50(prefix_name=''):
model = ResNet(layers=50, prefix_name=prefix_name)
return model
def ResNet101():
model = ResNet(layers=101)
return model
def ResNet152():
model = ResNet(layers=152)
return model
|
Python
| 0.000002
|
@@ -2751,16 +2751,88 @@
* 1.0)%0A
+ fc_name = fc_name if fc_name is None else prefix_name + fc_name%0A
|
ca58c653bf56235fb66c6d25ec2dc659552ad90f
|
support delete another prefix cache at once
|
djinn/datastore/cache.py
|
djinn/datastore/cache.py
|
# -*- coding: utf-8 -*-
#
# Copyright(c) 2014 palmhold.com
#
# 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 hashlib
import logging
import functools
import memcache
from tornado.escape import utf8
from tornado.options import define, options
define("cache_key_prefix", "", str, "cache key prefix to avoid key conflict")
define("cache_enabled", True, bool, "whether cache is enabled")
manager = None
def cache(key=None, timeout=3600, args_as_key=True):
def _wrapper(func):
@functools.wraps(func)
def __wrapper(*args, **kw):
if not options.cache_enabled:
return func(*args, **kw)
_key = key_gen(key, func, args_as_key, *args, **kw)
value = manager.get(_key)
if not value:
value = func(*args, **kw)
if value:
manager.set(_key, value, timeout)
return value
return __wrapper
return _wrapper
def delete(key):
_key = key_gen(key)
manager.delete(_key)
def key_gen(key="", func=None, args_as_key=True, *args, **kw):
assert key or func, "key and func must has one"
if key:
if args_as_key and "%s" in key:
args_ = []
for arg in args:
if isinstance(arg, (basestring, unicode, int, long)):
args_.append(arg)
key = key % tuple(args_)
else:
code = hashlib.md5()
code.update("%s-%s" % (func.__module__, func.__name__))
# copy args to avoid sort original args
c = list(args[:])
# sort c to avoid generate different key when args is the same
# but sequence is different
c.sort()
c = [utf8(v) if isinstance(v, (basestring, unicode))
else str(v) for v in c]
code.update("".join(c))
c = ["%s=%s" % (k, v) for k, v in kw.iteritems()]
c.sort()
code.update("".join(c))
key = code.hexdigest()
if options.cache_key_prefix:
key = "%s:%s" % (options.cache_key_prefix, key)
return key
def setup(servers, timeout=3):
global manager
if manager is None:
manager = CacheManager(servers, timeout)
return manager
def reconnect(func):
@functools.wraps(func)
def _wrapper(self, *args, **kwargs):
try:
r = func(self, *args, **kwargs)
return r
except Exception:
logging.exception("memcache server closed!")
self.close()
return _wrapper
class CacheManager(object):
def __init__(self, servers, timeout=3):
self.servers = servers
self.default_timeout = int(timeout)
self._cache = memcache.Client(self.servers)
logging.debug("Memcached start client %s" % servers)
@property
def cache(self):
if self._cache is None:
self._cache = memcache.Client(self.servers)
return self._cache
@reconnect
def add(self, key, value, timeout=0):
if isinstance(value, unicode):
value = utf8(value)
return self.cache.add(utf8(key), value,
timeout or self.default_timeout)
@reconnect
def get(self, key, default=None):
val = self.cache.get(utf8(key))
if val is None:
return default
else:
if isinstance(val, basestring):
return utf8(val)
else:
return val
@reconnect
def set(self, key, value, timeout=0):
if isinstance(value, unicode):
value = utf8(value)
return self.cache.set(utf8(key), value,
timeout or self.default_timeout)
@reconnect
def delete(self, key):
return self.cache.delete(utf8(key))
@reconnect
def get_many(self, keys):
return self.cache.get_multi(map(utf8, keys))
def close(self, **kwargs):
try:
self._cache.disconnect_all()
except Exception:
self._cache = None
@reconnect
def stats(self):
return self.cache.get_stats()
@reconnect
def flush_all(self):
self.cache.flush_all()
if __name__ == "__main__":
setup(["127.0.0.1"])
@cache()
def test(a):
return a
a = test(1)
key = key_gen("", test, 1)
assert manager.get(key) == a
|
Python
| 0
|
@@ -817,16 +817,145 @@
flict%22)%0A
+define(%22cache_key_prefix_another%22, %22%22, str,%0A %22another cache in different cache prefix, should be delete at the same time%22)%0A
define(%22
@@ -1603,28 +1603,312 @@
-_key = key_gen(key)%0A
+if options.cache_key_prefix:%0A key = %22%25s:%25s%22 %25 (options.cache_key_prefix, key)%0A manager.delete(key)%0A else:%0A manager.delete(key)%0A%0A if options.cache_key_prefix_another:%0A another_key = %22%25s:%25s%22 %25 (options.cache_key_prefix_another, key)%0A if another_key != key:%0A
@@ -1922,16 +1922,23 @@
.delete(
+another
_key)%0A%0A%0A
|
14d12b1d6bbcf5784256b82f58974f02fe8d1503
|
Remove unused imports. Gating tests so they do not run on Windows
|
tests/integration/states/test_cron.py
|
tests/integration/states/test_cron.py
|
# -*- coding: utf-8 -*-
'''
Tests for the cron state
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
log = logging.getLogger(__name__)
# Import Salt Testing libs
from tests.support.case import ModuleCase
from tests.support.unit import skipIf
from tests.support.paths import FILES, TMP, TMP_STATE_TREE
from tests.support.helpers import (
skip_if_not_root,
with_system_user_and_group,
with_tempfile,
Webserver,
)
class CronTest(ModuleCase):
'''
Validate the file state
'''
def setUp(self):
'''
Setup
'''
self.run_state('user.present', name='test_cron_user')
def tearDown(self):
'''
Teardown
'''
# Remove cron file
self.run_function('cmd.run',
cmd='crontab -u test_cron_user -r')
# Delete user
self.run_state('user.absent', name='test_cron_user')
def test_managed(self):
'''
file.managed
'''
ret = self.run_state(
'cron.file',
name='salt://issue-46881/cron',
user='test_cron_user'
)
_expected = '--- \n+++ \n@@ -1 +1,2 @@\n-\n+# Lines below here are managed by Salt, do not edit\n+@hourly touch /tmp/test-file\n'
self.assertIn('changes', ret['cron_|-salt://issue-46881/cron_|-salt://issue-46881/cron_|-file'])
self.assertIn('diff', ret['cron_|-salt://issue-46881/cron_|-salt://issue-46881/cron_|-file']['changes'])
self.assertEqual(_expected, ret['cron_|-salt://issue-46881/cron_|-salt://issue-46881/cron_|-file']['changes']['diff'])
|
Python
| 0
|
@@ -308,194 +308,119 @@
pIf%0A
-from tests.support.paths import FILES, TMP, TMP_STATE_TREE%0Afrom tests.support.helpers import (%0A skip_if_not_root,%0A with_system_user_and_group,%0A with_tempfile,%0A Webserver,%0A)%0A%0A
+%0A# Import Salt libs%0Aimport salt.utils.platform%0A%0A%0A@skipIf(salt.utils.platform.is_windows(), 'minion is windows')
%0Acla
|
6493cc31acdc09df6c0ad952e95380ac31a0e504
|
Update __init__.py
|
vispy/color/__init__.py
|
vispy/color/__init__.py
|
# -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
Convience interfaces to manipulate colors.
This module provides support for manipulating colors.
"""
<<<<<<< HEAD
__all__ = ['Color', 'ColorArray', 'Colormap',
'get_colormap', 'get_colormaps',
'get_color_names', 'get_color_dict']
from ._color_dict import get_color_names, get_color_dict # noqa
from .color_array import Color, ColorArray
from .colormap import (Colormap, # noqa
get_colormap, get_colormaps) # noqa
=======
__all__ = ['Color', 'ColorArray', 'LinearGradient', 'get_color_names',
'get_colormap_py']
from ._color_dict import get_color_names # noqa
from ._color import (Color, ColorArray, LinearGradient, # noqa
get_colormap, colormaps, get_colormap_py) # noqa
>>>>>>> new visuals/isocurve for tri mesh
|
Python
| 0.000072
|
@@ -248,21 +248,8 @@
%22%22%0A%0A
-%3C%3C%3C%3C%3C%3C%3C HEAD%0A
__al
@@ -596,340 +596,4 @@
oqa%0A
-=======%0A__all__ = %5B'Color', 'ColorArray', 'LinearGradient', 'get_color_names',%0A 'get_colormap_py'%5D%0A%0Afrom ._color_dict import get_color_names # noqa%0Afrom ._color import (Color, ColorArray, LinearGradient, # noqa%0A get_colormap, colormaps, get_colormap_py) # noqa%0A%3E%3E%3E%3E%3E%3E%3E new visuals/isocurve for tri mesh%0A
|
9b35aece13ee90005320996d962e1c8347a06e3b
|
remove debugging "print" statement
|
tests/twisted/jingle/payload-types.py
|
tests/twisted/jingle/payload-types.py
|
"""
Regression test for https://bugs.freedesktop.org/show_bug.cgi?id=18918
"""
from gabbletest import exec_test, make_result_iq, sync_stream, \
send_error_reply
from servicetest import make_channel_proxy, unwrap, tp_path_prefix, \
call_async, EventPattern
from twisted.words.xish import domish
import jingletest
import gabbletest
import dbus
import time
MEDIA_STREAM_TYPE_AUDIO = 0
def test(q, bus, conn, stream):
jt = jingletest.JingleTest(stream, 'test@localhost', 'foo@bar.com/Foo')
# Connecting
conn.Connect()
q.expect('dbus-signal', signal='StatusChanged', args=[1, 1])
q.expect('stream-authenticated')
q.expect('dbus-signal', signal='PresenceUpdate',
args=[{1L: (0L, {u'available': {}})}])
q.expect('dbus-signal', signal='StatusChanged', args=[0, 1])
self_handle = conn.GetSelfHandle()
# We need remote end's presence for capabilities
jt.send_remote_presence()
# Gabble doesn't trust it, so makes a disco
event = q.expect('stream-iq', query_ns='http://jabber.org/protocol/disco#info',
to='foo@bar.com/Foo')
jt.send_remote_disco_reply(event.stanza)
# Force Gabble to process the caps before calling RequestChannel
sync_stream(q, stream)
handle = conn.RequestHandles(1, [jt.remote_jid])[0]
path = conn.RequestChannel(
'org.freedesktop.Telepathy.Channel.Type.StreamedMedia',
1, handle, True)
channel = bus.get_object(conn.bus_name, path)
signalling_iface = make_channel_proxy(conn, path, 'Channel.Interface.MediaSignalling')
media_iface = make_channel_proxy(conn, path, 'Channel.Type.StreamedMedia')
group_iface = make_channel_proxy(conn, path, 'Channel.Interface.Group')
# FIXME: Hack to make sure the disco info has been processed - we need to
# send Gabble some XML that will cause an event when processed, and
# wait for that event (until
# https://bugs.freedesktop.org/show_bug.cgi?id=15769 is fixed)
el = domish.Element(('jabber.client', 'presence'))
el['from'] = 'bob@example.com/Bar'
stream.send(el.toXml())
q.expect('dbus-signal', signal='PresenceUpdate')
# OK, now we can continue. End of hack
# Test that codec parameters are correctly sent in <parameter> children of
# <payload-type> rather than as attributes of the latter.
media_iface.RequestStreams(handle, [MEDIA_STREAM_TYPE_AUDIO])
# S-E gets notified about new session handler, and calls Ready on it
e = q.expect('dbus-signal', signal='NewSessionHandler')
assert e.args[1] == 'rtp'
session_handler = make_channel_proxy(conn, e.args[0], 'Media.SessionHandler')
session_handler.Ready()
e = q.expect('dbus-signal', signal='NewStreamHandler')
stream_id = e.args[1]
stream_handler = make_channel_proxy(conn, e.args[0], 'Media.StreamHandler')
stream_handler.NewNativeCandidate("fake", jt.get_remote_transports_dbus())
codecs = dbus.Array( [ (96, 'speex', 0, 16000, 0, {'vbr': 'on'}) ],
signature='(usuuua{ss})')
stream_handler.Ready(codecs)
stream_handler.StreamState(2)
e = q.expect('stream-iq')
content = list(e.query.elements())[0]
assert content.name == 'content'
for child in content.elements():
if child.name == 'description':
description = child
break
assert description is not None
# there should be one <payload-type> tag for speex:
assert len(list(description.elements())) == 1
payload_type = list(description.elements())[0]
assert payload_type.name == 'payload-type'
assert payload_type['name'] == 'speex'
# the vbr parameter should not be an attribute on the <payload-type>, but
# a child <parameter/> tag
assert 'vbr' not in payload_type.attributes
assert len(list(payload_type.elements())) == 1
parameter = list(payload_type.elements())[0]
assert parameter.name == 'parameter'
assert parameter['name'] == 'vbr'
assert parameter['value'] == 'on'
channel.Close()
# Test that codec parameters are correctly extracted from <parameter>
# children of <payload-type> rather than from attributes of the latter.
jt.incoming_call({'misc': 'other'})
e = q.expect('dbus-signal', signal='NewSessionHandler')
assert e.args[1] == 'rtp'
session_handler = make_channel_proxy(conn, e.args[0], 'Media.SessionHandler')
session_handler.Ready()
e = q.expect('dbus-signal', signal='NewStreamHandler')
stream_id = e.args[1]
stream_handler = make_channel_proxy(conn, e.args[0], 'Media.StreamHandler')
stream_handler.Ready( dbus.Array( [], signature='(usuuua{ss})'))
e = q.expect('dbus-signal', signal='SetRemoteCodecs')
for codec in e.args[0]:
id, name, type, rate, channels, parameters = codec
assert len(parameters) == 1, parameters
assert parameters['misc'] == 'other', parameters
print e.args[0]
# Test completed, close the connection
conn.Disconnect()
q.expect('dbus-signal', signal='StatusChanged', args=[2, 1])
return True
if __name__ == '__main__':
exec_test(test)
|
Python
| 0.000003
|
@@ -4913,28 +4913,8 @@
rs%0A%0A
- print e.args%5B0%5D%0A
|
a364196814c3b33e7fd51a42b4c3a48a3aaeaee8
|
Update list of extraordinary gentlemen
|
volaparrot/constants.py
|
volaparrot/constants.py
|
ADMINFAG = ["RealDolos"]
PARROTFAG = "Parrot"
BLACKFAGS = [i.casefold() for i in (
"kalyx", "merc", "loliq", "annoying", "bot", "RootBeats", "JEW2FORU", "quag", "mire", "perici")]
OBAMAS = [i.casefold() for i in (
"counselor", "briseis", "apha", "bread", "ark3", "jizzbomb", "acid", "elkoalemos", "tarta")]
BLACKROOMS = "e7u-CG", "jAzmc3", "f66jeG", "24_zFd"
WHITEROOMS = "9pdLvy"
|
Python
| 0
|
@@ -122,15 +122,8 @@
ng%22,
- %22bot%22,
%22Ro
@@ -168,16 +168,114 @@
%22perici%22
+, %22Voldemort%22, %22briseis%22, %22brisis%22, %22GNUsuks%22, %22rhooes%22, %22n1sm4n%22, %22honeyhole%22, %22Printer%22, %22yume1%22
)%5D%0AOBAMA
@@ -397,16 +397,37 @@
%22tarta%22
+, %22counselor%22, %22myon%22
)%5D%0A%0ABLAC
@@ -473,16 +473,39 @@
%2224_zFd%22
+, %22BHfjGvT%22, %22BHI0pxg%22,
%0AWHITERO
@@ -515,12 +515,12 @@
= %22
-9pdLvy%22
+BEEPi%22,
%0A
|
84965de8b53dcb5b10788808a2bf135df82cd4d9
|
Update dev DB to sqlite3
|
vpr/vpr/settings/dev.py
|
vpr/vpr/settings/dev.py
|
# Django settings for vpr project.
from base import *
DEBUG = True
DEVELOPMENT = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
#'NAME': 'vpr.sqlite3', # Or path to database file if using sqlite3.
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'vpr_dev', # Or path to database file if using sqlite3.
'USER': 'vpr', # Not used with sqlite3.
'PASSWORD': 'vpr', # Not used with sqlite3.
'HOST': 'localhost', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '3306', # Set to empty string for default. Not used with sqlite3.
}
}
# Make this unique, and don't share it with anybody.
#SECRET_KEY = 'kw7#s$8t&6d9*7*$a$(gui0r1ze7f#u%(hua=^a3u66+vyj+9g'
ROOT_URLCONF = 'vpr.urls.dev'
INSTALLED_APPS += (
'django_extensions',
)
|
Python
| 0
|
@@ -144,17 +144,16 @@
-#
'ENGINE'
@@ -253,17 +253,16 @@
-#
'NAME':
@@ -338,32 +338,33 @@
qlite3.%0A
+#
'ENGINE': 'djang
|
52f9d95582456754aa4e9f9cd5d59a308c9e256c
|
remove comments
|
server.py
|
server.py
|
import socket
import communication
import time
import cv2
import numpy as np
from picamera import PiCamera
import sys
import signal
run_condition = True
def signal_handler(signal, frame):
print('Exiting...')
global run_condition
run_condition = False
sys.exit(0)
def generateRandomImg():
z = np.random.random((500, 500)) # Test data
print z.dtype
return z
def getCameraStill():
with PiCamera() as camera:
camera.resolution= (500,500)
camera.capture('temp.bmp')
data = np.asarray(cv2.imread('temp.bmp'), dtype='uint16')
return data
def getData():
z = getCameraStill()
return z
def waitForClient(sock):
connection, address = sock.accept()
#send SERVER_READY
print "sending ", communication.SERVER_READY
communication.send_msg(connection, communication.SERVER_READY)
#receive CLIENT_READY
msg = communication.recv_msg(connection)
print "received ", msg
return connection
camera_id = sys.argv[1].zfill(2)
signal.signal(signal.SIGINT, signal_handler)
print 'starting server ', camera_id
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("", 10006))
server_socket.listen(5)
while(run_condition):
try:
connection = waitForClient(server_socket)
#send camera id
print "sending ", camera_id
communication.send_msg(connection, camera_id)
#receive CAMERA_ID_ACK
print "received ", communication.recv_msg(connection)
data = getData()
print "sending image data"
communication.send_img(connection, data)
print "closing connection"
connection.close()
except:
print "Server failure, resetting connection"
server_socket.close()
|
Python
| 0
|
@@ -477,17 +477,16 @@
olution=
-
(500,500
@@ -487,16 +487,16 @@
00,500)%0A
+
@@ -725,31 +725,8 @@
t()%0A
- #send SERVER_READY%0A
@@ -841,34 +841,8 @@
DY)%0A
- #receive CLIENT_READY%0A
@@ -1254,32 +1254,8 @@
et)%0A
- #send camera id%0A
@@ -1286,16 +1286,16 @@
mera_id%0A
+
@@ -1344,39 +1344,8 @@
id)%0A
- #receive CAMERA_ID_ACK%0A
|
95495c1b0ae1a696b95eb486c7a40d54f507dacb
|
Add cross origin requests.
|
server.py
|
server.py
|
import pymzn
import os
from subprocess import Popen, PIPE
from flask import Flask, json, Response
app = Flask(__name__)
folder = 'models' #where the .mzn files are stored
models = []
for file in os.listdir(folder):
if file.endswith('.mzn'):
models.append(file)
@app.route('/')
def Allmodels():
return json.jsonify(result=models)
#inputs models musn't 'output'
@app.route('/model/<string:model>.json')
def Model(model):
if (model+".mzn" in models):
def output_line():
with Popen(["MiniZinc", folder + '/' + model+".mzn", "-a"], stdout=PIPE, bufsize=1, universal_newlines=True) as p: #-a outputs all solutions
for line in p.stdout:
markup = ['----------','==========']
if line.rstrip() not in markup: #each new solution is a new JSON object
yield str(pymzn.parse_dzn(line)) #use pymzn to turn output into nice JSON objects
return Response(output_line(), mimetype='text/json')
else:
return json.jsonify(model="no model found")
|
Python
| 0
|
@@ -490,13 +490,13 @@
n(%5B%22
-MiniZ
+miniz
inc%22
@@ -955,8 +955,387 @@
found%22)
+%0A%0A# TODO: Unsure if this is safe security wise, have to look into it.%0A# aka. CORS request.%0A@app.after_request%0Adef after_request(response):%0A response.headers.add('Access-Control-Allow-Origin', '*')%0A response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')%0A response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')%0A return response%0A
|
11000be28e9c150adde2d9109bb5e078a5c553b6
|
Assume the dimesions are good
|
server.py
|
server.py
|
#!/usr/bin/env python
import sys
import numpy
import math
import logging
from fuel.datasets import DogsVsCats
from fuel.schemes import ShuffledScheme
from fuel.server import start_server
from fuel.streams import DataStream
from fuel.transformers import ScaleAndShift, ForceFloatX
from fuel.transformers.image import (
RandomFixedSizeCrop,
SourcewiseTransformer, ExpectsAxisLabels)
from PIL import Image
class ForceMinimumDimension(SourcewiseTransformer, ExpectsAxisLabels):
def __init__(self, data_stream, min_dim, resample='nearest',
**kwargs):
self.min_dim = min_dim
try:
self.resample = getattr(Image, resample.upper())
except AttributeError:
raise ValueError("unknown resampling filter '{}'".format(resample))
kwargs.setdefault('produces_examples', data_stream.produces_examples)
kwargs.setdefault('axis_labels', data_stream.axis_labels)
super(ForceMinimumDimension, self).__init__(data_stream, **kwargs)
def transform_source_batch(self, batch, source_name):
self.verify_axis_labels(('batch', 'channel', 'height', 'width'),
self.data_stream.axis_labels[source_name],
source_name)
return [self._example_transform(im, source_name) for im in batch]
def transform_source_example(self, example, source_name):
self.verify_axis_labels(('channel', 'height', 'width'),
self.data_stream.axis_labels[source_name],
source_name)
return self._example_transform(example, source_name)
def _example_transform(self, example, _):
if example.ndim > 3 or example.ndim < 2:
raise NotImplementedError
original_min_dim = min(example.shape[-2:])
multiplier = self.min_dim / float(original_min_dim)
dt = example.dtype
# If we're dealing with a colour image, swap around the axes
# to be in the format that PIL needs.
if example.ndim == 3:
im = example.transpose(1, 2, 0)
else:
im = example
im = Image.fromarray(im)
width, height = im.size
width = int(math.ceil(width * multiplier))
height = int(math.ceil(height * multiplier))
im = numpy.array(im.resize((width, height))).astype(dt)
# If necessary, undo the axis swap from earlier.
if im.ndim == 3:
example = im.transpose(2, 0, 1)
else:
example = im
return example
def add_transformers(stream, random_crop=False):
stream = ForceMinimumDimension(stream, 128,
which_sources=['image_features'])
if random_crop:
stream = RandomFixedSizeCrop(stream, (128, 128),
which_sources=['image_features'])
stream = ScaleAndShift(stream, 1 / 255.0, 0,
which_sources=['image_features'])
stream = ForceFloatX(stream)
return stream
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
train = DogsVsCats(("train",), subset=slice(None, int(sys.argv[1]), None))
train_str = DataStream(
train, iteration_scheme=ShuffledScheme(train.num_examples, int(sys.argv[2])))
train_str = add_transformers(train_str, random_crop=True)
start_server(train_str, port=int(sys.argv[3]))
|
Python
| 0.999997
|
@@ -2612,24 +2612,82 @@
=False):%0A
+ # Now the dataset has images with good minimum size%0A #
stream = Fo
@@ -2718,24 +2718,26 @@
am, 128,%0A
+ #
|
8d92fa303dc3f451ff353c9bb7b5e55a7f363c33
|
correct example in docs
|
src/compas/datastructures/mesh/duality.py
|
src/compas/datastructures/mesh/duality.py
|
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from math import pi
from compas.utilities import flatten
__all__ = ['mesh_dual']
PI2 = 2.0 * pi
def mesh_dual(mesh, cls=None, boundary=0):
"""Construct the dual of a mesh.
Parameters
----------
mesh : :class:`~compas.datastructures.Mesh`
A mesh object.
cls : Type[:class:`~compas.datastructures.Mesh`], optional
The type of the dual mesh.
Defaults to the type of the provided mesh object.
boundary: float, optional
boundary mode for the dual mesh
Default mode is 0, not create faces on boundaries.
1, create faces on mesh edges, not include original mesh boundary vertices.
2. create faces on mesh edges and include original mesh boundary vertices on the corner.
3. create faces on mesh edges and include all original mesh boundary vertices.
Returns
-------
:class:`~compas.datastructures.Mesh`
The dual mesh object.
Examples
--------
>>> from compas.datastructures import Mesh
>>> mesh = Mesh.from_obj(compas.get('faces.obj'))
>>> mesh.delete_face(11)
>>> mesh.delete_face(6)
>>> mesh.delete_face(7)
>>> mesh.quads_to_triangles()
>>> mesh = mesh.subdivide('corner')
>>> dual = mesh.dual(boundary=3)
"""
if not cls:
cls = type(mesh)
dual = cls()
mesh.unify_cycles()
mesh.flip_cycles()
face_centroid = {face: mesh.face_centroid(face) for face in mesh.faces()}
outer = list(flatten(mesh.vertices_on_boundaries()))
vertex_xyz = {}
face_vertices = {}
edge_vertex = {}
# safe guarded if face index is arbitrary, random, not starting from 0
num_faces = max(max(list(mesh.faces())) + 1, mesh.number_of_faces())
for vertex in mesh.vertices():
faces = mesh.vertex_faces(vertex, ordered=True)
for face in faces:
if face not in vertex_xyz:
vertex_xyz[face] = face_centroid[face]
face_vertices[vertex] = faces
if not boundary:
continue
if boundary > 3:
raise ValueError("edge mode from 0 to 3!")
if vertex not in outer or len(faces) < 1:
continue
boundary_fids = faces[:]
current_face = vertex
corner_count = 0
edge_count = 0
for nbr_vertex in reversed(mesh.vertex_neighbors(vertex, ordered=True)):
if not mesh.is_edge_on_boundary(vertex, nbr_vertex):
continue
pt = mesh.edge_midpoint(vertex, nbr_vertex)
if num_faces not in vertex_xyz and len(faces) == 1 and corner_count == 0 and (boundary == 2 or boundary == 3):
vertex_xyz[num_faces] = mesh.vertex_coordinates(vertex)
current_face = num_faces
num_faces += 1
corner_count += 1
if num_faces not in vertex_xyz and len(faces) != 1 and edge_count == 0 and boundary == 3:
vertex_xyz[num_faces] = mesh.vertex_coordinates(vertex)
current_face = num_faces
num_faces += 1
edge_count += 1
if num_faces not in vertex_xyz and ((vertex, nbr_vertex) not in edge_vertex and
(nbr_vertex, vertex) not in edge_vertex):
vertex_xyz[num_faces] = pt
edge_vertex[vertex, nbr_vertex] = edge_vertex[nbr_vertex, vertex] = num_faces
boundary_fids.append(num_faces)
num_faces += 1
else:
boundary_fids.append(edge_vertex[vertex, nbr_vertex])
if vertex in outer and len(faces) == 1 and (boundary == 2 or boundary == 3):
boundary_fids.insert(len(faces) + 1, current_face)
if vertex in outer and len(faces) != 1 and boundary == 3:
boundary_fids.insert(len(faces) + 1, current_face)
face_vertices[vertex] = boundary_fids
for vertex in vertex_xyz:
x, y, z = vertex_xyz[vertex]
dual.add_vertex(vertex, x=x, y=y, z=z)
for face in face_vertices:
dual.add_face(face_vertices[face], fkey=face)
return dual
|
Python
| 0.000005
|
@@ -1058,24 +1058,46 @@
--------%0A
+ %3E%3E%3E import compas%0A
%3E%3E%3E from
|
eb889d08c6031ba6c2b55a883d09e22f5684f0ee
|
Add mode (training|arena) option to the command line
|
server.py
|
server.py
|
#!/usr/bin/env python
import os
import sys
import requests
import re
from bot import RandomBot
def get_new_game_state(server_host, key, number_of_turns = '20', mode='training'):
if(mode=='training'):
params = { 'key': key, 'turns': number_of_turns}
r = requests.post(server_host + '/api/training', params)
if(r.status_code == 200):
return r.json()
else:
print("Error when creating the game")
print(r.text)
else:
pass
def move(url, direction):
r = requests.post(url, {'dir': direction})
return r.json()
def start(server_host, key, bot, number_of_games = 20):
def play(state, games_played = 0):
if (state['game']['finished']):
games_played += 1
print('Game finished: %d/%d' % (games_played, number_of_games))
if(games_played < number_of_games):
print('asking a new game')
state = get_new_game_state(server_host, key)
play(state, games_played)
else:
url = state['playUrl']
direction = bot.move(state)
new_state = move(url, direction)
print("Playing turn %d with direction %s" % (state['game']['turn'], direction))
play(new_state, games_played)
state = get_new_game_state(server_host, key)
print("Start: " + state['viewUrl'])
play(state)
if __name__ == "__main__":
if (len(sys.argv) > 3):
start(sys.argv[1], sys.argv[2], RandomBot(), int(sys.argv[3]))
else:
print("Usage: %s <server> <key> <number-of-games-to-play>" % (sys.argv[0]))
print('Example: %s http://localhost:9000 mySecretKey 20' % (sys.argv[0]))
|
Python
| 0.000001
|
@@ -130,16 +130,33 @@
st, key,
+ mode='training',
number_
@@ -170,33 +170,16 @@
s = '20'
-, mode='training'
):%0A i
@@ -619,16 +619,22 @@
st, key,
+ mode,
bot, nu
@@ -1348,24 +1348,30 @@
er_host, key
+, mode
)%0A print(
@@ -1468,17 +1468,17 @@
argv) %3E
-3
+4
):%0A
@@ -1511,16 +1511,29 @@
argv%5B2%5D,
+ sys.argv%5B3%5D,
RandomB
@@ -1551,17 +1551,17 @@
ys.argv%5B
-3
+4
%5D))%0A
@@ -1605,16 +1605,35 @@
r%3E %3Ckey%3E
+ %3C%5Btraining%7Carena%5D%3E
%3Cnumber
@@ -1730,16 +1730,25 @@
cretKey
+training
20' %25 (s
|
35562f7b82a0da6625b63bf8e2aa83655f886c5f
|
Fix untested code.
|
server.py
|
server.py
|
from datetime import timedelta
from flask import Flask, redirect, render_template, request, url_for
import json
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.wsgi import WSGIContainer
from webpixels import PixelSet, RgbPixel
from webpixels.controller import ColorKinetics
app = Flask(__name__)
ioloop = IOLoop.instance()
config_file = None
channels = {}
pixels = {}
presets = {}
last_preset = None
def load_config(config_file):
with open(config_file) as f:
config = json.loads(f.read())
for name, controllerConfig in config['controllers'].items():
controllerType = controllerConfig['type']
if controllerType == 'ColorKinetics':
controller = ColorKinetics(name, controllerConfig['host'])
for channel in controller.channels:
channels[channel.get_name()] = channel
for name, pixelConfig in config['pixels'].items():
chan_set = [channels[channel] for channel in pixelConfig['channels']]
pixel = RgbPixel(name, *chan_set)
pixels[pixel.get_name()] = pixel
for name, fixtureConfig in config['fixtures'].items():
pixel_set = [pixels[pixel] for pixel in fixtureConfig['pixels']]
fixture = PixelSet(name, pixel_set)
pixels[fixture.get_name()] = fixture
all_pixels = [pixel for pixel in pixels.values()
if not isinstance(pixel, PixelSet)]
pixels['all'] = PixelSet('all', all_pixels)
if 'presets' in config:
presets.update(config['presets'])
def save_config(config_file):
controller_set = set()
saved_controllers = {}
saved_pixels = {}
saved_fixtures = {}
for pixel in pixels.values():
controller_set.update(pixel.get_controllers())
if isinstance(pixel, RgbPixel):
saved_pixels[pixel.get_name()] = {
'channels': [
pixel.red.get_name(),
pixel.green.get_name(),
pixel.blue.get_name()
]
}
elif isinstance(pixel, PixelSet) and pixel.get_name() != 'all':
saved_fixtures[pixel.get_name()] = {
'pixels': [subpixel.get_name() for subpixel in pixel.get_pixels()]
}
for controller in controller_set:
if isinstance(controller, ColorKinetics):
controller_type = "ColorKinetics"
saved_controllers[controller.get_name()] = {
'host': controller.host,
'type': controller_type
}
save_data = json.dumps({
'controllers': saved_controllers,
'pixels': saved_pixels,
'fixtures': saved_fixtures,
'presets': presets
}, sort_keys=True, indent=2, separators=(',', ': '))
with open(config_file, 'w') as f:
f.write(save_data)
def redirect_url():
return redirect(request.args.get('next') or \
request.referrer or \
url_for('index'))
fade_in_progress = False
def fade_step():
global fade_in_progress
need_more = False
controller_set = set()
for pixel in pixels:
if isinstance(pixel, RgbPixel):
if pixel.step():
need_more = True
for controller in controller_set:
controller.sync()
if need_more:
ioloop.add_timeout(timedelta(milliseconds=25))
else:
fade_in_progress = False
def start_fade():
global fade_in_progress
if fade_in_progress:
return
fade_in_progress = True
fade_step()
@app.route('/', methods=['GET'])
def index():
all_pixels = pixels['all'].get_html_color()
pixel_list = [(name, pixel.get_html_color())
for name, pixel in pixels.items()
if not isinstance(pixel, PixelSet)]
pixel_list.sort(key=lambda pixel: pixel[0])
fixture_list = []
for name, fixture in pixels.items():
if (not isinstance(fixture, PixelSet)) or name == "all":
continue
subpixels = [(pixel.get_name(), pixel.get_html_color())
for pixel in fixture.get_pixels()]
fixture_list.append((name, fixture.get_html_color(), subpixels))
fixture_list.sort(key=lambda fixture: fixture[0])
return render_template('index.html',
all=pixels['all'].get_html_color(),
fixtures=fixture_list)
@app.route('/pixel/<pixel>', methods=['GET', 'POST'])
def pixel(pixel):
pixel = pixels[pixel]
if request.method == 'POST':
return pixel_post(pixel)
else:
return pixel_get(pixel)
def pixel_post(pixel):
r = int(request.form['r'])
g = int(request.form['g'])
b = int(request.form['b'])
pixel.set_target(r, g, b)
start_fade()
return ""
def pixel_get(pixel):
r, g, b = pixel.get()
return render_template('pixel.html',
pixel=pixel.get_name(),
r=r, g=g, b=b)
@app.route('/presets', methods=['GET'])
def preset_list():
preset_list = list(presets.keys())
preset_list.sort()
return render_template('presets.html',
presets=preset_list,
last_preset=last_preset)
@app.route('/preset/save', methods=['POST'])
def preset_save():
preset = {}
for name, pixel in pixels.items():
if isinstance(pixel, PixelSet):
continue
preset[name] = pixel.get()
presets[request.form['name']] = preset
save_config(config_file)
global last_preset
last_preset = request.form['preset']
return ""
@app.route('/preset/apply', methods=['POST'])
def preset_apply():
name = request.form['preset']
preset = presets[name]
pixel_set = []
controller_set = set()
for name, value in preset.items():
pixel = pixels[name]
pixel.set_target(*value)
start_fade()
global last_preset
last_preset = name
return ""
@app.route('/preset/delete', methods=['POST'])
def preset_delete():
del presets[request.form['name']]
save_config(config_file)
return ""
if __name__ == '__main__':
import sys
if len(sys.argv) != 2:
print("Usage: python server.py config.json")
config_file = sys.argv[1]
load_config(config_file)
app.debug = True
http_server = HTTPServer(WSGIContainer(app))
http_server.listen(80)
ioloop.start()
|
Python
| 0.000022
|
@@ -2984,16 +2984,25 @@
n pixels
+.values()
:%0A
@@ -3219,16 +3219,27 @@
onds=25)
+, fade_step
)%0A els
|
03739fdd464aeb2ae3dbc0f0184c644cf02db6c4
|
add debug servr to CROS
|
server.py
|
server.py
|
#!/usr/bin/env python
import http.server
import socketserver
import os
import sys
import time
import json
import re
import argparse
from cgi import parse_header, parse_multipart
from urllib.parse import parse_qs
# sys.path.append('./cgi-bin/wnet')
sys.path.append('./cgi-bin/paint_x2_unet')
import cgi_exe
class MyHandler(http.server.CGIHTTPRequestHandler):
def __init__(self, req, client_addr, server):
http.server.CGIHTTPRequestHandler.__init__(
self, req, client_addr, server)
def parse_POST(self):
ctype, pdict = parse_header(self.headers['content-type'])
pdict['boundary'] = bytes(pdict['boundary'], "utf-8")
if ctype == 'multipart/form-data':
postvars = parse_multipart(self.rfile, pdict)
elif ctype == 'application/x-www-form-urlencoded':
length = int(self.headers['content-length'])
postvars = parse_qs(
self.rfile.read(length),
keep_blank_values=1)
else:
postvars = {}
return postvars
def do_POST(self):
t = []
t.append(time.time())
form = self.parse_POST()
t.append(time.time())
if "id" in form:
id_str = form["id"][0]
id_str = re.sub(r'\W+', '', id_str.decode() )
else:
self.ret_result(False)
return
if "line" in form:
bin1 = form["line"][0]
fout1 = open("./images/line/" + id_str + ".png", 'wb')
fout1.write(bin1)
fout1.close()
else:
self.ret_result(False)
return
if "ref" in form:
bin2 = form["ref"][0]
fout2 = open("./images/ref/" + id_str + ".png", 'wb')
fout2.write(bin2)
fout2.close()
else:
self.ret_result(False)
return
blur = 0
if "blur" in form:
blur = form["blur"][0].decode()
try:
blur = int(blur)
except ValueError:
blur = 0
t.append(time.time())
if "step" in form:
if form["step"][0].decode() == "S":
painter.colorize_s(id_str, blur=blur)
if form["step"][0].decode() == "L":
painter.colorize_l(id_str)
else:
painter.colorize(id_str, blur=blur)
t.append(time.time())
self.ret_result(True)
t.append(time.time())
for i, j in zip(t, t[1:]):
print("time [sec]", j - i)
return
def ret_result(self, success):
if success:
content = bytes(
"{ 'message':'The command Completed Successfully' , 'Status':'200 OK','success':true , 'used':" + str(args.gpu) + "}", "UTF-8")
self.send_response(200)
else:
content = bytes(
"{ 'message':'The command Failed' , 'Status':'503 NG','success':false , 'used':" + str(args.gpu) + "}", "UTF-8")
self.send_response(503)
self.send_header("Content-type", "application/json")
self.send_header("Content-Length", len(content))
self.send_header("Access-Control-Allow-Origin", "http://paintschainer.preferred.tech") # hard coding...
self.end_headers()
self.wfile.write(content)
parser = argparse.ArgumentParser(
description='chainer line drawing colorization server')
parser.add_argument('--gpu', '-g', type=int, default=0,
help='GPU ID (negative value indicates CPU)')
parser.add_argument('--port', '-p', type=int, default=8000,
help='using port')
parser.add_argument('--host', '-ho', default='localhost',
help='using host')
args = parser.parse_args()
print('GPU: {}'.format(args.gpu))
painter = cgi_exe.Painter(gpu=args.gpu)
httpd = http.server.HTTPServer((args.host, args.port), MyHandler)
print('serving at', args.host, ':', args.port, )
httpd.serve_forever()
|
Python
| 0.000001
|
@@ -3269,16 +3269,129 @@
ding...%0A
+ self.send_header(%22Access-Control-Allow-Origin%22, %22http://paintschainer5.preferred.tech%22) # hard coding...%0A
|
5ca44abba27a50aaac7be91eebc46f774246117f
|
Check that database is empty before adding demo data
|
server.py
|
server.py
|
import json
import logging
import sys
import os
from datetime import datetime
from flask import Flask, redirect, render_template, request, views
from flask_socketio import SocketIO
from flask_sqlalchemy import SQLAlchemy
from redis import Redis
def get_redis_connection(decode_responses = False, attach_redis_connection = None):
if attach_redis_connection is not None:
return attach_redis_connection
if 'docker' in sys.argv:
return Redis(host='redis', decode_responses = decode_responses)
return Redis(decode_responses = decode_responses)
ctime_format = "%a %b %d %H:%M:%S %Y"
logger = logging.getLogger('input_log')
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler('transact.log')
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
app = Flask(__name__)
if not os.path.exists('data'):
os.makedirs('data')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data/transact_data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
socketio = SocketIO(app)
db = SQLAlchemy(app)
class CreateOrder():
def __init__(self, redis):
self.redis = redis
def perform(self, json_data):
self.redis.rpush('queue', json_data)
# Orders API
@app.route('/api/v1/orders/', methods=['GET'])
def get_orders():
all_orders = Order.query.all()
as_dicts = [order.make_as_dict for order in all_orders]
return json.dumps(as_dicts)
@app.route('/api/v1/orders/<order_id>', methods=['GET'])
def get_order(order_id):
try:
order_id = int(order_id)
except ValueError:
return 'Error: order_id must be a number'
one_order = Order.query.filter(Order.order_id == order_id).first()
if one_order is None:
return 'Error: No such record'
return one_order.make_as_json
@app.route('/api/v1/orders/', methods=['POST'])
def post_order(json_data):
redis = get_redis_connection()
handler = CreateOrder(redis)
handler.perform(json_data)
# Page: New order form
@app.route('/new', methods=['GET'])
def get_new_order():
return render_template('orders/new-order.html')
@app.route('/new', methods=['POST'])
def post_new_order():
message = request.form.get('message', '')
drink = {
'g&t': 'Gin & Tonic',
'espresso-martini': 'Espresso Martini',
'negroni': 'Negroni',
'beer': 'Beer',
'other': request.form.get('other')
}.get(request.form.get('drink'))
if drink is None:
return (
'Something\'s wrong with your order, '
'perhaps you meant to select "Other".',
400)
broadcast(drink, message)
order = Order(drink, message)
json_data = order.make_as_json
redis = get_redis_connection()
handler = CreateOrder(redis)
handler.perform(json_data)
return ('drink', 204)
@app.route('/', methods=['GET'])
def get_index_page():
return redirect('/orders', code=302)
@app.route('/orders', methods=['GET'])
def get_orders_page():
all_orders = Order.query.all()
return render_template('/orders/index.html', orders = all_orders)
@app.route('/live', methods=['GET'])
def get_live_orders():
return render_template('/orders/live-orders.html')
def broadcast(drink, message):
socketio.emit(
'incomming',
{
'drink': drink,
'message': message
},
broadcast=True
)
class Order(db.Model):
order_id = db.Column(db.Integer, primary_key = True)
drink = db.Column(db.String(64), nullable = False)
message = db.Column(db.String(256), nullable = False)
order_received = db.Column(db.DateTime)
def __init__(self, drink, message, order_received = None):
if order_received is None:
order_received = datetime.now()
if not isinstance(order_received, datetime):
try:
order_received = datetime.strptime(order_received, ctime_format)
except ValueError:
raise ValueError('order_received must be datetime instance')
if False in (isinstance(drink, str), isinstance(message, str)):
raise ValueError('drink and message must be strings')
self.order_received = order_received
self.drink = drink
self.message = message
def save_order(self, database, commit=True):
database.session.add(self)
if commit: database.session.commit()
def __repr__(self):
return 'Order("{}", "{}", "{}")'.format(
self.drink, self.message, self.order_received)
@property
def nicely_formatted(self):
return '{}, {} (order received: {})'.format(
self.drink, self.message, self.order_received.ctime())
@property
def make_as_json(self):
return json.dumps([self.make_as_dict])
@property
def make_as_dict(self):
return {
'drink': self.drink,
'message': self.message,
'order_received': self.order_received.ctime()}
def consumer():
redis = get_redis_connection(decode_responses = True)
while True:
source, orders = redis.blpop(['queue'])
if source == 'queue':
for order in json.loads(orders):
Order(**order).save_order(db, commit = False)
db.session.commit()
def prepare_demo_data():
dummy_orders = [Order(*_) for _ in (
('Negroni', 'If you bring it here fast, I\'ll sing you a song.'),
('Espresso Martini', 'Hurry up, I\'m thirsty!'),
('Strawberry Daiquiri', 'Last time I had this was at a Bieber concert'),
('Magic Potion', 'Ya wouldn\'t happen to have any tiramisu, would ya?'),
('Injection attack', '<script> a = function(){ return "DROP TABLE Users or whatever"}</script>'),
('Rosy Martini', 'Shaken not stirred'))]
dummy_data = [order.make_as_dict for order in dummy_orders]
json_data = json.dumps(dummy_data)
post_order(json_data)
if __name__ == '__main__':
db.create_all()
try:
if 'dbwriter' in sys.argv:
consumer()
else:
prepare_demo_data()
socketio.run(app, host='0.0.0.0')
except KeyboardInterrupt:
logger.info('Server shut down by user')
|
Python
| 0.000001
|
@@ -6108,64 +6108,160 @@
-consumer()%0A else:%0A prepare_demo_data()
+if len(Order.query.all()) == 0:%0A print('Preparing demo data...')%0A prepare_demo_data()%0A consumer()%0A else:
%0A
|
d34368f3c9e570d751b21499d3bd1c5faabb1dba
|
check more places where fxc.exe might hide
|
fips-generators/util/hlslcompiler.py
|
fips-generators/util/hlslcompiler.py
|
'''
Python wrapper for HLSL compiler (fxc.exe)
NOTE: this module contains Windows specific code and should
only be imported when running on Windows.
'''
import subprocess, platform, os, sys
import genutil as util
if sys.version_info[0] < 3:
import _winreg as winreg
else:
import winreg
#-------------------------------------------------------------------------------
def findFxc() :
'''
fcx.exe is located in the 'Windows Kits' SDKs, we first check the
registry for the installation paths, and then see if we can
find the fxc.exe file there under 'bin/x86'
Returns an unicode path string of fxc.exe if found, or None if
not found.
'''
fxcPath = None;
fxcSubPath = u'bin\\x86\\fxc.exe'
# first get the preferred kit name (either 8.1 or 10, are there others?)
try :
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows Kits\\Installed Roots') as key :
for kit in ['KitsRoot10', 'KitsRoot81'] :
try :
fxcPath, _ = winreg.QueryValueEx(key, kit)
fxcPath += fxcSubPath
if os.path.isfile(fxcPath) :
return fxcPath
except :
fxcPath = None
# if registry is not found, try a few other likely paths
for path in [
'C:\\Program Files (x86)\\Windows Kits\\10\\',
'C:\\Program Files (x86)\\Windows Kits\\8.1\\'
] :
if os.path.isdir(path) :
fxcPath = path + fxcSubPath
if os.path.isfile(fxcPath) :
return fxcPath
return None
except WindowsError :
return None
#-------------------------------------------------------------------------------
def callFxc(cmd) :
'''
call the fxc compiler and return its output
'''
print(cmd)
child = subprocess.Popen(cmd, stderr=subprocess.PIPE)
out = ''
while True :
out += bytes.decode(child.stderr.read())
if child.poll() != None :
break
return out
#-------------------------------------------------------------------------------
def parseOutput(output, lines) :
'''
Parse error output lines from FXC,
map them to the original source code location and output
an error message compatible with Xcode or VStudio
'''
hasError = False
hasWarning = False
outLines = output.splitlines()
for outLine in outLines :
# extract generated shader source column, line and message
# format is 'filename(line,startcol-endcol): msg
lineStartIndex = outLine.find('(', 0) + 1
if lineStartIndex == 0 :
continue
lineEndIndex = outLine.find(',', lineStartIndex)
if lineEndIndex == -1 :
continue
colStartIndex = lineEndIndex + 1
colEndIndex = outLine.find('-', colStartIndex)
if colEndIndex == -1 :
colEndIndex = outLine.find(')', colStartIndex)
if colEndIndex == -1 :
continue
msgStartIndex = outLine.find(':', colStartIndex+1)
if msgStartIndex == -1 :
continue
colNr = int(outLine[colStartIndex:colEndIndex])
lineNr = int(outLine[lineStartIndex:lineEndIndex])
msg = outLine[msgStartIndex:]
# map to original location
lineIndex = lineNr - 1
if lineIndex >= len(lines) :
lineIndex = len(lines) - 1
srcPath = lines[lineIndex].path
srcLineNr = lines[lineIndex].lineNumber
# and output...
util.setErrorLocation(srcPath, srcLineNr)
if 'error' in outLine :
hasError = True
util.fmtError(msg, False)
elif 'warning' in outLine :
hasWarning = True
util.fmtWarning(msg)
if hasError :
for line in lines :
print(line.content)
sys.exit(10)
#-------------------------------------------------------------------------------
def compile(lines, base_path, type, c_name, args) :
fxcPath = findFxc()
if not fxcPath :
util.fmtError("fxc.exe not found!\n")
ext = {
'vs': '.vsh',
'fs': '.psh'
}
profile = {
'vs': 'vs_5_0',
'fs': 'ps_5_0'
}
hlsl_src_path = base_path + '.hlsl'
out_path = base_path + '.hlsl.h'
# /Gec is backward compatibility mode
cmd = [fxcPath, '/T', profile[type], '/Fh', out_path, '/Vn', c_name, '/Gec']
if 'debug' in args and args['debug'] == 'true' :
cmd.extend(['/Zi', '/Od'])
else :
cmd.append('/O3')
cmd.append(hlsl_src_path)
output = callFxc(cmd)
parseOutput(output, lines)
|
Python
| 0
|
@@ -576,16 +576,70 @@
bin/x86'
+, if it's not there%0A try any of the subdirectories.
%0A%0A Re
@@ -761,19 +761,16 @@
ath = u'
-bin
%5C%5Cx86%5C%5Cf
@@ -1079,23 +1079,26 @@
-fxcPath
+winkit_dir
, _ = wi
@@ -1153,18 +1153,315 @@
fxcPath
-+
=
+ winkit_dir + u'bin' + fxcSubPath%0A if os.path.isfile(fxcPath) :%0A return fxcPath%0A # try subdirectories%0A for cur_dir in os.listdir(winkit_dir + u'bin'):%0A fxcPath = winkit_dir + u'bin%5C%5C' + cur_dir +
fxcSubP
@@ -1456,32 +1456,36 @@
ir + fxcSubPath%0A
+
@@ -1506,35 +1506,38 @@
.isfile(fxcPath)
-
:%0A
+
|
7542d224d2ab15adec31a2d896a22cab6a7a2b37
|
add log
|
spider.py
|
spider.py
|
# -*- coding: utf-8 -*-
import http.client
from ltc.models import Record
import json
def get_current_price():
conn = http.client.HTTPSConnection('api.huobi.com')
conn.request('GET','/staticmarket/ticker_ltc_json.js')
r = conn.getResponse()
if r.status == 200 :
data = r.read()
string = data.decode('utf8').replace("'", '"')
json_data = json.loads(string)
json = json.dumps(json_data,indent=4, sort_keys=True)
price = json['ticker']['last']
date = json['time']
recod = Record.create(price,date)
record.save()
if __name__ == '__main__':
get_current_price()
|
Python
| 0.000002
|
@@ -452,16 +452,35 @@
s=True)%0A
+ print(json)
%0A
|
195e5cde1d81d7f73b77ce1b1c52f0beea8a2595
|
Fix tclist iterator slicing
|
ejdb/tc.py
|
ejdb/tc.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numbers
from . import c
from .utils import CObjectWrapper
class ListIterator(CObjectWrapper):
"""Python iterator wrapper for a `TCLIST *`.
"""
def __init__(self, wrapped, count=None):
super(ListIterator, self).__init__(
wrapped=wrapped, finalizer=c.tc.listdel,
)
if count is None:
count = c.tc.listnum(wrapped)
self._len = count
self._i = 0
def __iter__(self): # pragma: no cover
return self
def __len__(self):
return self._len
def __getitem__(self, key):
if isinstance(key, slice):
return [self[i] for i in range(key.indices(len(self)))]
elif isinstance(key, numbers.Number):
if key >= len(self):
raise IndexError('Iterator index out of range.')
value_p = c.tc.listval2(self._wrapped, key)
return self.instantiate(value_p)
return NotImplemented
def __next__(self):
if self._i >= self._len:
raise StopIteration
value_p = c.tc.listval2(self._wrapped, self._i)
self._i += 1
return self.instantiate(value_p)
def next(self): # pragma: no cover
"""Python 2 compatibility.
"""
return self.__next__()
def instantiate(self, value_p):
"""Subclasses should override this method to instantiate an item during
iteration.
:param value_p: Points to the current TCList iterator value of type
`c_void_p`.
"""
raise NotImplementedError
|
Python
| 0.000009
|
@@ -695,16 +695,17 @@
n range(
+*
key.indi
|
1e7869a5b7c5503498634dc0161fdfb29bbb4c7b
|
Fix imports to restore schema import.
|
grano/logic/schemata.py
|
grano/logic/schemata.py
|
import os
from grano.core import db, url_for
from grano.model import Schema, Attribute
from grano.logic.validation import validate_schema
from grano.logic import projects as projects_logic
from grano.logic import attributes
def save(project, data):
""" Create a schema. """
data = validate_schema(data)
name = data.get('name')
obj = Schema.by_name(project, name)
if obj is None:
obj = Schema()
obj.name = name
obj.project = project
obj.label = data.get('label')
obj.label_in = data.get('label_in') or obj.label
obj.label_out = data.get('label_out') or obj.label
obj.obj = data.get('obj')
obj.hidden = data.get('hidden')
db.session.add(obj)
names = []
for attribute in data.get('attributes', []):
attribute['schema'] = obj
attr = attributes.save(attribute)
obj.attributes.append(attr)
names.append(attr.name)
for attr in obj.attributes:
if attr.name not in names:
db.session.delete(attr)
return obj
def import_schema(project, fh):
data = yaml.load(fh.read())
try:
save(project, data)
db.session.commit()
except Invalid, inv:
pprint(inv.asdict())
def export_schema(project, path):
if not os.path.exists(path):
os.makedirs(path)
for schema in Schema.all().filter_by(project=project):
if schema.name == 'base':
continue
fn = os.path.join(path, schema.name + '.yaml')
with open(fn, 'w') as fh:
fh.write(yaml.dump(to_dict(schema)))
def to_basic(schema):
return {
'name': schema.name,
'label': schema.label
}
def to_index(schema):
data = to_basic(schema)
data['hidden'] = schema.hidden
return data
def to_rest_index(schema):
data = to_basic(schema)
data['project'] = projects_logic.to_rest_index(schema.project)
data['api_url'] = url_for('schemata_api.view', name=schema.name)
return data
def to_rest(schema):
data = to_rest_index(schema)
data['id'] = schema.id
data['hidden'] = schema.hidden
if schema.label_in:
data['label_in'] = schema.label_in
if schema.label_out:
data['label_out'] = schema.label_out
as_ = [attributes.to_rest(a) for a in schema.attributes]
data['attributes'] = as_
return data
def to_dict(schema):
data = to_basic(schema)
data['id'] = schema.id
data['obj'] = schema.obj
data['project'] = schema.project.slug
data['hidden'] = schema.hidden
data['label_in'] = schema.label_in
data['label_out'] = schema.label_out
data['attributes'] = [attributes.to_dict(a) for a in schema.attributes]
return data
|
Python
| 0
|
@@ -2,16 +2,54 @@
mport os
+%0Aimport yaml%0Afrom pprint import pprint
%0A%0Afrom g
@@ -169,16 +169,25 @@
e_schema
+, Invalid
%0Afrom gr
|
1aed7a2b0213d457e1efdf5923a159fc053caae5
|
Check for multiple teams in migrate_tips
|
gratipay/models/team.py
|
gratipay/models/team.py
|
"""Teams on Gratipay are plural participants with members.
"""
from postgres.orm import Model
class Team(Model):
"""Represent a Gratipay team.
"""
typname = 'teams'
def __eq__(self, other):
if not isinstance(other, Team):
return False
return self.id == other.id
def __ne__(self, other):
if not isinstance(other, Team):
return True
return self.id != other.id
# Constructors
# ============
@classmethod
def from_id(cls, id):
"""Return an existing team based on id.
"""
return cls._from_thing("id", id)
@classmethod
def from_slug(cls, slug):
"""Return an existing team based on slug.
"""
return cls._from_thing("slug_lower", slug.lower())
@classmethod
def _from_thing(cls, thing, value):
assert thing in ("id", "slug_lower")
return cls.db.one("""
SELECT teams.*::teams
FROM teams
WHERE {}=%s
""".format(thing), (value,))
@classmethod
def insert(cls, owner, **fields):
fields['slug_lower'] = fields['slug'].lower()
fields['owner'] = owner.username
return cls.db.one("""
INSERT INTO teams
(slug, slug_lower, name, homepage,
product_or_service, revenue_model, getting_involved, getting_paid,
owner)
VALUES (%(slug)s, %(slug_lower)s, %(name)s, %(homepage)s,
%(product_or_service)s, %(revenue_model)s, %(getting_involved)s,
%(getting_paid)s,
%(owner)s)
RETURNING teams.*::teams
""", fields)
def get_og_title(self):
out = self.name
receiving = self.receiving
if receiving > 0:
out += " receives $%.2f/wk" % receiving
else:
out += " is"
return out + " on Gratipay"
def update_receiving(self, cursor=None):
# Stubbed out for now. Migrate this over from Participant.
pass
@property
def status(self):
return { None: 'unreviewed'
, False: 'rejected'
, True: 'approved'
}[self.is_approved]
def migrate_tips(self):
subscriptions = self.db.all("""
SELECT s.*
FROM subscriptions s
JOIN teams t ON t.slug = s.team
WHERE team=%s
AND s.ctime < t.ctime
""", (self.slug,))
# Make sure the migration hasn't been done already
if subscriptions:
raise AlreadyMigrated
self.db.run("""
INSERT INTO subscriptions
(ctime, mtime, subscriber, team, amount, is_funded)
SELECT ct.ctime
, ct.mtime
, ct.tipper
, %(slug)s
, ct.amount
, ct.is_funded
FROM current_tips ct
JOIN participants p ON p.username = tipper
WHERE ct.tippee=%(owner)s
AND p.claimed_time IS NOT NULL
AND p.is_suspicious IS NOT TRUE
AND p.is_closed IS NOT TRUE
""", {'slug': self.slug, 'owner': self.owner})
class AlreadyMigrated(Exception): pass
|
Python
| 0
|
@@ -2482,19 +2482,85 @@
-WHERE team=
+ JOIN participants p ON t.owner = p.username%0A WHERE p.username =
%25s%0A
@@ -2614,21 +2614,23 @@
, (self.
-slug,
+owner,
))%0A%0A
|
9d354ea7db8c3085660e61b743ae4733ee552784
|
Change envvar names (less teams in Gratipay 2.1)
|
gratipay/models/team.py
|
gratipay/models/team.py
|
"""Teams on Gratipay receive payments and distribute payroll.
"""
import requests
from postgres.orm import Model
status_icons = { "unreviewed": "✋"
, "rejected": "❌"
, "approved": "✅"
}
class Team(Model):
"""Represent a Gratipay team.
"""
typname = 'teams'
def __eq__(self, other):
if not isinstance(other, Team):
return False
return self.id == other.id
def __ne__(self, other):
if not isinstance(other, Team):
return True
return self.id != other.id
# Constructors
# ============
@classmethod
def from_id(cls, id):
"""Return an existing team based on id.
"""
return cls._from_thing("id", id)
@classmethod
def from_slug(cls, slug):
"""Return an existing team based on slug.
"""
return cls._from_thing("slug_lower", slug.lower())
@classmethod
def _from_thing(cls, thing, value):
assert thing in ("id", "slug_lower")
return cls.db.one("""
SELECT teams.*::teams
FROM teams
WHERE {}=%s
""".format(thing), (value,))
@classmethod
def insert(cls, owner, **fields):
fields['slug_lower'] = fields['slug'].lower()
fields['owner'] = owner.username
return cls.db.one("""
INSERT INTO teams
(slug, slug_lower, name, homepage,
product_or_service, todo_url, onboarding_url,
owner)
VALUES (%(slug)s, %(slug_lower)s, %(name)s, %(homepage)s,
%(product_or_service)s, %(todo_url)s, %(onboarding_url)s,
%(owner)s)
RETURNING teams.*::teams
""", fields)
def generate_review_url(self):
import json, os
auth = (os.environ['TEAM_REVIEW_USERNAME'], os.environ['TEAM_REVIEW_TOKEN'])
data = json.dumps({ "title": "review {}".format(self.name)
, "body": "https://gratipay.com/{}/".format(self.slug)
})
r = requests.post( "https://api.github.com/repos/gratipay/review/issues"
, auth=auth
, data=data
)
if r.status_code != 201:
print(r.status_code)
print(r.text)
raise Heck
review_url = r.json()['html_url']
return self.update_review_url(review_url)
def update_review_url(self, review_url):
self.db.run("UPDATE teams SET review_url=%s WHERE id=%s", (review_url, self.id))
self.set_attributes(review_url=review_url)
return review_url
def get_og_title(self):
out = self.name
receiving = self.receiving
if receiving > 0:
out += " receives $%.2f/wk" % receiving
else:
out += " is"
return out + " on Gratipay"
def update_receiving(self, cursor=None):
r = (cursor or self.db).one("""
WITH our_receiving AS (
SELECT amount
FROM current_payment_instructions
JOIN participants p ON p.username = participant
WHERE team = %(slug)s
AND p.is_suspicious IS NOT true
AND amount > 0
AND is_funded
)
UPDATE teams t
SET receiving = COALESCE((SELECT sum(amount) FROM our_receiving), 0)
, nreceiving_from = COALESCE((SELECT count(*) FROM our_receiving), 0)
, distributing = COALESCE((SELECT sum(amount) FROM our_receiving), 0)
, ndistributing_to = 1
WHERE t.slug = %(slug)s
RETURNING receiving, nreceiving_from, distributing, ndistributing_to
""", dict(slug=self.slug))
# This next step is easy for now since we don't have payroll.
from gratipay.models.participant import Participant
Participant.from_username(self.owner).update_taking()
self.set_attributes( receiving=r.receiving
, nreceiving_from=r.nreceiving_from
, distributing=r.distributing
, ndistributing_to=r.ndistributing_to
)
@property
def status(self):
return { None: 'unreviewed'
, False: 'rejected'
, True: 'approved'
}[self.is_approved]
def migrate_tips(self):
payment_instructions = self.db.all("""
SELECT pi.*
FROM payment_instructions pi
JOIN teams t ON t.slug = pi.team
JOIN participants p ON t.owner = p.username
WHERE p.username = %s
AND pi.ctime < t.ctime
""", (self.owner, ))
# Make sure the migration hasn't been done already
if payment_instructions:
raise AlreadyMigrated
return self.db.one("""
WITH rows AS (
INSERT INTO payment_instructions
(ctime, mtime, participant, team, amount, is_funded)
SELECT ct.ctime
, ct.mtime
, ct.tipper
, %(slug)s
, ct.amount
, ct.is_funded
FROM current_tips ct
JOIN participants p ON p.username = tipper
WHERE ct.tippee=%(owner)s
AND p.claimed_time IS NOT NULL
AND p.is_suspicious IS NOT TRUE
AND p.is_closed IS NOT TRUE
RETURNING 1
) SELECT count(*) FROM rows;
""", {'slug': self.slug, 'owner': self.owner})
class AlreadyMigrated(Exception): pass
|
Python
| 0
|
@@ -1915,29 +1915,24 @@
os.environ%5B'
-TEAM_
REVIEW_USERN
@@ -1954,13 +1954,8 @@
on%5B'
-TEAM_
REVI
|
93ed74d3c904c743f91f0c9e81f6d36bda731a10
|
modify example.py
|
example.py
|
example.py
|
#! /usr/bin/python
from FixQueue import FixQueue
if __name__ == "__main__" :
fq = FixQueue(2) # 2 means queue size
fq.append('a')
fq.append('b')
print (fq) # ['a', 'b']
fq.append('c')
print (fq) # ['b', 'c']
print (fq.pop()) # b
print (fq) # ['b']
|
Python
| 0.000001
|
@@ -17,22 +17,8 @@
on%0A%0A
-from FixQueue
impo
|
80adb43a22f82a036d72bdd398d45ee4daa9a5ff
|
Update example.py
|
example.py
|
example.py
|
import pornhub
search_keywords = []
#client = pornhub.PornHub("5.135.164.72", 3128, search_keywords)
#With proxy, given a Proxy IP and Port. For the countries with restricted access like Turkey, etc.
client = pornhub.PornHub(search_keywords)
for star in client.getStars(10):
print(star)
print(star["name"])
for video in client.getVideos(10,page=2):
print(video)
for photo_url in client.getPhotos(5):
print(photo_url)
|
Python
| 0.000001
|
@@ -376,20 +376,16 @@
(video)%0A
-
%0Afor pho
@@ -435,8 +435,96 @@
oto_url)
+%0A%0Avideo = client.getVideo(%22SOME VIDEO URL%22)%0Aprint(video)%0Aprint(video%5B'accurate_views'%5D)%0A
|
4053baa698f1047f09540c9ff3d6e8a08d844335
|
Comment example
|
example.py
|
example.py
|
"""Example app to login to GitHub"""
import argparse
import mechanicalsoup
parser = argparse.ArgumentParser(description='Login to GitHub.')
parser.add_argument("username")
parser.add_argument("password")
args = parser.parse_args()
browser = mechanicalsoup.Browser()
# request github login page
login_page = browser.get("https://github.com/login")
# find login form
login_form = login_page.soup.select("#login")[0].select("form")[0]
# specify username and password
login_form.select("#login_field")[0]['value'] = args.username
login_form.select("#password")[0]['value'] = args.password
page2 = browser.submit(login_page.response, login_form)
assert page2.soup.select(".logout-form")
|
Python
| 0
|
@@ -584,16 +584,26 @@
ssword%0A%0A
+# submit!%0A
page2 =
@@ -649,16 +649,47 @@
in_form)
+%0A%0A# verify we are now logged in
%0Aassert
@@ -717,12 +717,209 @@
ogout-form%22)
+%0A%0A# verify we remain logged in (thanks to cookies) as we browse the rest of the site%0Apage3 = browser.get(%22https://github.com/matt-hickford/MechanicalSoup%22)%0Aassert page3.soup.select(%22.logout-form%22)%0A
|
c279eda7b56e1f793b0241a66fe155cfdbdd1d40
|
Remove intermediate string during gzip compression
|
api/tasks.py
|
api/tasks.py
|
from __future__ import absolute_import
import os
from celery import shared_task
from celery.utils.log import get_task_logger
from api.StormReplayParser import StormReplayParser
import boto
import StringIO
import json
import gzip
from boto.s3.key import Key
log = get_task_logger(__name__)
@shared_task
def LocallyStoredReplayParsingTask(fileName):
log.info('File name='+fileName)
replayFile = open(fileName)
srp = StormReplayParser(replayFile)
log.info("Created StormReplayParser, getting data")
retval = {
'unique_match_id': srp.getUniqueMatchId(),
'map': srp.getMapName(),
'players': srp.getReplayPlayers(),
'chat': srp.getChat(),
#'game': srp.getReplayGameEvents(),
}
log.info("Finished reading from StormReplay. Cleaning up.")
replayFile.close()
os.remove(replayFile.name)
return retval
@shared_task
def S3StoredReplayParsingTask(keyName):
splitKey = keyName.split('/')
if len(splitKey) != 2:
raise ValueError("keyName must be of the form: <folder>/<file>")
keyBase = splitKey[0]
resultKeyName = keyBase + '/replay.json.gz'
#todo: duplicate limiting
log.info('Key='+keyName)
s3 = boto.connect_s3()
bucket = s3.get_bucket(os.environ.get('AWS_BUCKET_NAME'), validate=False)
k = Key(bucket)
k.key = keyName
#todo: is there a better way than just pretending the string is a file?
# try: https://chromium.googlesource.com/external/boto/+/refs/heads/master/boto/s3/keyfile.py
# It's possible we just need to read this to a temp file to save memory.
# also: use cStringIO instead
replayFile = StringIO.StringIO(k.get_contents_as_string())
srp = StormReplayParser(replayFile)
log.info("Created StormReplayParser, getting data")
retval = {
'unique_match_id': srp.getUniqueMatchId(),
'map': srp.getMapName(),
'players': srp.getReplayPlayers(),
'chat': srp.getChat(),
#'game': srp.getReplayGameEvents(),
}
rk = Key(bucket)
rk.key = resultKeyName
rk.set_metadata('Content-Encoding', 'gzip')
out = StringIO.StringIO()
with gzip.GzipFile(fileobj=out, mode="w") as f:
f.write(json.dumps(retval))
rk.set_contents_from_string(out.getvalue())
out.close()
secondsToExpire = 1*60*60
responseHeaders = {
'response-content-encoding': 'gzip',
'response-content-type': 'application/json',
}
s3UrlToResultKey = rk.generate_url(secondsToExpire, 'GET', response_headers=responseHeaders)
log.info("Result: " + s3UrlToResultKey);
log.info("Finished reading from StormReplay. Cleaning up.")
return {
'url': s3UrlToResultKey
}
# todo: task specific logging?
# http://blog.mapado.com/task-specific-logging-in-celery/
|
Python
| 0.001237
|
@@ -201,16 +201,33 @@
StringIO
+%0Aimport cStringIO
%0A%0Aimport
@@ -1615,42 +1615,8 @@
ry.%0A
- # also: use cStringIO instead%0A
@@ -1628,16 +1628,17 @@
yFile =
+c
StringIO
@@ -2093,16 +2093,17 @@
'gzip')%0A
+%0A
out
@@ -2104,16 +2104,17 @@
out =
+c
StringIO
@@ -2213,24 +2213,25 @@
etval))%0A
+#
rk.set_conte
@@ -2258,24 +2258,72 @@
getvalue())%0A
+ rk.set_contents_from_file(out, rewind=True)%0A
out.clos
|
72b3642953d0e14d4b4c9ec03560a96d259f7d16
|
Remove monkey patching in favor of inheritance for SpatialReference
|
contones/srs.py
|
contones/srs.py
|
"""Spatial reference systems"""
from osgeo import osr
# Monkey patch SpatialReference since inheriting from SWIG classes is a hack
def srid(self):
"""Returns the EPSG ID as int if it exists."""
epsg_id = (self.GetAuthorityCode('PROJCS') or
self.GetAuthorityCode('GEOGCS'))
try:
return int(epsg_id)
except TypeError:
return
osr.SpatialReference.srid = property(srid)
def wkt(self):
"""Returns this projection in WKT format."""
return self.ExportToWkt()
osr.SpatialReference.wkt = property(wkt)
def proj4(self):
"""Returns this projection as a proj4 string."""
return self.ExportToProj4()
osr.SpatialReference.proj4 = property(proj4)
def __repr__(self): return self.wkt
osr.SpatialReference.__repr__ = __repr__
class SpatialReference(object):
def __new__(cls, sref):
sr = osr.SpatialReference()
if isinstance(sref, int):
sr.ImportFromEPSG(sref)
elif isinstance(sref, str):
if sref.strip().startswith('+proj='):
sr.ImportFromProj4(sref)
else:
sr.ImportFromWkt(sref)
# Add EPSG authority if applicable
sr.AutoIdentifyEPSG()
else:
raise TypeError('Cannot create SpatialReference '
'from {}'.format(str(sref)))
return sr
|
Python
| 0
|
@@ -53,85 +53,183 @@
r%0A%0A%0A
-# Monkey patch SpatialReference since inheriting from SWIG classes is a hack%0A
+class BaseSpatialReference(osr.SpatialReference):%0A %22%22%22Base class for extending osr.SpatialReference.%22%22%22%0A%0A def __repr__(self):%0A return self.wkt%0A%0A @property%0A
def
@@ -236,32 +236,36 @@
srid(self):%0A
+
+
%22%22%22Returns the E
@@ -299,16 +299,20 @@
%22%22%22%0A
+
+
epsg_id
@@ -365,16 +365,20 @@
+
+
self.Get
@@ -402,16 +402,20 @@
OGCS'))%0A
+
try:
@@ -415,16 +415,20 @@
try:%0A
+
@@ -447,16 +447,20 @@
psg_id)%0A
+
exce
@@ -485,59 +485,38 @@
+
return%0A
-osr.SpatialReference.srid = property(srid)%0A%0A
+%0A @property%0A
def
@@ -518,32 +518,36 @@
def wkt(self):%0A
+
%22%22%22Returns t
@@ -575,24 +575,28 @@
format.%22%22%22%0A
+
return s
@@ -617,43 +617,22 @@
t()%0A
-osr.SpatialReference.wkt =
+%0A @
property
(wkt
@@ -631,15 +631,13 @@
erty
-(wkt)%0A%0A
+%0A
def
@@ -645,24 +645,28 @@
roj4(self):%0A
+
%22%22%22Retur
@@ -702,24 +702,28 @@
string.%22%22%22%0A
+
return s
@@ -742,20 +742,24 @@
Proj4()%0A
-osr.
+%0A%0Aclass
SpatialR
@@ -770,173 +770,286 @@
ence
-.proj4 = property(proj4)%0A%0Adef __repr__(self): return self.wkt%0Aosr.SpatialReference.__repr__ = __repr__%0A%0A%0Aclass SpatialReference(object):%0A%0A def __new__(cls, sref):
+(object):%0A %22%22%22A spatial reference.%22%22%22%0A%0A def __new__(cls, sref):%0A %22%22%22Returns a new BaseSpatialReference instance%0A%0A This allows for customized construction of osr.SpatialReference which%0A has no init method which precludes the use of super().%0A %22%22%22
%0A
@@ -1058,20 +1058,20 @@
sr =
-osr.
+Base
SpatialR
|
aef91895b31a615bb9af4cfae96aae97d91cad91
|
Add Intercept transformer.
|
dftransformers.py
|
dftransformers.py
|
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
class ColumnSelector(BaseEstimator, TransformerMixin):
"""Transformer that selects a column in a numpy array or DataFrame
by index or name.
"""
def __init__(self, idxs=None, name=None):
self.idxs = np.asarray(idxs)
self.idxs = idxs
self.name = name
def fit(self, *args, **kwargs):
return self
def transform(self, X, **transform_params):
# Need to teat pandas data frames and numpy arrays slightly differently.
if isinstance(X, pd.DataFrame) and self.idxs:
return X.iloc[:, self.idxs]
if isinstance(X, pd.DataFrame) and self.name:
return X[self.name]
return X[:, self.idxs]
class FeatureUnion(TransformerMixin):
def __init__(self, transformer_list):
self.transformer_list = transformer_list
def fit(self, X, y=None):
for _, t in self.transformer_list:
t.fit(X, y)
def transform(self, X, *args, **kwargs):
Xs = [t.transform(X) for _, t in self.transformer_list]
if isinstance(X, pd.DataFrame):
return pd.concat(Xs, axis=1)
return np.hstack(Xs)
|
Python
| 0
|
@@ -1228,8 +1228,363 @@
ack(Xs)%0A
+%0A%0Aclass Intercept(TransformerMixin):%0A%0A def fit(self, *args, **kwargs):%0A return self%0A%0A def transform(self, X, *args, **kwargs):%0A if isinstance(X, pd.DataFrame) or isinstance(X, pd.Series):%0A return pd.Series(np.ones(X.shape%5B0%5D),%0A index=X.index, name=%22intercept%22)%0A return np.ones(X.shape%5B0%5D)%0A
|
c6268ebae09758aa2706babc254d38860db28bed
|
Fix permission check
|
api/views.py
|
api/views.py
|
#!/usr/bin/env python2
#
# Copyright 2016 Red Hat, Inc.
#
# Authors:
# Fam Zheng <famz@redhat.com>
#
# This work is licensed under the MIT License. Please see the LICENSE file or
# http://opensource.org/licenses/MIT.
from django.shortcuts import render
from django.views.generic import View
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse, Http404
from django.core.exceptions import PermissionDenied
from django.conf import settings
from .models import Project, Message
import json
from search import SearchEngine
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
class APIView(View):
name = None
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super(APIView, self).dispatch(request, *args, **kwargs)
def get(self, request):
raise PermissionDenied("API must use POST method")
def handle(self, request, **params):
raise Http404("unknown command")
def check_request(self, request):
pass
def post(self, request):
p = request.POST.get("params")
if p:
params = json.loads(p)
else:
params = {}
self.check_request(request)
r = self.handle(request, **params)
if r:
return HttpResponse(json.dumps(r))
else:
return HttpResponse()
class APILoginRequiredView(APIView):
allowed_groups = []
def check_permission(self, request):
return False
def check_request(self, request):
if not request.user.is_authenticated():
raise PermissionDenied()
if request.user.is_superuser:
return
for grp in request.user.groups.all():
if grp.is_superuser or grp.name in self.allowed_groups or \
self.check_permission(request):
return
raise PermissionDenied()
class VersionView(APIView):
name = "version"
def handle(self, request):
return settings.VERSION
class ListProjectView(APIView):
name = "list-projects"
def handle(self, request):
r = [x.name for x in Project.objects.all()]
return r
class AddProjectView(APILoginRequiredView):
name = "add-project"
def handle(self, request, name, mailing_list, url, git, description):
if Project.objects.filter(name=name):
raise Exception("Project already exists")
p = Project(name=name,
mailing_list=mailing_list,
url=url,
git=git,
description=description)
p.save()
class GetProjectPropertiesView(APILoginRequiredView):
name = "get-project-properties"
def handle(self, request, project):
po = Project.objects.get(name=project)
if not po.maintained_by(request.user):
raise PermissionDenied("Access denied to this project")
return po.get_properties()
class SetProjectPropertiesView(APILoginRequiredView):
name = "set-project-properties"
def handle(self, request, project, properties):
po = Project.objects.get(name=project)
if not po.maintained_by(request.user):
raise PermissionDenied("Access denied to this project")
for k, v in properties.iteritems():
po.set_property(k, v)
def render_series(s):
r = {"subject": s.subject,
"project": s.project.name,
"message-id": s.message_id,
"patches": [x.get_mbox() for x in s.get_patches()],
"properties": s.get_properties(),
}
return r
class SearchView(APIView):
name = "search"
def handle(self, request, terms):
se = SearchEngine()
r = se.search_series(*terms)
return [render_series(x) for x in r]
class ImportView(APILoginRequiredView):
name = "import"
allowed_groups = ["importers"]
def handle(self, request, mboxes):
for mbox in mboxes:
try:
Message.objects.add_message_from_mbox(mbox.encode("utf8"), request.user)
except Message.objects.DuplicateMessageError:
pass
class DeletreView(APILoginRequiredView):
""" Delete messages """
name = "delete"
def handle(self, request, terms=[]):
if not terms:
Message.objects.all().delete()
else:
se = SearchEngine()
for r in se.search_series(*terms):
Message.objects.delete_subthread(r)
class Logout(APIView):
name = "logout"
def handle(self, request):
logout(request)
class LoginComand(APIView):
name = "login"
def handle(self, request, username, password):
user = authenticate(username=username, password=password)
if user is not None:
# the password verified for the user
if user.is_active:
login(request, user)
return
else:
raise Exception("User is disabled")
else:
raise PermissionDenied("Wrong user name or password")
|
Python
| 0
|
@@ -1802,28 +1802,8 @@
if
-grp.is_superuser or
grp.
|
7ffae06efc649ce96807b0793c5d874ced0c64fc
|
Fix volume filter
|
src/nodeconductor_openstack/openstack/filters.py
|
src/nodeconductor_openstack/openstack/filters.py
|
import django_filters
from nodeconductor.core import filters as core_filters
from nodeconductor.core.filters import UUIDFilter
from nodeconductor.structure import filters as structure_filters
from . import models
class OpenStackServiceProjectLinkFilter(structure_filters.BaseServiceProjectLinkFilter):
service = core_filters.URLFilter(view_name='openstack-detail', name='service__uuid')
class Meta(object):
model = models.OpenStackServiceProjectLink
class InstanceFilter(structure_filters.BaseResourceFilter):
tenant_uuid = UUIDFilter(name='tenant__uuid')
class Meta(structure_filters.BaseResourceFilter.Meta):
model = models.Instance
fields = structure_filters.BaseResourceFilter.Meta.fields + ('tenant_uuid', 'runtime_state')
order_by = structure_filters.BaseResourceFilter.Meta.order_by + [
'ram',
'-ram',
'cores',
'-cores',
'system_volume_size',
'-system_volume_size',
'data_volume_size',
'-data_volume_size',
'runtime_state',
'-runtime_state',
]
order_by_mapping = dict(
# Backwards compatibility
project__customer__name='service_project_link__project__customer__name',
project__name='service_project_link__project__name',
project__project_groups__name='service_project_link__project__project_groups__name',
**structure_filters.BaseResourceFilter.Meta.order_by_mapping
)
class SecurityGroupFilter(django_filters.FilterSet):
name = django_filters.CharFilter(
name='name',
lookup_type='icontains',
)
description = django_filters.CharFilter(
name='description',
lookup_type='icontains',
)
service = UUIDFilter(
name='service_project_link__service__uuid',
)
project = UUIDFilter(
name='service_project_link__project__uuid',
)
settings_uuid = UUIDFilter(
name='service_project_link__service__settings__uuid'
)
service_project_link = core_filters.URLFilter(
view_name='openstack-spl-detail',
name='service_project_link__pk',
lookup_field='pk',
)
tenant_uuid = UUIDFilter(
name='tenant__uuid'
)
state = core_filters.StateFilter()
class Meta(object):
model = models.SecurityGroup
fields = [
'name',
'description',
'service',
'project',
'service_project_link',
'state',
'settings_uuid',
'tenant_uuid',
]
class IpMappingFilter(django_filters.FilterSet):
project = UUIDFilter(name='project__uuid')
# XXX: remove after upgrading to django-filter 0.12
# which is still unavailable at https://pypi.python.org/simple/django-filter/
private_ip = django_filters.CharFilter()
public_ip = django_filters.CharFilter()
class Meta(object):
model = models.IpMapping
fields = [
'project',
'private_ip',
'public_ip',
]
class FloatingIPFilter(django_filters.FilterSet):
project = UUIDFilter(name='service_project_link__project__uuid')
service = UUIDFilter(name='service_project_link__service__uuid')
service_project_link = core_filters.URLFilter(
view_name='openstack-spl-detail',
name='service_project_link__pk',
lookup_field='pk',
)
tenant_uuid = UUIDFilter(name='tenant__uuid')
class Meta(object):
model = models.FloatingIP
fields = [
'project',
'service',
'status',
'service_project_link',
'tenant_uuid'
]
class FlavorFilter(structure_filters.ServicePropertySettingsFilter):
class Meta(structure_filters.ServicePropertySettingsFilter.Meta):
model = models.Flavor
fields = dict({
'cores': ['exact', 'gte', 'lte'],
'ram': ['exact', 'gte', 'lte'],
'disk': ['exact', 'gte', 'lte'],
}, **{field: ['exact'] for field in structure_filters.ServicePropertySettingsFilter.Meta.fields})
order_by = [
'cores',
'-cores',
'ram',
'-ram',
'disk',
'-disk',
]
class BackupScheduleFilter(django_filters.FilterSet):
description = django_filters.CharFilter(
lookup_type='icontains',
)
instance = core_filters.URLFilter(
view_name='openstack-instance-detail',
name='instance__uuid',
)
instance_uuid = UUIDFilter(name='instance__uuid')
backup_type = django_filters.ChoiceFilter(choices=models.BackupSchedule.BackupTypes.CHOICES)
class Meta(object):
model = models.BackupSchedule
fields = (
'description', 'instance', 'instance_uuid', 'backup_type',
)
class BackupFilter(django_filters.FilterSet):
description = django_filters.CharFilter(
lookup_type='icontains',
)
instance = UUIDFilter(name='instance__uuid')
project = UUIDFilter(name='instance__service_project_link__project__uuid')
class Meta(object):
model = models.Backup
fields = (
'description',
'instance',
'project',
)
class DRBackupFilter(structure_filters.BaseResourceFilter):
source_instance_uuid = UUIDFilter(name='source_instance__uuid')
source_instance = core_filters.URLFilter(view_name='openstack-instance-detail', name='source_instance__uuid')
class Meta(structure_filters.BaseResourceFilter.Meta):
model = models.DRBackup
fields = structure_filters.BaseResourceFilter.Meta.fields + ('source_instance_uuid', 'source_instance')
class VolumeFilter(structure_filters.BaseResourceStateFilter):
instance_uuid = UUIDFilter(name='instances__uuid')
instance = core_filters.URLFilter(view_name='openstack-instance-detail', name='instances__uuid')
class Meta(structure_filters.BaseResourceStateFilter.Meta):
model = models.Volume
fields = structure_filters.BaseResourceStateFilter.Meta.fields + ('instance_uuid', 'instance')
class SnapshotFilter(structure_filters.BaseResourceFilter):
source_volume_uuid = UUIDFilter(name='source_volume__uuid')
source_volume = core_filters.URLFilter(view_name='openstack-volume-detail', name='source_volume__uuid')
backup_uuid = UUIDFilter(name='backups__uuid')
backup = core_filters.URLFilter(view_name='openstack-backup-detail', name='backups__uuid')
class Meta(structure_filters.BaseResourceStateFilter.Meta):
model = models.Snapshot
fields = structure_filters.BaseResourceStateFilter.Meta.fields + (
'source_volume_uuid', 'source_volume', 'backup_uuid', 'backup')
|
Python
| 0
|
@@ -5882,33 +5882,32 @@
r(name='instance
-s
__uuid')%0A ins
@@ -5990,17 +5990,16 @@
instance
-s
__uuid')
|
4a67891a1b8a96fcc666e12b2d4c27e3598d20a2
|
add support email
|
product_price_factor_online/__openerp__.py
|
product_price_factor_online/__openerp__.py
|
# -*- coding: utf-8 -*-
{
'name': "Product price factor for web shop",
'summary': """Multiplies price depending on product attributes""",
'category': 'Website',
'license': 'GPL-3',
'author': "IT-Projects LLC, Ildar Nasyrov",
'price': 20.00,
'currency': 'EUR',
'images': ['images/1.png'],
'website': "https://twitter.com/nasyrov_ildar",
'depends': ['website_sale', 'product_price_factor'],
'data': [
'views/templates.xml',
],
'auto_install': True,
}
|
Python
| 0
|
@@ -309,24 +309,64 @@
es/1.png'%5D,%0A
+ %22support%22: %22apps@it-projects.info%22,%0A
'website
|
6853fd1e45370a9db650b0983e9835c14ea9209e
|
Add diagnostics endpoint
|
gutenberg_http/views.py
|
gutenberg_http/views.py
|
from sanic.exceptions import RequestTimeout
from sanic.request import Request
from sanic.response import json
from gutenberg_http import app
from gutenberg_http.errors import InvalidUsage
from gutenberg_http.logic import body as _body
from gutenberg_http.logic import metadata as _metadata
from gutenberg_http.logic import search as _search
@app.route('/texts/<text_id:int>')
def metadata(request: Request, text_id: int):
include = _metadata(text_id, request.args.get('include'))
return json({'text_id': text_id, 'metadata': include})
# noinspection PyUnusedLocal
@app.route('/texts/<text_id:int>/body')
def body(request: Request, text_id: int):
fulltext = _body(text_id)
return json({'text_id': text_id, 'body': fulltext})
# noinspection PyUnusedLocal
@app.route('/search/<query>')
def search(request: Request, query: str):
results = _search(query, request.args.get('include'))
return json({'texts': results})
# noinspection PyUnusedLocal
@app.exception(InvalidUsage)
def bad_request(request: Request, exception: InvalidUsage):
error = {'error': 'invalid_usage', 'message': exception.message}
return json(error, exception.status_code)
# noinspection PyUnusedLocal
@app.exception(RequestTimeout)
def timeout(request: Request, exception: RequestTimeout):
error = {'error': 'timeout', 'message': 'The request timed out.'}
return json(error, exception.status_code)
# noinspection PyUnusedLocal
@app.exception(Exception)
def on_exception(request: Request, exception: Exception):
error = {'error': exception.__class__.__name__, 'message': str(exception)}
return json(error, getattr(exception, 'status_code', 500))
|
Python
| 0.000002
|
@@ -1663,8 +1663,336 @@
, 500))%0A
+%0A%0A# noinspection PyUnusedLocal,PyProtectedMember%0A@app.route('/healthcheck')%0Adef healthcheck(request: Request):%0A return json(%7B%0A 'caches': %7B%0A 'metadata': _metadata.cache_info()._asdict(),%0A 'body': _body.cache_info()._asdict(),%0A 'search': _search.cache_info()._asdict(),%0A %7D%0A %7D)%0A
|
c33ffffb0f85e7db96f9856640ad0efdd9dc145f
|
Wrap all exceptions in JSON
|
gutenberg_http/views.py
|
gutenberg_http/views.py
|
from sanic.exceptions import RequestTimeout
from sanic.request import Request
from sanic.response import json
from gutenberg_http import app
from gutenberg_http.errors import InvalidUsage
from gutenberg_http.logic import body as _body
from gutenberg_http.logic import metadata as _metadata
from gutenberg_http.logic import search as _search
@app.route('/texts/<text_id:int>')
def metadata(request: Request, text_id: int):
include = _metadata(text_id, request.args.get('include'))
return json({'text_id': text_id, 'metadata': include})
# noinspection PyUnusedLocal
@app.route('/texts/<text_id:int>/body')
def body(request: Request, text_id: int):
fulltext = _body(text_id)
return json({'text_id': text_id, 'body': fulltext})
# noinspection PyUnusedLocal
@app.route('/search/<query>')
def search(request: Request, query: str):
results = _search(query, request.args.get('include'))
return json({'texts': results})
# noinspection PyUnusedLocal
@app.exception(InvalidUsage)
def bad_request(request: Request, exception: InvalidUsage):
error = {'error': 'invalid_usage', 'message': exception.message}
return json(error, exception.status_code)
# noinspection PyUnusedLocal
@app.exception(RequestTimeout)
def timeout(request: Request, exception: RequestTimeout):
error = {'error': 'timeout', 'message': 'The request timed out.'}
return json(error, exception.status_code)
|
Python
| 0.999992
|
@@ -1386,28 +1386,285 @@
ror, exception.status_code)%0A
+%0A%0A# noinspection PyUnusedLocal%0A@app.exception(Exception)%0Adef on_exception(request: Request, exception: Exception):%0A error = %7B'error': exception.__class__.__name__, 'message': str(exception)%7D%0A return json(error, getattr(exception, 'status_code', 500))%0A
|
39f0e8ed68bea6318bcb58801b5368428582f549
|
remove SF checks from user api endpoint
|
api/views.py
|
api/views.py
|
from django.core.management import call_command
from django.utils.six import StringIO
from rest_framework import viewsets
from salesforce.models import Adopter
from salesforce.functions import check_if_faculty_pending
from social.apps.django_app.default.models import \
DjangoStorage as SocialAuthStorage
from wagtail.wagtailimages.models import Image
from .serializers import AdopterSerializer, ImageSerializer, UserSerializer
class AdopterViewSet(viewsets.ModelViewSet):
queryset = Adopter.objects.all()
serializer_class = AdopterSerializer
class ImageViewSet(viewsets.ModelViewSet):
queryset = Image.objects.all()
serializer_class = ImageSerializer
class UserView(viewsets.ModelViewSet):
serializer_class = UserSerializer
def get_queryset(self):
user = self.request.user
try:
social_auth = SocialAuthStorage.user.get_social_auth_for_user(user)
user.accounts_id = social_auth[0].uid
except:
user.accounts_id = None
try:
out = StringIO()
call_command('update_faculty_status', str(user.pk), stdout=out)
except:
pass
# check if there is a record in salesforce for this user - if so, they are pending verification
user.pending_verification = check_if_faculty_pending(user.pk)
return [user]
|
Python
| 0
|
@@ -816,531 +816,8 @@
er%0A%0A
- try:%0A social_auth = SocialAuthStorage.user.get_social_auth_for_user(user)%0A user.accounts_id = social_auth%5B0%5D.uid%0A except:%0A user.accounts_id = None%0A%0A try:%0A out = StringIO()%0A call_command('update_faculty_status', str(user.pk), stdout=out)%0A except:%0A pass%0A%0A # check if there is a record in salesforce for this user - if so, they are pending verification%0A user.pending_verification = check_if_faculty_pending(user.pk)%0A%0A
|
d994337007eb9cfe41edef591cbd30765660a822
|
Prepare for next development iteration
|
yarn_api_client/__init__.py
|
yarn_api_client/__init__.py
|
# -*- coding: utf-8 -*-
__version__ = '0.3.7'
__all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager']
from .application_master import ApplicationMaster
from .history_server import HistoryServer
from .node_manager import NodeManager
from .resource_manager import ResourceManager
|
Python
| 0
|
@@ -40,9 +40,13 @@
0.3.
-7
+8.dev
'%0A__
|
18e3746969f9a2a4c10553cd7c59793fafd955aa
|
uniform multi-website public users handling
|
addons/website_sale/models/res_partner.py
|
addons/website_sale/models/res_partner.py
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.http import request
class ResPartner(models.Model):
_inherit = 'res.partner'
last_website_so_id = fields.Many2one('sale.order', compute='_compute_last_website_so_id', string='Last Online Sales Order')
@api.multi
def _compute_last_website_so_id(self):
SaleOrder = self.env['sale.order']
for partner in self:
if request and hasattr(request, 'website') and not any([u._is_public() for u in partner.user_ids]):
partner.last_website_so_id = SaleOrder.search([
('partner_id', '=', partner.id),
('team_id.team_type', '=', 'website'),
('website_id', '=', request.website.id),
('state', '=', 'draft'),
], order='write_date desc', limit=1)
else:
partner.last_website_so_id = SaleOrder # Not in a website context or public User
|
Python
| 0.999999
|
@@ -483,16 +483,149 @@
n self:%0A
+ is_public = any(%5Bu._is_public()%0A for u in partner.with_context(active_test=False).user_ids%5D)%0A
@@ -679,24 +679,16 @@
and not
-any(%5Bu._
is_publi
@@ -692,38 +692,8 @@
blic
-() for u in partner.user_ids%5D)
:%0A
|
12a287181164faf65605d1d74de5a9cdf6a2f5d4
|
Remove unused code
|
ynr/apps/people/managers.py
|
ynr/apps/people/managers.py
|
from os.path import join
from django.core.files.storage import DefaultStorage
from django.db import models
from django.db import connection
from candidates.models import PersonRedirect
from ynr_refactoring.settings import PersonIdentifierFields
class PersonImageManager(models.Manager):
def create_from_file(self, image_filename, ideal_relative_name, defaults):
# Import the file to media root and create the ORM
# objects.
storage = DefaultStorage()
desired_storage_path = join("images", ideal_relative_name)
with open(image_filename, "rb") as f:
storage_filename = storage.save(desired_storage_path, f)
return self.create(image=storage_filename, **defaults)
def update_or_create_from_file(
self, image_filename, ideal_relative_name, person, defaults
):
try:
image = self.get(person=person, md5sum=defaults["md5sum"])
for k, v in defaults.items():
setattr(image, k, v)
image.save()
return image, False
except self.model.DoesNotExist:
# Prepare args for the base object first:
defaults["person"] = person
# And now the extra object:
image = self.create_from_file(
image_filename, ideal_relative_name, defaults
)
return image
class PersonIdentifierQuerySet(models.query.QuerySet):
def select_choices(self):
default_option = [(None, "")]
options = [(f.name, f.value) for f in PersonIdentifierFields]
return default_option + options
def editable_value_types(self):
"""
Until we have a way to truly manage any key/value pair there are some
IDs that we don't want to be user editable just yet.
In that case, we need a way to exclude non-editable models from
the edit form and the versions diff.
"""
return self.filter(
value_type__in=[vt[0] for vt in self.select_choices()]
)
POPULATE_NAME_SEARCH_COLUMN_SQL = """
UPDATE people_person
SET name_search_vector = sq.terms
FROM (
SELECT pp.id as id, setweight(to_tsvector(coalesce(pp.name, '')), 'A')
||
setweight(to_tsvector(coalesce(string_agg(ppon.name, ' '), '')), 'B') as terms
FROM people_person pp
LEFT JOIN popolo_othername ppon
ON pp.id = ppon.object_id
GROUP BY pp.id, pp.name
) as sq
where sq.id = people_person.id
"""
NAME_SEARCH_TRIGGER_SQL = """
DROP FUNCTION IF EXISTS people_person_search_trigger() CASCADE;
CREATE FUNCTION people_person_search_trigger() RETURNS trigger AS $$
begin
new.name_search_vector := (
WITH po_names as (
select array_to_string(
array(
select po.name
from popolo_othername po
where po.object_id = new.id
), ','
) as other_names
)
SELECT setweight(to_tsvector('pg_catalog.english', coalesce(new.name, '')), 'A') ||
setweight(to_tsvector(coalesce(po_names.other_names, '')), 'D')
FROM po_names
);
return new;
end
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS tsvectorupdate ON people_person CASCADE;
CREATE TRIGGER tsvectorupdate BEFORE INSERT OR UPDATE
ON people_person FOR EACH ROW EXECUTE PROCEDURE people_person_search_trigger();
"""
class PersonQuerySet(models.query.QuerySet):
def alive_now(self):
return self.filter(death_date="")
def joins_for_csv_output(self):
from popolo.models import Membership
return self.prefetch_related(
models.Prefetch(
"memberships",
Membership.objects.select_related(
"ballot", "ballot__election", "party", "post"
),
),
"images__uploading_user",
"tmp_person_identifiers",
)
def get_by_id_with_redirects(self, person_id):
try:
person = self.get(id=person_id)
except self.model.DoesNotExist:
try:
person_id = PersonRedirect.objects.get(
old_person_id=person_id
).new_person_id
return self.get_by_id_with_redirects(person_id)
except PersonRedirect.DoesNotExist:
raise self.model.DoesNotExist
return person
def _run_sql(self, SQL):
with connection.cursor() as cursor:
cursor.execute(SQL)
def update_name_search(self):
self._run_sql(POPULATE_NAME_SEARCH_COLUMN_SQL)
def update_name_search_trigger(self):
self._run_sql(NAME_SEARCH_TRIGGER_SQL)
|
Python
| 0.000006
|
@@ -3731,426 +3731,8 @@
%22)%0A%0A
- def joins_for_csv_output(self):%0A from popolo.models import Membership%0A%0A return self.prefetch_related(%0A models.Prefetch(%0A %22memberships%22,%0A Membership.objects.select_related(%0A %22ballot%22, %22ballot__election%22, %22party%22, %22post%22%0A ),%0A ),%0A %22images__uploading_user%22,%0A %22tmp_person_identifiers%22,%0A )%0A%0A
|
e3ff630917d6bb0f744330abace7c41d2b48ba8f
|
Add "pip_install" task
|
fabfile.py
|
fabfile.py
|
from fabric.api import env, task, local, cd, run, sudo, put
from tempfile import NamedTemporaryFile
env.use_ssh_config = True
env.hosts = ['skylines@skylines']
APP_DIR = '/home/skylines'
SRC_DIR = '%s/src' % APP_DIR
@task
def deploy(branch='master', force=False):
push(branch, force)
restart()
@task
def push(branch='master', force=False):
cmd = 'git push %s:%s %s:master' % (env.host_string, SRC_DIR, branch)
if force:
cmd += ' --force'
local(cmd)
@task
def restart():
with cd(SRC_DIR):
run('git reset --hard')
# compile i18n .mo files
manage('babel compile')
# generate JS/CSS assets
manage('assets build')
# do database migrations
manage('migrate upgrade')
# restart services
restart_service('skylines-api')
restart_service('skylines')
restart_service('mapserver')
restart_service('tracking')
restart_service('celery')
restart_service('mapproxy')
@task
def restart_service(service):
# Using the sudo() command somehow always provokes a password prompt,
# even if NOPASSWD is specified in the sudoers file...
run('sudo supervisorctl restart %s' % service)
@task
def manage(cmd, user=None):
with cd(SRC_DIR):
if user:
sudo('./manage.py %s' % cmd, user=user)
else:
run('./manage.py %s' % cmd)
@task
def update_mapproxy():
with NamedTemporaryFile() as f:
content = open('mapserver/mapproxy/mapproxy.yaml').read()
content = content.replace(
'base_dir: \'/tmp/cache_data\'',
'base_dir: \'%s/cache/mapproxy\'' % APP_DIR,
)
content = content.replace(
'lock_dir: \'/tmp/cache_data/tile_locks\'',
'lock_dir: \'%s/cache/mapproxy/tile_locks\'' % APP_DIR,
)
f.write(content)
f.flush()
put(f.name, '%s/config/mapproxy.yaml' % APP_DIR)
@task
def clean_mapproxy_cache():
with cd('/home/skylines/cache/mapproxy'):
run('rm -rv *')
|
Python
| 0.000011
|
@@ -1955,24 +1955,137 @@
APP_DIR)%0A%0A%0A
+@task%0Adef pip_install():%0A with cd(SRC_DIR):%0A run('git reset --hard')%0A run('pip install -e .')%0A%0A%0A
@task%0Adef cl
|
2d6e3beb7ea4fb5448cba6a123feb73fe25da2a1
|
add kobocat deployment details
|
fabfile.py
|
fabfile.py
|
import os
import sys
from fabric.api import env, run, cd
DEFAULTS = {
'home': '/home/wsgi/srv/',
'repo_name': 'formhub',
}
DEPLOYMENTS = {
'dev': {
'home': '/home/ubuntu/src/',
'host_string': 'ubuntu@dev.ona.io',
'project': 'ona',
'key_filename': os.path.expanduser('~/.ssh/ona.pem'),
'virtualenv': '/home/ubuntu/.virtualenvs/ona'
},
'prod': {
'home': '/home/ubuntu/src/',
'host_string': 'ubuntu@ona.io',
'project': 'ona',
'key_filename': os.path.expanduser('~/.ssh/ona.pem'),
'virtualenv': '/home/ubuntu/.virtualenvs/ona'
},
}
def run_in_virtualenv(command):
d = {
'activate': os.path.join(
env.virtualenv, 'bin', 'activate'),
'command': command,
}
run('source %(activate)s && %(command)s' % d)
def check_key_filename(deployment_name):
if 'key_filename' in DEPLOYMENTS[deployment_name] and \
not os.path.exists(DEPLOYMENTS[deployment_name]['key_filename']):
print "Cannot find required permissions file: %s" % \
DEPLOYMENTS[deployment_name]['key_filename']
return False
return True
def setup_env(deployment_name):
env.update(DEFAULTS)
env.update(DEPLOYMENTS[deployment_name])
if not check_key_filename(deployment_name):
sys.exit(1)
env.code_src = os.path.join(env.home, env.project)
env.pip_requirements_file = os.path.join(env.code_src, 'requirements.pip')
def deploy(deployment_name, branch='master'):
setup_env(deployment_name)
with cd(env.code_src):
run("git fetch origin")
run("git checkout origin/%s" % branch)
run("git submodule init")
run("git submodule update")
run('find . -name "*.pyc" -exec rm -rf {} \;')
# numpy pip install from requirements file fails
run_in_virtualenv("pip install numpy")
run_in_virtualenv("pip install -r %s" % env.pip_requirements_file)
with cd(env.code_src):
run_in_virtualenv(
"python manage.py syncdb --settings=formhub.local_settings")
run_in_virtualenv(
"python manage.py migrate --settings=formhub.local_settings")
run_in_virtualenv(
"python manage.py collectstatic --settings=formhub.local_settings "
"--noinput")
run("sudo /etc/init.d/celeryd-ona restart")
#run("sudo /etc/init.d/celerybeat-ona restart")
run("sudo /usr/local/bin/uwsgi --reload /var/run/ona.pid")
|
Python
| 0
|
@@ -125,22 +125,18 @@
rmhub',%0A
-
%7D%0A
+
%0ADEPLOYM
@@ -371,32 +371,78 @@
virtualenvs/ona'
+,%0A 'celeryd': '/etc/init.d/celeryd-ona'
%0A %7D,%0A 'pro
@@ -661,24 +661,418 @@
ualenvs/ona'
+,%0A 'celeryd': '/etc/init.d/celeryd-ona'%0A %7D,%0A 'kobocat': %7B%0A 'home': '/home/ubuntu/src/',%0A 'host_string':%0A 'ubuntu@ec2-54-200-151-185.us-west-2.compute.amazonaws.com',%0A 'project': 'kobocat',%0A 'key_filename': os.path.expanduser('~/.ssh/kobo01.pem'),%0A 'virtualenv': '/home/ubuntu/.virtualenvs/kobocat',%0A 'celeryd': '/etc/init.d/celeryd'
%0A %7D,%0A%7D%0A%0A%0A
@@ -1223,20 +1223,16 @@
ommand,%0A
-
%7D%0A
@@ -2772,40 +2772,33 @@
udo
-/etc/init.d/celeryd-ona restart%22
+%25s restart%22 %25 env.celeryd
)%0A
|
6bb647771150fb006ecde0ba1d4d237ae37e0f25
|
fix db perms
|
fabfile.py
|
fabfile.py
|
"""Fabric scripts.
Require mkvirtualenv to be installed on all machines and to be run in,
and WORKON_HOME defined in .bash_profile.
"""
from __future__ import with_statement
import os
from fabric.api import *
env.project = "h1ds"
env.git_url = "git@code.h1svr.anu.edu.au:h1ds/h1ds.git"
env.moin_git_url = "git@code.h1svr.anu.edu.au:h1ds/moinmoin-h1ds.git"
## TODO: use introspection to get python dir for venv.
env.python_dir = 'lib/python2.6'
def dev():
"""localhost with django dev server"""
env.environment = 'development'
env.mkvirtualenv = "mkvirtualenv -p python26 --no-site-packages --distribute"
env.hosts = ['localhost']
env.venv_dir = '/home/dave/.virtualenvs'
env.server_user = 'dave'
env.server_group = 'dave'
def staging():
"""localhost with apache"""
env.environment = 'staging'
env.mkvirtualenv = "mkvirtualenv -p python26 --no-site-packages --distribute"
env.hosts = ['localhost']
env.venv_dir = '/home/dave/.virtualenvs'
env.server_user = 'http'
env.server_group = 'http'
def production():
"""h1svr with apache."""
pass
def setup_moin():
env.settings = '%(project)s.settings_%(environment)s' % env
env.venv = "%(project)s_%(environment)s" %env
with prefix('workon %(venv)s' %env):
with cd("%(venv_dir)s/%(venv)s/src/moinmoin" %env):
run('git pull')
run('python setup.py install --force --install-data=%(venv_dir)s/%(venv)s/wikidata --record=install.log' % env)
with cd("%(venv_dir)s/%(venv)s/wikidata/share/moin" %env):
run('tar xf underlay.tar')
with cd("%(venv_dir)s/%(venv)s/wikidata/share" %env):
sudo('chown -R %(server_user)s:%(server_group)s moin' %env)
sudo('chmod -R ug+rwX moin')
sudo('chmod -R o-rwX moin')
def setup():
env.venv = "%(project)s_%(environment)s" %env
run('%(mkvirtualenv)s %(venv)s' % env)
with prefix('workon %(venv)s' %env):
run('cd $VIRTUAL_ENV && git clone %(git_url)s %(project)s' % env)
run('mkdir $VIRTUAL_ENV/src && cd $VIRTUAL_ENV/src && git clone %(moin_git_url)s moinmoin' % env)
run('mkdir $VIRTUAL_ENV/wikidata')
run('mkdir $VIRTUAL_ENV/static')
run('mkdir $VIRTUAL_ENV/log')
run('mkdir $VIRTUAL_ENV/db')
run('pip install fabric')
setup_moin()
def deploy():
env.settings = '%(project)s.settings_%(environment)s' % env
env.venv = "%(project)s_%(environment)s" %env
with prefix('workon %(venv)s' %env):
with cd("%(venv_dir)s/%(venv)s/%(project)s" %env):
run("git pull")
if env.environment == 'development':
run("./bootstrap.py -d")
else:
# TODO: remove the -d flag once git:// access is restored on code.h1svr
run("./bootstrap.py -d")
run('./manage.py syncdb --settings=%(settings)s' % env)
run('./manage.py collectstatic --settings=%(settings)s' % env)
run("./manage.py migrate h1ds_core --settings=%(settings)s" % env)
run("./manage.py migrate h1ds_mdsplus --settings=%(settings)s" % env)
run("./manage.py migrate h1ds_summary --settings=%(settings)s" % env)
# TODO: shouldn't need to treat environs differently here....
if env.environment == 'development':
with prefix('workon %(venv)s' %env):
with cd("%(venv_dir)s/%(venv)s/%(project)s" %env):
run("./manage.py loaddata data/mds_testing.json --settings=%(settings)s" % env)
run("./manage.py loaddata data/summarydb.json --settings=%(settings)s" % env)
sudo('chmod -R 666 %(venv_dir)s/%(venv)s/db')
elif env.environment == 'staging':
sudo('/etc/rc.d/httpd reload')
else:
sudo('/etc/init.d/apache2 reload')
|
Python
| 0.000001
|
@@ -3301,16 +3301,75 @@
ere....%0A
+ sudo('chmod -R ugo+rwX %25(venv_dir)s/%25(venv)s/db' %25env)%0A
if e
@@ -3704,58 +3704,8 @@
v)%0A%0A
- sudo('chmod -R 666 %25(venv_dir)s/%25(venv)s/db')%0A
|
6fae23c1d442880256ed2d4298844a50d6a7968e
|
Make sure "fab publish" cleans the dist folder
|
fabfile.py
|
fabfile.py
|
import fabric.api as fab
def generate_type_hierarchy():
"""
Generate a document containing the available variable types.
"""
fab.local('./env/bin/python -m puresnmp.types > docs/typetree.rst')
@fab.task
def doc():
generate_type_hierarchy()
fab.local('sphinx-apidoc '
'-o docs/developer_guide/api '
'-f '
'-e '
'puresnmp '
'puresnmp/test')
with fab.lcd('docs'):
fab.local('make html')
@fab.task
def publish():
fab.local('python3 setup.py bdist_wheel --universal')
fab.local('python3 setup.py sdist')
fab.local('twine upload dist/*')
|
Python
| 0
|
@@ -510,24 +510,53 @@
publish():%0A
+ fab.local('rm -rf dist')%0A
fab.loca
|
24c7c61b06ef8f1396d167bc0621d58d7a233fde
|
Generate local webserver using SimpleHTTPServer
|
fabfile.py
|
fabfile.py
|
from fabric.api import local
import urllib
def clean():
local('rm -rf output')
def update_cv():
"""Get current version of my CV."""
pdf_remote = "https://github.com/dplarson/CV/raw/master/David_Larson.pdf"
pdf_local = "output/David_Larson.pdf"
try:
urllib.urlretrieve(pdf_remote, pdf_local)
except:
print "Error: unable to download newest version of CV."
def gen():
clean()
local('pelican content -s settings.py')
update_cv()
def push():
gen()
local('rsync -rav output/ dplarson@ieng6.ucsd.edu:/home/linux/ieng6/oce/60/dplarson/public_html/')
|
Python
| 0.999891
|
@@ -401,24 +401,52 @@
%0Adef gen():%0A
+ %22%22%22Generate website.%22%22%22%0A
clean()%0A
@@ -515,15 +515,161 @@
def
-push():
+serve():%0A %22%22%22Server website locally.%22%22%22%0A gen()%0A local('cd output && python -m SimpleHTTPServer')%0A%0A%0Adef push():%0A %22%22%22Push website to server.%22%22%22
%0A
|
d94af25800a1e0b6d918659ef08d90f596c5a608
|
change uwsgi worker reload option to graceful reload
|
fabfile.py
|
fabfile.py
|
# -*- coding: utf-8 -*-
import os
from fabric.api import local, run, cd, prefix, env, sudo, settings, shell_env
from deploy import server
env.host_string = '{user}@{host}:{port}'.format(
user=env.pycon_user,
host=env.pycon_host,
port=env.pycon_port
)
def deploy(target='dev', sha1=None):
if sha1 is None:
# get current working git sha1
sha1 = local('git rev-parse HEAD', capture=True)
# server code reset to current working sha1
home_dir = '/home/pyconkr/{target}.pycon.kr/pyconkr-2016'.format(target=target)
if target == 'dev':
python_env = '/home/pyconkr/.pyenv/versions/pyconkr-2016-dev'
else:
python_env = '/home/pyconkr/.pyenv/versions/pyconkr-2016'
with settings(cd(home_dir), shell_env(DJANGO_SETTINGS_MODULE='pyconkr.settings_prod')):
sudo('git fetch --all -p', user='pyconkr')
sudo('git reset --hard ' + sha1, user='pyconkr')
sudo('bower install', user='pyconkr')
sudo('%s/bin/pip install -r requirements.txt' % python_env, user='pyconkr')
sudo('%s/bin/python manage.py compilemessages' % python_env, user='pyconkr')
sudo('%s/bin/python manage.py migrate' % python_env, user='pyconkr')
sudo('%s/bin/python manage.py collectstatic --noinput' % python_env, user='pyconkr')
# worker reload
if target == 'dev':
sudo('restart pyconkr-2016/uwsgi-%s' % target)
else:
sudo('restart pyconkr-2016/uwsgi')
def flatpages_mig(direction='www'):
dev_env = '/home/pyconkr/.pyenv/versions/pyconkr-2016-dev/bin/python'
www_env = '/home/pyconkr/.pyenv/versions/pyconkr-2016/bin/python'
from_env, to_env = (dev_env, www_env) if direction=='www' else (www_env, dev_env)
dev_dir = '/home/pyconkr/dev.pycon.kr/pyconkr-2016'
www_dir = '/home/pyconkr/www.pycon.kr/pyconkr-2016'
from_dir, to_dir = (dev_dir, www_dir) if direction=='www' else (www_dir, dev_dir)
with settings(cd(from_dir),
shell_env(DJANGO_SETTINGS_MODULE='pyconkr.settings_prod')
):
sudo('{python} manage.py dumpdata --indent 2 flatpages -o {fixture_to}'.format(
fixture_to=os.path.join(to_dir, 'pyconkr', 'fixtures', 'flatpages.json'),
python=from_env))
with settings(cd(to_dir),
shell_env(DJANGO_SETTINGS_MODULE='pyconkr.settings_prod')
):
sudo('{python} manage.py loaddata flatpages'.format(
python=to_env))
|
Python
| 0
|
@@ -1463,24 +1463,28 @@
='pyconkr')%0A
+
# worker
@@ -1503,54 +1503,31 @@
-if target == 'dev':%0A sudo('restart
+run('echo r %3E /var/run/
pyco
@@ -1538,17 +1538,16 @@
2016
-/uwsgi-%25s
+-%25s.fifo
' %25
@@ -1557,69 +1557,8 @@
get)
-%0A else:%0A sudo('restart pyconkr-2016/uwsgi')
%0A%0Ade
|
3a74328230d7e11357872cf604c9de0fa6a9553b
|
upgrade modules if necessary
|
fabfile.py
|
fabfile.py
|
import os
from datetime import datetime
from fabric.api import *
from fabric.contrib import *
from fabric.contrib.files import exists
from fabric import utils
_private_pypi = os.getenv('PRIVATE_PYPI')
PIP_OPTIONS = '-i %s' % _private_pypi if _private_pypi else ''
"""
Environments
"""
ENVIRONMENTS = ('dev', 'staging', 'production')
@task
def local():
env.environment = 'dev'
env.repo = "https://github.com/ox-it/talks.ox.git"
env.hosts = ['talks.vm']
env.user = 'talks'
env.settings_module = 'talks.settings'
env.remote_install_dir = '/srv/talks/talks.vm'
env.remote_git_checkout = '/srv/talks/talks.ox'
env.requirements = ['requirements.txt']
env.secrets_dir = '/etc/puppet/secrets/talks-dev.oucs.ox.ac.uk'
@task
def virtual():
env.environment = 'dev'
env.repo = "https://github.com/ox-it/talks.ox.git"
env.hosts = ['192.168.33.178']
env.user = 'talks'
env.settings_module = 'talks.settings'
env.remote_install_dir = '/srv/talks/talks-dev.oucs.ox.ac.uk'
env.remote_git_checkout = '/srv/talks/talks.ox'
env.requirements = ['requirements.txt']
env.secrets_dir = '/srv/%s/secrets' % (env.user)
@task
def staging():
env.environment = 'staging'
env.repo = "https://github.com/ox-it/talks.ox.git"
env.hosts = ['talks-dev.oucs.ox.ac.uk']
env.user = 'talks'
env.settings_module = 'talks.settings'
env.remote_install_dir = '/srv/talks/talks-dev.oucs.ox.ac.uk'
env.remote_git_checkout = '/srv/talks/talks.ox'
env.requirements = ['requirements.txt']
env.secrets_dir = '/srv/%s/secrets' % (env.user)
@task
def production():
env.environment = 'production'
env.repo = "https://github.com/ox-it/talks.ox.git"
env.hosts = ['talks-prod.oucs.ox.ac.uk']
env.user = 'talks'
env.settings_module = 'talks.settings'
env.remote_install_dir = '/srv/talks/talks-prod.oucs.ox.ac.uk'
env.remote_git_checkout = '/srv/talks/talks.ox'
env.requirements = ['requirements.txt']
env.secrets_dir = '/srv/%s/secrets' % (env.user)
"""
Methods
"""
@task
def deploy(version):
if not version:
utils.abort('You must specify a version (whether branch or tag).')
require('user', provided_by=ENVIRONMENTS)
git_hash = git_branch(version)
versioned_path = '/srv/%s/talks.ox-%s-%s' % (env.user, datetime.now().strftime('%Y%m%d%H%M'), git_hash)
createvirtualenv(versioned_path)
with prefix('source %s' % os.path.join(versioned_path, 'bin', 'activate')):
install_dir = prepare(versioned_path)
install(install_dir)
run('rm %s/secrets.py' % install_dir)
run('ln -s %s/secrets.py %s/secrets.py' % (env.secrets_dir, install_dir))
run('rm -f %s' % env.remote_install_dir)
run('ln -s %s %s' % (versioned_path, env.remote_install_dir))
run('touch %s' % os.path.join(env.remote_install_dir, 'talks', 'wsgi.py'))
def prepare(venv):
static_dir = os.path.join(venv, 'static')
install_dir = os.path.join(venv, 'talks')
run('cp -r %s %s' % (os.path.join(env.remote_git_checkout, 'static'), static_dir))
run('cp -r %s %s' % (os.path.join(env.remote_git_checkout, 'talks'), install_dir))
run('cp -r %s %s' % (os.path.join(env.remote_git_checkout, 'manage.py'), venv))
for req in env.requirements:
run('pip install -r %s %s' % (os.path.join(env.remote_git_checkout, req), PIP_OPTIONS))
return install_dir
def install(install_dir):
with cd(os.path.dirname(install_dir)):
run('python manage.py makemigrations --settings=%s' % env.settings_module)
run('python manage.py migrate --settings=%s' % env.settings_module)
run('python manage.py collectstatic --noinput --settings=%s' % env.settings_module)
@task
def rebuild_index():
with cd(env.remote_install_dir):
run('bin/python manage.py rebuild_index')
"""
Private methods
"""
def createvirtualenv(path):
run('virtualenv --system-site-packages %s' % path)
def git_check_existing_repo():
"""
Checks that git repo exists, create it if it doesn't
"""
if not exists(env.remote_git_checkout):
run('git clone %s %s' % (env.repo, env.remote_git_checkout))
def git_branch(name):
"""
Do a checkout on a branch
"""
git_check_existing_repo()
with cd(env.remote_git_checkout):
run('git fetch origin')
run('git checkout origin/%s' % name)
return run('git rev-parse --short HEAD')
|
Python
| 0.000001
|
@@ -3303,16 +3303,26 @@
install
+--upgrade
-r %25s %25s
|
fcdb3de7465467e4ea4a50faec1c39ec9a26e15c
|
set main function
|
async_crawler.py
|
async_crawler.py
|
#!/usr/bin/env python
# python 3.5 async web crawler.
# https://github.com/mehmetkose/python3.5-async-crawler
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2016 Mehmet Kose mehmet@linux.com
import aiohttp
import asyncio
from urllib.parse import urljoin, urldefrag
root_url = "http://python.org"
crawled_urls = []
url_hub = [root_url, "%s/robots.txt" % (root_url), "%s/sitemap.xml" % (root_url)]
async def get_body(url):
response = await aiohttp.request('GET', url)
return await response.read()
def remove_fragment(url):
pure_url, frag = urldefrag(url)
return pure_url
def get_links(html):
new_urls = [link.split('"')[0] for link in str(html).replace("'",'"').split('href="')[1:]]
return [urljoin(root_url, remove_fragment(new_url)) for new_url in new_urls]
if __name__ == '__main__':
loop = asyncio.get_event_loop()
client = aiohttp.ClientSession(loop=loop)
for to_crawl in url_hub:
raw_html = loop.run_until_complete(get_body(to_crawl))
for link in get_links(raw_html):
if root_url in link and not link in crawled_urls:
url_hub.append(link)
url_hub.remove(to_crawl)
crawled_urls.append(to_crawl)
print("url hub: %s | crawled: %s |url : %s" % (len(url_hub), len(crawled_urls), to_crawl))
client.close()
|
Python
| 0.000019
|
@@ -362,14 +362,10 @@
urls
+,
-= %5B%5D%0A
url_
@@ -375,45 +375,20 @@
= %5B
-root_url, %22%25s/robots.txt%22 %25 (
+%5D, %5B
root_url
), %22
@@ -383,17 +383,16 @@
root_url
-)
, %22%25s/si
@@ -810,116 +810,25 @@
s%5D%0A%0A
-if __name__ == '__main__':%0A loop = asyncio.get_event_loop()%0A client = aiohttp.ClientSession(loop=loop)
+async def main():
%0A
@@ -876,32 +876,14 @@
l =
-loop.run_until_complete(
+await
get_
@@ -892,25 +892,24 @@
dy(to_crawl)
-)
%0A for
@@ -1212,24 +1212,103 @@
l))%0A
- client.close()%0A%0A
+%0Aif __name__ == '__main__':%0A loop = asyncio.get_event_loop()%0A loop.run_until_complete(main())
|
d9c29036de29b1563efa8ca9ce75992393b236ad
|
fix import error
|
asyncio_hn/hn.py
|
asyncio_hn/hn.py
|
#!/usr/bin/env python3.6
import asyncio
import logging
import aiohttp
import tqdm
from aiohttp import HttpProcessingError
URL_GET_POST = "https://hacker-news.firebaseio.com/v0/item/{}.json"
URL_GET_USER = "https://hacker-news.firebaseio.com/v0/user/{}.json"
URL_MAX_ITEM = 'https://hacker-news.firebaseio.com/v0/maxitem.json'
URL_TOP_STORIES = "https://hacker-news.firebaseio.com/v0/topstories.json"
URL_NEW_STORIES = "https://hacker-news.firebaseio.com/v0/newstories.json"
URL_BEST_STORIES = "https://hacker-news.firebaseio.com/v0/beststories.json"
URL_UPDATES = "https://hacker-news.firebaseio.com/v0/updates.json"
URL_ASK_STORIES = "https://hacker-news.firebaseio.com/v0/askstories.json"
URL_SHOW_STORIES = "https://hacker-news.firebaseio.com/v0/showstories.json"
URL_JOB_STORIES = "https://hacker-news.firebaseio.com/v0/jobstories.json"
# The max tcp connection we open
MAX_CONNECTION = 1000
# setting up logger
logger = logging.getLogger(__name__)
console = logging.StreamHandler()
logger.addHandler(console)
class ClientHN(aiohttp.ClientSession):
def __init__(self, queue_size=10, progress_bar=False, debug=False, num_dlq_consumers=10, **kwargs):
super(ClientHN, self).__init__(**kwargs)
self.queue_size = queue_size
self.connector_limit = self.connector.limit
self._responses = []
self.progress_bar = progress_bar
self.num_dlq_consumers = num_dlq_consumers
if debug:
logger.setLevel(logging.DEBUG)
async def single_download(self, url):
async with self.get(url) as resp:
return await resp.json()
async def multi_download(self, itr, url, num_of_consumers=None, desc=""):
queue, dlq, responses = asyncio.Queue(
maxsize=self.queue_size), asyncio.Queue(), []
num_of_consumers = num_of_consumers or min(self.connector_limit, self.try_get_itr_len(itr))
consumers = [asyncio.ensure_future(
self._consumer(main_queue=queue, dlq=dlq, responses=responses)) for _ in
range(num_of_consumers or self.connector_limit)]
dlq_consumers = [asyncio.ensure_future(
self._consumer(dlq, dlq, responses)) for _ in range(self.num_dlq_consumers)]
produce = await self._produce(itr, url, queue, desc=desc)
await queue.join()
await dlq.join()
for consumer in consumers + dlq_consumers:
consumer.cancel()
return responses
def try_get_itr_len(self, itr):
try:
return len(itr)
except TypeError:
return 1000000
async def _produce(self, items, base_url, queue, desc=""):
for item in tqdm.tqdm(items, desc=desc + " (Estimation)", disable=not self.progress_bar):
await queue.put(base_url.format(item))
async def _consumer(self, main_queue, dlq, responses):
while True:
try:
url = await main_queue.get()
async with self.get(url, timeout=10) as response:
resp = response
resp.raise_for_status()
responses.append(await resp.json())
# Notify the queue that the item has been processed
main_queue.task_done()
except (HttpProcessingError, asyncio.TimeoutError) as e:
logger.debug("Problem with %s, Moving to DLQ" % url)
await dlq.put(url)
main_queue.task_done()
async def top_stories(self):
return await self.single_download(URL_TOP_STORIES)
async def best_stories(self):
return await self.single_download(URL_BEST_STORIES)
async def new_stories(self):
return await self.single_download(URL_NEW_STORIES)
async def ask_stories(self):
return await self.single_download(URL_ASK_STORIES)
async def updates(self):
return await self.single_download(URL_UPDATES)
async def job_stories(self):
return await self.single_download(URL_JOB_STORIES)
async def max_item(self):
return await self.single_download(URL_MAX_ITEM)
async def users(self, itr_users, num_of_futures=None):
return await self.multi_download(itr_users, URL_GET_USER, num_of_futures, "Download users")
async def items(self, posts_itr, num_of_futures=None):
return await self.multi_download(posts_itr, URL_GET_POST, num_of_futures, "Download items")
async def last_n_items(self, n, num_of_futures=None):
max_item = await self.max_item()
return await self.multi_download(range(max_item, max_item - n, -1), URL_GET_POST, num_of_futures,
"Download last N posts")
|
Python
| 0.000001
|
@@ -88,16 +88,32 @@
aiohttp
+.http_exceptions
import
|
949cf53e380a51042de1885215b94a0d32628dc6
|
Merge of r7486, a lxml version check, for thatch
|
trac/tests/functional/better_twill.py
|
trac/tests/functional/better_twill.py
|
#!/usr/bin/python
"""better_twill is a small wrapper around twill to set some sane defaults and
monkey-patch some better versions of some of twill's methods.
It also handles twill's absense.
"""
import os
from os.path import abspath, dirname, join
import sys
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
# On OSX lxml needs to be imported before twill to avoid Resolver issues
# somehow caused by the mac specific 'ic' module
try:
from lxml import etree
except ImportError:
pass
try:
import twill
except ImportError:
twill = None
# When twill tries to connect to a site before the site is up, it raises an
# exception. In 0.9b1, it's urlib2.URLError, but in -latest, it's
# _mechanize_dist._mechanize.BrowserStateError.
try:
from _mechanize_dist._mechanize import BrowserStateError as ConnectError
except ImportError:
from urllib2 import URLError as ConnectError
if twill:
# We want Trac to generate valid html, and therefore want to test against
# the html as generated by Trac. "tidy" tries to clean up broken html, and
# is responsible for one difficult to track down testcase failure (for
# #5497). Therefore we turn it off here.
twill.commands.config('use_tidy', '0')
# setup short names to reduce typing
# This twill browser (and the tc commands that use it) are essentially
# global, and not tied to our test fixture.
tc = twill.commands
b = twill.get_browser()
# Setup XHTML validation for all retrieved pages
try:
from lxml import etree
except ImportError:
print "SKIP: validation of XHTML output in functional tests " \
"(no lxml installed)"
else:
class _Resolver(etree.Resolver):
base_dir = dirname(abspath(__file__))
def resolve(self, system_url, public_id, context):
return self.resolve_filename(join(self.base_dir,
system_url.split("/")[-1]),
context)
_parser = etree.XMLParser(dtd_validation=True)
_parser.resolvers.add(_Resolver())
etree.set_default_parser(_parser)
def _format_error_log(data, log):
msg = []
for each in log:
context = data.splitlines()[max(0, each.line - 5):
each.line + 6]
msg.append("%s\n\nURL: %s\nLine %d, column %d\n\n%s" % (
each.message, each.filename, each.line, each.column,
"\n".join(context)))
return "\n".join(msg)
def _validate_xhtml(func_name, *args, **kwargs):
page = b.get_html()
if "xhtml1-strict.dtd" not in page:
return
etree.clear_error_log()
try:
doc = etree.parse(StringIO(page), base_url=b.get_url())
except etree.XMLSyntaxError, e:
raise twill.errors.TwillAssertionError(
_format_error_log(page, e.error_log))
b._post_load_hooks.append(_validate_xhtml)
# When we can't find something we expected, or find something we didn't
# expect, it helps the debugging effort to have a copy of the html to
# analyze.
def twill_write_html():
"""Write the current html to a file. Name the file based on the
current testcase.
"""
frame = sys._getframe()
while frame:
if frame.f_code.co_name in ('runTest', 'setUp', 'tearDown'):
testcase = frame.f_locals['self']
testname = testcase.__class__.__name__
tracdir = testcase._testenv.tracdir
break
frame = frame.f_back
else:
# We didn't find a testcase in the stack, so we have no clue what's
# going on.
raise Exception("No testcase was found on the stack. This was "
"really not expected, and I don't know how to handle it.")
filename = os.path.join(tracdir, 'log', "%s.html" % testname)
html_file = open(filename, 'w')
html_file.write(b.get_html())
html_file.close()
return filename
# Twill isn't as helpful with errors as I'd like it to be, so we replace
# the formvalue function. This would be better done as a patch to Twill.
def better_formvalue(form, field, value, fv=tc.formvalue):
try:
fv(form, field, value)
except (twill.errors.TwillAssertionError,
twill.utils.ClientForm.ItemNotFoundError), e:
filename = twill_write_html()
args = e.args + (filename,)
raise twill.errors.TwillAssertionError(*args)
tc.formvalue = better_formvalue
# Twill's formfile function leaves a filehandle open which prevents the
# file from being deleted on Windows. Since we would just assume use a
# StringIO object in the first place, allow the file-like object to be
# provided directly.
def better_formfile(formname, fieldname, filename, content_type=None,
fp=None):
if not fp:
filename = filename.replace('/', os.path.sep)
temp_fp = open(filename, 'rb')
data = temp_fp.read()
temp_fp.close()
fp = StringIO(data)
form = b.get_form(formname)
control = b.get_form_field(form, fieldname)
if not control.is_of_kind('file'):
raise twill.errors.TwillException('ERROR: field is not a file '
'upload field!')
b.clicked(form, control)
control.add_file(fp, content_type, filename)
tc.formfile = better_formfile
# Twill's tc.find() does not provide any guidance on what we got instead of
# what was expected.
def better_find(what, flags='', tcfind=tc.find):
try:
tcfind(what, flags)
except twill.errors.TwillAssertionError, e:
filename = twill_write_html()
args = e.args + (filename,)
raise twill.errors.TwillAssertionError(*args)
tc.find = better_find
def better_notfind(what, flags='', tcnotfind=tc.notfind):
try:
tcnotfind(what, flags)
except twill.errors.TwillAssertionError, e:
filename = twill_write_html()
args = e.args + (filename,)
raise twill.errors.TwillAssertionError(*args)
tc.notfind = better_notfind
else:
b = tc = None
|
Python
| 0
|
@@ -253,16 +253,62 @@
ort sys%0A
+from pkg_resources import parse_version as pv%0A
try:%0A
@@ -1757,27 +1757,296 @@
alled)%22%0A
-els
+ etree = None%0A%0A if etree and pv(etree.__version__) %3C pv('2.0.0'):%0A # 2.0.7 and 2.1.x are known to work.%0A print %22SKIP: validation of XHTML output in functional tests %22 %5C%0A %22(lxml %3C 2.0, api incompatibility)%22%0A etree = None%0A%0A if etre
e:%0A c
|
5c3213ffa866ab07d597b1f4abd747228d4ea0e9
|
Update report.py
|
frappe/core/doctype/report/report.py
|
frappe/core/doctype/report/report.py
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
import json
from frappe import _
import frappe.desk.query_report
from frappe.utils import cint
from frappe.model.document import Document
from frappe.modules.export_file import export_to_files
from frappe.modules import make_boilerplate
class Report(Document):
def validate(self):
"""only administrator can save standard report"""
if not self.module:
self.module = frappe.db.get_value("DocType", self.ref_doctype, "module")
if not self.is_standard:
self.is_standard = "No"
if frappe.session.user=="Administrator" and getattr(frappe.local.conf, 'developer_mode',0)==1:
self.is_standard = "Yes"
if self.is_standard == "No" and frappe.db.get_value("Report", self.name, "is_standard") == "Yes":
frappe.throw(_("Cannot edit a standard report. Please duplicate and create a new report"))
if self.is_standard == "Yes" and frappe.session.user!="Administrator":
frappe.throw(_("Only Administrator can save a standard report. Please rename and save."))
if self.report_type in ("Query Report", "Script Report") \
and frappe.session.user!="Administrator":
frappe.throw(_("Only Administrator allowed to create Query / Script Reports"))
if self.report_type == "Report Builder":
self.update_report_json()
def on_update(self):
self.export_doc()
def update_report_json(self):
data = json.loads(self.json)
data["add_total_row"] = self.add_total_row
self.json = json.dumps(data)
def export_doc(self):
if frappe.flags.in_import:
return
if self.is_standard == 'Yes' and (frappe.local.conf.get('developer_mode') or 0) == 1:
export_to_files(record_list=[['Report', self.name]],
record_module=self.module)
self.create_report_py()
def create_report_py(self):
if self.report_type == "Script Report":
make_boilerplate("controller.py", self, {"name": self.name})
make_boilerplate("controller.js", self, {"name": self.name})
def get_data(self, filters=None, limit=None, user=None):
out = []
if self.report_type in ('Query Report', 'Script Report'):
# query and script reports
data = frappe.desk.query_report.run(self.name, filters=filters, user=user)
columns_list = []
for d in data.get('columns'):
if isinstance(d, dict):
columns_list.append(d.get('label'))
else:
columns_list.append(d.split(':')[0])
out.append(columns_list)
out += data.get('result')
else:
# standard report
params = json.loads(self.json)
columns = params.get('columns')
filters = params.get('filters')
def _format(parts):
# sort by is saved as DocType.fieldname, covert it to sql
return '`tab{0}`.`{1}`'.format(*parts)
order_by = _format(params.get('sort_by').split('.')) + ' ' + params.get('sort_order')
if params.get('sort_by_next'):
order_by += ', ' + _format(params.get('sort_by_next').split('.')) + ' ' + params.get('sort_order_next')
result = frappe.get_list(self.ref_doctype, fields = [_format([c[1], c[0]]) for c in columns],
filters=filters, order_by = order_by, as_list=True, limit=limit, user=user)
meta = frappe.get_meta(self.ref_doctype)
out.append([meta.get_label(c[0]) for c in columns])
out = out + [list(d) for d in result]
return out
@Document.whitelist
def toggle_disable(self, disable):
self.db_set("disabled", cint(disable))
|
Python
| 0.000001
|
@@ -1462,16 +1462,33 @@
(self):%0A
+%09%09if self.json:%0A%09
%09%09data =
@@ -1510,16 +1510,17 @@
f.json)%0A
+%09
%09%09data%5B%22
@@ -1556,16 +1556,17 @@
tal_row%0A
+%09
%09%09self.j
|
604d610d7d7e5d883c643daeba09f5b65db943ce
|
Make aws template use non-interactive apt-get (#1098)
|
parsl/providers/aws/template.py
|
parsl/providers/aws/template.py
|
template_string = """#!/bin/bash
#sed -i 's/us-east-2\.ec2\.//g' /etc/apt/sources.list
cd ~
apt-get update -y
apt-get install -y python3 python3-pip libffi-dev g++ libssl-dev
pip3 install numpy scipy parsl
$worker_init
$user_script
# Shutdown the instance as soon as the worker scripts exits
# or times out to avoid EC2 costs.
if ! $linger
then
halt
fi
"""
|
Python
| 0
|
@@ -85,16 +85,54 @@
st%0Acd ~%0A
+export DEBIAN_FRONTEND=noninteractive%0A
apt-get
|
406987b860987894e297d5172a2a3eb0f4e082f8
|
Fix a bug in the data resizer.
|
core/data/DataResizer.py
|
core/data/DataResizer.py
|
"""
DataResizer
:Authors:
Berend Klein Haneveld
"""
from vtk import vtkImageResample
from vtk import vtkVersion
VTK_MAJOR_VERSION = vtkVersion.GetVTKMajorVersion()
class DataResizer(object):
"""
DataResizer is a tool that will resize a given image dataset.
You can specify a certain magnification factor or you can use a maximum
number of voxels that it should contain. If the image is larger than the
maximum amount of voxels, it will resize the volume to just below the
specified maximum.
It will never upscale a volume! So factor value that are higher than 1.0
will not have any result.
"""
def __init__(self):
super(DataResizer, self).__init__()
def ResizeData(self, imageData, factor=1.0, maximum=0):
self.imageResampler = vtkImageResample()
self.imageResampler.SetInterpolationModeToLinear()
if VTK_MAJOR_VERSION <= 5:
self.imageResampler.SetInput(imageData)
else:
self.imageResampler.SetInputData(imageData)
# If a maximum has been set: calculate the right factor
if maximum > 0:
factor = self.calculateFactor(imageData.GetDimensions(), maximum)
# Make sure that we are never upscaling the data
if factor > 1.0:
factor = 1.0
self.resampledImageData = None
if factor != 1.0:
self.imageResampler.SetAxisMagnificationFactor(0, factor)
self.imageResampler.SetAxisMagnificationFactor(1, factor)
self.imageResampler.SetAxisMagnificationFactor(2, factor)
self.imageResampler.Update()
self.resampledImageData = self.imageResampler.GetOutput()
else:
self.resampledImageData = imageData
return self.resampledImageData
# Private methods
def calculateFactor(self, dimensions, maximum):
voxels = dimensions[0] * dimensions[1] * dimensions[2]
factor = float(maximum) / float(voxels)
return factor
|
Python
| 0
|
@@ -1181,16 +1181,184 @@
= 1.0%0A%0A
+%09%09# The factor is now only in amount of pixels. This has to be translated%0A%09%09# to each of the dimensions: factor%5E(1/3)%0A%09%09axisMagnificationFactor = pow(factor, 1.0/3.0)%0A%0A
%09%09self.r
@@ -1456,17 +1456,34 @@
ctor(0,
-f
+axisMagnificationF
actor)%0A%09
@@ -1534,17 +1534,34 @@
ctor(1,
-f
+axisMagnificationF
actor)%0A%09
@@ -1612,17 +1612,34 @@
ctor(2,
-f
+axisMagnificationF
actor)%0A%09
@@ -1990,16 +1990,17 @@
%09%09return factor%0A
+%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.