function
stringlengths 11
56k
| repo_name
stringlengths 5
60
| features
sequence |
---|---|---|
def load_secret_data(file_to_load=None):
"""Load yaml file from a given location
:param str file_to_load: (optional) Path to the file we need to load.
:rtype: list
:returns: A list with the file's data. An empty list if data was not found.
"""
try:
with open(file_to_load, 'r') as sf:
return yaml.safe_load(sf)
except IOError:
return [] | oVirt/jenkins | [
16,
9,
16,
6,
1366658775
] |
def benchmark(func):
'''
Decorator method to help gather metrics.
'''
global _metrics
def wrapper(*__args, **__kwargs):
name = func.__name__
start_time = time.time()
result = func.__call__(*__args, **__kwargs)
delta_t = time.time() - start_time
try:
_metrics_lock.acquire()
if not _metrics.has_key(name):
_metrics[name] = [ 1, delta_t ]
else:
_metrics[name][0] += 1
_metrics[name][1] += delta_t
finally:
_metrics_lock.release()
return result
return wrapper | mikebryant/tsumufs | [
6,
2,
6,
1,
1343397416
] |
def _handle_decoded(self, decoded):
# Some message was received from the client in the server.
if decoded == 'echo':
# Actual implementations may want to put that in a queue and have an additional
# thread to check the queue and handle what was received and send the results back.
self.send('echo back') | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def send(self, obj):
# Send a message to the client
self.connection.sendall(self.pack_obj(obj)) | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def _handle_decoded(self, decoded):
print('Client received: %s' % (decoded,)) | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def get_free_port():
'''
Helper to get free port (usually not needed as the server can receive '0' to connect to a new
port).
'''
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 0))
_, port = s.getsockname()
s.close()
return port | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def wait_for_condition(condition, timeout=2.):
'''
Helper to wait for a condition with a timeout.
:param float condition:
Timeout to reach condition (in seconds). | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def assert_waited_condition(condition, timeout=2.):
'''
Helper to wait for a condition with a timeout. | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def __init__(self, connection_handler_class=None, params=(), thread_name='', thread_class=None):
if thread_class is None:
thread_class = threading.Thread
self._thread_class = thread_class
if connection_handler_class is None:
connection_handler_class = EchoHandler
self.connection_handler_class = connection_handler_class
self._params = params
self._block = None
self._shutdown_event = threading.Event()
self._thread_name = thread_name | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def serve_forever(self, host, port, block=False):
if self._block is not None:
raise AssertionError(
'Server already started. Please create new one instead of trying to reuse.')
if not block:
self.thread = self._thread_class(target=self._serve_forever, args=(host, port))
self.thread.setDaemon(True)
if self._thread_name:
self.thread.setName(self._thread_name)
self.thread.start()
else:
self._serve_forever(host, port)
self._block = block | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def is_alive(self):
if self._block is None:
return False | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def get_port(self):
'''
Note: only available after socket is already connected. Raises AssertionError if it's not
connected at this point.
'''
wait_for_condition(lambda: hasattr(self, '_sock'), timeout=5.0)
return self._sock.getsockname()[1] | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def shutdown(self):
if DEBUG:
sys.stderr.write('Shutting down server.\n') | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def after_bind_socket(self, host, port):
'''
Clients may override to do something after the host/port is bound.
''' | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def _serve_forever(self, host, port):
if DEBUG:
sys.stderr.write('Listening at: %s (%s)\n' % (host, port)) | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def pack_obj(self, obj):
'''
Mostly packs the object with umsgpack_s then adds the size (in bytes) to the front of the msg
and returns it to be passed on the socket.. | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def __init__(self, host, port, connection_handler_class=None):
'''
:param connection_handler_class: if passed, this is a full-duplex communication (so, handle
incoming requests from server).
'''
if DEBUG:
sys.stderr.write('Connecting to server at: %s (%s)\n' % (host, port))
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock.connect((host, port)) | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def get_host_port(self):
try:
return self._sock.getsockname()
except:
return None, None | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def is_alive(self):
try:
self._sock.getsockname()
return True
except:
return False | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def send(self, obj):
s = self._sock
if s is None:
raise RuntimeError('Connection already closed')
self._sock.sendall(self.pack_obj(obj)) | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def shutdown(self):
s = self._sock
if self._sock is None:
return
self._sock = None
try:
s.shutdown(socket.SHUT_RDWR)
except:
pass
try:
s.close()
except:
pass | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def __init__(self, connection, **kwargs):
threading.Thread.__init__(self, **kwargs)
self.setDaemon(True)
self.connection = connection
try:
connection.settimeout(None) # No timeout
except:
pass | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def run(self):
data = _as_bytes('')
number_of_bytes = 0
try:
while True:
# I.e.: check if the remaining bytes from our last recv already contained
# a new message.
if number_of_bytes == 0 and data.__len__() >= 4:
number_of_bytes = data[
:4] # first 4 bytes say the number_of_bytes of the message
number_of_bytes = struct.unpack("<I", number_of_bytes)[0]
assert number_of_bytes >= 0, 'Error: wrong message received. Shutting down connection!'
data = data[4:] # The remaining is the actual data | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def _handle_msg(self, msg_as_bytes):
if DEBUG > 3:
sys.stderr.write('%s handling message: %s\n' % (self, binascii.b2a_hex(msg_as_bytes)))
decoded = umsgpack_s.unpackb(msg_as_bytes)
self._handle_decoded(decoded) | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def _handle_decoded(self, decoded):
pass | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def _handle_decoded(self, decoded):
sys.stdout.write('%s\n' % (decoded,)) | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def _handle_decoded(self, decoded):
# Some message was received from the client in the server.
if decoded == 'echo':
# Actual implementations may want to put that in a queue and have an additional
# thread to check the queue and handle what was received and send the results back.
self.send('echo back') | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def send(self, obj):
# Send a message to the client
self.connection.sendall(self.pack_obj(obj)) | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def _handle_decoded(self, decoded):
print('Client received: %s' % (decoded,))
received[0] = True | fabioz/mu-repo | [
263,
33,
263,
6,
1337264338
] |
def _render(width, height, text):
# text must already be i18n-ed to Unicode.
data = []
lines = tuple(from_unicode(l) for l in text.split('\n'))
for line in lines:
data.append(line)
# pad page with empty rows
while len(data) % height:
data.append(tuple())
return tuple(data) | Bristol-Braille/canute-ui | [
30,
6,
30,
75,
1431898028
] |
def render_home_menu_help(width, height):
text = _('''\ | Bristol-Braille/canute-ui | [
30,
6,
30,
75,
1431898028
] |
def is_valid_delay(instance):
"""Something that ends with ms."""
if not isinstance(instance, str):
return False
if not instance.endswith("ms"):
return False
return True | BeyondTheClouds/enoslib | [
7,
14,
7,
1,
1505462529
] |
def is_valid_rate(instance):
"""Something that ends with kbit, mbit or gbit."""
if not isinstance(instance, str):
return False
if (
not instance.endswith("gbit")
and not instance.endswith("mbit")
and not instance.endswith("kbit")
):
return False
return True | BeyondTheClouds/enoslib | [
7,
14,
7,
1,
1505462529
] |
def is_valid_loss(instance):
"""semantic:
None: don't set any netem loss rule
x: set a rule with x% loss
"""
if instance is None:
return True
if isinstance(instance, float) or isinstance(instance, int):
return True
if instance <= 1 and instance >= 0:
return True
return False | BeyondTheClouds/enoslib | [
7,
14,
7,
1,
1505462529
] |
def is_valid_ipv4(instance):
import ipaddress
try:
# accept ipv4 and ipv6
ipaddress.ip_interface(instance)
return True
except ipaddress.AddressValueError:
return False | BeyondTheClouds/enoslib | [
7,
14,
7,
1,
1505462529
] |
def test_gng_m3():
_ = gng_m3(
data="example", niter=10, nwarmup=5, nchain=1, ncore=1) | CCS-Lab/hBayesDM | [
176,
104,
176,
26,
1459284853
] |
def __init__(self, **kwargs: typing.Any) -> None:
# COVERAGE NOTE: Below condition is never false, as we never pass a custom help text.
if not kwargs.get("help_text"): # pragma: no branch
kwargs["help_text"] = _(
"""The Certificate Signing Request (CSR) in PEM format. To create a new one: | mathiasertl/django-ca | [
106,
40,
106,
2,
1450884177
] |
def prepare_value(
self, value: typing.Optional[typing.Union[str, "LazyCertificateSigningRequest"]] | mathiasertl/django-ca | [
106,
40,
106,
2,
1450884177
] |
def to_python(self, value: str) -> x509.CertificateSigningRequest: # type: ignore[override]
"""Coerce given str to correct data type, raises ValidationError if not possible.
This function is called during form validation.
"""
if not value.startswith(self.start) or not value.strip().endswith(self.end):
raise forms.ValidationError(mark_safe(self.simple_validation_error))
try:
return x509.load_pem_x509_csr(value.encode("utf-8"))
except ValueError as ex:
raise forms.ValidationError(ex) from ex | mathiasertl/django-ca | [
106,
40,
106,
2,
1450884177
] |
def __init__(self, **kwargs: typing.Any) -> None:
fields = tuple(forms.CharField(required=v in self.required_oids) for v in ADMIN_SUBJECT_OIDS)
# NOTE: do not pass initial here as this is done on webserver invocation
# This screws up tests.
kwargs.setdefault("widget", SubjectWidget)
super().__init__(fields=fields, require_all_fields=False, **kwargs) | mathiasertl/django-ca | [
106,
40,
106,
2,
1450884177
] |
def __init__(self, **kwargs: typing.Any) -> None:
fields = (
forms.CharField(required=False),
forms.BooleanField(required=False),
)
kwargs.setdefault("widget", SubjectAltNameWidget)
kwargs.setdefault("initial", ["", profile.cn_in_san])
super().__init__(fields=fields, require_all_fields=False, **kwargs) | mathiasertl/django-ca | [
106,
40,
106,
2,
1450884177
] |
def __init__(
self, extension: typing.Type[Extension[typing.Any, typing.Any, typing.Any]], **kwargs: typing.Any | mathiasertl/django-ca | [
106,
40,
106,
2,
1450884177
] |
def compress(
self, data_list: typing.Tuple[typing.List[str], bool] | mathiasertl/django-ca | [
106,
40,
106,
2,
1450884177
] |
def disable(self):
self.HEADER = ''
self.OKBLUE = ''
self.OK = ''
self.WARNING = ''
self.FAIL = ''
self.END = '' | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def clear():
bcolor.HEADER = ''
bcolor.OKBLUE = ''
bcolor.OK = ''
bcolor.WARNING = ''
bcolor.FAIL = ''
bcolor.END = '' | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def __init__(self, imagedir=''):
self._imagedir = os.path.join(IMAGEDIR, imagedir) | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def __del__(self):
self.printTestStat() | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def accuracy(self, img):
output = self.makeOutput(img)
report_str = Popen([ACCURACY, self.makeSampleName(img), output], stdout=PIPE).communicate()[0] | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def addArg(self, arg):
self._args.append(arg) | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def addImage(self, img):
self._images.append(img) | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def addImages(self, files):
self._images += files | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def clear(self):
self._images = [] | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def cuneiform(self, args, **kwargs):
cmd = [CUNEIFORM] + args
retcode = call(cmd, **kwargs)
if retcode != 0:
print ' '.join(cmd)
return retcode | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def cuneiformTest(self, img, process=False):
if not os.path.exists(img):
self.printError("image file not exists: %s\n" % img)
return False | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def diff(self, first, second, **kwargs):
cmd = ['diff', DIFFOPTS, first, second]
#print cmd
return call(cmd, **kwargs) | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def diffOdf(self, first, second, **kwargs):
first_odf = zipfile.ZipFile(first)
second_odf = zipfile.ZipFile(second) | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def diffXml(self, xml1, xml2, **kwargs):
first_xml = open(xml1, 'r')
second_xml = open(xml2, 'r')
dom1 = minidom.parseString(first_xml.read())
dom2 = minidom.parseString(second_xml.read())
self.unsetBoostVersion(dom1)
self.unsetBoostVersion(dom2)
first_xml.close()
second_xml.close()
res = self.isEqualElement(dom1.documentElement, dom2.documentElement)
if res == True:
return 0
else:
self.diff(xml1, xml2, **kwargs)
return 1 | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def diffTest(self, img):
if not self.cuneiformTest(img):
return False | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def fileReplace(self, filename, pattern, to):
f = open(filename, 'r')
new_f = re.sub(pattern, to, f.read())
f.close()
f = open(filename, 'w')
f.write(new_f)
f.close() | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def isEqualElement(self, a, b):
if a.tagName != b.tagName:
print " [XML] Different tag names: %s %s" % (a.tagName, b.tagName)
return False
if sorted(a.attributes.items()) != sorted(b.attributes.items()):
print " [XML] Different attributes..."
return False
if len(a.childNodes) != len(b.childNodes):
return False
for ac, bc in zip(a.childNodes, b.childNodes):
if ac.nodeType != bc.nodeType:
return False
if ac.nodeType == ac.TEXT_NODE and ac.data != bc.data:
print " [XML] Different values: '%s' and '%s' in tag <%s>" % (ac.data, bc.data, a.tagName)
return False
if ac.nodeType == ac.ELEMENT_NODE and not self.isEqualElement(ac, bc):
return False
return True | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def makeArgs(self, img):
args = []
args.extend(self._args)
if self._language is not None:
args += ['--language', self._language]
if self._output is not None:
args += ['--output', self._output]
if self._format is not None:
args += ['--format', self._format]
if self._output_image_dir is not None:
args += ['--output-image-dir', self._output_image_dir] | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def makeDiffName(self):
return "%s.diff" % self._output | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def makeFullImageName(self, image):
return os.path.join(IMAGEDIR, self._imagedir, image) | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def makeOutput(self, image):
return '%s.%s.%s' % (os.path.splitext(os.path.basename(image))[0], self.version(), self._format) | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def makeSampleName(self, img):
path = os.path.split(img)
name = os.path.join(path[0], "%s.sample." % os.path.splitext(path[1])[0])
if self._sample_ext is not None:
name += self._sample_ext
else:
name += self._format | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def output(self):
return self._output | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def passed(self):
return self._tests_failed == 0 | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def printError(self, msg):
print "%s Error: %s %s" % (bcolor.FAIL, bcolor.END, msg) | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def printFail(self, img, msg):
print "%-35s %-15s %s FAIL %s %s" % (os.path.basename(img), 'OCR(%s)' % self._format, bcolor.FAIL, bcolor.END, msg) | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def printOk(self, img):
print "%-35s %-15s %s Ok %s" % (os.path.basename(img), 'OCR(%s)' % self._format, bcolor.OK, bcolor.END) | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def printTestStat(self):
print "Tests total: %d, passed: %d, failed: %d" % (self.total(), self._tests_passed, self._tests_failed) | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def removeArg(self, arg):
self._args.remove(arg) | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def setFormat(self, format):
self._format = format | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def setImageOutputDir(self, path):
self._output_image_dir = path | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def setLanguage(self, lang):
self._language = lang | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def setLineBreaks(self, value):
if value:
self._line_breaks = True
else:
self._line_breaks = False | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def setSampleExt(self, ext):
self._sample_ext = ext | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def setPageNumber(self, number):
self._pagenum = number | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def total(self):
return self._tests_failed + self._tests_passed | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def version(self):
if self._version is None:
self._version = Popen([CUNEIFORM, '-V'], stdout=PIPE).communicate()[0].split('\n')[0].split()[-1] | uliss/quneiform | [
10,
2,
10,
6,
1306885353
] |
def index(request):
# get all districts with active school surveys
active_schools = School.objects.filter(
Q(surveyset__begin__lte=datetime.now()) &
Q(surveyset__end__gte=datetime.now())
)
districts = District.objects.filter(school__in=active_schools).distinct()
return render_to_response('survey/index.html', locals(), context_instance=RequestContext(request)) | MAPC/myschoolcommute | [
2,
1,
2,
13,
1300309003
] |
def district_list(request):
districts = District.objects.all()
districts = districts.annotate(school_count=Count('school', distinct=True))
districts = districts.annotate(survey_count=Count('school__survey', distinct=True))
return render_to_response('survey/district_list.html', locals(), context_instance=RequestContext(request)) | MAPC/myschoolcommute | [
2,
1,
2,
13,
1300309003
] |
def school_edit(request, district_slug, school_slug, **kwargs):
# check if district exists
district = get_object_or_404(District.objects, slug__iexact=district_slug)
# get school in district
school = get_object_or_404(School.objects, districtid=district, slug__iexact=school_slug)
# translate to lat/lon
school.geometry.transform(4326)
class BaseSurveySetFormSet(BaseModelFormSet):
def __init__(self, *args, **kwargs):
super(BaseSurveySetFormSet, self).__init__(*args, **kwargs)
self.queryset = SurveySet.objects.filter(school=school).order_by('-begin')
surveysets = SurveySet.objects.filter(school=school)
SurveySetFormSet = modelformset_factory(
SurveySet, formset=BaseSurveySetFormSet, form=SurveySetForm,
can_delete=True, extra=1
)
if request.method == 'POST':
formset = SurveySetFormSet(request.POST)
if formset.is_valid():
sets = formset.save(commit=False)
for surveyset in sets:
surveyset.school = school
surveyset.save()
formset = SurveySetFormSet()
else:
#formset = SurveySetFormSet()
formset = SurveySetFormSet()
surveys = Survey.objects.filter(school=school)
count_day = surveys.filter(created__gte=datetime.today() - timedelta(hours=24)).count()
count_week = surveys.filter(created__gte=datetime.today() - timedelta(days=7)).count()
return render_to_response('survey/school_edit.html', {
'school': school,
'district': district,
'surveys': surveys,
'count_day': count_day,
'count_week': count_week,
'formset': formset,
'surveysets': surveysets,
'now': datetime.now()
},
context_instance=RequestContext(request)
) | MAPC/myschoolcommute | [
2,
1,
2,
13,
1300309003
] |
def school_report(request, school_id, start, end):
school = School.objects.get(pk=school_id)
start_d = dateparse.parse_date(start)
end_d = dateparse.parse_date(end)
report_path = "reports/%s/%s_%s_report.pdf" % (
school.slug, start, end
)
full_path = settings.MEDIA_ROOT + '/' + report_path
full_url = settings.MEDIA_URL + '/' + report_path
path = ForkRunR(
school.pk,
start_d,
end_d
)
dir_name = os.path.dirname(full_path)
if not os.path.exists(dir_name):
os.makedirs(dir_name)
os.rename(path, full_path)
send_mail(
"Your report for school %s, date range %s - %s" % (
school, start, end
),
"You may download it at http://%s/%s" % (
request.META['HTTP_HOST'], full_url
),
settings.SERVER_EMAIL,
[request.user.email]
)
return HttpResponseRedirect(full_url) | MAPC/myschoolcommute | [
2,
1,
2,
13,
1300309003
] |
def get_streets(request, districtid):
"""
Returns all streets for given district
"""
# check if district exists
district = get_object_or_404(District.objects, districtid=districtid)
streets = Street.objects.filter(districtid=districtid)
street_list = []
for street in streets:
street_list.append(street.name)
return HttpResponse(simplejson.dumps(street_list), mimetype='application/json') | MAPC/myschoolcommute | [
2,
1,
2,
13,
1300309003
] |
def school_crossing(request, school_id, street, query=None):
"""
Returns list of unique streets within 5000 meters of school crossing
another street, by name
"""
school = School.objects.get(pk=school_id)
intersections = school.get_intersections()
streets = intersections.filter(st_name_1__iexact=street).values('st_name_2').distinct()
if query is not None and query.strip() != '':
streets = streets.filter(st_name_2__icontains=query)
data = [row['st_name_2'].title() for row in list(streets)]
return HttpResponse(simplejson.dumps(data), mimetype='application/json') | MAPC/myschoolcommute | [
2,
1,
2,
13,
1300309003
] |
def form(request, district_slug, school_slug, **kwargs):
# check if district exists
district = get_object_or_404(District.objects, slug__iexact=district_slug)
# get school in district
school = get_object_or_404(School.objects, districtid=district, slug__iexact=school_slug)
# translate to lat/lon
school.geometry.transform(4326)
SurveyFormset = inlineformset_factory(Survey, Child, form=ChildForm, extra=1, can_delete=False)
formerror = False
if request.method == 'POST':
surveyform = SurveyForm(request.POST, school=school)
if surveyform.is_valid():
survey = surveyform.save(commit=False)
survey.school = school
survey.update_distance()
survey.created = datetime.now()
survey.ip = request.META['REMOTE_ADDR']
surveyformset = SurveyFormset(request.POST, instance=survey)
if surveyformset.is_valid():
survey.save()
surveyformset.save()
return render_to_response(
'survey/thanks.html',
context_instance=RequestContext(request)
)
else:
surveyformset = SurveyFormset(request.POST, instance=Survey())
formerror = True
else:
surveyformset = SurveyFormset(request.POST, instance=Survey())
formerror = True
else:
survey = Survey()
surveyform = SurveyForm(instance=survey)
surveyformset = SurveyFormset(instance=survey)
return render_to_response('survey/form.html', {
'formerror': formerror,
'school': school,
'surveyform': surveyform,
'surveyformset': surveyformset,
},
context_instance=RequestContext(request)
) | MAPC/myschoolcommute | [
2,
1,
2,
13,
1300309003
] |
def batch_form(request, district_slug, school_slug, **kwargs):
# check if district exists
district = get_object_or_404(District.objects, slug__iexact=district_slug)
# get school in district
school = get_object_or_404(School.objects, districtid=district, slug__iexact=school_slug)
# translate to lat/lon
school.geometry.transform(4326)
SurveyFormset = inlineformset_factory(Survey, Child, form=ChildForm, extra=1, can_delete=False)
formerror = False
message = "New survey"
if request.method == 'POST':
surveyform = BatchForm(request.POST, school=school)
if surveyform.is_valid():
survey = surveyform.save(commit=False)
# Ugly Fix: created should save to model, but does not!
created = surveyform.cleaned_data['created']
survey.created = created
survey.user = request.user
survey.school = school
survey.update_distance()
if survey.location is None or survey.location.x == 0:
survey.update_location()
survey.ip = request.META['REMOTE_ADDR']
surveyformset = SurveyFormset(request.POST, instance=survey)
if surveyformset.is_valid():
survey.save()
surveyformset.save()
#Done. Make new form.
message = "Survey submitted. New Entry."
#Save created to reduce repeating
survey = Survey(created=created)
surveyform = BatchForm(instance=survey, initial={
'created': created
})
surveyformset = SurveyFormset(instance=survey)
else:
surveyformset = SurveyFormset(
request.POST, instance=Survey(created=created)
)
formerror = True
else:
surveyformset = SurveyFormset(request.POST, instance=Survey())
formerror = True
else:
survey = Survey()
surveyform = BatchForm(instance=survey)
surveyformset = SurveyFormset(instance=survey)
return render_to_response('survey/batch.html', {
'message': message,
'formerror': formerror,
'school': school,
'surveyform': surveyform,
'surveyformset': surveyformset,
},
context_instance=RequestContext(request)
) | MAPC/myschoolcommute | [
2,
1,
2,
13,
1300309003
] |
def __init__(self):
self._engine = GithubEngine()
self._user = None
self._repo = None
self._website = None
self._current_version = None
self._subfolder_path = None
self._tags = list()
self._tag_latest = None
self._tag_names = list()
self._latest_release = None
self._use_releases = False
self._include_branches = False
self._include_branch_list = ['master']
self._include_branch_auto_check = False
self._manual_only = False
self._version_min_update = None
self._version_max_update = None
# By default, backup current addon on update/target install.
self._backup_current = True
self._backup_ignore_patterns = None
# Set patterns the files to overwrite during an update.
self._overwrite_patterns = ["*.py", "*.pyc"]
self._remove_pre_update_patterns = list()
# By default, don't auto disable+re-enable the addon after an update,
# as this is less stable/often won't fully reload all modules anyways.
self._auto_reload_post_update = False
# Settings for the frequency of automated background checks.
self._check_interval_enabled = False
self._check_interval_months = 0
self._check_interval_days = 7
self._check_interval_hours = 0
self._check_interval_minutes = 0
# runtime variables, initial conditions
self._verbose = False
self._use_print_traces = True
self._fake_install = False
self._async_checking = False # only true when async daemon started
self._update_ready = None
self._update_link = None
self._update_version = None
self._source_zip = None
self._check_thread = None
self._select_link = None
self.skip_tag = None
# Get data from the running blender module (addon).
self._addon = __package__.lower()
self._addon_package = __package__ # Must not change.
self._updater_path = os.path.join(
os.path.dirname(__file__), self._addon + "_updater")
self._addon_root = os.path.dirname(__file__)
self._json = dict()
self._error = None
self._error_msg = None
self._prefiltered_tag_count = 0
# UI properties, not used within this module but still useful to have.
# to verify a valid import, in place of placeholder import
self.show_popups = True # UI uses to show popups or not.
self.invalid_updater = False
# pre-assign basic select-link function
def select_link_function(self, tag):
return tag["zipball_url"]
self._select_link = select_link_function | TheDuckCow/MCprep | [
213,
21,
213,
63,
1383027728
] |
def print_verbose(self, msg):
"""Print out a verbose logging message if verbose is true."""
if not self._verbose:
return
print("{} addon: ".format(self.addon) + msg) | TheDuckCow/MCprep | [
213,
21,
213,
63,
1383027728
] |
def addon(self):
return self._addon | TheDuckCow/MCprep | [
213,
21,
213,
63,
1383027728
] |
def addon(self, value):
self._addon = str(value) | TheDuckCow/MCprep | [
213,
21,
213,
63,
1383027728
] |
def api_url(self):
return self._engine.api_url | TheDuckCow/MCprep | [
213,
21,
213,
63,
1383027728
] |
def api_url(self, value):
if not self.check_is_url(value):
raise ValueError("Not a valid URL: " + value)
self._engine.api_url = value | TheDuckCow/MCprep | [
213,
21,
213,
63,
1383027728
] |
def async_checking(self):
return self._async_checking | TheDuckCow/MCprep | [
213,
21,
213,
63,
1383027728
] |
def auto_reload_post_update(self):
return self._auto_reload_post_update | TheDuckCow/MCprep | [
213,
21,
213,
63,
1383027728
] |
def auto_reload_post_update(self, value):
try:
self._auto_reload_post_update = bool(value)
except:
raise ValueError("auto_reload_post_update must be a boolean value") | TheDuckCow/MCprep | [
213,
21,
213,
63,
1383027728
] |
def backup_current(self):
return self._backup_current | TheDuckCow/MCprep | [
213,
21,
213,
63,
1383027728
] |
def backup_current(self, value):
if value is None:
self._backup_current = False
else:
self._backup_current = value | TheDuckCow/MCprep | [
213,
21,
213,
63,
1383027728
] |
def backup_ignore_patterns(self):
return self._backup_ignore_patterns | TheDuckCow/MCprep | [
213,
21,
213,
63,
1383027728
] |
Subsets and Splits