prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>test_views.py<|end_file_name|><|fim▁begin|>from django.test import TestCase, RequestFactory
from main.models import *
from main.views import *
from bs4 import BeautifulSoup
from .base import *
import datetime
from feedback.models import IndividualFeedback
class StatusCheckTest(TestCase):
"""Testing the decorator test functions"""
def test_user_teacher_test_works(self):
elmar = create_teacher()
self.assertTrue(is_staff(elmar.user))
self.assertTrue(is_teacher(elmar.user))
self.assertFalse(is_admin(elmar.user))
self.assertFalse(is_student(elmar.user))
def test_staff_admin_status_is_properly_undertood_at_login(self):
admin = create_admin()
self.assertTrue(is_staff(admin.user))
self.assertFalse(is_teacher(admin.user))
self.assertTrue(is_admin(admin.user))
self.assertFalse(is_student(admin.user))
def test_student_is_student_and_neither_admin_nor_teacher(self):
bugs_user = User.objects.create_user(
username='bb42', password='ilovecarrots')
bugs = Student.objects.create(
student_id='bb42',
last_name='Bunny',
first_name='Bugs',
user=bugs_user
)
self.assertTrue(is_student(bugs_user))
self.assertFalse(is_staff(bugs_user))
self.assertFalse(is_admin(bugs_user))
self.assertFalse(is_teacher(bugs_user))
class HomePageTest(TeacherUnitTest):
"""Simple tests for the home page"""
def test_home_page_renders_home_template(self):
response = self.client.get('/')
self.assertTemplateUsed(response, 'home.html')
def test_home_page_title_contains_uni_name(self):
response = self.client.get('/')
self.assertContains(response, 'Acme University')
class HomePageForStudentTest(StudentUnitTest):
"""Student homepage is shown"""
def test_student_home_shows_student_template(self):
response = self.client.get('/')
self.assertTemplateUsed(response, 'student_home.html')
def test_student_sees_links_to_all_marksheets(self):
student = self.user.student
module1 = create_module()
performance1 = Performance.objects.create(
student=student, module=module1)
assessment1 = Assessment.objects.create(
module=module1,
value=50,
title='Essay',
available=True,
resit_available=True
)
assessment2 = Assessment.objects.create(
module=module1,
value=50,
title='Exam',
available=True
)
assessment_result_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=30,
resit_mark=40,
)
feedback_1_1 = IndividualFeedback.objects.create(
assessment_result=assessment_result_1,
attempt='first',
completed=True
)
feedback_1_2 = IndividualFeedback.objects.create(
assessment_result=assessment_result_1,
attempt='resit',
completed=True
)
performance1.assessment_results.add(assessment_result_1)
link1 = (
'<a href="/export_feedback/' +
module1.code +
'/' +
str(module1.year) +
'/' +
assessment1.slug +
'/' +
student.student_id +
'/'
)
link1_1 = link1 + 'first/'
link1_2 = link1 + 'resit/'
assessment_result_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=30,
resit_mark=40,
)
feedback_2_1 = IndividualFeedback.objects.create(
assessment_result=assessment_result_2,
attempt='first',
completed=True
)
performance1.assessment_results.add(assessment_result_2)
link2_1 = (
'<a href="/export_feedback/' +
module1.code +
'/' +
str(module1.year) +
'/' +
assessment2.slug +
'/' +
student.student_id +
'/first/'
)
module2 = Module.objects.create(
title="Introduction to Squaredance",
year=1901,
code='i2sq42'
)
student.modules.add(module2)
performance2 = Performance.objects.create(
student=student, module=module2)
assessment3 = Assessment.objects.create(
module=module2,
value=50,
title='Essay',
available=False,
resit_available=False
)
assessment_result_3 = AssessmentResult.objects.create(
assessment=assessment3,
mark=30,
resit_mark=40,
)
feedback_3_1 = IndividualFeedback.objects.create(
assessment_result=assessment_result_3,
attempt='first',
completed=True
)
feedback_3_2 = IndividualFeedback.objects.create(
assessment_result=assessment_result_3,
attempt='resit',
completed=True
)
performance2.assessment_results.add(assessment_result_3)
link3 = (
'<a href="/export_feedback/' +
module2.code +
'/' +
str(module2.year) +
'/' +
assessment3.slug +
'/' +
student.student_id
)
link3_1 = link3 + '/first/'
link3_2 = link3 + '/resit/'
assessment4 = Assessment.objects.create(
module=module2,
value=50,
title='Exam',
available=False
)
assessment_result_4 = AssessmentResult.objects.create(
assessment=assessment4,
mark=30,
resit_mark=40,
)
feedback_4_1 = IndividualFeedback.objects.create(
assessment_result=assessment_result_4,
attempt='first',
completed=True
)
performance2.assessment_results.add(assessment_result_4)
link4_1 = (
'<a href="/export_feedback/' +
module2.code +
'/' +
str(module2.year) +
'/' +
assessment2.slug +
'/' +
student.student_id +
'/first/'
)
response = self.client.get('/')
self.assertContains(response, link1_1)
self.assertContains(response, link1_2)
self.assertContains(response, link2_1)
self.assertNotContains(response, link3_1)
self.assertNotContains(response, link3_2)
self.assertNotContains(response, link4_1)
class AdminDashboardTest(AdminUnitTest):
"""Checks the Admin Dashboard"""
def test_admin_page_uses_right_template(self):
response = self.client.get('/admin_dashboard/')
self.assertNotContains(response, 'Main Settings')
self.user.staff.main_admin = True
self.user.staff.save()
response = self.client.get('/admin_dashboard/')
self.assertContains(response, 'Main Settings')
def test_admin_page_shows_all_subjects_and_years_for_main_admin(self):
self.user.staff.main_admin = True
self.user.staff.save()
subject_area_1 = SubjectArea.objects.create(name='Cartoon Studies')
subject_area_2 = SubjectArea.objects.create(name='Evil Plotting')
course_1 = Course.objects.create(
title='BA in Cartoon Studies',
short_title='Cartoon Studies',
)
course_1.subject_areas.add(subject_area_1)
course_2 = Course.objects.create(
title='BA in Evil Plotting',
short_title='Evil Plotting',
)
course_2.subject_areas.add(subject_area_2)
course_3 = Course.objects.create(
title='BA in Cartoon Studies with Evil Plotting',
short_title='Cartoon Studies / Evil Plotting',
)
course_3.subject_areas.add(subject_area_1)
course_3.subject_areas.add(subject_area_2)
stuff = set_up_stuff()
student_1 = stuff[1]
student_1.course = course_1
student_1.year = 1
student_1.save()
student_2 = stuff[2]
student_2.course = course_2
student_2.year = 2
student_2.save()
student_3 = stuff[3]
student_3.course = course_3
student_3.year = 3
student_3.save()
response = self.client.get('/admin_dashboard/')
url = (
'<a href="/assign_tutors/' +
subject_area_1.slug +
'/1/">'
)
self.assertContains(response, url)
url = (
'<a href="/assign_tutors/' +
subject_area_1.slug +
'/2/">'
)
self.assertNotContains(response, url)
url = (
'<a href="/assign_tutors/' +
subject_area_1.slug +
'/3/">'
)
self.assertContains(response, url)
url = (
'<a href="/assign_tutors/' +
subject_area_2.slug +
'/1/">'
)
self.assertNotContains(response, url)
url = (
'<a href="/assign_tutors/' +
subject_area_2.slug +
'/2/">'
)
self.assertContains(response, url)
url = (
'<a href="/assign_tutors/' +
subject_area_2.slug +
'/3/">'
)
self.assertContains(response, url)
def test_admin_page_shows_own_subjects_and_years_for_normal_admin(self):
subject_area_1 = SubjectArea.objects.create(name='Cartoon Studies')
self.user.staff.subject_areas.add(subject_area_1)
subject_area_2 = SubjectArea.objects.create(name='Evil Plotting')
course_1 = Course.objects.create(
title='BA in Cartoon Studies',
short_title='Cartoon Studies',
)
course_1.subject_areas.add(subject_area_1)
course_2 = Course.objects.create(
title='BA in Evil Plotting',
short_title='Evil Plotting',
)
course_2.subject_areas.add(subject_area_2)
course_3 = Course.objects.create(
title='BA in Cartoon Studies with Evil Plotting',
short_title='Cartoon Studies / Evil Plotting',
)
course_3.subject_areas.add(subject_area_1)
course_3.subject_areas.add(subject_area_2)
stuff = set_up_stuff()
student_1 = stuff[1]
student_1.course = course_1
student_1.year = 1
student_1.save()
student_2 = stuff[2]
student_2.course = course_2
student_2.year = 2
student_2.save()
student_3 = stuff[3]
student_3.course = course_3
student_3.year = 3
student_3.save()
response = self.client.get('/admin_dashboard/')
url = (
'<a href="/assign_tutors/' +
subject_area_1.slug +
'/1/">'
)
self.assertContains(response, url)
url = (
'<a href="/assign_tutors/' +
subject_area_1.slug +
'/2/">'
)
self.assertNotContains(response, url)
url = (
'<a href="/assign_tutors/' +
subject_area_1.slug +
'/3/">'
)
self.assertContains(response, url)
url = (
'<a href="/assign_tutors/' +
subject_area_2.slug +
'/1/">'
)
self.assertNotContains(response, url)
url = (
'<a href="/assign_tutors/' +
subject_area_2.slug +
'/2/">'
)
self.assertNotContains(response, url)
url = (
'<a href="/assign_tutors/' +
subject_area_2.slug +
'/3/">'
)
self.assertNotContains(response, url)
class StudentViewTest(TeacherUnitTest):
"""Tests for the student view function"""
def test_student_view_renders_student_view_template(self):
student = create_student()
response = self.client.get(student.get_absolute_url())
self.assertTemplateUsed(response, 'student_view.html')
self.assertContains(response, "bb23")
self.assertContains(response, "Bunny")
self.assertContains(response, "Bugs")
class AddEditStudentTest(TeacherUnitTest):
"""Tests for the student form function"""
def send_form(self):
response = self.client.post(
'/add_student/',
data={
'student_id': 'bb23',
'last_name': 'Bünny',
'first_name': 'Bugs Middle Names'
}
)
return response
def test_add_edit_student_renders_right_template(self):
response = self.client.get('/add_student/')
self.assertTemplateUsed(response, 'student_form.html')
def test_add_student_adds_student_to_database(self):
self.send_form()
student = Student.objects.first()
self.assertEqual(student.student_id, 'bb23')
self.assertEqual(student.last_name, 'Bünny')
self.assertEqual(student.first_name, 'Bugs Middle Names')
def test_edit_student_shows_correct_data(self):
student = create_student()
response = self.client.get(student.get_edit_url())
self.assertTemplateUsed(response, 'student_form.html')
self.assertContains(response, 'Bunny')
self.assertContains(response, 'Bugs')
self.assertContains(response, 'bb23')
class InviteStudentTest(AdminUnitTest):
"""Already added students can be invited"""
def test_students_can_be_invited_users_get_created(self):
subject_area = create_subject_area()
course = Course.objects.create(
title='BA in Cartoon Studies',
short_title='BA CS',
)
course.subject_areas.add(subject_area)
course.save()
student1 = create_student()
student1.email = '[email protected]'
student1.save()
student2 = Student.objects.create(
student_id='bb4223',
first_name='Buster Middle Names',
last_name='Bunny',
email='[email protected]',
year=2,
course=course
)
url = '/invite_students/' + subject_area.slug + '/'
request = self.factory.post(
url,
data={
'selected_student_id': [
student1.student_id,
student2.student_id
]
}
)
request.user = self.user
invite_students(request, subject_area.slug, testing=True)
user1 = User.objects.get(username='bmnb1')
user2 = User.objects.get(username='bmnb2')
student1_out = Student.objects.get(student_id='bb23')
student2_out = Student.objects.get(first_name='Buster Middle Names')
self.assertEqual(student1_out.user, user1)
self.assertEqual(student2_out.user, user2)
def test_invitation_status_is_displayed_correctly(self):
subject_area = create_subject_area()
course = Course.objects.create(
title='BA in Cartoon Studies',
short_title='BA CS',
)
course.subject_areas.add(subject_area)
course.save()
student1 = create_student() # No email address
student2 = Student.objects.create(
student_id='bb4223',
first_name='Buster',
last_name='Bunny',
year=2,
email='[email protected]',
course=course
)
url = '/invite_students/' + subject_area.slug + '/'
request = self.factory.post(
url,
data={'selected_student_id': [
student1.student_id, student2.student_id
]
}
)
request.user = self.user
response = invite_students(request, subject_area.slug, testing=True)
soup = BeautifulSoup(response.content)
added = str(soup.select('#students_added')[0])
not_added = str(soup.select('#students_without_email')[0])
self.assertIn(student1.name(), not_added)
self.assertIn(student2.name(), added)
class StaffResetPasswordTest(AdminUnitTest):
"""Password can be reset by staff"""
def test_staff_can_reset_password(self):
request = self.factory.get(
'/reset_password/',
data={'email': self.user.email}
)
request.user = self.user
response = reset_password(request, testing=True)
self.assertContains(response, self.user.first_name)
class StudentResetPasswordTest(NotYetLoggedInUnitTest):
def test_student_can_reset_password(self):
user = User.objects.create_user(
username='bb42', password='ilovecarrots')
student = Student.objects.create(
student_id='bb42',
last_name='Bunny',
first_name='Bugs',
user=user,
email='[email protected]'
)
request = self.factory.get(
'/reset_password/',
data={'email': student.email}
)
request.user = self.user
response = reset_password(request, testing=True)
self.assertContains(response, student.short_first_name())
class ModuleViewTest(TeacherUnitTest):
"""Tests for the module view"""
def test_module_view_renders_module_view_template(self):
module = Module.objects.create(
title="Hunting Practice",
code="hp23",
year=1900
)
response = self.client.get(module.get_absolute_url())
self.assertTemplateUsed(response, 'module_view.html')
def test_performances_in_a_module_are_shown(self):
module = Module.objects.create(
title="Hunting Practice",
code="hp23",
year=1900,
eligible="1"
)
student = Student.objects.create(
last_name="Pig",
first_name="Porky",
student_id="pp2323",
year=2
)
response = self.client.post(
module.get_add_students_url(),
data={'student_ids': [student.student_id]}
)
out_response = self.client.get(module.get_absolute_url())
self.assertContains(out_response, "Pig, Porky")
def test_only_active_students_appear_in_module_view(self):
module = create_module()
student1 = create_student()
student2 = Student.objects.create(
last_name="Pig",
first_name="Porky",
student_id="pp2323",
active=False
)
student1.modules.add(module)
performance1 = Performance.objects.create(
student=student1, module=module)
performance2 = Performance.objects.create(
student=student2, module=module)
student2.modules.add(module)
response = self.client.get(module.get_absolute_url())
self.assertContains(response, 'Bunny, Bugs')
self.assertNotContains(response, 'Pig, Porky')
def test_assessment_availability_is_shown_correctly(self):
module = create_module()
student = create_student()
student.modules.add(module)
performance = Performance.objects.create(
student=student, module=module)
assessment = Assessment.objects.create(
title="Essay",
value=100,
available=False,
marksheet_type="Something"
)
module.assessments.add(assessment)
response = self.client.get(module.get_absolute_url())
self.assertContains(
response,
'<span class="glyphicon glyphicon-eye-close">'
)
self.assertContains(
response,
'Show Essay to students'
)
assessment.available = True
assessment.save()
response = self.client.get(module.get_absolute_url())
self.assertContains(
response,
'<span class="glyphicon glyphicon-eye-open">'
)
self.assertContains(
response,
'Hide Essay from students'
)
def test_only_assessments_with_marksheet_show_availability(self):
module = create_module()
student = create_student()
student.modules.add(module)
performance = Performance.objects.create(
student=student, module=module)
assessment1 = Assessment.objects.create(
title="Essay",
value=50,
available=False,
marksheet_type="Something"
)
assessment2 = Assessment.objects.create(
title="Exam",
value=50,
available=False,
)
module.assessments.add(assessment1)
module.assessments.add(assessment2)
response = self.client.get(module.get_absolute_url())
self.assertContains(
response,
'Show Essay to students'
)
self.assertNotContains(
response,
'Show Exam to students'
)
def test_resit_menu_shows_when_required(self):
stuff = set_up_stuff()
module = stuff[0]
module.foundational = True
module.save()
student1 = stuff[1]
student1.qld = True
student1.save()
student2 = stuff[2]
student2.qld = True
student2.save()
performance1 = Performance.objects.get(
module=module, student=student1
)
performance2 = Performance.objects.get(
module=module, student=student2
)
assessment1 = Assessment.objects.create(
module=module,
title='Essay',
value=50
)
assessment2 = Assessment.objects.create(
module=module,
title='Presentation',
value=50
)
result1_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=42
)
result1_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=40
)
performance1.assessment_results.add(result1_1)
performance1.assessment_results.add(result1_2)
result2_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=60,
)
result2_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=80
)
performance2.assessment_results.add(result2_1)
performance2.assessment_results.add(result2_2)
response = self.client.get(module.get_absolute_url())
resit_string = (
'<a class = "btn btn-default dropdown-toggle" data-toggle' +
'="dropdown">Resits <span class="caret"></span></a>'
)
self.assertNotContains(
response,
resit_string
)
result1_1.mark = 0
result1_1.save()
response = self.client.get(module.get_absolute_url())
self.assertContains(
response,
resit_string
)
result1_1.mark = 50
result1_1.save()
result2_1.mark = 39
result2_1.save()
response = self.client.get(module.get_absolute_url())
self.assertContains(
response,
resit_string
)
def test_two_resit_with_feedback_symbols_show(self):
stuff = set_up_stuff()
module = stuff[0]
module.foundational = True
module.save()
student1 = stuff[1]
student1.qld = True
student1.save()
performance1 = Performance.objects.get(
module=module, student=student1
)
assessment1 = Assessment.objects.create(
module=module,
title='Essay',
value=50,
marksheet_type='ESSAY',
resit_marksheet_type='ESSAY',
)
assessment2 = Assessment.objects.create(
module=module,
title='Presentation',
value=50,
marksheet_type='PRESENTATION',
resit_marksheet_type='PRESENTATION',
)
result1_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=38,
resit_mark=80
)
result1_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=36,
resit_mark=80
)
performance1.assessment_results.add(result1_1)
performance1.assessment_results.add(result1_2)
resit_string_essay = (
'<a href="/individual_feedback/' +
stuff[0].code +
'/' +
str(stuff[0].year) +
'/' +
assessment1.slug +
'/' +
stuff[1].student_id +
'/resit/">'
)
resit_string_presentation = (
'<a href="/individual_feedback/' +
stuff[0].code +
'/' +
str(stuff[0].year) +
'/' +
assessment2.slug +
'/' +
stuff[1].student_id +
'/resit/">'
)
response = self.client.get(module.get_absolute_url())
self.assertContains(
response,
resit_string_essay
)
self.assertContains(
response,
resit_string_presentation
)
def test_two_resit_with_feedback_symbols_show_with_3_assessments(self):
stuff = set_up_stuff()
module = stuff[0]
module.save()
student1 = stuff[1]
student1.save()
performance1 = Performance.objects.get(
module=module, student=student1
)
assessment1 = Assessment.objects.create(
module=module,
title='Essay',
value=25,
marksheet_type='ESSAY',
resit_marksheet_type='ESSAY',
)
assessment2 = Assessment.objects.create(
module=module,
title='Presentation',
value=25,
marksheet_type='PRESENTATION',
resit_marksheet_type='PRESENTATION',
)
assessment3 = Assessment.objects.create(
module=module,
title='Second Essay',
value=50,
marksheet_type='ESSAY',
resit_marksheet_type='ESSAY',
)
result1_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=30,
resit_mark=80
)
result1_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=28,
resit_mark=80
)
result1_3 = AssessmentResult.objects.create(
assessment=assessment3,
mark=40,
)
performance1.assessment_results.add(result1_1)
performance1.assessment_results.add(result1_2)
performance1.assessment_results.add(result1_3)
resit_string_essay = (
'<a href="/individual_feedback/' +
stuff[0].code +
'/' +
str(stuff[0].year) +
'/' +
assessment1.slug +
'/' +
stuff[1].student_id +
'/resit/">'
)
resit_string_presentation = (
'<a href="/individual_feedback/' +
stuff[0].code +
'/' +
str(stuff[0].year) +
'/' +
assessment2.slug +
'/' +
stuff[1].student_id +
'/resit/">'
)
resit_string_second_essay = (
'<a href="/individual_feedback/' +
stuff[0].code +
'/' +
str(stuff[0].year) +
'/' +
assessment3.slug +
'/' +
stuff[1].student_id +
'/resit/">'
)
response = self.client.get(module.get_absolute_url())
self.assertContains(
response,
resit_string_essay
)
self.assertContains(
response,
resit_string_presentation
)
self.assertNotContains(
response,
resit_string_second_essay
)
class AddStudentsToModuleTest(TeacherUnitTest):
"""Tests for the function to add students to a module"""
def test_add_students_to_module_uses_right_template(self):
module = create_module()
response = self.client.get(module.get_add_students_url())
self.assertTemplateUsed(response, 'add_students_to_module.html')
def test_only_students_from_same_subject_areas_and_year_are_shown(self):
subject_area1 = create_subject_area()
subject_area2 = SubjectArea.objects.create(name="Evil Plotting")
course = Course.objects.create(title="BA in Cartoon Studies")
course.subject_areas.add(subject_area1)
course.save()
course2 = Course.objects.create(
title="BA in Evil Plotting")
course2.subject_areas.add(subject_area2)
course2.save()
module = create_module()
module.subject_areas.add(subject_area1)
module.save()
student1 = create_student()
student1.course = course
student1.year = 1
student1.save()
student2 = Student.objects.create(
last_name="Duck",
first_name="Daffy",
student_id="dd42",
course=course2,
year=1
)
student3 = Student.objects.create(
last_name="Pig",
first_name="Porky",
student_id="pp2323",
course=course,
year=2
)
student4 = Student.objects.create(
last_name="Runner",
first_name="Road",
student_id="rr42",
course=course,
year=1,
active=False
)
response = self.client.get(module.get_add_students_url())
self.assertContains(response, 'Bunny')
self.assertNotContains(response, 'Duck')
self.assertNotContains(response, 'Pig')
self.assertNotContains(response, 'Runner')
def test_submitting_an_empty_form_does_not_break_it(self):
module = create_module()
response = self.client.post(
'/add_students_to_module/%s/%s' % (module.code, module.year),
data={}
)
self.assertTrue(response.status_code in [301, 302])
class RemoveStudentFromModuleTest(TeacherUnitTest):
"""Tests for the function to remove a student from a module"""
def test_student_removed_from_module_is_not_in_module_anymore(self):
module = create_module()
student = create_student()
student.modules.add(module)
Performance.objects.create(module=module, student=student)
url = (
'/remove_student_from_module/' +
module.code +
'/' +
str(module.year) +
'/' +
student.student_id +
'/'
)
request = self.factory.get(url)
request.user = self.user
response = remove_student_from_module(
request, module.code, module.year, student.student_id)
self.assertEqual(Performance.objects.count(), 0)
self.assertEqual(student.modules.count(), 0)
def test_assessment_results_are_deleted(self):
module = create_module()
student = create_student()
student.modules.add(module)
performance = Performance.objects.create(
module=module, student=student)
assessment = Assessment.objects.create(
module=module,
title='Essay'
)
result = AssessmentResult.objects.create(assessment=assessment)
self.assertEqual(AssessmentResult.objects.count(), 1)
performance.assessment_results.add(result)
url = (
'/remove_student_from_module/' +
module.code +
'/' +
str(module.year) +
'/' +
student.student_id +
'/'
)
response = self.client.get(url)
self.assertEqual(AssessmentResult.objects.count(), 0)
def test_feedback_gets_deleted(self):
module = create_module()
student = create_student()
student.modules.add(module)
performance = Performance.objects.create(
module=module, student=student)
assessment = Assessment.objects.create(
module=module,
title='Essay'
)
result = AssessmentResult.objects.create(assessment=assessment)
performance.assessment_results.add(result)
feedback = IndividualFeedback.objects.create(
assessment_result=result,
attempt='first'
)
url = (
'/remove_student_from_module/' +
module.code +
'/' +
str(module.year) +
'/' +
student.student_id +
'/'
)
response = self.client.get(url)
self.assertEqual(IndividualFeedback.objects.count(), 0)
class DeleteModuleTest(TeacherUnitTest):
"""Tests that the Delete Module Function removes performances and marks"""
def test_deleting_module_deletes_everything_else(self):
module = create_module()
module.teachers.add(self.user.staff)
student = create_student()
student.modules.add(module)
performance = Performance.objects.create(
module=module, student=student)
assessment = Assessment.objects.create(
module=module,
title="Dissertation",
value=100,
)
result = AssessmentResult.objects.create(
assessment=assessment,
mark=60
)
performance.assessment_results.add(result)
response = self.client.get(module.get_delete_self_url())
self.assertEqual(Module.objects.count(), 0)
self.assertEqual(Student.objects.count(), 1)
self.assertEqual(Performance.objects.count(), 0)
self.assertEqual(Assessment.objects.count(), 0)
self.assertEqual(AssessmentResult.objects.count(), 0)
def test_only_instructor_or_admin_can_delete_a_module(self):
module = create_module()
student = create_student()
student.modules.add(module)
performance = Performance.objects.create(
module=module, student=student)
assessment = Assessment.objects.create(
module=module,
title="Dissertation",
value=100,
)
result = AssessmentResult.objects.create(
assessment=assessment,
mark=60
)
performance.assessment_results.add(result)
response = self.client.get(module.get_delete_self_url())
self.assertEqual(Module.objects.count(), 1)
self.assertEqual(Student.objects.count(), 1)
self.assertEqual(Performance.objects.count(), 1)
self.assertEqual(Assessment.objects.count(), 1)
self.assertEqual(AssessmentResult.objects.count(), 1)
class SeminarGroupTest(TeacherUnitTest):
"""Tests involving the seminar group setup"""
def test_seminar_groups_can_be_saved(self):
stuff = set_up_stuff()
module = stuff[0]
student1 = stuff[1]
student2 = stuff[2]
student3 = stuff[3]
request = self.factory.post(
module.get_seminar_groups_url(),
data={
'action': 'Save students',
student1.student_id: '1',
student2.student_id: '2',
student3.student_id: '1'
}
)
request.user = self.user
response = assign_seminar_groups(request, module.code, module.year)
performance1 = Performance.objects.get(student=student1, module=module)
performance2 = Performance.objects.get(student=student2, module=module)
performance3 = Performance.objects.get(student=student3, module=module)
self.assertEqual(performance1.seminar_group, 1)
self.assertEqual(performance2.seminar_group, 2)
self.assertEqual(performance3.seminar_group, 1)
def test_seminar_groups_can_be_randomized_ignoring_previous_values(self):
stuff = set_up_stuff()
module = stuff[0]
student1 = stuff[1]
student2 = stuff[2]
student3 = stuff[3]
student4 = stuff[4]
student5 = stuff[5]
request = self.factory.post(
module.get_seminar_groups_url(),
data={
'action': 'Go',
'ignore': True,
'number_of_groups': '3'
}
)
request.user = self.user
response = assign_seminar_groups(request, module.code, module.year)
performance1 = Performance.objects.get(student=student1, module=module)
performance2 = Performance.objects.get(student=student2, module=module)
performance3 = Performance.objects.get(student=student3, module=module)
performance4 = Performance.objects.get(student=student4, module=module)
performance5 = Performance.objects.get(student=student5, module=module)
self.assertNotEqual(performance1.seminar_group, None)
self.assertNotEqual(performance2.seminar_group, None)
self.assertNotEqual(performance3.seminar_group, None)
self.assertNotEqual(performance4.seminar_group, None)
self.assertNotEqual(performance5.seminar_group, None)
list_of_seminar_groups = []
list_of_seminar_groups.append(performance1.seminar_group)
list_of_seminar_groups.append(performance2.seminar_group)
list_of_seminar_groups.append(performance3.seminar_group)
list_of_seminar_groups.append(performance4.seminar_group)
list_of_seminar_groups.append(performance5.seminar_group)
self.assertTrue(1 in list_of_seminar_groups)
self.assertTrue(2 in list_of_seminar_groups)
self.assertTrue(3 in list_of_seminar_groups)
def test_seminar_groups_can_be_randomized_leaving_previous_values(self):
stuff = set_up_stuff()
module = stuff[0]
student1 = stuff[1]
performance1 = Performance.objects.get(student=student1, module=module)
performance1.seminar_group = 1
performance1.save()
student2 = stuff[2]
student3 = stuff[3]
student4 = stuff[4]
student5 = stuff[5]
request = self.factory.post(
module.get_seminar_groups_url(),
data={
student2.student_id: '2',
'action': 'Go',
'number_of_groups': '3'
}
)
request.user = self.user
response = assign_seminar_groups(request, module.code, module.year)
performance1 = Performance.objects.get(student=student1, module=module)
performance2 = Performance.objects.get(student=student2, module=module)
performance3 = Performance.objects.get(student=student3, module=module)
performance4 = Performance.objects.get(student=student4, module=module)
performance5 = Performance.objects.get(student=student5, module=module)
self.assertEqual(performance1.seminar_group, 1)
self.assertEqual(performance2.seminar_group, 2)
self.assertNotEqual(performance3.seminar_group, None)
self.assertNotEqual(performance4.seminar_group, None)
self.assertNotEqual(performance5.seminar_group, None)
def test_seminar_group_overview_uses_correct_template(self):
module = create_module()
response = self.client.get(module.get_seminar_group_overview_url())
self.assertTemplateUsed(response, 'seminar_group_overview.html')
def test_seminar_group_overview_is_correct(self):
stuff = set_up_stuff()
module = stuff[0]
student1 = stuff[1]
student2 = stuff[2]
student3 = stuff[3]
student4 = stuff[4]
student5 = stuff[5]
performance1 = Performance.objects.get(student=student1, module=module)
performance1.seminar_group = 1
performance1.save()
performance2 = Performance.objects.get(student=student2, module=module)
performance2.seminar_group = 2
performance2.save()
performance3 = Performance.objects.get(student=student3, module=module)
performance3.seminar_group = 1
performance3.save()
performance4 = Performance.objects.get(student=student4, module=module)
performance4.seminar_group = 2
performance4.save()
performance5 = Performance.objects.get(student=student5, module=module)
performance5.seminar_group = 1
performance5.save()
request = self.factory.get(module.get_seminar_group_overview_url())
request.user = self.user
response = seminar_group_overview(request, module.code, module.year)
soup = BeautifulSoup(response.content)
group_1 = str(soup.select('#group_1')[0])
group_2 = str(soup.select('#group_2')[0])
self.assertIn(student1.short_name(), group_1)
self.assertIn(student2.short_name(), group_2)
self.assertIn(student3.short_name(), group_1)
self.assertIn(student4.short_name(), group_2)
self.assertIn(student5.short_name(), group_1)
class AssessmentTest(TeacherUnitTest):
"""Tests involving setting and deleting of assessments"""
def test_assessments_page_uses_right_template(self):
module = set_up_stuff()[0]
response = self.client.get(module.get_assessment_url())
self.assertTemplateUsed(response, 'assessment.html')
def test_assessments_can_be_added_to_module(self):
module = set_up_stuff()[0]
request = self.factory.post(
module.get_assessment_url(),
data={
'title': 'Hunting Exercise',
'value': 40,
}
)
request.user = self.user
assessment(request, module.code, module.year)
assessment_out = Assessment.objects.first()
self.assertEqual(assessment_out.title, 'Hunting Exercise')
self.assertEqual(assessment_out.value, 40)
def test_assessment_can_be_deleted(self):
stuff = set_up_stuff()
module = stuff[0]
performance = Performance.objects.first()
assessment = Assessment.objects.create(
module=module,
title="Hunting Exercise",
value=40
)
result = AssessmentResult.objects.create(
assessment=assessment,
mark=40
)
performance.assessment_results.add(result)
self.assertEqual(Assessment.objects.count(), 1)
self.assertEqual(AssessmentResult.objects.count(), 1)
request = self.factory.get(assessment.get_delete_url())
request.user = self.user
delete_assessment(request, module.code, module.year, assessment.slug)
self.assertEqual(Assessment.objects.count(), 0)
self.assertEqual(AssessmentResult.objects.count(), 0)
def test_toggle_assessment_availability_works(self):
module = create_module()
assessment = Assessment.objects.create(
module=module,
title='Hunting Exercise',
value=100
)
self.assertFalse(assessment.available)
request = self.factory.get(assessment.get_toggle_availability_url())
request.user = self.user
response = toggle_assessment_availability(
request, module.code, module.year, assessment.slug, 'first')
assessment_out = Assessment.objects.first()
self.assertTrue(assessment_out.available)
request = self.factory.get(assessment.get_toggle_availability_url())
request.user = self.user
response = toggle_assessment_availability(
request, module.code, module.year, assessment.slug, 'first')
assessment_out = Assessment.objects.first()
self.assertFalse(assessment_out.available)
request = self.factory.get(
assessment.get_toggle_availability_url('resit'))
request.user = self.user
response = toggle_assessment_availability(
request, module.code, module.year, assessment.slug, 'resit')
assessment_out = Assessment.objects.first()
self.assertTrue(assessment_out.resit_available)
request = self.factory.get(
assessment.get_toggle_availability_url('resit'))
request.user = self.user
response = toggle_assessment_availability(
request, module.code, module.year, assessment.slug, 'resit')
assessment_out = Assessment.objects.first()
self.assertFalse(assessment_out.resit_available)
request = self.factory.get(
assessment.get_toggle_availability_url('second_resit'))
request.user = self.user
response = toggle_assessment_availability(
request, module.code, module.year, assessment.slug, 'second_resit')
assessment_out = Assessment.objects.first()
self.assertTrue(assessment_out.second_resit_available)
request = self.factory.get(
assessment.get_toggle_availability_url('second_resit'))
request.user = self.user
response = toggle_assessment_availability(
request, module.code, module.year, assessment.slug, 'second_resit')
assessment_out = Assessment.objects.first()
self.assertFalse(assessment_out.second_resit_available)
class AttendanceTest(TeacherUnitTest):
"""Tests around the attendance function"""
def test_attendance_uses_correct_template(self):
module = set_up_stuff()[0]
response = self.client.get(module.get_attendance_url('all'))
self.assertTemplateUsed(response, 'attendance.html')
def test_attendance_form_shows_seminar_group(self):
stuff = set_up_stuff()
module = stuff[0]
student1 = stuff[1]
student2 = stuff[2]
student3 = stuff[3]
student4 = stuff[4]
student5 = stuff[5]
performance1 = Performance.objects.get(student=student1, module=module)
performance2 = Performance.objects.get(student=student2, module=module)
performance3 = Performance.objects.get(student=student3, module=module)
performance4 = Performance.objects.get(student=student4, module=module)
performance5 = Performance.objects.get(student=student5, module=module)
performance1.seminar_group = 1
performance1.save()
performance2.seminar_group = 1
performance2.save()
performance3.seminar_group = 1
performance3.save()
performance4.seminar_group = 2
performance4.save()
performance5.seminar_group = 2
performance5.save()
request = self.factory.get(module.get_attendance_url(1))
request.user = self.user
response = attendance(request, module.code, module.year, '1')
self.assertContains(response, student1.last_name)
self.assertContains(response, student2.last_name)
self.assertContains(response, student3.last_name)
self.assertNotContains(response, student4.last_name)
self.assertNotContains(response, student5.last_name)
request = self.factory.get(module.get_attendance_url(2))
request.user = self.user
response = attendance(request, module.code, module.year, '2')
self.assertNotContains(response, student1.last_name)
self.assertNotContains(response, student2.last_name)
self.assertNotContains(response, student3.last_name)
self.assertContains(response, student4.last_name)
self.assertContains(response, student5.last_name)
request = self.factory.get(module.get_attendance_url('all'))
request.user = self.user
response = attendance(request, module.code, module.year, 'all')
self.assertContains(response, student1.last_name)
self.assertContains(response, student2.last_name)
self.assertContains(response, student3.last_name)
self.assertContains(response, student4.last_name)
self.assertContains(response, student5.last_name)
def test_attendance_form_shows_only_active_students(self):
stuff = set_up_stuff()
module = stuff[0]
student1 = stuff[1]
student2 = stuff[2]
student3 = stuff[3]
student4 = stuff[4]
student5 = stuff[5]
student5.active = False
student5.save()
performance1 = Performance.objects.get(student=student1, module=module)
performance2 = Performance.objects.get(student=student2, module=module)
performance3 = Performance.objects.get(student=student3, module=module)
performance4 = Performance.objects.get(student=student4, module=module)
performance5 = Performance.objects.get(student=student5, module=module)
performance1.seminar_group = 1
performance1.save()
performance2.seminar_group = 1
performance2.save()
performance3.seminar_group = 1
performance3.save()
performance4.seminar_group = 1
performance4.save()
performance5.seminar_group = 1
performance5.save()
request = self.factory.get(module.get_attendance_url(1))
request.user = self.user
response = attendance(request, module.code, module.year, '1')
self.assertContains(response, student1.last_name)
self.assertContains(response, student2.last_name)
self.assertContains(response, student3.last_name)
self.assertContains(response, student4.last_name)
self.assertNotContains(response, student5.last_name)
def test_attendance_can_be_added_through_form(self):
stuff = set_up_stuff()
module = stuff[0]
request = self.factory.post(
module.get_attendance_url('all'),
data={
'bb23_1': 'p',
'bb23_2': 'a',
'bb23_3': 'e',
'dd42_1': 'p',
'dd42_3': 'a',
'save': 'Save Changes for all weeks'
}
)
request.user = self.user
response = attendance(request, module.code, module.year, 'all')
student1_out = Student.objects.get(student_id='bb23')
performance1_out = Performance.objects.get(
student=student1_out, module=module)
student2_out = Student.objects.get(student_id='dd42')
performance2_out = Performance.objects.get(
student=student2_out, module=module)
self.assertEqual(performance1_out.attendance_for(1), 'p')
self.assertEqual(performance1_out.attendance_for(2), 'a')
self.assertEqual(performance1_out.attendance_for(3), 'e')
self.assertEqual(performance2_out.attendance_for(1), 'p')
self.assertEqual(performance2_out.attendance_for(2), None)
self.assertEqual(performance2_out.attendance_for(3), 'a')
def test_attendance_changes_are_ignored_for_hidden_weeks(self):
stuff = set_up_stuff()
module = stuff[0]
student1 = stuff[1]
performance1 = Performance.objects.get(student=student1, module=module)
performance1.save_attendance('1', 'e')
request = self.factory.post(
module.get_attendance_url('all'),
data={
'bb23_1': 'p',
'bb23_2': 'a',
'bb23_3': 'e',
'dd42_1': 'p',
'dd42_3': 'a',
'save': 'Save Changes for Week 2'
}
)
request.user = self.user
attendance(request, module.code, module.year, 'all')
student1_out = Student.objects.get(student_id='bb23')
performance1_out = Performance.objects.get(
student=student1_out, module=module)
student2_out = Student.objects.get(student_id='dd42')
performance2_out = Performance.objects.get(
student=student2_out, module=module)
self.assertEqual(performance1_out.attendance_for(1), 'e')
self.assertEqual(performance1_out.attendance_for(2), 'a')
self.assertEqual(performance1_out.attendance_for(3), None)
self.assertEqual(performance2_out.attendance_for(1), None)
self.assertEqual(performance2_out.attendance_for(2), None)
self.assertEqual(performance2_out.attendance_for(3), None)
class MarkAllAssessmentsTest(TeacherUnitTest):
"""Testing the function to mark all for one assessment openly."""
def test_mark_all_template_is_used(self):
stuff = set_up_stuff()
module = stuff[0]
student = stuff[1]
assessment = Assessment.objects.create(
module=module, title="Essay", value=100)
response = self.client.get(assessment.get_mark_all_url())
self.assertTemplateUsed(response, 'mark_all.html')
def test_all_students_are_shown_in_mark_all_page(self):
stuff = set_up_stuff()
module = stuff[0]
student1 = stuff[1]
student2 = stuff[2]
student3 = stuff[3]
other_student = Student.objects.create(
first_name="Road",
last_name="Runner",
student_id="rr42"
)
assessment = Assessment.objects.create(
module=module, title="Essay", value=100)
request = self.factory.get(assessment.get_mark_all_url())
request.user = self.user
response = mark_all(
request,
module.code,
module.year,
'essay',
'first'
)
self.assertContains(response, student1.name())
self.assertContains(response, student2.name())
self.assertContains(response, student3.name())
self.assertNotContains(response, other_student.name())
def test_only_students_who_need_resit_show_in_mark_all_resit_page(self):
stuff = set_up_stuff()
module = stuff[0]
student1 = stuff[1]
student2 = stuff[2]
student3 = stuff[3]
student4 = stuff[4]
assessment1 = Assessment.objects.create(
module=module, title="Essay", value=50)
assessment2 = Assessment.objects.create(
module=module, title="Exam", value=50)
performance1 = Performance.objects.get(
module=module,
student=student1
)
performance2 = Performance.objects.get(
module=module,
student=student2
)
performance3 = Performance.objects.get(
module=module,
student=student3
)
performance4 = Performance.objects.get(
module=module,
student=student4
)
result_1_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=60
)
performance1.assessment_results.add(result_1_1)
result_1_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=60
)
performance1.assessment_results.add(result_1_2)
# Student 1 clearly passed and should not be in either
result_2_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=30
)
performance2.assessment_results.add(result_2_1)
result_2_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=30
)
performance2.assessment_results.add(result_2_2)
# Student 2 clearly failed and should be in both
result_3_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=35
)
performance3.assessment_results.add(result_3_1)
result_3_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=40
)
performance3.assessment_results.add(result_3_2)
# Student 3 failed (not so clearly) and should be in 1 only
request = self.factory.get(
assessment1.get_mark_all_url(attempt='resit')
)
result_4_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=60,
concessions='G'
)
performance4.assessment_results.add(result_4_1)
result_4_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=60
)
performance4.assessment_results.add(result_4_2)
# Student 4 has concessions for the passed essay and should be in 1
request.user = self.user
response1 = mark_all(
request,
module.code,
module.year,
'essay',
'resit'
)
self.assertNotContains(response1, student1.name())
self.assertContains(response1, student2.name())
self.assertContains(response1, student3.name())
self.assertContains(response1, student4.name())
request = self.factory.get(
assessment2.get_mark_all_url(attempt='resit')
)
request.user = self.user
response2 = mark_all(
request,
module.code,
module.year,
'exam',
'resit'
)
self.assertNotContains(response2, student1.name())
self.assertContains(response2, student2.name())
self.assertNotContains(response2, student3.name())
self.assertNotContains(response2, student4.name())
def test_existing_results_show_up_in_mark_all_page(self):
stuff = set_up_stuff()
module = stuff[0]
student1 = stuff[1]
assessment1 = Assessment.objects.create(
module=module, title="Essay 1", value=50)
assessment2 = Assessment.objects.create(
module=module, title="Essay 2", value=50)
performance1 = Performance.objects.get(
module=module, student=student1)
ar1_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=50
)
ar1_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=60
)
performance1.assessment_results.add(ar1_1)
performance1.assessment_results.add(ar1_2)
request = self.factory.get(assessment1.get_mark_all_url())
request.user = self.user
response = mark_all(
request,
module.code,
module.year,
'essay-1',
'first'
)
self.assertContains(response, 60)
html = (
'<input class="form-control assessment_mark" type="number" ' +
'min="0" max="100" id="essay-1_' +
student1.student_id +
'" name="mark_' +
student1.student_id +
'" type="number" value="50" /><small>Previously: 50</small>'
)
self.assertContains(response, html)
def test_marks_can_be_saved_with_existing_ar_objects(self):
stuff = set_up_stuff()
module = stuff[0]
student1 = stuff[1]
student2 = stuff[2]
assessment1 = Assessment.objects.create(
module=module, title="Essay 1", value=50)
assessment2 = Assessment.objects.create(
module=module, title="Essay 2", value=50)
result1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=50
)
performance1 = Performance.objects.get(module=module, student=student1)
performance1.assessment_results.add(result1)
result2 = AssessmentResult.objects.create(assessment=assessment1)
performance2 = Performance.objects.get(module=module, student=student2)
performance2.assessment_results.add(result2)
id1 = 'mark_' + student1.student_id
id2 = 'mark_' + student2.student_id
request = self.factory.post(
assessment1.get_mark_all_url(),
data={
id1: '20',
id2: '40'
}
)
request.user = self.user
response = mark_all(
request,
module.code,
module.year,
'essay-1',
'first'
)
performance1_out = Performance.objects.get(
module=module, student=student1)
self.assertEqual(
performance1_out.get_assessment_result('essay-1', 'first'),
20
)
performance2_out = Performance.objects.get(
module=module, student=student2)
self.assertEqual(
performance2_out.get_assessment_result('essay-1', 'first'),
40
)
def test_marks_can_be_saved_without_existing_ar_objects(self):
stuff = set_up_stuff()
module = stuff[0]
student1 = stuff[1]<|fim▁hole|> module=module, title="Essay 2", value=50)
id1 = 'mark_' + student1.student_id
id2 = 'mark_' + student2.student_id
request = self.factory.post(
assessment1.get_mark_all_url(),
data={
id1: '20',
id2: '40'
}
)
request.user = self.user
response = mark_all(
request,
module.code,
module.year,
'essay-1',
'first'
)
performance1_out = Performance.objects.get(
module=module, student=student1)
self.assertEqual(
performance1_out.get_assessment_result('essay-1', 'first'),
20
)
performance2_out = Performance.objects.get(
module=module, student=student2)
self.assertEqual(
performance2_out.get_assessment_result('essay-1', 'first'),
40
)
class MarkAllAssessmentsAnonymouslyTest(TeacherUnitTest):
"""Testing the function to mark all for one assessment anonymously."""
def test_only_exam_ids_are_shown_if_anonymous_is_set(self):
stuff = set_up_stuff()
module = stuff[0]
student1 = stuff[1]
student1.exam_id = '1234'
student1.save()
student2 = stuff[2]
student2.exam_id = '2345'
student2.save()
student3 = stuff[3]
student3.exam_id = '3456'
student3.save()
assessment = Assessment.objects.create(
module=module, title="Essay", value=100)
request = self.factory.get(assessment.get_mark_all_url(anonymous=True))
request.user = self.user
response = mark_all_anonymously(
request,
module.code,
module.year,
'essay',
'first',
)
self.assertContains(response, student1.exam_id)
self.assertContains(response, student2.exam_id)
self.assertContains(response, student3.exam_id)
self.assertNotContains(response, student1.first_name)
self.assertNotContains(response, student1.last_name)
self.assertNotContains(response, student1.student_id)
self.assertNotContains(response, student2.first_name)
self.assertNotContains(response, student2.last_name)
self.assertNotContains(response, student2.student_id)
self.assertNotContains(response, student3.first_name)
self.assertNotContains(response, student3.last_name)
self.assertNotContains(response, student3.student_id)
def test_anonymous_marks_can_be_saved_with_existing_ar_objects(self):
stuff = set_up_stuff()
module = stuff[0]
student1 = stuff[1]
student1.exam_id = '1234'
student1.save()
student2 = stuff[2]
student2.exam_id = '2345'
student2.save()
assessment1 = Assessment.objects.create(
module=module, title="Essay 1", value=50)
assessment2 = Assessment.objects.create(
module=module, title="Essay 2", value=50)
result1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=50
)
performance1 = Performance.objects.get(module=module, student=student1)
performance1.assessment_results.add(result1)
result2 = AssessmentResult.objects.create(assessment=assessment1)
performance2 = Performance.objects.get(module=module, student=student2)
performance2.assessment_results.add(result2)
id1 = 'mark_' + student1.exam_id
id2 = 'mark_' + student2.exam_id
request = self.factory.post(
assessment1.get_mark_all_url(anonymous=True),
data={
id1: '20',
id2: '40'
}
)
request.user = self.user
response = mark_all_anonymously(
request,
module.code,
module.year,
'essay-1',
'first'
)
performance1_out = Performance.objects.get(
module=module, student=student1)
self.assertEqual(
performance1_out.get_assessment_result('essay-1', 'first'),
20
)
performance2_out = Performance.objects.get(
module=module, student=student2)
self.assertEqual(
performance2_out.get_assessment_result('essay-1', 'first'),
40
)
def test_anonymous_marks_can_be_saved_without_existing_ar_objects(self):
stuff = set_up_stuff()
module = stuff[0]
student1 = stuff[1]
student1.exam_id = '1234'
student1.save()
student2 = stuff[2]
student2.exam_id = '2345'
student2.save()
assessment1 = Assessment.objects.create(
module=module, title="Essay 1", value=50)
assessment2 = Assessment.objects.create(
module=module, title="Essay 2", value=50)
id1 = 'mark_' + student1.exam_id
id2 = 'mark_' + student2.exam_id
request = self.factory.post(
assessment1.get_mark_all_url(anonymous=True),
data={
id1: '20',
id2: '40'
}
)
request.user = self.user
response = mark_all_anonymously(
request,
module.code,
module.year,
'essay-1',
'first'
)
performance1_out = Performance.objects.get(
module=module, student=student1)
self.assertEqual(
performance1_out.get_assessment_result('essay-1', 'first'),
20
)
performance2_out = Performance.objects.get(
module=module, student=student2)
self.assertEqual(
performance2_out.get_assessment_result('essay-1', 'first'),
40
)
def test_only_students_who_need_resit_show_in_mark_all_resit_a_page(self):
stuff = set_up_stuff()
module = stuff[0]
student1 = stuff[1]
student1.exam_id = '1234'
student1.save()
student2 = stuff[2]
student2.exam_id = '2345'
student2.save()
student3 = stuff[3]
student3.exam_id = '3456'
student3.save()
student4 = stuff[4]
student4.exam_id = '4567'
student4.save()
assessment1 = Assessment.objects.create(
module=module, title="Essay", value=50)
assessment2 = Assessment.objects.create(
module=module, title="Exam", value=50)
performance1 = Performance.objects.get(
module=module,
student=student1
)
performance2 = Performance.objects.get(
module=module,
student=student2
)
performance3 = Performance.objects.get(
module=module,
student=student3
)
performance4 = Performance.objects.get(
module=module,
student=student4
)
result_1_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=60
)
performance1.assessment_results.add(result_1_1)
result_1_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=60
)
performance1.assessment_results.add(result_1_2)
# Student 1 clearly passed and should not be in either
result_2_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=30
)
performance2.assessment_results.add(result_2_1)
result_2_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=30
)
performance2.assessment_results.add(result_2_2)
# Student 2 clearly failed and should be in both
result_3_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=35
)
performance3.assessment_results.add(result_3_1)
result_3_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=40
)
performance3.assessment_results.add(result_3_2)
# Student 3 failed (not so clearly) and should be in 1 only
request = self.factory.get(
assessment1.get_mark_all_url(attempt='resit')
)
result_4_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=60,
concessions='G'
)
performance4.assessment_results.add(result_4_1)
result_4_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=60
)
performance4.assessment_results.add(result_4_2)
# Student 4 has concessions for the passed essay and should be in 1
request.user = self.user
request = self.factory.get(
assessment1.get_mark_all_url(
anonymous=True,
attempt='resit'
)
)
request.user = self.user
response1 = mark_all_anonymously(
request,
module.code,
module.year,
'essay',
'resit',
)
self.assertNotContains(response1, student1.exam_id)
self.assertContains(response1, student2.exam_id)
self.assertContains(response1, student3.exam_id)
self.assertContains(response1, student4.exam_id)
request = self.factory.get(
assessment2.get_mark_all_url(
anonymous=True,
attempt='resit'
)
)
request.user = self.user
response2 = mark_all_anonymously(
request,
module.code,
module.year,
'exam',
'resit'
)
self.assertNotContains(response2, student1.exam_id)
self.assertContains(response2, student2.exam_id)
self.assertNotContains(response2, student3.exam_id)
self.assertNotContains(response2, student4.exam_id)
class AddEditStaffTest(AdminUnitTest):
"""Tests for adding and adding a new staff member"""
def test_staff_can_be_added_new_user_gets_created(self):
subject_area = SubjectArea.objects.create(name='Cartoon Studies')
request = self.factory.post('/add_staff/', data={
'first_name': 'Elmar',
'last_name': 'Fudd',
'email': '[email protected]',
'role': 'teacher'
})
request.user = self.user
add_or_edit_staff(request, testing=True)
user = User.objects.get(last_name='Fudd')
staff = Staff.objects.get(user=user)
self.assertEqual(user.staff, staff)
self.assertEqual(user.first_name, 'Elmar')
self.assertEqual(user.email, '[email protected]')
self.assertEqual(staff.role, 'teacher')
def test_form_for_existing_staff_shows_right_details(self):
user_in = create_user()
subject_area = SubjectArea.objects.create(name='Cartoon Studies')
staff_in = Staff.objects.create(user=user_in, role='teacher')
staff_in.subject_areas.add(subject_area)
staff_in.save()
request = self.factory.get(staff_in.get_edit_url())
request.user = self.user
response = add_or_edit_staff(request, user_in.username)
soup = BeautifulSoup(response.content)
first_name = str(soup.select('#id_first_name')[0]['value'])
self.assertEqual(first_name, 'Elmar')
last_name = str(soup.select('#id_last_name')[0]['value'])
self.assertEqual(last_name, 'Fudd')
last_name = str(soup.select('#id_email')[0]['value'])
self.assertEqual(last_name, '[email protected]')
teacher_option = str(soup.find(value='teacher'))
self.assertTrue('selected="selected"' in teacher_option)
def test_staff_member_can_be_edited(self):
user_in = User.objects.create_user(
'ef10', '[email protected]', 'rabbitseason')
user_in.last_name = 'Fadd'
user_in.first_name = 'Elmar'
user_in.save()
subject_area = SubjectArea.objects.create(name='Cartoon Studies')
staff_in = Staff.objects.create(user=user_in, role='teacher')
staff_in.subject_areas.add(subject_area)
staff_in.save()
request = self.factory.post(staff_in.get_edit_url(), data={
'first_name': 'Elmar',
'last_name': 'Fudd',
'email': '[email protected]',
'role': 'admin'
})
request.user = self.user
add_or_edit_staff(request, user_in.username, testing=True)
staff_out = Staff.objects.get(user=user_in)
self.assertEqual(staff_out.user.last_name, 'Fudd')
self.assertEqual(staff_out.role, 'admin')
class ViewStaffTest(AdminUnitTest):
"""Tests for Viewing Staff Members"""
def test_staff_view_by_subject_uses_correct_template(self):
response = self.client.get('/view_staff_by_subject/')
self.assertTemplateUsed(response, 'all_staff_by_subject.html')
def test_staff_view_by_subject_contains_staff(self):
subject_area_1 = create_subject_area()
subject_area_2 = SubjectArea.objects.create(name='Evil Plotting')
staff1 = create_teacher()
staff1.subject_areas.add(subject_area_1)
staff1.save()
user2 = User.objects.create_user(
'ys142', '[email protected]', 'squaredance')
user2.last_name = 'Sam'
user2.first_name = 'Yosemite'
user2.save()
staff2 = Staff.objects.create(user=user2, role='Teacher')
staff2.subject_areas.add(subject_area_1)
staff2.subject_areas.add(subject_area_2)
staff2.save()
user3 = User.objects.create_user(
'ta123', '[email protected]', 'othergod')
user3.first_name = 'Tex'
user3.last_name = 'Avery'
user3.save()
staff3 = Staff.objects.create(user=user3, role='Admin')
staff3.subject_areas.add(subject_area_1)
staff3.save()
request = self.factory.get('/view_staff_by_subject/')
request.user = self.user
response = view_staff_by_subject(request)
soup = BeautifulSoup(response.content)
table1 = str(soup.find(id=subject_area_1.slug))
self.assertTrue(staff1.name() in table1)
self.assertTrue(staff2.name() in table1)
self.assertTrue(staff3.name() in table1)
table2 = str(soup.find(id=subject_area_2.slug))
self.assertFalse(staff1.name() in table2)
self.assertTrue(staff2.name() in table2)
self.assertFalse(staff3.name() in table2)
def test_staff_view_by_name_contains_staff(self):
subject_area_1 = create_subject_area()
subject_area_2 = SubjectArea.objects.create(name='Evil Plotting')
staff1 = create_teacher()
staff1.subject_areas.add(subject_area_1)
staff1.save()
user2 = User.objects.create_user(
'ys142', '[email protected]', 'squaredance')
user2.last_name = 'Sam'
user2.first_name = 'Yosemite'
user2.save()
staff2 = Staff.objects.create(user=user2, role='Teacher')
staff2.subject_areas.add(subject_area_1)
staff2.subject_areas.add(subject_area_2)
staff2.save()
user3 = User.objects.create_user(
'ta142', '[email protected]', 'othergod')
user3.first_name = 'Tex'
user3.last_name = 'Avery'
user3.save()
staff3 = Staff.objects.create(user=user3, role='Admin')
staff3.subject_areas.add(subject_area_1)
staff3.save()
request = self.factory.get('/view_staff_by_name/')
request.user = self.user
response = view_staff_by_name(request)
self.assertContains(response, staff1.name())
self.assertContains(response, staff2.name())
self.assertContains(response, staff3.name())
class YearViewTest(AdminUnitTest):
"""Tests around the year view function from a teacher's perspective"""
def test_year_view_uses_right_template(self):
response = self.client.get('/students/all/')
self.assertTemplateUsed(response, 'year_view.html')
def test_teachers_see_all_students_from_their_only_subject_area(self):
stuff = set_up_stuff()
subject_area1 = SubjectArea.objects.create(name="Cartoon Studies")
subject_area2 = SubjectArea.objects.create(name="Evil Plotting")
self.user.staff.subject_areas.add(subject_area1)
course1 = Course.objects.create(
title="BA in Cartoon Studies", short_title="Cartoon Studies")
course1.subject_areas.add(subject_area1)
course2 = Course.objects.create(
title="BA in Evil Plotting", short_title="Evil Plotting")
course2.subject_areas.add(subject_area2)
course3 = Course.objects.create(
title="BA in Cartoon Studies with Evil Plotting",
short_title="Cartoon Studies / Evil Plotting"
)
course3.subject_areas.add(subject_area1)
course3.subject_areas.add(subject_area2)
student1 = stuff[1]
student1.year = 1
student1.course = course1
student1.save()
student2 = stuff[2]
student2.year = 1
student2.course = course1
student2.save()
student3 = stuff[3]
student3.course = course2
student3.year = 1
student3.save()
student4 = stuff[4]
student4.course = course3
student4.year = 1
student4.save()
request = self.factory.get('/year_view/1/')
request.user = self.user
response = year_view(request, '1')
self.assertContains(response, student1.last_name)
self.assertContains(response, student2.last_name)
self.assertNotContains(response, student3.last_name)
self.assertContains(response, student4.last_name)
def test_teachers_see_all_students_from_their_many_subject_areas(self):
stuff = set_up_stuff()
subject_area1 = SubjectArea.objects.create(name="Cartoon Studies")
subject_area2 = SubjectArea.objects.create(name="Evil Plotting")
self.user.staff.subject_areas.add(subject_area1)
self.user.staff.subject_areas.add(subject_area2)
course1 = Course.objects.create(
title="BA in Cartoon Studies", short_title="Cartoon Studies")
course1.subject_areas.add(subject_area1)
course2 = Course.objects.create(
title="BA in Evil Plotting", short_title="Evil Plotting")
course2.subject_areas.add(subject_area2)
course3 = Course.objects.create(
title="BA in Cartoon Studies with Evil Plotting",
short_title="Cartoon Studies / Evil Plotting"
)
course3.subject_areas.add(subject_area1)
course3.subject_areas.add(subject_area2)
student1 = stuff[1]
student1.year = 1
student1.course = course1
student1.save()
student2 = stuff[2]
student2.year = 1
student2.course = course1
student2.save()
student3 = stuff[3]
student3.course = course2
student3.year = 1
student3.save()
student4 = stuff[4]
student4.course = course3
student4.year = 1
student4.save()
request = self.factory.get('/year_view/1/')
request.user = self.user
response = year_view(request, '1')
self.assertContains(response, student1.last_name)
self.assertContains(response, student2.last_name)
self.assertContains(response, student3.last_name)
self.assertContains(response, student4.last_name)
def test_main_admin_sees_all_active_students_for_a_year_are_shown(self):
stuff = set_up_stuff()
self.user.staff.main_admin = True
self.user.staff.save()
student1 = stuff[1]
student2 = stuff[2]
student3 = stuff[3]
student4 = stuff[4]
student4.year = 2
student4.save()
student5 = stuff[5]
student5.active = False
student5.save()
request = self.factory.get('/year_view/1/')
request.user = self.user
response = year_view(request, '1')
self.assertContains(response, student1.last_name)
self.assertContains(response, student2.last_name)
self.assertContains(response, student3.last_name)
self.assertNotContains(response, student4.last_name)
self.assertNotContains(response, student5.last_name)
def test_only_admin_and_programme_director_see_edit_stuff(self):
stuff = set_up_stuff()
subject_area = create_subject_area()
course = create_course()
course.subject_areas.add(subject_area)
self.user.staff.role = 'admin'
self.user.staff.subject_areas.add(subject_area)
self.user.staff.save()
student1 = stuff[1]
student1.course = course
student1.save()
student2 = stuff[2]
student2.course = course
student2.save()
request = self.factory.get('/year_view/1/')
request.user = self.user
response = year_view(request, '1')
self.assertContains(response, 'bulkfunctions')
self.user.staff.role = 'teacher'
self.user.staff.save()
request = self.factory.get('/year_view/1/')
request.user = self.user
response = year_view(request, '1')
self.assertNotContains(response, 'bulkfunctions')
self.user.staff.role = 'teacher'
self.user.staff.programme_director = True
self.user.staff.save()
request = self.factory.get('/year_view/1/')
request.user = self.user
response = year_view(request, '1')
self.assertContains(response, 'bulkfunctions')
def test_bulk_changing_functions_work(self):
stuff = set_up_stuff()
subject_area = create_subject_area()
course1 = create_course()
course1.subject_areas.add(subject_area)
course2 = Course.objects.create(
title='BA in Evil Plotting', short_title='Evil Plotting')
subject_area2 = SubjectArea.objects.create(name='Evil Plotting')
course2.subject_areas.add(subject_area2)
self.user.staff.role = 'admin'
self.user.staff.subject_areas.add(subject_area)
self.user.staff.save()
student1 = stuff[1]
student1.course = course1
student1.qld = True
student1.save()
student2 = stuff[2]
student2.course = course1
student2.qld = True
student2.save()
student3 = stuff[3]
student3.course = course1
student3.qld = True
student3.save()
stuff[4].delete()
stuff[5].delete()
# Set course
request = self.factory.post('/year_view/1/', data={
'selected_student_id': [student2.student_id, student3.student_id],
'modify': 'course_BA in Evil Plotting'
})
request.user = self.user
response = year_view(request, '1')
student1_out = Student.objects.get(student_id=student1.student_id)
student2_out = Student.objects.get(student_id=student2.student_id)
student3_out = Student.objects.get(student_id=student3.student_id)
self.assertEqual(student1_out.course, course1)
self.assertEqual(student2_out.course, course2)
self.assertEqual(student3_out.course, course2)
# Set QLD
request = self.factory.post('/year_view/1/', data={
'selected_student_id': [student1.student_id, student2.student_id],
'modify': 'qld_off'
})
request.user = self.user
response = year_view(request, '1')
student1_out = Student.objects.get(student_id=student1.student_id)
student2_out = Student.objects.get(student_id=student2.student_id)
student3_out = Student.objects.get(student_id=student3.student_id)
self.assertEqual(student1_out.qld, False)
self.assertEqual(student2_out.qld, False)
self.assertEqual(student3_out.qld, True)
# Set begin of studies
request = self.factory.post('/year_view/1/', data={
'selected_student_id': [student1.student_id, student2.student_id],
'modify': 'since_1900'
})
request.user = self.user
response = year_view(request, '1')
student1_out = Student.objects.get(student_id=student1.student_id)
student2_out = Student.objects.get(student_id=student2.student_id)
student3_out = Student.objects.get(student_id=student3.student_id)
self.assertEqual(student1_out.since, 1900)
self.assertEqual(student2_out.since, 1900)
self.assertEqual(student3_out.since, None)
# Set Year
request = self.factory.post('/year_view/1/', data={
'selected_student_id': [student1.student_id, student2.student_id],
'modify': 'year_2'
})
request.user = self.user
response = year_view(request, '1')
student1_out = Student.objects.get(student_id=student1.student_id)
student2_out = Student.objects.get(student_id=student2.student_id)
student3_out = Student.objects.get(student_id=student3.student_id)
self.assertEqual(student1_out.year, 2)
self.assertEqual(student2_out.year, 2)
self.assertEqual(student3_out.year, 1)
# Active
request = self.factory.post('/year_view/1/', data={
'selected_student_id': [student1.student_id, student2.student_id],
'modify': 'active_no'
})
request.user = self.user
response = year_view(request, '1')
student1_out = Student.objects.get(student_id=student1.student_id)
student2_out = Student.objects.get(student_id=student2.student_id)
student3_out = Student.objects.get(student_id=student3.student_id)
self.assertEqual(student1_out.active, False)
self.assertEqual(student2_out.active, False)
self.assertEqual(student3_out.active, True)
# Delete
request = self.factory.post('/year_view/1/', data={
'selected_student_id': [student1.student_id, student2.student_id],
'modify': 'delete_yes'
})
request.user = self.user
response = year_view(request, '1')
self.assertEqual(Student.objects.count(), 1)
def test_deleting_student_deletes_everything(self):
module = create_module()
student = create_student()
student.modules.add(module)
performance = Performance.objects.create(
module=module, student=student)
assessment = Assessment.objects.create(
module=module,
title='Essay'
)
result = AssessmentResult.objects.create(assessment=assessment)
feedback = IndividualFeedback.objects.create(
assessment_result=result,
attempt='first'
)
self.assertEqual(AssessmentResult.objects.count(), 1)
self.assertEqual(IndividualFeedback.objects.count(), 1)
performance.assessment_results.add(result)
request = self.factory.post('/year_view/1/', data={
'selected_student_id': [student.student_id],
'modify': 'delete_yes'
})
request.user = self.user
response = year_view(request, '1')
self.assertEqual(AssessmentResult.objects.count(), 0)
self.assertEqual(IndividualFeedback.objects.count(), 0)
class CSVParsingTests(AdminUnitTest):
"""Tests for the CSV Parsing"""
def test_csv_data_gets_parsed_properly(self):
parsed_csvlist = (
'bb42;Bunny;Bugs;1900;1;[email protected];+112345678/////' +
'dd23;Duck;Daffy;1900;1;[email protected];+123456789/////' +
'pp42;Pig;Porky;1899;2;[email protected];+134567890/////' +
'test;wrong;entry;to;beignored'
)
data = Data.objects.create(id='randomstring', value=parsed_csvlist)
request = self.factory.post('/parse_csv/randomstring/', data={
'column1': 'student_id',
'column2': 'last_name',
'column3': 'first_name',
'column4': 'since',
'column5': 'year',
'column6': 'email',
'column7': 'phone_number',
'exclude': '4'
})
request.user = self.user
parse_csv(request, data.id)
self.assertEqual(Student.objects.count(), 3)
student1 = Student.objects.get(student_id='bb42')
student2 = Student.objects.get(student_id='dd23')
student3 = Student.objects.get(student_id='pp42')
self.assertEqual(student1.last_name, 'Bunny')
self.assertEqual(student1.first_name, 'Bugs')
self.assertEqual(student1.since, 1900)
self.assertEqual(student1.email, '[email protected]')
self.assertEqual(student1.phone_number, '+112345678')
class AssignTutorsTest(AdminUnitTest):
"""Tests for the assigning tutors view from an admin perspective"""
def test_right_template_used(self):
SubjectArea.objects.create(name="Cartoon Studies")
response = self.client.get('/assign_tutors/cartoon-studies/1/')
self.assertTemplateUsed(response, 'assign_tutors.html')
def test_assign_tutors_view_shows_right_tutors(self):
subject_area1 = SubjectArea.objects.create(name="Cartoon Studies")
subject_area2 = SubjectArea.objects.create(name="Evil Plotting")
user1 = User.objects.create_user(
username='ef1',
password='rabbitseason',
last_name='Fudd',
first_name='Elmar'
)
staff1 = Staff.objects.create(user=user1, role='teacher')
staff1.subject_areas.add(subject_area1)
user2 = User.objects.create_user(
username='ys2',
password='squaredance',
last_name='Sam',
first_name='Yosemite'
)
staff2 = Staff.objects.create(user=user2, role='teacher')
staff2.subject_areas.add(subject_area2)
user3 = User.objects.create_user(
username='mtm3',
password='zapp',
last_name='The Martian',
first_name='Marvin'
)
staff3 = Staff.objects.create(user=user3, role='teacher')
staff3.subject_areas.add(subject_area1)
staff3.subject_areas.add(subject_area2)
request = self.factory.get('/assign_tutors/cartoon-studies/1')
request.user = self.user
response = assign_tutors(request, 'cartoon-studies', '1')
soup = BeautifulSoup(response.content)
table = str(soup.select('#teachers')[0])
self.assertTrue(user1.last_name in table)
self.assertFalse(user2.last_name in table)
self.assertTrue(user3.last_name in table)
def test_assign_tutors_view_shows_right_students(self):
subject_area1 = SubjectArea.objects.create(name="Cartoon Studies")
subject_area2 = SubjectArea.objects.create(name="Evil Plotting")
course1 = Course.objects.create(title='BA in Cartoon Studies')
course1.subject_areas.add(subject_area1)
course2 = Course.objects.create(title='BA in Evil Plotting')
course2.subject_areas.add(subject_area2)
course3 = Course.objects.create(
title='BA in Cartoon Studies with Evil Plotting')
course3.subject_areas.add(subject_area1, subject_area2)
user1 = User.objects.create_user(
username='ef1',
password='rabbitseason',
last_name='Fudd',
first_name='Elmar'
)
staff1 = Staff.objects.create(user=user1, role='teacher')
staff1.subject_areas.add(subject_area1)
student1 = Student.objects.create(
student_id='bb42',
first_name='Bugs',
last_name='Bunny',
course=course1,
year=1
)
student2 = Student.objects.create(
student_id='dd23',
first_name='Duck',
last_name='Daffy',
course=course2,
year=1
)
student3 = Student.objects.create(
student_id='pp23',
first_name='Porky',
last_name='Pig',
course=course3,
year=1
)
student4 = Student.objects.create(
student_id='rr23',
first_name='Road',
last_name='Runner',
course=course1,
year=2
)
request = self.factory.get('/assign_tutors/cartoon-studies/1')
request.user = self.user
response = assign_tutors(request, 'cartoon-studies', '1')
self.assertContains(response, 'Bunny')
self.assertNotContains(response, 'Duck')
self.assertContains(response, 'Pig')
self.assertNotContains(response, 'Runner')
def test_tutors_can_be_assigned(self):
subject_area = SubjectArea.objects.create(name="Cartoon Studies")
course = Course.objects.create(title='BA in Cartoon Studies')
course.subject_areas.add(subject_area)
user1 = User.objects.create_user(
username='ef1',
password='rabbitseason',
last_name='Fudd',
first_name='Elmar'
)
staff1 = Staff.objects.create(user=user1, role='teacher')
staff1.subject_areas.add(subject_area)
user2 = User.objects.create_user(
username='ys2',
password='squaredance',
last_name='Sam',
first_name='Yosemite'
)
staff2 = Staff.objects.create(user=user2, role='teacher')
staff2.subject_areas.add(subject_area)
student1 = Student.objects.create(
student_id='bb42',
first_name='Bugs',
last_name='Bunny',
course=course,
year=1
)
student2 = Student.objects.create(
student_id='dd23',
first_name='Duck',
last_name='Daffy',
course=course,
year=1
)
student3 = Student.objects.create(
student_id='pp23',
first_name='Porky',
last_name='Pig',
course=course,
year=1
)
student4 = Student.objects.create(
student_id='rr23',
first_name='Road',
last_name='Runner',
course=course,
year=1
)
request = self.factory.post(
'/assign_tutors/cartoon-studies/1',
data={
'bb42': 'ef1',
'dd23': 'ys2',
'pp23': 'ef1'
}
)
request.user = self.user
response = assign_tutors(request, 'cartoon-studies', '1')
student1_out = Student.objects.get(student_id='bb42')
self.assertEqual(student1_out.tutor, staff1)
student2_out = Student.objects.get(student_id='dd23')
self.assertEqual(student2_out.tutor, staff2)
student3_out = Student.objects.get(student_id='pp23')
self.assertEqual(student3_out.tutor, staff1)
student4_out = Student.objects.get(student_id='rr23')
self.assertEqual(student4_out.tutor, None)
class AllTuteeMeetingTest(TeacherUnitTest):
"""Tests about the function showing all tutee meetings"""
def test_page_can_only_be_seen_by_pd(self):
subject_area = create_subject_area()
url = (
'/all_tutee_meetings/' +
subject_area.slug +
'/1/'
)
request = self.factory.get(url)
request.user = self.user
response = all_tutee_meetings(request, 'cartoon-studies', '1')
self.assertNotEqual(response.status_code, 200)
self.user.staff.programme_director = True
self.user.staff.save()
request = self.factory.get(url)
request.user = self.user
response = all_tutee_meetings(request, 'cartoon-studies', '1')
self.assertEqual(response.status_code, 200)
def test_page_uses_right_template(self):
subject_area = create_subject_area()
url = (
'/all_tutee_meetings/' +
subject_area.slug +
'/1/'
)
self.user.staff.programme_director = True
self.user.staff.save()
response = self.client.get(url)
self.assertTemplateUsed(response, 'all_tutees.html')
def test_students_in_the_right_year_show_up(self):
subject_area = create_subject_area()
course = Course.objects.create(title='Cartoon Studies')
course.subject_areas.add(subject_area)
student1 = Student.objects.create(
student_id='bb1',
first_name='Bugs',
last_name='Bunny',
year=1,
course=course
)
student2 = Student.objects.create(
student_id='dd1',
first_name='Duck',
last_name='Daffy',
year=2,
course=course
)
url = (
'/all_tutee_meetings/' +
subject_area.slug +
'/1/'
)
self.user.staff.programme_director = True
self.user.staff.save()
request = self.factory.get(url)
request.user = self.user
response = all_tutee_meetings(request, 'cartoon-studies', '1')
self.assertContains(response, student1.get_absolute_url())
self.assertNotContains(response, student2.get_absolute_url())
def test_tutor_appears_on_page(self):
subject_area = create_subject_area()
course = Course.objects.create(title='Cartoon Studies')
course.subject_areas.add(subject_area)
teacher = create_teacher()
student1 = Student.objects.create(
student_id='bb1',
first_name='Bugs',
last_name='Bunny',
year=1,
course=course,
tutor=teacher
)
url = (
'/all_tutee_meetings/' +
subject_area.slug +
'/1/'
)
self.user.staff.programme_director = True
self.user.staff.save()
request = self.factory.get(url)
request.user = self.user
response = all_tutee_meetings(request, 'cartoon-studies', '1')
self.assertContains(response, student1.get_absolute_url())
self.assertContains(response, teacher.name())
def test_tutor_meetings_appear(self):
subject_area = create_subject_area()
course = Course.objects.create(title='Cartoon Studies')
course.subject_areas.add(subject_area)
teacher = create_teacher()
student1 = Student.objects.create(
student_id='bb1',
first_name='Bugs',
last_name='Bunny',
year=1,
course=course,
tutor=teacher
)
student2 = Student.objects.create(
student_id='dd1',
first_name='Duck',
last_name='Daffy',
year=1,
course=course,
tutor=teacher
)
date = datetime.date(1900, 1, 1)
meeting1 = TuteeSession.objects.create(
tutor=teacher,
tutee=student1,
date_of_meet=date,
notes="Some Text"
)
url = (
'/all_tutee_meetings/' +
subject_area.slug +
'/1/'
)
self.user.staff.programme_director = True
self.user.staff.save()
request = self.factory.get(url)
request.user = self.user
response = all_tutee_meetings(request, 'cartoon-studies', '1')
self.assertContains(response, '1 Jan 1900')
self.assertContains(response, meeting1.get_absolute_url())
class MyTuteesTests(TeacherUnitTest):
"""Making sure that the my tutee view shows everything necessary"""
def test_all_tutees_are_shown(self):
stuff = set_up_stuff()
student1 = stuff[1]
student2 = stuff[2]
student3 = stuff[3]
student4 = stuff[4]
student5 = stuff[5]
student1.tutor = self.user.staff
student1.save()
student2.tutor = self.user.staff
student2.save()
student3.tutor = self.user.staff
student3.save()
request = self.factory.get('/my_tutees/')
request.user = self.user
response = my_tutees(request)
self.assertContains(response, student1.name())
self.assertContains(response, student2.name())
self.assertContains(response, student3.name())
self.assertNotContains(response, student4.name())
self.assertNotContains(response, student5.name())
def test_all_tutee_meetings_are_shown(self):
student = create_student()
student.tutor = self.user.staff
student.save()
date1 = datetime.date(1900, 1, 1)
date2 = datetime.date(1900, 1, 2)
meeting1 = TuteeSession.objects.create(
tutor=self.user.staff,
tutee=student,
date_of_meet=date1,
notes='Text'
)
meeting2 = TuteeSession.objects.create(
tutor=self.user.staff,
tutee=student,
date_of_meet=date2,
notes='Text'
)
request = self.factory.get('/my_tutees/')
request.user = self.user
response = my_tutees(request)
self.assertContains(response, '1 Jan 1900')
self.assertContains(response, '2 Jan 1900')
class AddressNinesTest(TeacherUnitTest):
"""Tests the function that allows to change averages ending with 9"""
def test_address_nines_uses_right_template(self):
module = create_module()
response = self.client.get(module.get_address_nines_url())
self.assertTemplateUsed(response, 'address_nines.html')
def test_address_nines_shows_all_averages_ending_with_nine(self):
stuff = set_up_stuff()
module = stuff[0]
assessment1 = Assessment.objects.create(
module=module,
title='Assessment 1',
value=20
)
assessment2 = Assessment.objects.create(
module=module,
title='Assessment 2',
value=30
)
assessment3 = Assessment.objects.create(
module=module,
title='Assessment 3',
value=50
)
# Student 1 with average of 49
student1 = stuff[1]
performance1 = Performance.objects.get(module=module, student=student1)
result1_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=50
)
performance1.assessment_results.add(result1_1)
result1_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=48
)
performance1.assessment_results.add(result1_2)
result1_3 = AssessmentResult.objects.create(
assessment=assessment3,
mark=50
)
performance1.assessment_results.add(result1_3)
performance1.calculate_average()
# Student 2 with 59 Average
student2 = stuff[2]
performance2 = Performance.objects.get(module=module, student=student2)
result2_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=62
)
performance2.assessment_results.add(result2_1)
result2_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=58
)
performance2.assessment_results.add(result2_2)
result2_3 = AssessmentResult.objects.create(
assessment=assessment3,
mark=59
)
performance2.assessment_results.add(result2_3)
performance2.calculate_average()
# Student 3 with 60 Average
student3 = stuff[3]
performance3 = Performance.objects.get(module=module, student=student3)
result3_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=60
)
performance3.assessment_results.add(result3_1)
result3_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=60
)
performance3.assessment_results.add(result3_2)
result3_3 = AssessmentResult.objects.create(
assessment=assessment3,
mark=60
)
performance3.assessment_results.add(result3_3)
performance3.calculate_average()
request = self.factory.get(module.get_address_nines_url())
request.user = self.user
response = address_nines(request, module.code, module.year)
self.assertContains(response, student1.short_name())
self.assertContains(response, student2.short_name())
self.assertNotContains(response, student3.short_name())
def test_address_nines_shows_no_nines_found_message_when_no_nines(self):
stuff = set_up_stuff()
module = stuff[0]
assessment1 = Assessment.objects.create(
module=module,
title='Assessment 1',
value=20
)
assessment2 = Assessment.objects.create(
module=module,
title='Assessment 2',
value=30
)
assessment3 = Assessment.objects.create(
module=module,
title='Assessment 3',
value=50
)
# Student 1 with 40 average
student1 = stuff[1]
performance1 = Performance.objects.get(module=module, student=student1)
result1_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=40
)
performance1.assessment_results.add(result1_1)
result1_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=40
)
performance1.assessment_results.add(result1_2)
result1_3 = AssessmentResult.objects.create(
assessment=assessment3,
mark=40
)
performance1.assessment_results.add(result1_3)
performance1.calculate_average()
# Student 2 with 55 Average
student2 = stuff[2]
performance2 = Performance.objects.get(module=module, student=student2)
result2_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=55
)
performance2.assessment_results.add(result2_1)
result2_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=55
)
performance2.assessment_results.add(result2_2)
result2_3 = AssessmentResult.objects.create(
assessment=assessment3,
mark=55
)
performance2.assessment_results.add(result2_3)
performance2.calculate_average()
# Student 3 with 60 Average
student3 = stuff[3]
performance3 = Performance.objects.get(module=module, student=student3)
result3_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=60
)
performance3.assessment_results.add(result3_1)
result3_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=60
)
performance3.assessment_results.add(result3_2)
result3_3 = AssessmentResult.objects.create(
assessment=assessment3,
mark=60
)
performance3.assessment_results.add(result3_3)
performance3.calculate_average()
request = self.factory.get(module.get_address_nines_url())
request.user = self.user
response = address_nines(request, module.code, module.year)
self.assertNotContains(response, student1.short_name())
self.assertNotContains(response, student2.short_name())
self.assertNotContains(response, student3.short_name())
self.assertContains(response, 'no averages ending with a 9')
def test_address_nines_changes_marks(self):
stuff = set_up_stuff()
module = stuff[0]
assessment1 = Assessment.objects.create(
module=module,
title='Assessment 1',
value=20
)
assessment2 = Assessment.objects.create(
module=module,
title='Assessment 2',
value=30
)
assessment3 = Assessment.objects.create(
module=module,
title='Assessment 3',
value=50
)
# Student 1 with average of 49
student1 = stuff[1]
performance1 = Performance.objects.get(module=module, student=student1)
result1_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=50
)
r1_1_field = 'mark_' + assessment1.slug + '_' + student1.student_id
performance1.assessment_results.add(result1_1)
result1_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=48
)
performance1.assessment_results.add(result1_2)
r1_2_field = 'mark_' + assessment2.slug + '_' + student1.student_id
result1_3 = AssessmentResult.objects.create(
assessment=assessment3,
mark=50
)
performance1.assessment_results.add(result1_3)
r1_3_field = 'mark_' + assessment3.slug + '_' + student1.student_id
performance1.calculate_average()
# Student 2 with 59 Average
student2 = stuff[2]
performance2 = Performance.objects.get(module=module, student=student2)
result2_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=62
)
performance2.assessment_results.add(result2_1)
r2_1_field = 'mark_' + assessment1.slug + '_' + student2.student_id
result2_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=58
)
performance2.assessment_results.add(result2_2)
r2_2_field = 'mark_' + assessment2.slug + '_' + student2.student_id
result2_3 = AssessmentResult.objects.create(
assessment=assessment3,
mark=59
)
performance2.assessment_results.add(result2_3)
r2_3_field = 'mark_' + assessment3.slug + '_' + student2.student_id
performance2.calculate_average()
request = self.factory.post(
module.get_address_nines_url(),
data={
r1_1_field: '50',
r1_2_field: '49',
r1_3_field: '50',
r2_1_field: '63',
r2_2_field: '58',
r2_3_field: '59'
}
)
request.user = self.user
response = address_nines(request, module.code, module.year)
performance_1_out = Performance.objects.get(
student=student1, module=module
)
performance_2_out = Performance.objects.get(
student=student2, module=module
)
self.assertEqual(performance_1_out.average, 50)
self.assertEqual(performance_2_out.average, 60)
def test_address_nines_templates_contains_correct_form_tags(self):
stuff = set_up_stuff()
module = stuff[0]
assessment1 = Assessment.objects.create(
module=module,
title='Assessment 1',
value=20
)
assessment2 = Assessment.objects.create(
module=module,
title='Assessment 2',
value=30
)
assessment3 = Assessment.objects.create(
module=module,
title='Assessment 3',
value=50
)
# Student 1 with average of 49
student1 = stuff[1]
performance1 = Performance.objects.get(module=module, student=student1)
result1_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=50
)
r1_1_field = (
'name="mark_' +
assessment1.slug +
'_' +
student1.student_id +
'"'
)
performance1.assessment_results.add(result1_1)
result1_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=48
)
r1_2_field = (
'name="mark_' +
assessment2.slug +
'_' +
student1.student_id +
'"'
)
performance1.assessment_results.add(result1_2)
result1_3 = AssessmentResult.objects.create(
assessment=assessment3,
mark=50
)
r1_3_field = (
'name="mark_' +
assessment3.slug +
'_' +
student1.student_id +
'"'
)
performance1.assessment_results.add(result1_3)
performance1.calculate_average()
request = self.factory.get(module.get_address_nines_url())
request.user = self.user
response = address_nines(request, module.code, module.year)
self.assertContains(response, r1_1_field)
self.assertContains(response, r1_2_field)
self.assertContains(response, r1_3_field)
class EditExamIDsTest(AdminUnitTest):
"""Testing the function to manually edit Exam IDs"""
def test_right_template_used(self):
subject_area = SubjectArea.objects.create(name="Cartoon Studies")
url = (
'/edit_exam_ids/' +
subject_area.slug +
'/1/'
)
response = self.client.get(url)
self.assertTemplateUsed(response, 'edit_exam_ids.html')
def test_only_active_students_with_right_SA_and_year_appear_in_form(self):
subject_area1 = SubjectArea.objects.create(name="Cartoon Studies")
subject_area2 = SubjectArea.objects.create(name="Evil Plotting")
course1 = Course.objects.create(
title="MA in Cartoon Studies",
short_title="Cartoon Studies"
)
course1.subject_areas.add(subject_area1)
course2 = Course.objects.create(
title="MSc in Evil Plotting",
short_title="Evil Plotting"
)
course2.subject_areas.add(subject_area2)
course3 = Course.objects.create(
title="MA in Cartoon Studies and Evil Plotting",
short_title="Cartoon Studies/Evil Plotting"
)
course3.subject_areas.add(subject_area1)
course3.subject_areas.add(subject_area2)
stuff = set_up_stuff()
student1 = stuff[1]
student1.active = True
student1.course = course1
student1.year = 1
student1.save()
student2 = stuff[2]
student2.active = False
student2.course = course1
student2.year = 1
student2.save()
student3 = stuff[3]
student3.active = True
student3.course = course2
student3.year = 1
student3.save()
student4 = stuff[4]
student4.active = True
student4.course = course3
student4.year = 1
student4.save()
student5 = stuff[5]
student5.active = True
student5.course = course3
student5.year = 2
student5.save()
url = (
'/edit_exam_ids/' +
subject_area1.slug +
'/1/'
)
request = self.factory.get(url)
request.user = self.user
response = edit_exam_ids(request, subject_area1.slug, '1')
self.assertContains(response, student1.student_id)
self.assertNotContains(response, student2.student_id)
self.assertNotContains(response, student3.student_id)
self.assertContains(response, student4.student_id)
self.assertNotContains(response, student5.student_id)
def test_existing_exam_ids_are_shown(self):
subject_area = SubjectArea.objects.create(name="Cartoon Studies")
course = Course.objects.create(
title="MA in Cartoon Studies",
short_title="Cartoon Studies"
)
course.subject_areas.add(subject_area)
stuff = set_up_stuff()
student1 = stuff[1]
student1.active = True
student1.course = course
student1.year = 1
student1.exam_id = '1234'
student1.save()
student2 = stuff[2]
student2.active = True
student2.course = course
student2.year = 1
student2.exam_id = '56789ABC'
student2.save()
url = (
'/edit_exam_ids/' +
subject_area.slug +
'/1/'
)
request = self.factory.get(url)
request.user = self.user
response = edit_exam_ids(request, subject_area.slug, '1')
self.assertContains(response, '1234')
self.assertContains(response, '56789ABC')
def test_exam_ids_get_saved_properly(self):
subject_area = SubjectArea.objects.create(name="Cartoon Studies")
course = Course.objects.create(
title="MA in Cartoon Studies",
short_title="Cartoon Studies"
)
course.subject_areas.add(subject_area)
stuff = set_up_stuff()
student1 = stuff[1]
student1.active = True
student1.course = course
student1.year = 1
student1.save()
student2 = stuff[2]
student2.active = True
student2.course = course
student2.year = 1
student2.save()
student3 = stuff[3]
student3.active = True
student3.course = course
student3.year = 1
student3.save()
url = (
'/edit_exam_ids/' +
subject_area.slug +
'/1/'
)
request = self.factory.post(
url,
data={
student1.student_id: '1234',
student2.student_id: '56789E',
student3.student_id: ''
}
)
request.user = self.user
response = edit_exam_ids(request, subject_area.slug, '1')
student1_out = Student.objects.get(student_id=student1.student_id)
student2_out = Student.objects.get(student_id=student2.student_id)
student3_out = Student.objects.get(student_id=student3.student_id)
self.assertEqual(student1_out.exam_id, '1234')
self.assertEqual(student2_out.exam_id, '56789E')
self.assertEqual(student3_out.exam_id, None)
class ConcessionsTest(AdminUnitTest):
"""Testing the concessions form"""
def test_concessions_form_uses_right_template(self):
module = create_module()
response = self.client.get(module.get_concessions_url('first'))
self.assertTemplateUsed(response, 'concessions.html')
def test_all_active_students_appear_in_template(self):
stuff = set_up_stuff()
module = stuff[0]
student1 = stuff[1]
student2 = stuff[2]
student3 = stuff[3]
student3.active = False
student3.save()
request = self.factory.get(module.get_concessions_url('first'))
request.user = self.user
response = concessions(request, module.code, module.year, 'first')
self.assertContains(response, student1.short_name())
self.assertContains(response, student2.short_name())
self.assertNotContains(response, student3.short_name())
def test_correct_names_for_values_in_template(self):
stuff = set_up_stuff()
module = stuff[0]
student1 = stuff[1]
student2 = stuff[2]
assessment1 = Assessment.objects.create(
module=module,
title="Assessment 1"
)
assessment2 = Assessment.objects.create(
module=module,
title="Assessment 2"
)
performance1 = Performance.objects.get(module=module, student=student1)
assessment_result_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=38,
concessions='N'
)
assessment_result_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=38,
concessions='G'
)
performance1.assessment_results.add(assessment_result_1)
performance1.assessment_results.add(assessment_result_2)
request = self.factory.get(module.get_concessions_url('first'))
request.user = self.user
response = concessions(request, module.code, module.year, 'first')
tag_name_1_1 = (
'name="' +
student1.student_id +
'_' +
assessment1.slug +
'"'
)
tag_name_1_2 = (
'name="' +
student1.student_id +
'_' +
assessment2.slug +
'"'
)
self.assertContains(response, tag_name_1_1)
self.assertContains(response, tag_name_1_2)
tag_name_2_1 = (
'name="' +
student2.student_id +
'_' +
assessment1.slug +
'"'
)
tag_name_2_2 = (
'name="' +
student2.student_id +
'_' +
assessment2.slug +
'"'
)
self.assertContains(response, tag_name_2_1)
self.assertContains(response, tag_name_2_2)
def test_existing_concessions_are_displayed(self):
stuff = set_up_stuff()
module = stuff[0]
student1 = stuff[1]
assessment1 = Assessment.objects.create(
module=module,
title="Assessment 1"
)
assessment2 = Assessment.objects.create(
module=module,
title="Assessment 2"
)
performance1 = Performance.objects.get(module=module, student=student1)
assessment_result_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=38,
concessions='N'
)
assessment_result_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=38,
concessions='G'
)
performance1.assessment_results.add(assessment_result_1)
performance1.assessment_results.add(assessment_result_2)
request = self.factory.get(module.get_concessions_url('first'))
request.user = self.user
response = concessions(request, module.code, module.year, 'first')
soup = BeautifulSoup(response.content)
tag_name_1_1 = (
'#' +
student1.student_id +
'_' +
assessment1.slug
)
select1 = str(soup.select(tag_name_1_1)[0])
options1 = select1.split('<option')
for part in options1:
if 'value="N"' in part:
option1 = part
self.assertIn('selected', option1)
tag_name_1_2 = (
'#' +
student1.student_id +
'_' +
assessment2.slug
)
select2 = str(soup.select(tag_name_1_2)[0])
options2 = select2.split('<option')
for part in options2:
if 'value="N"' in part:
option2 = part
self.assertNotIn('selected', option2)
for part in options2:
if 'value="G"' in part:
option2 = part
self.assertIn('selected', option2)
def test_submitting_the_form_saves_concessions(self):
stuff = set_up_stuff()
module = stuff[0]
student1 = stuff[1]
student2 = stuff[2]
assessment1 = Assessment.objects.create(
module=module,
title="Assessment 1"
)
assessment2 = Assessment.objects.create(
module=module,
title="Assessment 2"
)
performance1 = Performance.objects.get(module=module, student=student1)
assessment_result_1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=38,
concessions='N'
)
assessment_result_2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=38,
concessions='G'
)
performance1.assessment_results.add(assessment_result_1)
performance1.assessment_results.add(assessment_result_2)
tag_name_1_1 = (
student1.student_id +
'_' +
assessment1.slug
)
tag_name_1_2 = (
student1.student_id +
'_' +
assessment2.slug
)
tag_name_2_1 = (
student2.student_id +
'_' +
assessment1.slug
)
tag_name_2_2 = (
student2.student_id +
'_' +
assessment2.slug
)
request = self.factory.post(
module.get_concessions_url('first'),
data={
tag_name_1_1: 'G',
tag_name_1_2: 'P',
tag_name_2_1: 'N',
tag_name_2_2: 'G',
}
)
request.user = self.user
response = concessions(request, module.code, module.year, 'first')
assessment_result_1_1_out = AssessmentResult.objects.get(
assessment = assessment1,
part_of = performance1
)
assessment_result_1_2_out = AssessmentResult.objects.get(
assessment = assessment2,
part_of = performance1
)
performance2 = Performance.objects.get(module=module, student=student2)
assessment_result_2_1_out = AssessmentResult.objects.get(
assessment = assessment1,
part_of = performance2
)
assessment_result_2_2_out = AssessmentResult.objects.get(
assessment = assessment2,
part_of = performance2
)
self.assertEqual(assessment_result_1_1_out.concessions, 'G')
self.assertEqual(assessment_result_1_2_out.concessions, 'P')
self.assertEqual(assessment_result_2_1_out.concessions, 'N')
self.assertEqual(assessment_result_2_2_out.concessions, 'G')
class NextYearTest(MainAdminUnitTest):
"""Testing the switch to the next year with all its complications"""
def populate_db_with_students(self):
subject_area_1 = SubjectArea.objects.create(name="Cartoon Studies")
subject_area_2 = SubjectArea.objects.create(name="Evil Plotting")
course_1 = Course.objects.create(
title='BA in Cartoon Studies',
short_title='Cartoon Studies',
)
course_1.subject_areas.add(subject_area_1)
course_2 = Course.objects.create(
title='BA in Evil Plotting',
short_title='Evil Plotting',
)
course_2.subject_areas.add(subject_area_2)
course_3 = Course.objects.create(
title='BA in Cartoon Studies with Evil Plotting',
short_title='Cartoon Studies / Evil Plotting',
)
course_3.subject_areas.add(subject_area_1)
course_3.subject_areas.add(subject_area_2)
students = {}
student1_1 = Student.objects.create(
first_name='Bugs',
last_name='Bunny',
student_id='bb23',
year=1,
course=course_1,
)
students['1-2'] = student1_1
student1_2 = Student.objects.create(
first_name='Daffy',
last_name='Duck',
student_id='dd42',
year=1,
is_part_time=True,
course=course_1
)
students['1-spty'] = student1_2
student1_3 = Student.objects.create(
first_name='Silvester',
last_name='Cat',
student_id='sc23',
year=1,
is_part_time=True,
second_part_time_year=True,
course=course_1
)
students['spty-2'] = student1_3
student1_4 = Student.objects.create(
first_name='While E',
last_name='Coyote',
student_id='wec23',
year=1,
course=course_3
)
students['mixed_course'] = student1_4
student2_1 = Student.objects.create(
first_name='Tweety',
last_name='Bird',
student_id='tb23',
year=2,
course=course_1
)
students['2-3'] = student2_1
student3_1 = Student.objects.create(
first_name='Tasmanian',
last_name='Devil',
student_id='td23',
year=3,
course=course_1
)
students['3-4'] = student3_1
student4_1 = Student.objects.create(
first_name='Marvin',
last_name='Martian',
student_id='mm23',
year=1,
course=course_2
)
students['different_course'] = student4_1
return students
def test_enter_student_progression_uses_correct_template(self):
students = self.populate_db_with_students()
response = self.client.get(
'/enter_student_progression/cartoon-studies/1/'
)
self.assertTemplateUsed(response, 'enter_student_progression.html')
def test_enter_student_progression_shows_correct_students(self):
students = self.populate_db_with_students()
request = self.factory.get(
'/enter_student_progression/cartoon-studies/1/'
)
request.user = self.user
response = enter_student_progression(
request, 'cartoon-studies', '1')
self.assertContains(response, students['1-2'].student_id)
self.assertContains(response, students['1-spty'].student_id)
self.assertContains(response, students['mixed_course'].student_id)
self.assertNotContains(
response, students['different_course'].student_id)
self.assertNotContains(response, students['2-3'].student_id)
self.assertNotContains(response, students['3-4'].student_id)
def test_pass_and_proceed(self):
student = Student.objects.create(
first_name="Bugs",
last_name="Bunny",
student_id="bb23",
year=1,
next_year='PP'
)
this_year = int(Setting.objects.get(name="current_year").value)
next_year = str(this_year + 1)
request = self.factory.get(reverse('proceed_to_next_year'))
request.user = self.user
response = proceed_to_next_year(request)
student_out = Student.objects.first()
self.assertEqual(student_out.year, 2)
new_year = Setting.objects.get(name="current_year").value
self.assertEqual(new_year, next_year)
def test_pass_and_proceed_for_part_time_student(self):
student1 = Student.objects.create(
first_name="Bugs",
last_name="Bunny",
student_id="bb23",
year=1,
is_part_time=True,
next_year='PP'
)
student2 = Student.objects.create(
first_name="Daffy",
last_name="Duck",
student_id="dd23",
year=1,
is_part_time=True,
second_part_time_year=True,
next_year='PP'
)
request = self.factory.get(reverse('proceed_to_next_year'))
request.user = self.user
response = proceed_to_next_year(request)
student1_out = Student.objects.get(first_name="Bugs")
student2_out = Student.objects.get(first_name="Daffy")
self.assertEqual(student1_out.year, 1)
self.assertTrue(student1_out.second_part_time_year)
self.assertEqual(student2_out.year, 2)
self.assertFalse(student2_out.second_part_time_year)
def test_pass_and_proceed_with_qld_resit(self):
student = Student.objects.create(
first_name="Bugs",
last_name="Bunny",
student_id="bb23",
year=1,
qld=True,
next_year='PQ'
)
this_year = int(Setting.objects.get(name="current_year").value)
module = Module.objects.create(
title="Carrot Eating",
code="CE23",
year=this_year,
foundational=True
)
assessment1 = Assessment.objects.create(
title="Essay",
value=20
)
assessment2 = Assessment.objects.create(
title="Exam",
value=80
)
result1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=38,
resit_mark=38
)
result2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=80,
)
performance = Performance.objects.create(
student=student,
module=module,
belongs_to_year=1
)
performance.assessment_results.add(result1)
performance.assessment_results.add(result2)
self.assertEqual(performance.qld_failures_after_resit(), [result1])
request = self.factory.get(reverse('proceed_to_next_year'))
request.user = self.user
response = proceed_to_next_year(request)
student_out = Student.objects.first()
self.assertEqual(student_out.year, 2)
comment_str = (
'In Year 2, Bugs will have to resit Carrot Eating ' +
'(Essay) for QLD purposes'
)
self.assertEqual(student_out.notes, comment_str)
def test_pass_and_proceed_with_trailed_resits(self):
student = Student.objects.create(
first_name="Bugs",
last_name="Bunny",
student_id="bb23",
year=1,
qld=True,
next_year='PT'
)
this_year = int(Setting.objects.get(name="current_year").value)
module = Module.objects.create(
title="Carrot Eating",
code="CE23",
year=this_year,
foundational=True
)
assessment1 = Assessment.objects.create(
title="Essay",
value=20
)
assessment2 = Assessment.objects.create(
title="Exam",
value=80
)
result1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=38,
)
result2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=35,
)
performance = Performance.objects.create(
student=student,
module=module,
belongs_to_year=1
)
performance.assessment_results.add(result1)
performance.assessment_results.add(result2)
performance.calculate_average()
request = self.factory.get(reverse('proceed_to_next_year'))
request.user = self.user
response = proceed_to_next_year(request)
student_out = Student.objects.first()
self.assertEqual(student_out.year, 2)
comment_str = (
'In Year 2, Bugs will have to resit Carrot Eating ' +
'(Essay); Carrot Eating (Exam) (trailed)'
)
self.assertEqual(student_out.notes, comment_str)
def test_pass_and_proceed_with_compensation(self):
student = Student.objects.create(
first_name="Bugs",
last_name="Bunny",
student_id="bb23",
year=1,
qld=True,
next_year='PC'
)
this_year = int(Setting.objects.get(name="current_year").value)
module = Module.objects.create(
title="Carrot Eating",
code="CE23",
year=this_year,
foundational=True
)
assessment1 = Assessment.objects.create(
title="Essay",
value=20
)
assessment2 = Assessment.objects.create(
title="Exam",
value=80
)
result1 = AssessmentResult.objects.create(
assessment=assessment1,
mark=38,
)
result2 = AssessmentResult.objects.create(
assessment=assessment2,
mark=35,
)
performance = Performance.objects.create(
student=student,
module=module,
belongs_to_year=1
)
performance.assessment_results.add(result1)
performance.assessment_results.add(result2)
performance.calculate_average()
request = self.factory.get(reverse('proceed_to_next_year'))
request.user = self.user
response = proceed_to_next_year(request)
student_out = Student.objects.first()
self.assertEqual(student_out.year, 2)
comment_str = 'Failure in %s (%s) has been compensated' %(
module.title, performance.real_average)
self.assertEqual(student_out.notes, comment_str)
def test_repeat_year_works(self):
student = Student.objects.create(
first_name="Bugs",
last_name="Bunny",
student_id="bb23",
year=1,
next_year='R'
)
this_year = int(Setting.objects.get(name="current_year").value)
next_year = str(this_year + 1)
request = self.factory.get(reverse('proceed_to_next_year'))
request.user = self.user
response = proceed_to_next_year(request)
student_out = Student.objects.first()
self.assertEqual(student_out.year, 1)
new_year = Setting.objects.get(name="current_year").value
self.assertEqual(new_year, next_year)
self.assertEqual(student_out.notes, 'Repeated Year 1')
def test_repeat_year_absj_works(self):
student = Student.objects.create(
first_name="Bugs",
last_name="Bunny",
student_id="bb23",
year=1,
next_year='ABSJ'
)
this_year = int(Setting.objects.get(name="current_year").value)
next_year = str(this_year + 1)
request = self.factory.get(reverse('proceed_to_next_year'))
request.user = self.user
response = proceed_to_next_year(request)
student_out = Student.objects.first()
self.assertEqual(student_out.year, 1)
new_year = Setting.objects.get(name="current_year").value
self.assertEqual(new_year, next_year)
self.assertEqual(student_out.notes, 'Repeated Year 1 ABSJ')
def test_graduate_with_first(self):
student = Student.objects.create(
first_name="Bugs",
last_name="Bunny",
student_id="bb23",
year=3,
next_year='1'
)
request = self.factory.get(reverse('proceed_to_next_year'))
request.user = self.user
response = proceed_to_next_year(request)
student_out = Student.objects.first()
self.assertEqual(student_out.year, 9)
self.assertTrue(student_out.active)
self.assertEqual(student_out.achieved_degree, 1)
def test_graduate_with_21(self):
student = Student.objects.create(
first_name="Bugs",
last_name="Bunny",
student_id="bb23",
year=3,
next_year='21'
)
request = self.factory.get(reverse('proceed_to_next_year'))
request.user = self.user
response = proceed_to_next_year(request)
student_out = Student.objects.first()
self.assertEqual(student_out.year, 9)
self.assertTrue(student_out.active)
self.assertEqual(student_out.achieved_degree, 21)
def test_graduate_with_22(self):
student = Student.objects.create(
first_name="Bugs",
last_name="Bunny",
student_id="bb23",
year=3,
next_year='22'
)
request = self.factory.get(reverse('proceed_to_next_year'))
request.user = self.user
response = proceed_to_next_year(request)
student_out = Student.objects.first()
self.assertEqual(student_out.year, 9)
self.assertTrue(student_out.active)
self.assertEqual(student_out.achieved_degree, 22)
def test_graduate_with_3rd(self):
student = Student.objects.create(
first_name="Bugs",
last_name="Bunny",
student_id="bb23",
year=3,
next_year='3'
)
request = self.factory.get(reverse('proceed_to_next_year'))
request.user = self.user
response = proceed_to_next_year(request)
student_out = Student.objects.first()
self.assertEqual(student_out.year, 9)
self.assertTrue(student_out.active)
self.assertEqual(student_out.achieved_degree, 3)
def test_graduate_with_cert_he(self):
student = Student.objects.create(
first_name="Bugs",
last_name="Bunny",
student_id="bb23",
year=3,
next_year='C'
)
request = self.factory.get(reverse('proceed_to_next_year'))
request.user = self.user
response = proceed_to_next_year(request)
student_out = Student.objects.first()
self.assertEqual(student_out.year, 9)
self.assertTrue(student_out.active)
self.assertEqual(student_out.achieved_degree, 7)
def test_graduate_with_dipl_he(self):
student = Student.objects.create(
first_name="Bugs",
last_name="Bunny",
student_id="bb23",
year=3,
next_year='D'
)
request = self.factory.get(reverse('proceed_to_next_year'))
request.user = self.user
response = proceed_to_next_year(request)
student_out = Student.objects.first()
self.assertEqual(student_out.year, 9)
self.assertTrue(student_out.active)
self.assertEqual(student_out.achieved_degree, 6)
def test_graduate_with_ordinary_degree(self):
student = Student.objects.create(
first_name="Bugs",
last_name="Bunny",
student_id="bb23",
year=3,
next_year='O'
)
request = self.factory.get(reverse('proceed_to_next_year'))
request.user = self.user
response = proceed_to_next_year(request)
student_out = Student.objects.first()
self.assertEqual(student_out.year, 9)
self.assertTrue(student_out.active)
self.assertEqual(student_out.achieved_degree, 5)
def test_withdraw_student(self):
student = Student.objects.create(
first_name="Bugs",
last_name="Bunny",
student_id="bb23",
year=3,
next_year='WD'
)
request = self.factory.get(reverse('proceed_to_next_year'))
request.user = self.user
response = proceed_to_next_year(request)
student_out = Student.objects.first()
self.assertEqual(student_out.year, 9)
self.assertTrue(student_out.active)
self.assertEqual(student_out.achieved_degree, 8)
def test_proceed_to_next_year_with_multiple_students(self):
students = self.populate_db_with_students()
for student in students:
students[student].next_year = 'PP'
students[student].save()
students['3-4'].next_year = '1'
students['3-4'].save()
request = self.factory.get(reverse('proceed_to_next_year'))
request.user = self.user
response = proceed_to_next_year(request)
student_1_2 = Student.objects.get(
student_id=students['1-2'].student_id)
self.assertEqual(student_1_2.year, 2)
student_1_spty = Student.objects.get(
student_id=students['1-spty'].student_id)
self.assertEqual(student_1_spty.year, 1)
self.assertTrue(student_1_spty.second_part_time_year)
student_spty_2 = Student.objects.get(
student_id=students['spty-2'].student_id)
self.assertEqual(student_spty_2.year, 2)
self.assertFalse(student_spty_2.second_part_time_year)
student_2_3 = Student.objects.get(
student_id=students['2-3'].student_id)
self.assertEqual(student_2_3.year, 3)
student_3_4 = Student.objects.get(
student_id=students['3-4'].student_id)
self.assertEqual(student_3_4.year, 9)
self.assertEqual(student_3_4.achieved_degree, 1)<|fim▁end|>
|
student2 = stuff[2]
assessment1 = Assessment.objects.create(
module=module, title="Essay 1", value=50)
assessment2 = Assessment.objects.create(
|
<|file_name|>slider.rs<|end_file_name|><|fim▁begin|>use {
Backend,
CharacterCache,
Color,
Colorable,
FontSize,
Frameable,
Labelable,
IndexSlot,
KidArea,
Mouse,
Padding,
Positionable,
Range,
Rect,
Rectangle,
Scalar,
Text,
Widget,
};
use num::{Float, NumCast, ToPrimitive};
use widget;
/// Linear value selection. If the slider's width is greater than it's height, it will
/// automatically become a horizontal slider, otherwise it will be a vertical slider. Its reaction
/// is triggered if the value is updated or if the mouse button is released while the cursor is
/// above the rectangle.
pub struct Slider<'a, T, F> {
common: widget::CommonBuilder,
value: T,
min: T,
max: T,
/// The amount in which the slider's display should be skewed.
///
/// Higher skew amounts (above 1.0) will weight lower values.
///
/// Lower skew amounts (below 1.0) will weight heigher values.
///
/// All skew amounts should be greater than 0.0.
pub skew: f32,
/// Set the reaction for the Slider.
///
/// It will be triggered if the value is updated or if the mouse button is released while the
/// cursor is above the rectangle.
pub maybe_react: Option<F>,
maybe_label: Option<&'a str>,
style: Style,
/// Whether or not user input is enabled for the Slider.
pub enabled: bool,
}
widget_style!{
KIND;
/// Graphical styling unique to the Slider widget.
style Style {
/// The color of the slidable rectangle.
- color: Color { theme.shape_color }
/// The length of the frame around the edges of the slidable rectangle.
- frame: Scalar { theme.frame_width }
/// The color of the Slider's frame.
- frame_color: Color { theme.frame_color }
/// The color of the Slider's label.
- label_color: Color { theme.label_color }
/// The font-size for the Slider's label.
- label_font_size: FontSize { theme.font_size_medium }
}
}
/// Represents the state of the Slider widget.
#[derive(Clone, Debug, PartialEq)]
pub struct State<T> {
value: T,
min: T,
max: T,
skew: f32,
interaction: Interaction,
frame_idx: IndexSlot,
slider_idx: IndexSlot,
label_idx: IndexSlot,
}
/// Unique kind for the widget type.
pub const KIND: widget::Kind = "Slider";
/// The ways in which the Slider can be interacted with.
#[derive(Clone, Copy, Debug, PartialEq)]<|fim▁hole|> Clicked,
}
impl Interaction {
/// Return the color associated with the state.
fn color(&self, color: Color) -> Color {
match *self {
Interaction::Normal => color,
Interaction::Highlighted => color.highlighted(),
Interaction::Clicked => color.clicked(),
}
}
}
/// Check the current state of the slider.
fn get_new_interaction(is_over: bool, prev: Interaction, mouse: Mouse) -> Interaction {
use mouse::ButtonPosition::{Down, Up};
use self::Interaction::{Normal, Highlighted, Clicked};
match (is_over, prev, mouse.left.position) {
(true, Normal, Down) => Normal,
(true, _, Down) => Clicked,
(true, _, Up) => Highlighted,
(false, Clicked, Down) => Clicked,
_ => Normal,
}
}
impl<'a, T, F> Slider<'a, T, F> {
/// Construct a new Slider widget.
pub fn new(value: T, min: T, max: T) -> Self {
Slider {
common: widget::CommonBuilder::new(),
value: value,
min: min,
max: max,
skew: 1.0,
maybe_react: None,
maybe_label: None,
style: Style::new(),
enabled: true,
}
}
builder_methods!{
pub skew { skew = f32 }
pub react { maybe_react = Some(F) }
pub enabled { enabled = bool }
}
}
impl<'a, T, F> Widget for Slider<'a, T, F>
where F: FnOnce(T),
T: ::std::any::Any + ::std::fmt::Debug + Float + NumCast + ToPrimitive,
{
type State = State<T>;
type Style = Style;
fn common(&self) -> &widget::CommonBuilder {
&self.common
}
fn common_mut(&mut self) -> &mut widget::CommonBuilder {
&mut self.common
}
fn unique_kind(&self) -> &'static str {
KIND
}
fn init_state(&self) -> State<T> {
State {
value: self.value,
min: self.min,
max: self.max,
skew: self.skew,
interaction: Interaction::Normal,
frame_idx: IndexSlot::new(),
slider_idx: IndexSlot::new(),
label_idx: IndexSlot::new(),
}
}
fn style(&self) -> Style {
self.style.clone()
}
fn kid_area<C: CharacterCache>(&self, args: widget::KidAreaArgs<Self, C>) -> KidArea {
const LABEL_PADDING: Scalar = 10.0;
KidArea {
rect: args.rect,
pad: Padding {
x: Range::new(LABEL_PADDING, LABEL_PADDING),
y: Range::new(LABEL_PADDING, LABEL_PADDING),
},
}
}
/// Update the state of the Slider.
fn update<B: Backend>(self, args: widget::UpdateArgs<Self, B>) {
use self::Interaction::{Clicked, Highlighted, Normal};
use utils::{clamp, map_range, percentage, value_from_perc};
let widget::UpdateArgs { idx, state, rect, style, mut ui, .. } = args;
let Slider { value, min, max, skew, enabled, maybe_label, maybe_react, .. } = self;
let maybe_mouse = ui.input(idx).maybe_mouse;
let interaction = state.view().interaction;
let new_interaction = match (enabled, maybe_mouse) {
(false, _) | (true, None) => Normal,
(true, Some(mouse)) => {
let is_over = rect.is_over(mouse.xy);
get_new_interaction(is_over, interaction, mouse)
},
};
match (interaction, new_interaction) {
(Highlighted, Clicked) => { ui.capture_mouse(idx); },
(Clicked, Highlighted) |
(Clicked, Normal) => { ui.uncapture_mouse(idx); },
_ => (),
}
let is_horizontal = rect.w() > rect.h();
let frame = style.frame(ui.theme());
let inner_rect = rect.pad(frame);
let new_value = if let Some(mouse) = maybe_mouse {
if is_horizontal {
// Horizontal.
let inner_w = inner_rect.w();
let w_perc = match (interaction, new_interaction) {
(Highlighted, Clicked) | (Clicked, Clicked) => {
let slider_w = mouse.xy[0] - inner_rect.x.start;
let perc = clamp(slider_w, 0.0, inner_w) / inner_w;
let skewed_perc = (perc).powf(skew as f64);
skewed_perc
},
_ => {
let value_percentage = percentage(value, min, max);
let slider_w = clamp(value_percentage as f64 * inner_w, 0.0, inner_w);
let perc = slider_w / inner_w;
perc
},
};
value_from_perc(w_perc as f32, min, max)
} else {
// Vertical.
let inner_h = inner_rect.h();
let h_perc = match (interaction, new_interaction) {
(Highlighted, Clicked) | (Clicked, Clicked) => {
let slider_h = mouse.xy[1] - inner_rect.y.start;
let perc = clamp(slider_h, 0.0, inner_h) / inner_h;
let skewed_perc = (perc).powf(skew as f64);
skewed_perc
},
_ => {
let value_percentage = percentage(value, min, max);
let slider_h = clamp(value_percentage as f64 * inner_h, 0.0, inner_h);
let perc = slider_h / inner_h;
perc
},
};
value_from_perc(h_perc as f32, min, max)
}
} else {
value
};
// If the value has just changed, or if the slider has been clicked/released, call the
// reaction function.
if let Some(react) = maybe_react {
let should_react = value != new_value
|| (interaction == Highlighted && new_interaction == Clicked)
|| (interaction == Clicked && new_interaction == Highlighted);
if should_react {
react(new_value)
}
}
if state.view().interaction != new_interaction {
state.update(|state| state.interaction = new_interaction);
}
if state.view().value != new_value {
state.update(|state| state.value = value);
}
if state.view().min != min {
state.update(|state| state.min = min);
}
if state.view().max != max {
state.update(|state| state.max = max);
}
if state.view().skew != skew {
state.update(|state| state.skew = skew);
}
// The **Rectangle** for the frame.
let frame_idx = state.view().frame_idx.get(&mut ui);
let frame_color = new_interaction.color(style.frame_color(ui.theme()));
Rectangle::fill(rect.dim())
.middle_of(idx)
.graphics_for(idx)
.color(frame_color)
.set(frame_idx, &mut ui);
// The **Rectangle** for the adjustable slider.
let slider_rect = if is_horizontal {
let left = inner_rect.x.start;
let right = map_range(new_value, min, max, left, inner_rect.x.end);
let x = Range::new(left, right);
let y = inner_rect.y;
Rect { x: x, y: y }
} else {
let bottom = inner_rect.y.start;
let top = map_range(new_value, min, max, bottom, inner_rect.y.end);
let x = inner_rect.x;
let y = Range::new(bottom, top);
Rect { x: x, y: y }
};
let color = new_interaction.color(style.color(ui.theme()));
let slider_idx = state.view().slider_idx.get(&mut ui);
let slider_xy_offset = [slider_rect.x() - rect.x(), slider_rect.y() - rect.y()];
Rectangle::fill(slider_rect.dim())
.xy_relative_to(idx, slider_xy_offset)
.graphics_for(idx)
.parent(idx)
.color(color)
.set(slider_idx, &mut ui);
// The **Text** for the slider's label (if it has one).
if let Some(label) = maybe_label {
let label_color = style.label_color(ui.theme());
let font_size = style.label_font_size(ui.theme());
//const TEXT_PADDING: f64 = 10.0;
let label_idx = state.view().label_idx.get(&mut ui);
Text::new(label)
.and(|text| if is_horizontal { text.mid_left_of(idx) }
else { text.mid_bottom_of(idx) })
.graphics_for(idx)
.color(label_color)
.font_size(font_size)
.set(label_idx, &mut ui);
}
}
}
impl<'a, T, F> Colorable for Slider<'a, T, F> {
builder_method!(color { style.color = Some(Color) });
}
impl<'a, T, F> Frameable for Slider<'a, T, F> {
builder_methods!{
frame { style.frame = Some(Scalar) }
frame_color { style.frame_color = Some(Color) }
}
}
impl<'a, T, F> Labelable<'a> for Slider<'a, T, F> {
builder_methods!{
label { maybe_label = Some(&'a str) }
label_color { style.label_color = Some(Color) }
label_font_size { style.label_font_size = Some(FontSize) }
}
}<|fim▁end|>
|
pub enum Interaction {
Normal,
Highlighted,
|
<|file_name|>sync.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 SUSE Linux GmbH. All rights reserved.
#
# This file is part of kiwi.
#
# kiwi is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# kiwi is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with kiwi. If not, see <http://www.gnu.org/licenses/>
#
import os
import logging
from stat import ST_MODE
import xattr
# project
from kiwi.command import Command
log = logging.getLogger('kiwi')
class DataSync:
"""
**Sync data from a source directory to a target directory
using the rsync protocol**
:param str source_dir: source directory path name
:param str target_dir: target directory path name
"""
def __init__(self, source_dir, target_dir):
self.source_dir = source_dir
self.target_dir = target_dir
def sync_data(self, options=None, exclude=None):
"""
Sync data from source to target using rsync
:param list options: rsync options
:param list exclude: file patterns to exclude
"""
target_entry_permissions = None
exclude_options = []
rsync_options = []
if options:
rsync_options = options
if not self.target_supports_extended_attributes():
warn_me = False
if '-X' in rsync_options:
rsync_options.remove('-X')
warn_me = True
if '-A' in rsync_options:
rsync_options.remove('-A')
warn_me = True
if warn_me:
log.warning(
'Extended attributes not supported for target: %s',
self.target_dir
)
if exclude:
for item in exclude:
exclude_options.append('--exclude')
exclude_options.append(
'/' + item
)
if os.path.exists(self.target_dir):
target_entry_permissions = os.stat(self.target_dir)[ST_MODE]
Command.run(
['rsync'] + rsync_options + exclude_options + [
self.source_dir, self.target_dir
]
)
if target_entry_permissions:
# rsync applies the permissions of the source directory
# also to the target directory which is unwanted because
# only permissions of the files and directories from the
# source directory and its contents should be transfered
# but not from the source directory itself. Therefore
# the permission bits of the target directory before the
# sync are applied back after sync to ensure they have<|fim▁hole|> os.chmod(self.target_dir, target_entry_permissions)
def target_supports_extended_attributes(self):
"""
Check if the target directory supports extended filesystem
attributes
:return: True or False
:rtype: bool
"""
try:
xattr.getxattr(self.target_dir, 'user.mime_type')
except Exception as e:
if format(e).startswith('[Errno 95]'):
# libc interface [Errno 95] Operation not supported:
return False
return True<|fim▁end|>
|
# not changed
|
<|file_name|>provider_test.go<|end_file_name|><|fim▁begin|>package openstack_test
import (
"flag"
. "launchpad.net/gocheck"
"testing"<|fim▁hole|>func Test(t *testing.T) {
if *live {
registerOpenStackTests()
}
registerLocalTests()
TestingT(t)
}<|fim▁end|>
|
)
var live = flag.Bool("live", false, "Include live OpenStack (Canonistack) tests")
|
<|file_name|>_security_rules_operations.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class SecurityRulesOperations:
"""SecurityRulesOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2020_05_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
async def _delete_initial(
self,
resource_group_name: str,
network_security_group_name: str,
security_rule_name: str,
**kwargs: Any
) -> None:
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-05-01"
accept = "application/json"
# Construct URL
url = self._delete_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'),
'securityRuleName': self._serialize.url("security_rule_name", security_rule_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}'} # type: ignore
async def begin_delete(
self,
resource_group_name: str,
network_security_group_name: str,
security_rule_name: str,
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes the specified network security rule.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param network_security_group_name: The name of the network security group.
:type network_security_group_name: str
:param security_rule_name: The name of the security rule.
:type security_rule_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling.
Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial(
resource_group_name=resource_group_name,
network_security_group_name=network_security_group_name,
security_rule_name=security_rule_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'),
'securityRuleName': self._serialize.url("security_rule_name", security_rule_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}'} # type: ignore
async def get(
self,
resource_group_name: str,
network_security_group_name: str,
security_rule_name: str,
**kwargs: Any
) -> "_models.SecurityRule":
"""Get the specified network security rule.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param network_security_group_name: The name of the network security group.
:type network_security_group_name: str
:param security_rule_name: The name of the security rule.
:type security_rule_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SecurityRule, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2020_05_01.models.SecurityRule
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.SecurityRule"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-05-01"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'),
'securityRuleName': self._serialize.url("security_rule_name", security_rule_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('SecurityRule', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}'} # type: ignore
async def _create_or_update_initial(
self,
resource_group_name: str,
network_security_group_name: str,
security_rule_name: str,
security_rule_parameters: "_models.SecurityRule",
**kwargs: Any
) -> "_models.SecurityRule":
cls = kwargs.pop('cls', None) # type: ClsType["_models.SecurityRule"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-05-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._create_or_update_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'),
'securityRuleName': self._serialize.url("security_rule_name", security_rule_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(security_rule_parameters, 'SecurityRule')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('SecurityRule', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('SecurityRule', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}'} # type: ignore
async def begin_create_or_update(
self,
resource_group_name: str,
network_security_group_name: str,
security_rule_name: str,
security_rule_parameters: "_models.SecurityRule",
**kwargs: Any
) -> AsyncLROPoller["_models.SecurityRule"]:
"""Creates or updates a security rule in the specified network security group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param network_security_group_name: The name of the network security group.
:type network_security_group_name: str
:param security_rule_name: The name of the security rule.
:type security_rule_name: str
:param security_rule_parameters: Parameters supplied to the create or update network security
rule operation.
:type security_rule_parameters: ~azure.mgmt.network.v2020_05_01.models.SecurityRule
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling.
Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either SecurityRule or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2020_05_01.models.SecurityRule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.SecurityRule"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_or_update_initial(
resource_group_name=resource_group_name,
network_security_group_name=network_security_group_name,
security_rule_name=security_rule_name,
security_rule_parameters=security_rule_parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('SecurityRule', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})<|fim▁hole|>
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'),
'securityRuleName': self._serialize.url("security_rule_name", security_rule_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}'} # type: ignore
def list(
self,
resource_group_name: str,
network_security_group_name: str,
**kwargs: Any
) -> AsyncIterable["_models.SecurityRuleListResult"]:
"""Gets all security rules in a network security group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param network_security_group_name: The name of the network security group.
:type network_security_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SecurityRuleListResult or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2020_05_01.models.SecurityRuleListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.SecurityRuleListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-05-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('SecurityRuleListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules'} # type: ignore<|fim▁end|>
|
return deserialized
|
<|file_name|>MultiLineFunctionDeclarationUnitTest.js<|end_file_name|><|fim▁begin|>function someFunctionWithAVeryLongName(firstParameter='something',
secondParameter='booooo',
third=null, fourthParameter=false,
fifthParameter=123.12,
sixthParam=true
){
}
function someFunctionWithAVeryLongName2(
firstParameter='something',
secondParameter='booooo',
) {
}
function blah() {
}
function blah()
{
}
var object =
{
someFunctionWithAVeryLongName: function(
firstParameter='something',
secondParameter='booooo',
third=null,
fourthParameter=false,
fifthParameter=123.12,
sixthParam=true
) /** w00t */ {
}
someFunctionWithAVeryLongName2: function (firstParameter='something',
secondParameter='booooo',
third=null
) {<|fim▁hole|> firstParameter, secondParameter, third=null
) {
}
someFunctionWithAVeryLongName4: function (
firstParameter, secondParameter
) {
}
someFunctionWithAVeryLongName5: function (
firstParameter,
secondParameter=array(1,2,3),
third=null
) {
}
}
var a = Function('return 1+1');<|fim▁end|>
|
}
someFunctionWithAVeryLongName3: function (
|
<|file_name|>exceptions.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
class APIClientException(Exception):
pass
class APIForbidden(APIClientException):
pass
<|fim▁hole|>
class APIInvalidData(APIClientException):
pass
class APIDuplicateObject(APIClientException):
def __init__(self, msg, duplicate_id, *args, **kwargs):
self.duplicate_id = duplicate_id
super().__init__(msg, *args, **kwargs)<|fim▁end|>
|
class APINotAuthorized(APIClientException):
pass
|
<|file_name|>slushfile.js<|end_file_name|><|fim▁begin|>/*
* slush-ml-3t
* https://github.com/edmacabebe/slush-ml-3t
*
* Copyright (c) 2017, edmacabebe
* Licensed under the MIT license.
*/
'use strict';
var gulp = require('gulp'),<|fim▁hole|> rename = require('gulp-rename'),
_ = require('underscore.string'),
inquirer = require('inquirer'),
path = require('path');
function format(string) {
var username = string.toLowerCase();
return username.replace(/\s/g, '');
}
var defaults = (function () {
var workingDirName = path.basename(process.cwd()),
homeDir, osUserName, configFile, user;
if (process.platform === 'win32') {
homeDir = process.env.USERPROFILE;
osUserName = process.env.USERNAME || path.basename(homeDir).toLowerCase();
}
else {
homeDir = process.env.HOME || process.env.HOMEPATH;
osUserName = homeDir && homeDir.split('/').pop() || 'root';
}
configFile = path.join(homeDir, '.gitconfig');
user = {};
if (require('fs').existsSync(configFile)) {
user = require('iniparser').parseSync(configFile).user;
}
return {
appName: workingDirName,
userName: osUserName || format(user.name || ''),
authorName: user.name || '',
authorEmail: user.email || ''
};
})();
gulp.task('default', function (done) {
var prompts = [{
name: 'appName',
message: 'What is the name of your project?',
default: defaults.appName
}, {
name: 'appDescription',
message: 'What is the description?'
}, {
name: 'appVersion',
message: 'What is the version of your project?',
default: '0.1.0'
}, {
name: 'authorName',
message: 'What is the author name?',
default: defaults.authorName
}, {
name: 'authorEmail',
message: 'What is the author email?',
default: defaults.authorEmail
}, {
name: 'userName',
message: 'What is the github username?',
default: defaults.userName
}, {
type: 'confirm',
name: 'moveon',
message: 'Continue?'
}];
//Ask
inquirer.prompt(prompts,
function (answers) {
if (!answers.moveon) {
return done();
}
answers.appNameSlug = _.slugify(answers.appName);
gulp.src(__dirname + '/templates/**')
.pipe(template(answers))
.pipe(rename(function (file) {
if (file.basename[0] === '_') {
file.basename = '.' + file.basename.slice(1);
}
}))
.pipe(conflict('./'))
.pipe(gulp.dest('./'))
.pipe(install())
.on('end', function () {
done();
});
});
});<|fim▁end|>
|
install = require('gulp-install'),
conflict = require('gulp-conflict'),
template = require('gulp-template'),
|
<|file_name|>scriptin.js<|end_file_name|><|fim▁begin|>/* webui functions */
function model_server(data) {
var self = this;
$.extend(self, data);
self.mem_utilization = ko.computed(function() {
return '{0} / {1}'.format(parseInt(self.memory), self.java_xmx);
})
self.capacity = ko.computed(function() {
return '{0} / {1}'.format(self.players_online, self.max_players);
})
self.overextended = ko.computed(function() {
try {
return parseInt(self.memory) > parseInt(self.java_xmx)
} catch (err) {
return false;
}
})
self.online_pct = ko.computed(function() {
return parseInt((self.players_online / self.max_players) * 100)
})
self.memory_pct = ko.computed(function() {
return parseInt((parseInt(self.memory) / parseInt(self.java_xmx)) * 100)
})
if (self.eula == null)
self.eula_ok = true;
else if (self.eula.toLowerCase() == 'false')
self.eula_ok = false;
else
self.eula_ok = true;
}
function model_property(server_name, option, value, section, new_prop) {
var self = this;
self.option = ko.observable(option);
self.val = ko.observable(value);
self.section = ko.observable(section);
self.success = ko.observable(null);
self.newly_created = ko.observable(new_prop || false);
self.type = 'textbox';
self.check_type = function(option, section) {
if (section) {
var fixed = [
{section: 'java', option: 'java_debug', type: 'truefalse'},
{section: 'onreboot', option: 'restore', type: 'truefalse'},
{section: 'onreboot', option: 'start', type: 'truefalse'},
{section: 'crontabs', option: 'archive_interval', type: 'interval'},
{section: 'crontabs', option: 'backup_interval', type: 'interval'},
{section: 'crontabs', option: 'restart_interval', type: 'interval'}
]
$.each(fixed, function(i,v) {
if (v.section == section && v.option == option){
self.type = v.type;
self.id = v.id;
return false;
}
})
} else {
var fixed = [
{option: 'pvp', type: 'truefalse'},
{option: 'allow-nether', type: 'truefalse'},
{option: 'spawn-animals', type: 'truefalse'},
{option: 'enable-query', type: 'truefalse'},
{option: 'generate-structures', type: 'truefalse'},
{option: 'hardcore', type: 'truefalse'},
{option: 'allow-flight', type: 'truefalse'},
{option: 'online-mode', type: 'truefalse'},
{option: 'spawn-monsters', type: 'truefalse'},
{option: 'force-gamemode', type: 'truefalse'},
{option: 'spawn-npcs', type: 'truefalse'},
{option: 'snooper-enabled', type: 'truefalse'},
{option: 'white-list', type: 'truefalse'},
{option: 'enable-rcon', type: 'truefalse'},
{option: 'announce-player-achievements', type: 'truefalse'},
{option: 'enable-command-block', type: 'truefalse'}
]
$.each(fixed, function(i,v) {
if (v.option == option){
self.type = v.type;
return false;
}
})
}
if (self.type == 'truefalse') {
if (self.val().toLowerCase() == 'true')
self.val(true);
else
self.val(false);
}
}
self.toggle = function(model, eventobj) {
$(eventobj.currentTarget).find('input').iCheck('destroy');
if (self.val() == true) {
$(eventobj.currentTarget).find('input').iCheck('uncheck');
self.val(false);
} else if (self.val() == false) {
var target = $(eventobj.currentTarget).find('input');
$(target).iCheck({
checkboxClass: 'icheckbox_minimal-grey',
radioClass: 'iradio_minimal-grey',
increaseArea: '40%' // optional
});
$(target).iCheck('check');
self.val(true);
}
}
self.change_select = function(model, eventobj) {
var new_value = $(eventobj.currentTarget).val();
var params = {
server_name: server_name,
cmd: 'modify_config',
option: self.option(),
value: new_value,
section: self.section()
}
$.getJSON('/server', params)
}
self.val.subscribe(function(value) {
function flash_success(data) {
if (data.result == 'success') {
self.newly_created(false);
self.success(true);
setTimeout(function() {self.success(null)}, 5000)
} else {
self.success(false);
}
}
function flash_failure(data) {
self.success(false);
}
var params = {
server_name: server_name,
cmd: 'modify_config',
option: self.option(),
value: self.val(),
section: self.section()
}
$.getJSON('/server', params).then(flash_success, flash_failure)
}, self)
self.check_type(option, section);
self.id = '{0}_{1}'.format((section ? section : ''), option);
}
function model_logline(str) {
var self = this;
self.timestamp = '';
self.entry = ansi_up.ansi_to_html(ansi_up.linkify(ansi_up.escape_for_html(str)));
}
function model_profile(data) {
var self = this;
$.extend(self, data);
self.description = ko.observable(self.desc);
self.success = ko.observable(null);
self.description.subscribe(function(value) {
var params = {
cmd: 'modify_profile',
option: 'desc',
value: self.description(),
section: self.profile
}
$.getJSON('/host', params)
}, self)
}
function webui() {
var self = this;
self.server = ko.observable({});
self.page = ko.observable();
self.profile = ko.observable({});
self.server.extend({ notify: 'always' });
self.page.extend({ notify: 'always' });
self.refresh_rate = 100;
self.refresh_loadavg = 2000;
self.dashboard = {
whoami: ko.observable(''),
group: ko.observable(),
groups: ko.observableArray([]),
memfree: ko.observable(),
uptime: ko.observable(),
servers_up: ko.observable(0),
disk_usage: ko.observable(),
disk_usage_pct: ko.observable(),
pc_permissions: ko.observable(),
pc_group: ko.observable(),
git_hash: ko.observable(),
stock_profiles: ko.observableArray([]),
base_directory: ko.observable()
}
self.logs = {
reversed: ko.observable(true)
}
self.load_averages = {
one: [0],
five: [0],
fifteen: [0],
autorefresh: ko.observable(true),
options: {
series: {
lines: {
show: true,
fill: .3
},
shadowSize: 0
},
yaxis: {
min: 0,
max: 1,
axisLabel: "Load Average for last minute",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 3
},
xaxis: { min: 0, max: 30, show: false },
grid: {
borderWidth: 0,
hoverable: false
},
legend: {
labelBoxBorderColor: "#858585",
position: "ne"
}
}
}
self.vmdata = {
pings: ko.observableArray(),
archives: ko.observableArray(),
increments: ko.observableArray(),
importable: ko.observableArray(),
profiles: ko.observableArray(),
sp: ko.observableArray(),
sc: ko.observableArray(),
logs: ko.observableArray()
}
self.import_information = ko.observable();
self.profile_type = ko.observable();
self.summary = {
backup: {
most_recent: ko.computed(function() {
try { return self.vmdata.increments()[0].timestamp } catch (e) { return 'None' }
}),
first: ko.computed(function() {
try { return self.vmdata.increments()[self.vmdata.increments().length-1].timestamp } catch (e) { return 'None' }
}),
cumulative: ko.computed(function() {
try { return self.vmdata.increments()[self.vmdata.increments().length-1].cumulative_size } catch (e) { return '0 MB' }
})
},
archive: {
most_recent: ko.computed(function() {
try { return self.vmdata.archives()[0].friendly_timestamp } catch (e) { return 'None' }
}),
first: ko.computed(function() {
try { return self.vmdata.archives()[self.vmdata.archives().length-1].friendly_timestamp } catch (e) { return 'None' }
}),
cumulative: ko.computed(function() {
return bytes_to_mb(self.vmdata.archives().sum('size'))
})
},
owner: ko.observable(''),
group: ko.observable(''),
du_cwd: ko.observable(0),
du_bwd: ko.observable(0),
du_awd: ko.observable(0)
}
self.pruning = {
increments: {
user_input: ko.observable(''),
remove_count: ko.observable(0),
step: '',
space_reclaimed: ko.observable(0.0)
},
archives: {
user_input: ko.observable(),
filename: ko.observable(),
remove_count: ko.observable(0),
archives_to_delete: '',
space_reclaimed: ko.observable(0.0)
},
profiles: {
profile: ko.observable()
}
}
/* beginning root functions */
self.save_state = function() {
var state_to_save = {
page: self.page(),
server: JSON.stringify(self.server()),
profile: self.profile()
}
history.pushState(state_to_save, 'MineOS Web UI');
}
self.restore_state = function(state) {
var server = new model_server(JSON.parse(state.server));
$('.container-fluid').hide();
if ($.isEmptyObject(server)) {
self.server({})
$('#dashboard').show();
} else {
self.server(server);
self.page(state.page);
$('.container-fluid').hide();
$('#{0}'.format(self.page())).show();
}
}
self.toggle_loadaverages = function() {
if (self.load_averages.autorefresh())
self.load_averages.autorefresh(false);
else {
self.load_averages.autorefresh(true);
self.redraw.chart();
}
}
self.reset_logs = function() {
self.vmdata.logs([]);
$.getJSON('/logs', {server_name: self.server().server_name, reset: true}).then(self.refresh.logs);
}
self.select_server = function(model) {
self.server(model);
if (self.page() == 'dashboard')
self.show_page('server_status');
else
self.ajax.refresh(null);
}
self.select_profile = function(model) {
self.profile(model);
self.show_page('profile_view');
}
self.new_property = function(vm, event) {
var config = $(event.target).data('config');
if (config == 'sp') {
self.vmdata.sp.push(new model_property(self.server().server_name, null, null, null, true))
} else if (config == 'sc') {
self.vmdata.sc.push(new model_property(self.server().server_name, null, null, null, true))
}
}
self.show_page = function(vm, event) {
try {
self.page($(event.currentTarget).data('page'));
} catch (e) {
self.page(vm);
}
$('.container-fluid').hide();
$('#{0}'.format(self.page())).show();
self.save_state();
}
self.extract_required = function(required, element, vm) {
var params = {};
$.each(required, function(i,v) {
//checks if required param in DOM element
//then falls back to vm
var required_param = v.replace(/\s/g, '');
if (required_param in $(element).data())
params[required_param] = $(element).data(required_param);
else if (required_param in vm)
params[required_param] = vm[required_param];
})
return params;
}
self.remember_import = function(model, eventobj) {
var target = $(eventobj.currentTarget);
var params = {
path: model['path'],
filename: model['filename']
}
$.extend(params, self.extract_required(['path','filename'], target, model));
self.import_information(params);
}
self.import_server = function(vm, eventobj) {
var params = self.import_information();
params['server_name'] = $('#import_server_modal').find('input[name="newname"]').val();
$.getJSON('/import_server', params).then(self.ajax.received, self.ajax.lost)
.then(self.show_page('dashboard'));
}
self.prune_archives = function(vm, eventobj) {
var params = {
cmd: 'prune_archives',
server_name: self.server().server_name,
filename: self.pruning.archives.archives_to_delete
}
$.getJSON('/server', params).then(self.ajax.received, self.ajax.lost)
.then(function() {self.ajax.refresh(null)});
}
self.prune_increments = function(vm, eventobj) {
var params = {
cmd: 'prune',
server_name: self.server().server_name,
step: self.pruning.increments.step
}
$.getJSON('/server', params).then(self.ajax.received, self.ajax.lost)
.then(function() {self.ajax.refresh(null)});
}
self.remember_profile = function(model, eventobj) {
self.pruning.profiles.profile(model.profile);
}
self.prune_profile = function(vm, eventobj) {
var params = {
cmd: 'remove_profile',
profile: self.pruning.profiles.profile
}
$.getJSON('/host', params).then(self.ajax.received, self.ajax.lost)
.then(function() {self.ajax.refresh(null)});
}
self.delete_server = function(vm, eventobj) {
var params = {
server_name: self.server().server_name
}
var unchecked = $('#delete_confirmations input[type=checkbox]').filter(function(i,v) {
return !$(v).prop('checked');
})
if (unchecked.length == 0) {
$.getJSON('/delete_server', params)
.then(self.ajax.received, self.ajax.lost)
.done(function(){ self.show_page('dashboard') },
function(){})
} else {
$.gritter.add({
text: 'No action taken; must confirm all content will be deleted to continue.',
sticky: false,
time: '3000',
class_name: 'gritter-warning'
});
}
}
self.change_group = function(vm, eventobj) {
var params = {
group: $(eventobj.currentTarget).val(),
server_name: self.server().server_name
}
$.getJSON('/change_group', params).then(self.ajax.received, self.ajax.lost)
}
self.change_pc_group = function(vm, eventobj) {
var params = {
group: $(eventobj.currentTarget).val()
}
$.getJSON('/change_pc_group', params).then(self.ajax.received, self.ajax.lost)
}
self.command = function(vm, eventobj) {
var target = $(eventobj.currentTarget);
var cmd = $(target).data('cmd');
var required = $(target).data('required').split(',');
var params = {cmd: cmd};
$.extend(params, self.extract_required(required, target, vm));
if (required.indexOf('force') >= 0)
params['force'] = true;
//console.log(params)
var refresh_time = parseInt($(target).data('refresh'));
if (required.indexOf('server_name') >= 0) {
$.extend(params, {server_name: self.server().server_name});
$.getJSON('/server', params).then(self.ajax.received, self.ajax.lost)
.then(function() {self.ajax.refresh(refresh_time)});
} else {
$.getJSON('/host', params).then(self.ajax.received, self.ajax.lost)
.then(function() {self.ajax.refresh(refresh_time)});
}
}
self.page.subscribe(function(page){
var server_name = self.server().server_name;
var params = {server_name: server_name};
switch(page) {
case 'dashboard':
$.getJSON('/vm/status').then(self.refresh.pings);
$.getJSON('/vm/dashboard').then(self.refresh.dashboard).then(self.redraw.gauges);
self.redraw.chart();
break;
case 'backup_list':
$.getJSON('/vm/increments', params).then(self.refresh.increments);
break;
case 'archive_list':
$.getJSON('/vm/archives', params).then(self.refresh.archives);
break;
case 'server_status':
$.getJSON('/vm/status').then(self.refresh.pings).then(self.redraw.gauges);
$.getJSON('/vm/increments', params).then(self.refresh.increments);
$.getJSON('/vm/archives', params).then(self.refresh.archives);
$.getJSON('/vm/server_summary', params).then(self.refresh.summary);
setTimeout(function() {
$('#delete_server input[type="checkbox"]').not('.nostyle').iCheck({
checkboxClass: 'icheckbox_minimal-grey',
radioClass: 'iradio_minimal-grey',
increaseArea: '40%' // optional
});
}, 500)
break;
case 'profiles':
$.getJSON('/vm/profiles').then(self.refresh.profiles);
break;
case 'profile_view':
$.getJSON('/vm/profiles').then(self.refresh.profiles);
break;
case 'create_server':
$.getJSON('/vm/profiles').then(self.refresh.profiles);
break;
case 'server_properties':
$.getJSON('/server', $.extend({}, params, {'cmd': 'sp'})).then(self.refresh.sp);
break;
case 'server_config':
$.getJSON('/server', $.extend({}, params, {'cmd': 'sc'})).then(self.refresh.sc);
break;
case 'importable':
$.getJSON('/vm/importable', {}).then(self.refresh.importable);
break;
case 'console':
$.getJSON('/logs', params).then(self.refresh.logs);
break;
default:
break;
}
})
self.pruning.archives.user_input.subscribe(function(new_value) {
var clone = self.vmdata.archives().slice(0).reverse();
var match;
var reclaimed = 0.0;
$.each(clone, function(i,v) {
if (v.friendly_timestamp == new_value) {
match = i;
self.pruning.archives.filename(v.filename);
return false;
}
reclaimed += v.size;
})
if (!match){
self.pruning.archives.remove_count(0);
self.pruning.archives.space_reclaimed(0.0);
self.pruning.archives.archives_to_delete = '';
} else {
var hits = clone.slice(0,match).map(function(e) { return e.filename });
self.pruning.archives.remove_count(hits.length);
self.pruning.archives.space_reclaimed(bytes_to_mb(reclaimed));
self.pruning.archives.archives_to_delete = hits.join(' ');
}
})
self.pruning.increments.user_input.subscribe(function(new_value){
var clone = self.vmdata.increments().slice(0).reverse();
var match;
var reclaimed = 0.0;
$.each(clone, function(i,v) {
if (v.timestamp == new_value || v.step == new_value) {
match = i;
self.pruning.increments.step = v.step;
return false;
}
if (v.increment_size.slice(-2) == 'KB')
reclaimed += parseFloat(v.increment_size) / 1000;
else
reclaimed += parseFloat(v.increment_size);
})
if (!match){
self.pruning.increments.remove_count(0);
self.pruning.increments.space_reclaimed(0);
self.pruning.increments.step = '';
} else {
self.pruning.increments.remove_count(clone.slice(0,match).length);
self.pruning.increments.space_reclaimed(reclaimed);
}
})
/* form submissions */
self.create_server = function(form) {
var server_name = $(form).find('input[name="server_name"]').val();
var group = $(form).find('select[name=group]').val();
var step1 = $(form).find('fieldset#step1 :input').filter(function() {
return ($(this).val() ? true : false);
})
var step2 = $(form).find('fieldset#step2 :input').filter(function() {
return ($(this).val() ? true : false);
})
var step3 = $(form).find('fieldset#step3 :input').filter(function() {
return ($(this).val() ? true : false);
})
var sp = {};
$.each($(step2).serialize().split('&'), function(i,v) {
sp[v.split('=')[0]] = v.split('=')[1];
})
var sc = {};
$.each(step3, function(i,v) {
input = $(v);
section = input.data('section');
if (!(section in sc))
sc[section] = {};
if ($(input).is(':checkbox')) {
sc[section][input.attr('name')] = $(input).is(':checked');
} else{
sc[section][input.attr('name')] = input.val();
}
})
params = {
'server_name': server_name,
'sp': JSON.stringify(sp),
'sc': JSON.stringify(sc),
'group': group
}
$.getJSON('/create', params)
.then(self.ajax.received, self.ajax.lost)
.done(function() {
self.show_page('dashboard');
},function(){
});
}
self.console_command = function(form) {
var user_input = $(form).find('input[name=console_command]');
params = {
cmd: user_input.val(),
server_name: self.server().server_name
}
$.getJSON('/server', params)
.then(self.ajax.received, self.ajax.lost).then(function() {
self.ajax.refresh(null);
user_input.val('');
});
}
self.define_profile = function(form) {
var step1 = $(form).find('fieldset :input').filter(function() {
return ($(this).val() ? true : false);
})
var properties = {};
$(step1).each(function() {
properties[ $(this).attr('name') ] = $(this).val();
})
var props = $(form).find('input[name="tags"]').map(function(i,v) {
return $(this).val();
});
properties['ignore'] = (props.length > 0) ? props.get().join(' ') : '';
delete properties.tags;
params = {
'cmd': 'define_profile',
'profile_dict': JSON.stringify(properties),
}
$.getJSON('/host', params)
.then(self.ajax.received, self.ajax.lost)
.done(function() {
self.show_page('profiles');
},function(){
});
}
/* promises */
self.ajax = {
received: function(data) {
$.gritter.add({
text: (data.payload) ? data.payload : '{0} [{1}]'.format(data.cmd, data.result),
sticky: false,
time: '3000',
class_name: 'gritter-{0}'.format(data.result)
});
console.log(data);
if (data.result == 'success')
return $.Deferred().resolve().promise();
else
return $.Deferred().reject().promise();
},
lost: function(data) {
$.gritter.add({
text: data.payload || 'Server did not respond to request',
time: '4000',
class_name: 'gritter-warning'
});
console.log(data);
return $.Deferred().reject().promise();
},
refresh: function(time) {
setTimeout(self.page.valueHasMutated, time || self.refresh_rate)
}
}
self.refresh = {
dashboard: function(data) {
self.dashboard.uptime(seconds_to_days(data.uptime));
self.dashboard.memfree(data.memfree);
self.dashboard.whoami(data.whoami);
self.dashboard.group(data.group);
self.dashboard.disk_usage(data.df);
self.dashboard.disk_usage_pct((str_to_bytes(self.dashboard.disk_usage().used) /
str_to_bytes(self.dashboard.disk_usage().total) * 100).toFixed(1));
self.dashboard.groups(data.groups);
self.dashboard.pc_permissions(data.pc_permissions);
self.dashboard.pc_group(data.pc_group);
self.dashboard.git_hash(data.git_hash);
self.dashboard.stock_profiles(data.stock_profiles);
self.dashboard.base_directory(data.base_directory);
$('#pc_group option').filter(function () {
return $(this).val() == data.pc_group
}).prop('selected', true);
},
pings: function(data) {
self.vmdata.pings.removeAll();
self.dashboard.servers_up(0);
$.each(data.ascending_by('server_name'), function(i,v) {
self.vmdata.pings.push( new model_server(v) );
if (self.server().server_name == v.server_name)
self.server(new model_server(v));
if (v.up)
self.dashboard.servers_up(self.dashboard.servers_up()+1)
})
},
archives: function(data) {
self.vmdata.archives(data.ascending_by('timestamp').reverse());
$("input#prune_archive_input").autocomplete({
source: self.vmdata.archives().map(function(i) {
return i.friendly_timestamp
})
});
},
increments: function(data) {
self.vmdata.increments(data);
$("input#prune_increment_input").autocomplete({
source: self.vmdata.increments().map(function(i) {
return i.timestamp
})
});
},
summary: function(data) {
self.summary.owner(data.owner);
self.summary.group(data.group);
self.summary.du_cwd(bytes_to_mb(data.du_cwd));
setTimeout(function() {
$('#available_groups option').filter(function () {
return $(this).val() == self.summary.group()
}).prop('selected', true)}, 50)
},
profiles: function(data) {
self.vmdata.profiles.removeAll();
$.each(data, function(i,v) {
self.vmdata.profiles.push( new model_profile(v) );
if (self.profile().profile == v.profile)
self.profile(new model_profile(v));
})
self.vmdata.profiles(self.vmdata.profiles().ascending_by('profile'));
},
sp: function(data) {
self.vmdata.sp.removeAll();
$.each(data.payload, function(option, value) {
self.vmdata.sp.push( new model_property(self.server().server_name, option, value) )
})
self.vmdata.sp(self.vmdata.sp().ascending_by('option'));
$('table#table_properties input[type="checkbox"]').not('.nostyle').iCheck({
checkboxClass: 'icheckbox_minimal-grey',
radioClass: 'iradio_minimal-grey',
increaseArea: '40%' // optional
});
},
sc: function(data) {
self.vmdata.sc.removeAll();
$.each(data.payload, function(section, option_value_pair){
$.each(option_value_pair, function(option, value){
self.vmdata.sc.push(new model_property(self.server().server_name, option, value, section))
})
})
self.vmdata.sc(self.vmdata.sc().ascending_by('section'));
$('table#table_config input[type="checkbox"]').not('.nostyle').iCheck({
checkboxClass: 'icheckbox_minimal-grey',
radioClass: 'iradio_minimal-grey',
increaseArea: '40%' // optional
});
setTimeout(function() {
$.each(self.vmdata.sc(), function(i,v) {
if (v.type == 'interval'){
$('#{0}_{1} option'.format(v.section(), v.option())).filter(function () {
return $(this).val() == v.val()
}).prop('selected', true)
}
})
}, 50)
<|fim▁hole|> },
logs: function(data) {
if (!data.payload.length) {
self.reset_logs();
} else {
$.each(data.payload, function(i,v) {
if (!v.match(/\[INFO\] \/127.0.0.1:\d+ lost connection/) && !v.match(/\[SEVERE\] Reached end of stream for \/127.0.0.1/))
self.vmdata.logs.push(new model_logline(v));
})
}
}
}
/* redraw functions */
self.judge_severity = function(percent) {
var colors = ['green', 'yellow', 'orange', 'red'];
var thresholds = [0, 60, 75, 90];
var gauge_color = colors[0];
for (var i=0; i < colors.length; i++)
gauge_color = (parseInt(percent) >= thresholds[i] ? colors[i] : gauge_color)
return gauge_color;
}
self.redraw = {
gauges: function() {
$('#{0} .gauge'.format(self.page())).easyPieChart({
barColor: $color[self.judge_severity( $(this).data('percent') )],
scaleColor: false,
trackColor: '#999',
lineCap: 'butt',
lineWidth: 4,
size: 50,
animate: 1000
});
},
chart: function() {
function rerender(data) {
function enumerate(arr) {
var res = [];
for (var i = 0; i < arr.length; ++i)
res.push([i, arr[i]])
return res;
}
self.load_averages.one.push(data[0])
self.load_averages.five.push(data[1])
self.load_averages.fifteen.push(data[2])
while (self.load_averages.one.length > (self.load_averages.options.xaxis.max + 1)){
self.load_averages.one.splice(0,1)
self.load_averages.five.splice(0,1)
self.load_averages.fifteen.splice(0,1)
}
//colors http://www.jqueryflottutorial.com/tester-4.html
var dataset = [
{ label: "fifteen", data: enumerate(self.load_averages['fifteen']), color: "#0077FF" },
{ label: "five", data: enumerate(self.load_averages['five']), color: "#ED7B00" },
{ label: "one", data: enumerate(self.load_averages['one']), color: "#E8E800" }
]
self.load_averages.options.yaxis.max = Math.max(
self.load_averages.one.max(),
self.load_averages.five.max(),
self.load_averages.fifteen.max()) || 1;
var plot = $.plot($("#load_averages"), dataset, self.load_averages.options);
plot.draw();
}
function update() {
if (self.page() != 'dashboard' || !self.load_averages.autorefresh()) {
self.load_averages.one.push.apply(self.load_averages.one, [0,0,0])
self.load_averages.five.push.apply(self.load_averages.five, [0,0,0])
self.load_averages.fifteen.push.apply(self.load_averages.fifteen, [0,0,0])
return
}
$.getJSON('/vm/loadavg').then(rerender);
setTimeout(update, self.refresh_loadavg);
}
update();
}
}
/* viewmodel startup */
self.show_page('dashboard');
}
/* prototypes */
String.prototype.format = String.prototype.f = function() {
var s = this,
i = arguments.length;
while (i--) { s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);}
return s;
};
Array.prototype.max = function () {
return Math.max.apply(Math, this);
};
Array.prototype.ascending_by = function(param) {
return this.sort(function(a, b) {return a[param] == b[param] ? 0 : (a[param] < b[param] ? -1 : 1) })
}
Array.prototype.sum = function(param) {
var total = 0;
for (var i=0; i < this.length; i++)
total += this[i][param]
return total;
}
function seconds_to_days(seconds){
var numdays = Math.floor(seconds / 86400);
var numhours = Math.floor((seconds % 86400) / 3600);
var numminutes = Math.floor(((seconds % 86400) % 3600) / 60);
var numseconds = ((seconds % 86400) % 3600) % 60;
return numdays + " days " + ('0' + numhours).slice(-2) + ":" + ('0' + numminutes).slice(-2) + ":" + ('0' + numseconds).slice(-2);
}
function seconds_to_time(seconds) {
function zero_pad(number){
if (number.toString().length == 1)
return '0' + number;
else
return number;
}
var hours = Math.floor(seconds / (60 * 60));
var divisor_for_minutes = seconds % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
return '{0}:{1}:{2}'.format(hours, zero_pad(minutes), zero_pad(seconds));
}
function str_to_bytes(str) {
if (str.substr(-1) == 'T')
return parseFloat(str) * Math.pow(10,12);
else if (str.substr(-1) == 'G')
return parseFloat(str) * Math.pow(10,9);
else if (str.substr(-1) == 'M')
return parseFloat(str) * Math.pow(10,6);
else if (str.substr(-1) == 'K')
return parseFloat(str) * Math.pow(10,3);
else
return parseFloat(str);
}
function bytes_to_mb(bytes){
//http://stackoverflow.com/a/18650828
if (bytes == 0)
return '0B';
else if (bytes < 1024)
return bytes + 'B';
var k = 1024;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return (bytes / Math.pow(k, i)).toPrecision(3) + sizes[i];
}<|fim▁end|>
|
},
importable: function(data) {
self.vmdata.importable(data.ascending_by('filename'));
|
<|file_name|>megaslider.js<|end_file_name|><|fim▁begin|>$(document).ready(function(){
'use strict';<|fim▁hole|>
//Turn off and on the music
$("#sound-control").click(function() {
var toggle = document.getElementById("sound-control");
var music = document.getElementById("music");
if(music.paused){
music.play();
$("#sound-control").attr('src', 'img/ljud_pa.png');
} else {
music.pause();
$("#sound-control").attr('src', 'img/ljud_av.png');
}
});
//The slideshow
var started = false;
//Backwards navigation
$("#back").click(function() {
stopSlideshow();
navigate("back");
});
//Forward navigation
$("#next").click(function() {
stopSlideshow();
navigate("next");
});
var interval;
$("#control").click(function(){
if(started)
{
stopSlideshow();
}
else
{
startSlideshow();
}
});
var activeContainer = 1;
var currentImg = 0;
var animating = false;
var navigate = function(direction) {
//Check if no animation is running
if(animating) {
return;
}
//Check wich current image we need to show
if(direction == "next") {
currentImg++;
if(currentImg == photos.length + 1) {
currentImg = 1;
}
} else {
currentImg--;
if(currentImg == 0) {
currentImg = photos.length;
}
}
//Check wich container we need to use
var currentContainer = activeContainer;
if(activeContainer == 1) {
activeContainer = 2;
} else {
activeContainer = 1;
}
showImage(photos[currentImg - 1], currentContainer, activeContainer);
};
var currentZindex = -1;
var showImage = function(photoObject, currentContainer, activeContainer) {
animating = true;
//Make sure the new container is always on the background
currentZindex--;
//Set the background image of the new active container
$("#slideimg" + activeContainer).css({
"background-image" : "url(" + photoObject.image + ")",
"display" : "block",
"z-index" : currentZindex
});
//Fade out and hide the slide-text when the new image is loading
$("#slide-text").fadeOut();
$("#slide-text").css({"display" : "none"});
//Set the new header text
$("#firstline").html(photoObject.firstline);
$("#secondline")
.attr("href", photoObject.url)
.html(photoObject.secondline);
//Fade out the current container
//and display the slider-text when animation is complete
$("#slideimg" + currentContainer).fadeOut(function() {
setTimeout(function() {
$("#slide-text").fadeIn();
animating = false;
}, 500);
});
};
var stopSlideshow = function() {
//Change the background image to "play"
$("#control").css({"background-image" : "url(img/play.png)" });
//Clear the interval
clearInterval(interval);
started = false;
};
var startSlideshow = function() {
$("#control").css({ "background-image" : "url(img/pause.png)" });
navigate("next");
interval = setInterval(function() { navigate("next"); }, slideshowSpeed);
started = true;
};
$.preloadImages = function() {
$(photos).each(function() {
$('<img>')[0].src = this.image;
});
startSlideshow();
}
$.preloadImages();
});<|fim▁end|>
| |
<|file_name|>IssueView.ts<|end_file_name|><|fim▁begin|>// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as Common from '../../core/common/common.js';
import * as Host from '../../core/host/host.js';
import * as i18n from '../../core/i18n/i18n.js';
import type * as Platform from '../../core/platform/platform.js';
import * as Protocol from '../../generated/protocol.js';
import * as IssuesManager from '../../models/issues_manager/issues_manager.js';
import * as IconButton from '../../ui/components/icon_button/icon_button.js';
import * as IssueCounter from '../../ui/components/issue_counter/issue_counter.js';
import * as MarkdownView from '../../ui/components/markdown_view/markdown_view.js';
import * as UI from '../../ui/legacy/legacy.js';
import * as Adorners from '../../ui/components/adorners/adorners.js';
import * as NetworkForward from '../../panels/network/forward/forward.js';
import * as Root from '../../core/root/root.js';
import * as Components from './components/components.js';
import {AffectedDirectivesView} from './AffectedDirectivesView.js';
import {AffectedBlockedByResponseView} from './AffectedBlockedByResponseView.js';
import {AffectedCookiesView, AffectedRawCookieLinesView} from './AffectedCookiesView.js';
import {AffectedDocumentsInQuirksModeView} from './AffectedDocumentsInQuirksModeView.js';
import {AffectedElementsView} from './AffectedElementsView.js';
import {AffectedElementsWithLowContrastView} from './AffectedElementsWithLowContrastView.js';
import {AffectedHeavyAdView} from './AffectedHeavyAdView.js';
import {AffectedItem, AffectedResourcesView, extractShortPath} from './AffectedResourcesView.js';
import {AffectedSharedArrayBufferIssueDetailsView} from './AffectedSharedArrayBufferIssueDetailsView.js';
import {AffectedSourcesView} from './AffectedSourcesView.js';
import {AffectedTrustedWebActivityIssueDetailsView} from './AffectedTrustedWebActivityIssueDetailsView.js';
import {CorsIssueDetailsView} from './CorsIssueDetailsView.js';
import {GenericIssueDetailsView} from './GenericIssueDetailsView.js';
import {AttributionReportingIssueDetailsView} from './AttributionReportingIssueDetailsView.js';
import type {AggregatedIssue} from './IssueAggregator.js';
import type {HiddenIssuesMenuData} from './components/HideIssuesMenu.js';
const UIStrings = {
/**
*@description Noun, singular. Label for a column or field containing the name of an entity.
*/
name: 'Name',
/**
*@description The kind of resolution for a mixed content issue
*/
blocked: 'blocked',
/**
*@description Label for a type of issue that can appear in the Issues view. Noun for singular or plural number of network requests.
*/
nRequests: '{n, plural, =1 {# request} other {# requests}}',
/**
*@description Label for singular or plural number of affected resources in issue view
*/
nResources: '{n, plural, =1 {# resource} other {# resources}}',
/**
*@description Label for mixed content issue's restriction status
*/
restrictionStatus: 'Restriction Status',
/**
* @description When there is a Heavy Ad, the browser can choose to deal with it in different ways.
* This string indicates that the ad was only warned, and not removed.
*/
warned: 'Warned',
/**
*@description Header for the section listing affected resources
*/
affectedResources: 'Affected Resources',
/**
*@description Title for a link to further information in issue view
*@example {SameSite Cookies Explained} PH1
*/
learnMoreS: 'Learn more: {PH1}',
/**
*@description The kind of resolution for a mixed content issue
*/
automaticallyUpgraded: 'automatically upgraded',
/**
*@description Menu entry for hiding a particular issue, in the Hide Issues context menu.
*/
hideIssuesLikeThis: 'Hide issues like this',
/**
*@description Menu entry for unhiding a particular issue, in the Hide Issues context menu.
*/
unhideIssuesLikeThis: 'Unhide issues like this',
};
const str_ = i18n.i18n.registerUIStrings('panels/issues/IssueView.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
class AffectedRequestsView extends AffectedResourcesView {
#appendAffectedRequests(affectedRequests: Iterable<Protocol.Audits.AffectedRequest>): void {
let count = 0;
for (const affectedRequest of affectedRequests) {
const element = document.createElement('tr');
element.classList.add('affected-resource-request');
const category = this.issue.getCategory();
const tab = issueTypeToNetworkHeaderMap.get(category) || NetworkForward.UIRequestLocation.UIRequestTabs.Headers;
element.appendChild(this.createRequestCell(affectedRequest, {
networkTab: tab,
additionalOnClickAction() {
Host.userMetrics.issuesPanelResourceOpened(category, AffectedItem.Request);
},
}));
this.affectedResources.appendChild(element);
count++;
}
this.updateAffectedResourceCount(count);
}
protected getResourceNameWithCount(count: number): Platform.UIString.LocalizedString {
return i18nString(UIStrings.nRequests, {n: count});
}
update(): void {
this.clear();
// eslint-disable-next-line @typescript-eslint/no-unused-vars
for (const unused of this.issue.getBlockedByResponseDetails()) {
// If the issue has blockedByResponseDetails, the corresponding AffectedBlockedByResponseView
// will take care of displaying the request.
this.updateAffectedResourceCount(0);
return;
}
if (this.issue.getCategory() === IssuesManager.Issue.IssueCategory.MixedContent) {
// The AffectedMixedContentView takes care of displaying the resources.
this.updateAffectedResourceCount(0);
return;
}
this.#appendAffectedRequests(this.issue.requests());
}
}
const issueTypeToNetworkHeaderMap =
new Map<IssuesManager.Issue.IssueCategory, NetworkForward.UIRequestLocation.UIRequestTabs>([
[
IssuesManager.Issue.IssueCategory.Cookie,
NetworkForward.UIRequestLocation.UIRequestTabs.Cookies,
],
[
IssuesManager.Issue.IssueCategory.CrossOriginEmbedderPolicy,
NetworkForward.UIRequestLocation.UIRequestTabs.Headers,
],
[
IssuesManager.Issue.IssueCategory.MixedContent,
NetworkForward.UIRequestLocation.UIRequestTabs.Headers,
],
]);
class AffectedMixedContentView extends AffectedResourcesView {
#appendAffectedMixedContentDetails(mixedContentIssues: Iterable<IssuesManager.MixedContentIssue.MixedContentIssue>):
void {
const header = document.createElement('tr');
this.appendColumnTitle(header, i18nString(UIStrings.name));
this.appendColumnTitle(header, i18nString(UIStrings.restrictionStatus));
this.affectedResources.appendChild(header);
let count = 0;
for (const issue of mixedContentIssues) {
const details = issue.getDetails();
this.appendAffectedMixedContent(details);
count++;
}
this.updateAffectedResourceCount(count);
}
protected getResourceNameWithCount(count: number): Platform.UIString.LocalizedString {
return i18nString(UIStrings.nResources, {n: count});
}
appendAffectedMixedContent(mixedContent: Protocol.Audits.MixedContentIssueDetails): void {
const element = document.createElement('tr');
element.classList.add('affected-resource-mixed-content');
if (mixedContent.request) {
const networkTab = issueTypeToNetworkHeaderMap.get(this.issue.getCategory()) ||
NetworkForward.UIRequestLocation.UIRequestTabs.Headers;
element.appendChild(this.createRequestCell(mixedContent.request, {
networkTab,
additionalOnClickAction() {
Host.userMetrics.issuesPanelResourceOpened(
IssuesManager.Issue.IssueCategory.MixedContent, AffectedItem.Request);
},
}));
} else {
const filename = extractShortPath(mixedContent.insecureURL);
const cell = this.appendIssueDetailCell(element, filename, 'affected-resource-mixed-content-info');
cell.title = mixedContent.insecureURL;
}
this.appendIssueDetailCell(
element, AffectedMixedContentView.translateStatus(mixedContent.resolutionStatus),
'affected-resource-mixed-content-info');
this.affectedResources.appendChild(element);
}
private static translateStatus(resolutionStatus: Protocol.Audits.MixedContentResolutionStatus):
Platform.UIString.LocalizedString {
switch (resolutionStatus) {
case Protocol.Audits.MixedContentResolutionStatus.MixedContentBlocked:
return i18nString(UIStrings.blocked);
case Protocol.Audits.MixedContentResolutionStatus.MixedContentAutomaticallyUpgraded:
return i18nString(UIStrings.automaticallyUpgraded);
case Protocol.Audits.MixedContentResolutionStatus.MixedContentWarning:
return i18nString(UIStrings.warned);
}
}
update(): void {
this.clear();
this.#appendAffectedMixedContentDetails(this.issue.getMixedContentIssues());
}
}
export class IssueView extends UI.TreeOutline.TreeElement {
#issue: AggregatedIssue;
#description: IssuesManager.MarkdownIssueDescription.IssueDescription;
toggleOnClick: boolean;
affectedResources: UI.TreeOutline.TreeElement;
readonly #affectedResourceViews: AffectedResourcesView[];
#aggregatedIssuesCount: HTMLElement|null;
#issueKindIcon: IconButton.Icon.Icon|null = null;
#hasBeenExpandedBefore: boolean;
#throttle: Common.Throttler.Throttler;
#needsUpdateOnExpand = true;
#hiddenIssuesMenu?: Components.HideIssuesMenu.HideIssuesMenu;
#contentCreated: boolean = false;
constructor(issue: AggregatedIssue, description: IssuesManager.MarkdownIssueDescription.IssueDescription) {
super();
this.#issue = issue;
this.#description = description;
this.#throttle = new Common.Throttler.Throttler(250);
this.toggleOnClick = true;
this.listItemElement.classList.add('issue');
this.childrenListElement.classList.add('body');
this.childrenListElement.classList.add(IssueView.getBodyCSSClass(this.#issue.getKind()));
this.affectedResources = this.#createAffectedResources();
this.#affectedResourceViews = [
new AffectedCookiesView(this, this.#issue),
new AffectedElementsView(this, this.#issue),
new AffectedRequestsView(this, this.#issue),
new AffectedMixedContentView(this, this.#issue),
new AffectedSourcesView(this, this.#issue),
new AffectedHeavyAdView(this, this.#issue),
new AffectedDirectivesView(this, this.#issue),
new AffectedBlockedByResponseView(this, this.#issue),
new AffectedSharedArrayBufferIssueDetailsView(this, this.#issue),
new AffectedElementsWithLowContrastView(this, this.#issue),
new AffectedTrustedWebActivityIssueDetailsView(this, this.#issue),
new CorsIssueDetailsView(this, this.#issue),
new GenericIssueDetailsView(this, this.#issue),
new AffectedDocumentsInQuirksModeView(this, this.#issue),
new AttributionReportingIssueDetailsView(this, this.#issue),
new AffectedRawCookieLinesView(this, this.#issue),
];
if (Root.Runtime.experiments.isEnabled('hideIssuesFeature')) {
this.#hiddenIssuesMenu = new Components.HideIssuesMenu.HideIssuesMenu();
}
this.#aggregatedIssuesCount = null;
this.#hasBeenExpandedBefore = false;
}
/**
* Sets the issue to take the resources from. Assumes that the description
* this IssueView was initialized with fits the new issue as well, i.e.
* title and issue description will not be updated.
*/
setIssue(issue: AggregatedIssue): void {
if (this.#issue !== issue) {
this.#needsUpdateOnExpand = true;
}
this.#issue = issue;
this.#affectedResourceViews.forEach(view => view.setIssue(issue));
}
private static getBodyCSSClass(issueKind: IssuesManager.Issue.IssueKind): string {
switch (issueKind) {
case IssuesManager.Issue.IssueKind.BreakingChange:
return 'issue-kind-breaking-change';
case IssuesManager.Issue.IssueKind.PageError:
return 'issue-kind-page-error';
case IssuesManager.Issue.IssueKind.Improvement:
return 'issue-kind-improvement';
}
}
getIssueTitle(): string {
return this.#description.title;
}
onattach(): void {
if (!this.#contentCreated) {
this.createContent();
return;
}
this.update();
}
createContent(): void {
this.#appendHeader();
this.#createBody();
this.appendChild(this.affectedResources);
for (const view of this.#affectedResourceViews) {
this.appendAffectedResource(view);
view.update();
}
this.#createReadMoreLinks();
this.updateAffectedResourceVisibility();
this.#contentCreated = true;
}
appendAffectedResource(resource: UI.TreeOutline.TreeElement): void {
this.affectedResources.appendChild(resource);
}
#appendHeader(): void {
const header = document.createElement('div');
header.classList.add('header');
this.#issueKindIcon = new IconButton.Icon.Icon();
this.#issueKindIcon.classList.add('leading-issue-icon');
this.#aggregatedIssuesCount = document.createElement('span');
const countAdorner = new Adorners.Adorner.Adorner();
countAdorner.data = {
name: 'countWrapper',
content: this.#aggregatedIssuesCount,
};
countAdorner.classList.add('aggregated-issues-count');
header.appendChild(this.#issueKindIcon);
header.appendChild(countAdorner);
const title = document.createElement('div');
title.classList.add('title');
title.textContent = this.#description.title;
header.appendChild(title);
if (this.#hiddenIssuesMenu) {
header.appendChild(this.#hiddenIssuesMenu);
}
this.#updateFromIssue();
this.listItemElement.appendChild(header);
}
onexpand(): void {
Host.userMetrics.issuesPanelIssueExpanded(this.#issue.getCategory());
if (this.#needsUpdateOnExpand) {
this.#doUpdate();
}
if (!this.#hasBeenExpandedBefore) {
this.#hasBeenExpandedBefore = true;
for (const view of this.#affectedResourceViews) {
view.expandIfOneResource();
}
}
}
#updateFromIssue(): void {
if (this.#issueKindIcon) {
const kind = this.#issue.getKind();
this.#issueKindIcon.data = IssueCounter.IssueCounter.getIssueKindIconData(kind);
this.#issueKindIcon.title = IssuesManager.Issue.getIssueKindDescription(kind);
}
if (this.#aggregatedIssuesCount) {
this.#aggregatedIssuesCount.textContent = `${this.#issue.getAggregatedIssuesCount()}`;
}
this.listItemElement.classList.toggle('hidden-issue', this.#issue.isHidden());
if (this.#hiddenIssuesMenu) {
const data: HiddenIssuesMenuData = {
menuItemLabel: this.#issue.isHidden() ? i18nString(UIStrings.unhideIssuesLikeThis) :<|fim▁hole|> values[this.#issue.code()] = this.#issue.isHidden() ? IssuesManager.IssuesManager.IssueStatus.Unhidden :
IssuesManager.IssuesManager.IssueStatus.Hidden;
setting.set(values);
},
};
this.#hiddenIssuesMenu.data = data;
}
}
updateAffectedResourceVisibility(): void {
const noResources = this.#affectedResourceViews.every(view => view.isEmpty());
this.affectedResources.hidden = noResources;
}
#createAffectedResources(): UI.TreeOutline.TreeElement {
const wrapper = new UI.TreeOutline.TreeElement();
wrapper.setCollapsible(false);
wrapper.setExpandable(true);
wrapper.expand();
wrapper.selectable = false;
wrapper.listItemElement.classList.add('affected-resources-label');
wrapper.listItemElement.textContent = i18nString(UIStrings.affectedResources);
wrapper.childrenListElement.classList.add('affected-resources');
return wrapper;
}
#createBody(): void {
const messageElement = new UI.TreeOutline.TreeElement();
messageElement.setCollapsible(false);
messageElement.selectable = false;
const markdownComponent = new MarkdownView.MarkdownView.MarkdownView();
markdownComponent.data = {tokens: this.#description.markdown};
messageElement.listItemElement.appendChild(markdownComponent);
this.appendChild(messageElement);
}
#createReadMoreLinks(): void {
if (this.#description.links.length === 0) {
return;
}
const linkWrapper = new UI.TreeOutline.TreeElement();
linkWrapper.setCollapsible(false);
linkWrapper.listItemElement.classList.add('link-wrapper');
const linkList = linkWrapper.listItemElement.createChild('ul', 'link-list');
for (const description of this.#description.links) {
const link = UI.Fragment.html`<x-link class="link devtools-link" tabindex="0" href=${description.link}>${
i18nString(UIStrings.learnMoreS, {PH1: description.linkTitle})}</x-link>` as UI.XLink.XLink;
const linkIcon = new IconButton.Icon.Icon();
linkIcon.data = {iconName: 'link_icon', color: 'var(--color-link)', width: '16px', height: '16px'};
linkIcon.classList.add('link-icon');
link.prepend(linkIcon);
link.addEventListener('x-link-invoke', () => {
Host.userMetrics.issuesPanelResourceOpened(this.#issue.getCategory(), AffectedItem.LearnMore);
});
const linkListItem = linkList.createChild('li');
linkListItem.appendChild(link);
}
this.appendChild(linkWrapper);
}
#doUpdate(): void {
if (this.expanded) {
this.#affectedResourceViews.forEach(view => view.update());
this.updateAffectedResourceVisibility();
}
this.#needsUpdateOnExpand = !this.expanded;
this.#updateFromIssue();
}
update(): void {
void this.#throttle.schedule(async () => this.#doUpdate());
}
getIssueKind(): IssuesManager.Issue.IssueKind {
return this.#issue.getKind();
}
isForHiddenIssue(): boolean {
return this.#issue.isHidden();
}
toggle(expand?: boolean): void {
if (expand || (expand === undefined && !this.expanded)) {
this.expand();
} else {
this.collapse();
}
}
}<|fim▁end|>
|
i18nString(UIStrings.hideIssuesLikeThis),
menuItemAction: () => {
const setting = IssuesManager.IssuesManager.getHideIssueByCodeSetting();
const values = setting.get();
|
<|file_name|>test_compat.py<|end_file_name|><|fim▁begin|>from django.db import models
from django.test import TestCase<|fim▁hole|>from ..models.compat import YAMLField
class TestYAMLModel(models.Model):
yaml_field = YAMLField()
class TestYAMLField(TestCase):
...
def test_to_python(self):
yaml_data = """
main:
- 1
- 2
- 3
"""
yaml_field = YAMLField()
yaml_field.to_python(yaml_data)
yaml_data = ""
yaml_field = YAMLField()
self.assertEqual(None, yaml_field.to_python(yaml_data))
yaml_data = """`"""
yaml_field = YAMLField()
with self.assertRaises(Exception):
yaml_field.to_python(yaml_data)
def test_get_prep_value(self):
yaml_field = YAMLField()
self.assertEqual("", yaml_field.get_prep_value(None))
yaml_field = YAMLField()
data = {"aaa": "aaa😺",}
self.assertEqual(
"aaa: aaa😺\n",
yaml_field.get_prep_value(data)
)<|fim▁end|>
| |
<|file_name|>config_personal.py<|end_file_name|><|fim▁begin|>import os.path as osp
import os
USE_GPU = False
AWS_REGION_NAME = 'us-east-2'<|fim▁hole|># DOCKER_IMAGE = 'dwicke/jump:docker'
DOCKER_IMAGE = 'dwicke/parameterized:latest'
DOCKER_LOG_DIR = '/tmp/expt'
AWS_S3_PATH = 's3://pytorchrl/pytorchrl/experiments'
AWS_CODE_SYNC_S3_PATH = 's3://pytorchrl/pytorchrl/code'
ALL_REGION_AWS_IMAGE_IDS = {
'ap-northeast-1': 'ami-002f0167',
'ap-northeast-2': 'ami-590bd937',
'ap-south-1': 'ami-77314318',
'ap-southeast-1': 'ami-1610a975',
'ap-southeast-2': 'ami-9dd4ddfe',
'eu-central-1': 'ami-63af720c',
'eu-west-1': 'ami-41484f27',
'sa-east-1': 'ami-b7234edb',
'us-east-1': 'ami-83f26195',
'us-east-2': 'ami-66614603',
'us-west-1': 'ami-576f4b37',
'us-west-2': 'ami-b8b62bd8'
}
AWS_IMAGE_ID = ALL_REGION_AWS_IMAGE_IDS[AWS_REGION_NAME]
if USE_GPU:
AWS_INSTANCE_TYPE = 'g2.2xlarge'
else:
AWS_INSTANCE_TYPE = 'c4.2xlarge'
ALL_REGION_AWS_KEY_NAMES = {
"us-east-2": "pytorchrl-us-east-2",
"us-east-1": "pytorchrl-us-east-1"
}
AWS_KEY_NAME = ALL_REGION_AWS_KEY_NAMES[AWS_REGION_NAME]
AWS_SPOT = True
AWS_SPOT_PRICE = '0.1'
AWS_ACCESS_KEY = os.environ.get('AWS_ACCESS_KEY', None)
AWS_ACCESS_SECRET = os.environ.get('AWS_ACCESS_SECRET', None)
AWS_IAM_INSTANCE_PROFILE_NAME = 'pytorchrl'
AWS_SECURITY_GROUPS = ['pytorchrl-sg']
ALL_REGION_AWS_SECURITY_GROUP_IDS = {
"us-east-2": [
"sg-18009370"
],
"us-east-1": [
"sg-46308b34"
]
}
AWS_SECURITY_GROUP_IDS = ALL_REGION_AWS_SECURITY_GROUP_IDS[AWS_REGION_NAME]
FAST_CODE_SYNC_IGNORES = [
'.git',
'data/local',
'data/s3',
'data/video',
'src',
'.idea',
'.pods',
'tests',
'examples',
'docs',
'.idea',
'.DS_Store',
'.ipynb_checkpoints',
'blackbox',
'blackbox.zip',
'*.pyc',
'*.ipynb',
'scratch-notebooks',
'conopt_root',
'private/key_pairs',
]
FAST_CODE_SYNC = True<|fim▁end|>
|
if USE_GPU:
DOCKER_IMAGE = 'dementrock/rllab3-shared-gpu'
else:
|
<|file_name|>encodable.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The compiler code necessary to implement the `#[derive(Encodable)]`
//! (and `Decodable`, in decodable.rs) extension. The idea here is that
//! type-defining items may be tagged with `#[derive(Encodable, Decodable)]`.
//!
//! For example, a type like:
//!
//! ```ignore
//! #[derive(Encodable, Decodable)]
//! struct Node { id: usize }
//! ```
//!
//! would generate two implementations like:
//!
//! ```ignore
//! impl<S: Encoder<E>, E> Encodable<S, E> for Node {
//! fn encode(&self, s: &mut S) -> Result<(), E> {
//! s.emit_struct("Node", 1, |this| {
//! this.emit_struct_field("id", 0, |this| {
//! Encodable::encode(&self.id, this)
//! /* this.emit_usize(self.id) can also be used */
//! })
//! })
//! }
//! }
//!
//! impl<D: Decoder<E>, E> Decodable<D, E> for Node {
//! fn decode(d: &mut D) -> Result<Node, E> {
//! d.read_struct("Node", 1, |this| {
//! match this.read_struct_field("id", 0, |this| Decodable::decode(this)) {
//! Ok(id) => Ok(Node { id: id }),
//! Err(e) => Err(e),
//! }
//! })
//! }
//! }
//! ```
//!
//! Other interesting scenarios are when the item has type parameters or
//! references other non-built-in types. A type definition like:
//!
//! ```ignore
//! #[derive(Encodable, Decodable)]
//! struct Spanned<T> { node: T, span: Span }
//! ```
//!
//! would yield functions like:
//!
//! ```ignore
//! impl<
//! S: Encoder<E>,
//! E,
//! T: Encodable<S, E>
//! > Encodable<S, E> for Spanned<T> {
//! fn encode(&self, s: &mut S) -> Result<(), E> {
//! s.emit_struct("Spanned", 2, |this| {
//! this.emit_struct_field("node", 0, |this| self.node.encode(this))
//! .ok().unwrap();
//! this.emit_struct_field("span", 1, |this| self.span.encode(this))
//! })
//! }
//! }
//!
//! impl<
//! D: Decoder<E>,
//! E,
//! T: Decodable<D, E>
//! > Decodable<D, E> for Spanned<T> {
//! fn decode(d: &mut D) -> Result<Spanned<T>, E> {
//! d.read_struct("Spanned", 2, |this| {
//! Ok(Spanned {
//! node: this.read_struct_field("node", 0, |this| Decodable::decode(this))
//! .ok().unwrap(),
//! span: this.read_struct_field("span", 1, |this| Decodable::decode(this))
//! .ok().unwrap(),
//! })
//! })
//! }
//! }
//! ```
use ast::{MetaItem, Item, Expr, ExprRet, MutMutable};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token;
use ptr::P;
pub fn expand_deriving_rustc_encodable<F>(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Item,
push: F) where
F: FnOnce(P<Item>),
{
expand_deriving_encodable_imp(cx, span, mitem, item, push, "rustc_serialize")
}
pub fn expand_deriving_encodable<F>(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Item,
push: F) where
F: FnOnce(P<Item>),
{
expand_deriving_encodable_imp(cx, span, mitem, item, push, "serialize")
}
fn expand_deriving_encodable_imp<F>(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Item,
push: F,
krate: &'static str) where
F: FnOnce(P<Item>),
{
if !cx.use_std {
// FIXME(#21880): lift this requirement.
cx.span_err(span, "this trait cannot be derived with #![no_std]");
return;
}
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new_(vec!(krate, "Encodable"), None, vec!(), true),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "encode",
generics: LifetimeBounds {
lifetimes: Vec::new(),
bounds: vec!(("__S", vec!(Path::new_(
vec!(krate, "Encoder"), None,
vec!(), true))))
},
explicit_self: borrowed_explicit_self(),
args: vec!(Ptr(box Literal(Path::new_local("__S")),
Borrowed(None, MutMutable))),
ret_ty: Literal(Path::new_(
pathvec_std!(cx, core::result::Result),
None,
vec!(box Tuple(Vec::new()), box Literal(Path::new_(
vec!["__S", "Error"], None, vec![], false
))),
true
)),
attributes: Vec::new(),
combine_substructure: combine_substructure(Box::new(|a, b, c| {
encodable_substructure(a, b, c)
})),
}
),
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, item, push)
}
fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
substr: &Substructure) -> P<Expr> {
let encoder = substr.nonself_args[0].clone();
// throw an underscore in front to suppress unused variable warnings
let blkarg = cx.ident_of("_e");
let blkencoder = cx.expr_ident(trait_span, blkarg);
let encode = cx.ident_of("encode");
return match *substr.fields {
Struct(ref fields) => {
let emit_struct_field = cx.ident_of("emit_struct_field");
let mut stmts = Vec::new();
for (i, &FieldInfo {
name,
ref self_,
span,
..
}) in fields.iter().enumerate() {
let name = match name {
Some(id) => token::get_ident(id),
None => {
token::intern_and_get_ident(&format!("_field{}", i))
}
};
let enc = cx.expr_method_call(span, self_.clone(),
encode, vec!(blkencoder.clone()));
let lambda = cx.lambda_expr_1(span, enc, blkarg);
let call = cx.expr_method_call(span, blkencoder.clone(),
emit_struct_field,
vec!(cx.expr_str(span, name),
cx.expr_usize(span, i),
lambda));
// last call doesn't need a try!
let last = fields.len() - 1;
let call = if i != last {
cx.expr_try(span, call)
} else {
cx.expr(span, ExprRet(Some(call)))
};
stmts.push(cx.stmt_expr(call));
}
// unit structs have no fields and need to return Ok()
if stmts.is_empty() {
let ret_ok = cx.expr(trait_span,
ExprRet(Some(cx.expr_ok(trait_span,
cx.expr_tuple(trait_span, vec![])))));
stmts.push(cx.stmt_expr(ret_ok));
}
let blk = cx.lambda_stmts_1(trait_span, stmts, blkarg);
cx.expr_method_call(trait_span,
encoder,
cx.ident_of("emit_struct"),
vec!(
cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
cx.expr_usize(trait_span, fields.len()),
blk
))
}
EnumMatching(idx, variant, ref fields) => {
// We're not generating an AST that the borrow checker is expecting,
// so we need to generate a unique local variable to take the
// mutable loan out on, otherwise we get conflicts which don't
// actually exist.
let me = cx.stmt_let(trait_span, false, blkarg, encoder);
let encoder = cx.expr_ident(trait_span, blkarg);
let emit_variant_arg = cx.ident_of("emit_enum_variant_arg");
let mut stmts = Vec::new();
if fields.len() > 0 {
let last = fields.len() - 1;
for (i, &FieldInfo { ref self_, span, .. }) in fields.iter().enumerate() {
let enc = cx.expr_method_call(span, self_.clone(),
encode, vec!(blkencoder.clone()));
let lambda = cx.lambda_expr_1(span, enc, blkarg);
let call = cx.expr_method_call(span, blkencoder.clone(),
emit_variant_arg,
vec!(cx.expr_usize(span, i),
lambda));
let call = if i != last {
cx.expr_try(span, call)
} else {
cx.expr(span, ExprRet(Some(call)))
};
stmts.push(cx.stmt_expr(call));
}
} else {
let ret_ok = cx.expr(trait_span,
ExprRet(Some(cx.expr_ok(trait_span,
cx.expr_tuple(trait_span, vec![])))));
stmts.push(cx.stmt_expr(ret_ok));
}
let blk = cx.lambda_stmts_1(trait_span, stmts, blkarg);
let name = cx.expr_str(trait_span, token::get_ident(variant.node.name));
let call = cx.expr_method_call(trait_span, blkencoder,
cx.ident_of("emit_enum_variant"),
vec!(name,
cx.expr_usize(trait_span, idx),
cx.expr_usize(trait_span, fields.len()),
blk));
let blk = cx.lambda_expr_1(trait_span, call, blkarg);
let ret = cx.expr_method_call(trait_span,<|fim▁hole|> cx.ident_of("emit_enum"),
vec!(
cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
blk
));
cx.expr_block(cx.block(trait_span, vec!(me), Some(ret)))
}
_ => cx.bug("expected Struct or EnumMatching in derive(Encodable)")
};
}<|fim▁end|>
|
encoder,
|
<|file_name|>mkfs.py<|end_file_name|><|fim▁begin|># -*- coding: utf8 -*-
"""
@todo: Update argument parser options
"""
# Imports. {{{1
import sys
# Try to load the required modules from Python's standard library.
try:
import os
import argparse
from time import time
import hashlib
except ImportError as e:
msg = "Error: Failed to load one of the required Python modules! (%s)\n"
sys.stderr.write(msg % str(e))
sys.exit(1)
from dedupsqlfs.log import logging
from dedupsqlfs.lib import constants
from dedupsqlfs.db import check_engines
import dedupsqlfs
def mkfs(options, compression_methods=None, hash_functions=None):
from dedupsqlfs.fuse.dedupfs import DedupFS
from dedupsqlfs.fuse.operations import DedupOperations
ops = None
ret = 0
try:
ops = DedupOperations()
_fuse = DedupFS(
ops, None,
options,
fsname="dedupsqlfs", allow_root=True)
if not _fuse.checkIfLocked():
_fuse.saveCompressionMethods(compression_methods)<|fim▁hole|>
_fuse.setOption("gc_umount_enabled", False)
_fuse.setOption("gc_vacuum_enabled", False)
_fuse.setOption("gc_enabled", False)
_fuse.operations.init()
_fuse.operations.destroy()
except Exception:
import traceback
print(traceback.format_exc())
ret = -1
if ops:
ops.getManager().close()
return ret
def main(): # {{{1
"""
This function enables using mkfs.dedupsqlfs.py as a shell script that creates FUSE
mount points. Execute "mkfs.dedupsqlfs -h" for a list of valid command line options.
"""
logger = logging.getLogger("mkfs.dedupsqlfs/main")
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler(sys.stderr))
parser = argparse.ArgumentParser(
prog="%s/%s mkfs/%s python/%s" % (dedupsqlfs.__name__, dedupsqlfs.__version__, dedupsqlfs.__fsversion__, sys.version.split()[0]),
conflict_handler="resolve")
# Register some custom command line options with the option parser.
option_stored_in_db = " (this option is only useful when creating a new database, because your choice is stored in the database and can't be changed after that)"
parser.add_argument('-h', '--help', action='help', help="show this help message followed by the command line options defined by the Python FUSE binding and exit")
parser.add_argument('-v', '--verbose', action='count', dest='verbosity', default=0, help="increase verbosity: 0 - error, 1 - warning, 2 - info, 3 - debug, 4 - verbose")
parser.add_argument('--log-file', dest='log_file', help="specify log file location")
parser.add_argument('--log-file-only', dest='log_file_only', action='store_true',
help="Don't send log messages to stderr.")
parser.add_argument('--data', dest='data', metavar='DIRECTORY', default="~/data", help="Specify the base location for the files in which metadata and blocks data is stored. Defaults to ~/data")
parser.add_argument('--name', dest='name', metavar='DATABASE', default="dedupsqlfs", help="Specify the name for the database directory in which metadata and blocks data is stored. Defaults to dedupsqlfs")
parser.add_argument('--temp', dest='temp', metavar='DIRECTORY', help="Specify the location for the files in which temporary data is stored. By default honour TMPDIR environment variable value.")
parser.add_argument('-b', '--block-size', dest='block_size', metavar='BYTES', default=1024*128, type=int, help="Specify the maximum block size in bytes" + option_stored_in_db + ". Defaults to 128kB.")
parser.add_argument('--memory-limit', dest='memory_limit', action='store_true', help="Use some lower values for less memory consumption.")
parser.add_argument('--cpu-limit', dest='cpu_limit', metavar='NUMBER', default=0, type=int, help="Specify the maximum CPU count to use in multiprocess compression. Defaults to 0 (auto).")
engines, msg = check_engines()
if not engines:
logger.error("No storage engines available! Please install sqlite or pymysql python module!")
return 1
parser.add_argument('--storage-engine', dest='storage_engine', metavar='ENGINE', choices=engines, default=engines[0],
help=msg)
if "mysql" in engines:
from dedupsqlfs.db.mysql import get_table_engines
table_engines = get_table_engines()
msg = "One of MySQL table engines: "+", ".join(table_engines)+". Default: %r. Aria and TokuDB engine can be used only with MariaDB or Percona server." % table_engines[0]
parser.add_argument('--table-engine', dest='table_engine', metavar='ENGINE',
choices=table_engines, default=table_engines[0],
help=msg)
parser.add_argument('--no-cache', dest='use_cache', action='store_false', help="Don't use cache in memory and delayed write to storage.")
parser.add_argument('--no-transactions', dest='use_transactions', action='store_false', help="Don't use transactions when making multiple related changes, this might make the file system faster or slower (?).")
parser.add_argument('--no-sync', dest='synchronous', action='store_false', help="Disable SQLite's normal synchronous behavior which guarantees that data is written to disk immediately, because it slows down the file system too much (this means you might lose data when the mount point isn't cleanly unmounted).")
# Dynamically check for supported hashing algorithms.
msg = "Specify the hashing algorithm that will be used to recognize duplicate data blocks: one of %s. Choose wisely - it can't be changed on the fly."
hash_functions = list({}.fromkeys([h.lower() for h in hashlib.algorithms_available]).keys())
hash_functions.sort()
work_hash_funcs = set(hash_functions) & constants.WANTED_HASH_FUCTIONS
msg %= ', '.join('%r' % fun for fun in work_hash_funcs)
defHash = 'md5' # Hope it will be there always. Stupid.
msg += ". Defaults to %r." % defHash
parser.add_argument('--hash', dest='hash_function', metavar='FUNCTION', choices=work_hash_funcs, default=defHash, help=msg)
# Dynamically check for supported compression methods.
compression_methods = [constants.COMPRESSION_TYPE_NONE]
compression_methods_cmd = [constants.COMPRESSION_TYPE_NONE]
for modname in constants.COMPRESSION_SUPPORTED:
try:
module = __import__(modname)
if hasattr(module, 'compress') and hasattr(module, 'decompress'):
compression_methods.append(modname)
if modname not in constants.COMPRESSION_READONLY:
compression_methods_cmd.append(modname)
except ImportError:
pass
if len(compression_methods) > 1:
compression_methods_cmd.append(constants.COMPRESSION_TYPE_BEST)
compression_methods_cmd.append(constants.COMPRESSION_TYPE_CUSTOM)
msg = "Enable compression of data blocks using one of the supported compression methods: one of %s"
msg %= ', '.join('%r' % mth for mth in compression_methods_cmd)
msg += ". Defaults to %r." % constants.COMPRESSION_TYPE_NONE
msg += " You can use <method>:<level> syntax, <level> can be integer or value from --compression-level."
if len(compression_methods_cmd) > 1:
msg += " %r will try all compression methods and choose one with smaller result data." % constants.COMPRESSION_TYPE_BEST
msg += " %r will try selected compression methods (--custom-compress) and choose one with smaller result data." % constants.COMPRESSION_TYPE_CUSTOM
msg += "\nDefaults to %r." % constants.COMPRESSION_TYPE_NONE
parser.add_argument('--compress', dest='compression', metavar='METHOD', action="append",
default=[constants.COMPRESSION_TYPE_NONE], help=msg)
msg = "Enable compression of data blocks using one or more of the supported compression methods: %s"
msg %= ', '.join('%r' % mth for mth in compression_methods_cmd[:-2])
msg += ". To use two or more methods select this option in command line for each compression method."
msg += " You can use <method>=<level> syntax, <level> can be integer or value from --compression-level."
parser.add_argument('--force-compress', dest='compression_forced', action="store_true", help="Force compression even if resulting data is bigger than original.")
parser.add_argument('--minimal-compress-size', dest='compression_minimal_size', metavar='BYTES', type=int, default=1024, help="Minimal block data size for compression. Defaults to 1024 bytes. Value -1 means auto - per method absolute minimum. Not compress if data size is less then BYTES long. If not forced to.")
parser.add_argument('--minimal-compress-ratio', dest='compression_minimal_ratio', metavar='RATIO', type=float, default=0.05, help="Minimal data compression ratio. Defaults to 0.05 (5%%). Do not compress if ratio is less than RATIO. If not forced to.")
levels = (constants.COMPRESSION_LEVEL_DEFAULT, constants.COMPRESSION_LEVEL_FAST, constants.COMPRESSION_LEVEL_NORM, constants.COMPRESSION_LEVEL_BEST)
parser.add_argument('--compression-level', dest='compression_level', metavar="LEVEL", default=constants.COMPRESSION_LEVEL_DEFAULT,
help="Compression level ratio: one of %s; or INT. Defaults to %r. Not all methods support this option." % (
', '.join('%r' % lvl for lvl in levels), constants.COMPRESSION_LEVEL_DEFAULT
))
# Dynamically check for profiling support.
try:
# Using __import__() here because of pyflakes.
for p in 'cProfile', 'pstats': __import__(p)
parser.add_argument('--profile', action='store_true', default=False, help="Use the Python modules cProfile and pstats to create a profile of time spent in various function calls and print out a table of the slowest functions at exit (of course this slows everything down but it can nevertheless give a good indication of the hot spots).")
except ImportError:
logger.warning("No profiling support available, --profile option disabled.")
logger.warning("If you're on Ubuntu try 'sudo apt-get install python-profiler'.")
args = parser.parse_args()
if args.profile:
sys.stderr.write("Enabling profiling..\n")
import cProfile, pstats
profile = '.dedupsqlfs.cprofile-%i' % time()
profiler = cProfile.Profile()
result = profiler.runcall(mkfs, args, compression_methods, hash_functions)
profiler.dump_stats(profile)
sys.stderr.write("\n Profiling statistics:\n\n")
s = pstats.Stats(profile)
s.sort_stats('calls').print_stats(0.1)
s.sort_stats('cumtime').print_stats(0.1)
s.sort_stats('tottime').print_stats(0.1)
os.unlink(profile)
else:
result = mkfs(args, compression_methods, hash_functions)
return result
# vim: ts=4 sw=4 et<|fim▁end|>
|
for modname in compression_methods:
_fuse.appendCompression(modname)
|
<|file_name|>webpack.dev.conf.js<|end_file_name|><|fim▁begin|>var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')<|fim▁hole|>var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
// add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})
module.exports = merge(baseWebpackConfig, {
node: {
console: false,
fs: 'empty',
net: 'empty',
tls: 'empty'
},
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
},
{
loader: 'file-loader',
options: {
name: '../static/theme/2001/*.fmi'
}
},
{
loader: 'file-loader',
options: {
name: '../static/10347/10347.fmap'
}
},
// cheap-module-eval-source-map is faster for development
devtool: '#cheap-module-eval-source-map',
plugins: [
new webpack.DefinePlugin({
'process.env': config.dev.env
}),
// https://github.com/glenjamin/webpack-hot-middleware#installation--usage
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
new FriendlyErrorsPlugin()
]
})<|fim▁end|>
|
var merge = require('webpack-merge')
|
<|file_name|>test_dms.py<|end_file_name|><|fim▁begin|># -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under the GNU Public Licence, v2 or any higher version
#
# Please cite your use of MDAnalysis in published work:
#
# R. J. Gowers, M. Linke, J. Barnoud, T. J. E. Reddy, M. N. Melo, S. L. Seyler,
# D. L. Dotson, J. Domanski, S. Buchoux, I. M. Kenney, and O. Beckstein.
# MDAnalysis: A Python package for the rapid analysis of molecular dynamics
# simulations. In S. Benthall and S. Rostrup editors, Proceedings of the 15th
# Python in Science Conference, pages 102-109, Austin, TX, 2016. SciPy.
# doi: 10.25080/majora-629e541a-00e
#
# N. Michaud-Agrawal, E. J. Denning, T. B. Woolf, and O. Beckstein.<|fim▁hole|>#
import MDAnalysis as mda
import numpy as np
import pytest
from numpy.testing import assert_equal
from MDAnalysis.lib.mdamath import triclinic_vectors
from MDAnalysisTests.datafiles import (DMS)
class TestDMSReader(object):
@pytest.fixture()
def universe(self):
return mda.Universe(DMS)
@pytest.fixture()
def ts(self, universe):
return universe.trajectory.ts
def test_global_cell(self, ts):
assert ts.dimensions is None
def test_velocities(self, ts):
assert_equal(hasattr(ts, "_velocities"), False)
def test_number_of_coords(self, universe):
# Desired value taken from VMD
# Info) Atoms: 3341
assert_equal(len(universe.atoms), 3341)
def test_coords_atom_0(self, universe):
# Desired coordinates taken directly from the SQLite file. Check unit
# conversion
coords_0 = np.array([-11.0530004501343,
26.6800003051758,
12.7419996261597, ],
dtype=np.float32)
assert_equal(universe.atoms[0].position, coords_0)
def test_n_frames(self, universe):
assert_equal(universe.trajectory.n_frames, 1,
"wrong number of frames in pdb")
def test_time(self, universe):
assert_equal(universe.trajectory.time, 0.0,
"wrong time of the frame")
def test_frame(self, universe):
assert_equal(universe.trajectory.frame, 0, "wrong frame number "
"(0-based, should be 0 for single frame readers)")
def test_frame_index_0(self, universe):
universe.trajectory[0]
assert_equal(universe.trajectory.ts.frame, 0,
"frame number for frame index 0 should be 0")
def test_frame_index_1_raises_IndexError(self, universe):
with pytest.raises(IndexError):
universe.trajectory[1]<|fim▁end|>
|
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
|
<|file_name|>clients.go<|end_file_name|><|fim▁begin|>package core
<|fim▁hole|>type Clients []*Client
// RLockRecursive _
func (cs *Clients) RLockRecursive() {
for _, client := range *cs {
client.RLockAnon()
}
}
// RUnlockRecursive _
func (cs *Clients) RUnlockRecursive() {
for _, client := range *cs {
client.RUnlockAnon()
}
}<|fim▁end|>
|
// Clients _
|
<|file_name|>directors_api.py<|end_file_name|><|fim▁begin|># coding: utf-8
"""
Server API
Reference for Server API (REST/Json)
OpenAPI spec version: 2.0.6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import sys
import os
import re
# python 2 and python 3 compatibility library
from six import iteritems
from ..configuration import Configuration
from ..api_client import ApiClient
class DirectorsApi(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
config = Configuration()
if api_client:
self.api_client = api_client
else:
if not config.api_client:
config.api_client = ApiClient()
self.api_client = config.api_client
def attach_director_to_category(self, category_id, director_id, **kwargs):
"""
Attach director to category
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.attach_director_to_category(category_id, director_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int category_id: Category ID to fetch (required)
:param int director_id: Director ID to attach (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.attach_director_to_category_with_http_info(category_id, director_id, **kwargs)
else:
(data) = self.attach_director_to_category_with_http_info(category_id, director_id, **kwargs)
return data
def attach_director_to_category_with_http_info(self, category_id, director_id, **kwargs):
"""
Attach director to category
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.attach_director_to_category_with_http_info(category_id, director_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int category_id: Category ID to fetch (required)
:param int director_id: Director ID to attach (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['category_id', 'director_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method attach_director_to_category" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'category_id' is set
if ('category_id' not in params) or (params['category_id'] is None):
raise ValueError("Missing the required parameter `category_id` when calling `attach_director_to_category`")
# verify the required parameter 'director_id' is set
if ('director_id' not in params) or (params['director_id'] is None):
raise ValueError("Missing the required parameter `director_id` when calling `attach_director_to_category`")
collection_formats = {}
resource_path = '/categories/{category_id}/directors'.replace('{format}', 'json')
path_params = {}
if 'category_id' in params:
path_params['category_id'] = params['category_id']
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
if 'director_id' in params:
form_params.append(('director_id', params['director_id']))
self.api_client.set_default_header('Content-Type', 'application/x-www-form-urlencoded')
body_params = None
# Authentication setting
auth_settings = ['ApiClientId', 'ApiClientSecret']
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def attach_director_to_product(self, product_id, director_id, **kwargs):
"""
Attach director to product
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.attach_director_to_product(product_id, director_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int product_id: Product ID to fetch (required)
:param int director_id: Director ID to attach (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.attach_director_to_product_with_http_info(product_id, director_id, **kwargs)
else:
(data) = self.attach_director_to_product_with_http_info(product_id, director_id, **kwargs)
return data
def attach_director_to_product_with_http_info(self, product_id, director_id, **kwargs):
"""
Attach director to product
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.attach_director_to_product_with_http_info(product_id, director_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int product_id: Product ID to fetch (required)
:param int director_id: Director ID to attach (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['product_id', 'director_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method attach_director_to_product" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'product_id' is set
if ('product_id' not in params) or (params['product_id'] is None):
raise ValueError("Missing the required parameter `product_id` when calling `attach_director_to_product`")
# verify the required parameter 'director_id' is set
if ('director_id' not in params) or (params['director_id'] is None):
raise ValueError("Missing the required parameter `director_id` when calling `attach_director_to_product`")
collection_formats = {}
resource_path = '/products/{product_id}/directors'.replace('{format}', 'json')
path_params = {}
if 'product_id' in params:
path_params['product_id'] = params['product_id']
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
if 'director_id' in params:
form_params.append(('director_id', params['director_id']))
self.api_client.set_default_header('Content-Type', 'application/x-www-form-urlencoded')
body_params = None
# Authentication setting
auth_settings = ['ApiClientId', 'ApiClientSecret']
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def create_director(self, body, **kwargs):
"""
Create new director
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_director(body, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param CreateDirectorRequest body: Directory settings (required)
:return: Director
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.create_director_with_http_info(body, **kwargs)
else:
(data) = self.create_director_with_http_info(body, **kwargs)
return data
def create_director_with_http_info(self, body, **kwargs):
"""
Create new director
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_director_with_http_info(body, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param CreateDirectorRequest body: Directory settings (required)
:return: Director
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_director" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_director`")
collection_formats = {}
resource_path = '/directors'.replace('{format}', 'json')
path_params = {}
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
self.api_client.set_default_header('Content-Type', 'application/json')
# Authentication setting
auth_settings = ['ApiClientId', 'ApiClientSecret']
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Director',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_director(self, director_id, **kwargs):
"""
Delete director<|fim▁hole|> asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_director(director_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int director_id: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.delete_director_with_http_info(director_id, **kwargs)
else:
(data) = self.delete_director_with_http_info(director_id, **kwargs)
return data
def delete_director_with_http_info(self, director_id, **kwargs):
"""
Delete director
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_director_with_http_info(director_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int director_id: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['director_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_director" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'director_id' is set
if ('director_id' not in params) or (params['director_id'] is None):
raise ValueError("Missing the required parameter `director_id` when calling `delete_director`")
collection_formats = {}
resource_path = '/directors/{director_id}'.replace('{format}', 'json')
path_params = {}
if 'director_id' in params:
path_params['director_id'] = params['director_id']
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = ['ApiClientId', 'ApiClientSecret']
return self.api_client.call_api(resource_path, 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def detach_director_from_category(self, category_id, director_id, **kwargs):
"""
Detach director from category
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.detach_director_from_category(category_id, director_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int category_id: Category ID to fetch (required)
:param int director_id: Director ID to detach (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.detach_director_from_category_with_http_info(category_id, director_id, **kwargs)
else:
(data) = self.detach_director_from_category_with_http_info(category_id, director_id, **kwargs)
return data
def detach_director_from_category_with_http_info(self, category_id, director_id, **kwargs):
"""
Detach director from category
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.detach_director_from_category_with_http_info(category_id, director_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int category_id: Category ID to fetch (required)
:param int director_id: Director ID to detach (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['category_id', 'director_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method detach_director_from_category" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'category_id' is set
if ('category_id' not in params) or (params['category_id'] is None):
raise ValueError("Missing the required parameter `category_id` when calling `detach_director_from_category`")
# verify the required parameter 'director_id' is set
if ('director_id' not in params) or (params['director_id'] is None):
raise ValueError("Missing the required parameter `director_id` when calling `detach_director_from_category`")
collection_formats = {}
resource_path = '/categories/{category_id}/directors/{director_id}'.replace('{format}', 'json')
path_params = {}
if 'category_id' in params:
path_params['category_id'] = params['category_id']
if 'director_id' in params:
path_params['director_id'] = params['director_id']
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = ['ApiClientId', 'ApiClientSecret']
return self.api_client.call_api(resource_path, 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_category_directors(self, category_id, **kwargs):
"""
Get directors attached to category
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_category_directors(category_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int category_id: Category ID to fetch (required)
:param int page:
:param int per_page:
:return: CategoryDirectorsListResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_category_directors_with_http_info(category_id, **kwargs)
else:
(data) = self.get_category_directors_with_http_info(category_id, **kwargs)
return data
def get_category_directors_with_http_info(self, category_id, **kwargs):
"""
Get directors attached to category
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_category_directors_with_http_info(category_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int category_id: Category ID to fetch (required)
:param int page:
:param int per_page:
:return: CategoryDirectorsListResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['category_id', 'page', 'per_page']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_category_directors" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'category_id' is set
if ('category_id' not in params) or (params['category_id'] is None):
raise ValueError("Missing the required parameter `category_id` when calling `get_category_directors`")
collection_formats = {}
resource_path = '/categories/{category_id}/directors'.replace('{format}', 'json')
path_params = {}
if 'category_id' in params:
path_params['category_id'] = params['category_id']
query_params = {}
if 'page' in params:
query_params['page'] = params['page']
if 'per_page' in params:
query_params['per_page'] = params['per_page']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = ['ApiClientId', 'ApiClientSecret']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='CategoryDirectorsListResponse',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_director(self, director_id, **kwargs):
"""
Get Director
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_director(director_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int director_id: Director ID to fetch (required)
:return: DirectorResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_director_with_http_info(director_id, **kwargs)
else:
(data) = self.get_director_with_http_info(director_id, **kwargs)
return data
def get_director_with_http_info(self, director_id, **kwargs):
"""
Get Director
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_director_with_http_info(director_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int director_id: Director ID to fetch (required)
:return: DirectorResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['director_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_director" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'director_id' is set
if ('director_id' not in params) or (params['director_id'] is None):
raise ValueError("Missing the required parameter `director_id` when calling `get_director`")
collection_formats = {}
resource_path = '/directors/{director_id}'.replace('{format}', 'json')
path_params = {}
if 'director_id' in params:
path_params['director_id'] = params['director_id']
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = ['ApiClientId', 'ApiClientSecret']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='DirectorResponse',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_director_cover_image(self, director_id, **kwargs):
"""
Get cover image of a director
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_director_cover_image(director_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int director_id: Director ID to fetch (required)
:return: ImageResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_director_cover_image_with_http_info(director_id, **kwargs)
else:
(data) = self.get_director_cover_image_with_http_info(director_id, **kwargs)
return data
def get_director_cover_image_with_http_info(self, director_id, **kwargs):
"""
Get cover image of a director
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_director_cover_image_with_http_info(director_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int director_id: Director ID to fetch (required)
:return: ImageResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['director_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_director_cover_image" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'director_id' is set
if ('director_id' not in params) or (params['director_id'] is None):
raise ValueError("Missing the required parameter `director_id` when calling `get_director_cover_image`")
collection_formats = {}
resource_path = '/directors/{director_id}/cover'.replace('{format}', 'json')
path_params = {}
if 'director_id' in params:
path_params['director_id'] = params['director_id']
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = ['ApiClientId', 'ApiClientSecret']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='ImageResponse',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_director_products(self, director_id, **kwargs):
"""
Get director products
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_director_products(director_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int director_id: Director ID to fetch (required)
:param int page:
:param int per_page:
:param str sort_by: Sort by this attribute (id by default)
:param str sort_direction: Sorting direction (asc by default)
:param str ip: Filter by user IP
:param str features: ``` features[*][value]=string&features[*][operator]=strict&features[1][value]=string&features[1][operator]=strict _______________ { \"*\": { \"value\": \"string\", \"operator\": \"strict\" }, \"1\": { \"value\": \"string\", \"operator\": \"contains\" } } ``` Operator can be: strict, contains, between, in, gt (greater than), lt (lower than). To search on all features, you can pass * as featureId.
:param str filters: ``` name[value]=string&name][operator]=contains&date_add[value]=string&date_add[operator]=lt _______________ { \"name\": { \"value\": \"string\", \"operator\": \"contains\" }, \"date_add\": { \"value\": \"string\", \"operator\": \"lt\" } } ``` Operator can be: strict, contains, between, in, gt (greater than), lt (lower than).
:return: DirectorProductListResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_director_products_with_http_info(director_id, **kwargs)
else:
(data) = self.get_director_products_with_http_info(director_id, **kwargs)
return data
def get_director_products_with_http_info(self, director_id, **kwargs):
"""
Get director products
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_director_products_with_http_info(director_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int director_id: Director ID to fetch (required)
:param int page:
:param int per_page:
:param str sort_by: Sort by this attribute (id by default)
:param str sort_direction: Sorting direction (asc by default)
:param str ip: Filter by user IP
:param str features: ``` features[*][value]=string&features[*][operator]=strict&features[1][value]=string&features[1][operator]=strict _______________ { \"*\": { \"value\": \"string\", \"operator\": \"strict\" }, \"1\": { \"value\": \"string\", \"operator\": \"contains\" } } ``` Operator can be: strict, contains, between, in, gt (greater than), lt (lower than). To search on all features, you can pass * as featureId.
:param str filters: ``` name[value]=string&name][operator]=contains&date_add[value]=string&date_add[operator]=lt _______________ { \"name\": { \"value\": \"string\", \"operator\": \"contains\" }, \"date_add\": { \"value\": \"string\", \"operator\": \"lt\" } } ``` Operator can be: strict, contains, between, in, gt (greater than), lt (lower than).
:return: DirectorProductListResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['director_id', 'page', 'per_page', 'sort_by', 'sort_direction', 'ip', 'features', 'filters']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_director_products" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'director_id' is set
if ('director_id' not in params) or (params['director_id'] is None):
raise ValueError("Missing the required parameter `director_id` when calling `get_director_products`")
collection_formats = {}
resource_path = '/directors/{director_id}/products'.replace('{format}', 'json')
path_params = {}
if 'director_id' in params:
path_params['director_id'] = params['director_id']
query_params = {}
if 'page' in params:
query_params['page'] = params['page']
if 'per_page' in params:
query_params['per_page'] = params['per_page']
if 'sort_by' in params:
query_params['sort_by'] = params['sort_by']
if 'sort_direction' in params:
query_params['sort_direction'] = params['sort_direction']
if 'ip' in params:
query_params['ip'] = params['ip']
if 'features' in params:
query_params['features'] = params['features']
if 'filters' in params:
query_params['filters'] = params['filters']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = ['ApiClientId', 'ApiClientSecret']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='DirectorProductListResponse',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_director_products_role(self, director_id, **kwargs):
"""
Get Products linked to Product with their role
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_director_products_role(director_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int director_id: Director ID to fetch (required)
:param int page:
:param int per_page:
:return: DirectorProductRoleListResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_director_products_role_with_http_info(director_id, **kwargs)
else:
(data) = self.get_director_products_role_with_http_info(director_id, **kwargs)
return data
def get_director_products_role_with_http_info(self, director_id, **kwargs):
"""
Get Products linked to Product with their role
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_director_products_role_with_http_info(director_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int director_id: Director ID to fetch (required)
:param int page:
:param int per_page:
:return: DirectorProductRoleListResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['director_id', 'page', 'per_page']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_director_products_role" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'director_id' is set
if ('director_id' not in params) or (params['director_id'] is None):
raise ValueError("Missing the required parameter `director_id` when calling `get_director_products_role`")
collection_formats = {}
resource_path = '/directors/{director_id}/products-role'.replace('{format}', 'json')
path_params = {}
if 'director_id' in params:
path_params['director_id'] = params['director_id']
query_params = {}
if 'page' in params:
query_params['page'] = params['page']
if 'per_page' in params:
query_params['per_page'] = params['per_page']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = ['ApiClientId', 'ApiClientSecret']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='DirectorProductRoleListResponse',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_directors(self, **kwargs):
"""
Get directors list
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_directors(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int page:
:param int per_page:
:return: DirectorListResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_directors_with_http_info(**kwargs)
else:
(data) = self.get_directors_with_http_info(**kwargs)
return data
def get_directors_with_http_info(self, **kwargs):
"""
Get directors list
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_directors_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int page:
:param int per_page:
:return: DirectorListResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['page', 'per_page']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_directors" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
resource_path = '/directors'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'page' in params:
query_params['page'] = params['page']
if 'per_page' in params:
query_params['per_page'] = params['per_page']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = ['ApiClientId', 'ApiClientSecret']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='DirectorListResponse',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_product_directors(self, product_id, **kwargs):
"""
Get directors of a product
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_product_directors(product_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int product_id: Product ID to fetch (required)
:param int page:
:param int per_page:
:param str image_type:
:return: DirectorListResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_product_directors_with_http_info(product_id, **kwargs)
else:
(data) = self.get_product_directors_with_http_info(product_id, **kwargs)
return data
def get_product_directors_with_http_info(self, product_id, **kwargs):
"""
Get directors of a product
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_product_directors_with_http_info(product_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int product_id: Product ID to fetch (required)
:param int page:
:param int per_page:
:param str image_type:
:return: DirectorListResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['product_id', 'page', 'per_page', 'image_type']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_product_directors" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'product_id' is set
if ('product_id' not in params) or (params['product_id'] is None):
raise ValueError("Missing the required parameter `product_id` when calling `get_product_directors`")
collection_formats = {}
resource_path = '/products/{product_id}/directors'.replace('{format}', 'json')
path_params = {}
if 'product_id' in params:
path_params['product_id'] = params['product_id']
query_params = {}
if 'page' in params:
query_params['page'] = params['page']
if 'per_page' in params:
query_params['per_page'] = params['per_page']
if 'image_type' in params:
query_params['image_type'] = params['image_type']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = ['ApiClientId', 'ApiClientSecret']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='DirectorListResponse',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_product_directors_role(self, product_id, **kwargs):
"""
Get Directors attached to Product with their role
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_product_directors_role(product_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int product_id: Product ID to fetch (required)
:param int page:
:param int per_page:
:return: DirectorRoleListResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_product_directors_role_with_http_info(product_id, **kwargs)
else:
(data) = self.get_product_directors_role_with_http_info(product_id, **kwargs)
return data
def get_product_directors_role_with_http_info(self, product_id, **kwargs):
"""
Get Directors attached to Product with their role
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_product_directors_role_with_http_info(product_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int product_id: Product ID to fetch (required)
:param int page:
:param int per_page:
:return: DirectorRoleListResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['product_id', 'page', 'per_page']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_product_directors_role" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'product_id' is set
if ('product_id' not in params) or (params['product_id'] is None):
raise ValueError("Missing the required parameter `product_id` when calling `get_product_directors_role`")
collection_formats = {}
resource_path = '/products/{product_id}/directors-role'.replace('{format}', 'json')
path_params = {}
if 'product_id' in params:
path_params['product_id'] = params['product_id']
query_params = {}
if 'page' in params:
query_params['page'] = params['page']
if 'per_page' in params:
query_params['per_page'] = params['per_page']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = ['ApiClientId', 'ApiClientSecret']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='DirectorRoleListResponse',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def update_director(self, director_id, body, **kwargs):
"""
Update director
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.update_director(director_id, body, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int director_id: (required)
:param UpdateDirectorRequest body: Directory settings (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.update_director_with_http_info(director_id, body, **kwargs)
else:
(data) = self.update_director_with_http_info(director_id, body, **kwargs)
return data
def update_director_with_http_info(self, director_id, body, **kwargs):
"""
Update director
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.update_director_with_http_info(director_id, body, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int director_id: (required)
:param UpdateDirectorRequest body: Directory settings (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['director_id', 'body']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method update_director" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'director_id' is set
if ('director_id' not in params) or (params['director_id'] is None):
raise ValueError("Missing the required parameter `director_id` when calling `update_director`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `update_director`")
collection_formats = {}
resource_path = '/directors/{director_id}'.replace('{format}', 'json')
path_params = {}
if 'director_id' in params:
path_params['director_id'] = params['director_id']
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
self.api_client.set_default_header('Content-Type', 'application/json')
# Authentication setting
auth_settings = ['ApiClientId', 'ApiClientSecret']
return self.api_client.call_api(resource_path, 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def upload_director_cover(self, director_id, **kwargs):
"""
Upload director cover
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.upload_director_cover(director_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param float director_id: Director ID to fetch (required)
:param file file:
:param str hash:
:param str hash_algorithm: Hash algorithm to check the hash file (default value is: sha256)
:return: ImageResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.upload_director_cover_with_http_info(director_id, **kwargs)
else:
(data) = self.upload_director_cover_with_http_info(director_id, **kwargs)
return data
def upload_director_cover_with_http_info(self, director_id, **kwargs):
"""
Upload director cover
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.upload_director_cover_with_http_info(director_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param float director_id: Director ID to fetch (required)
:param file file:
:param str hash:
:param str hash_algorithm: Hash algorithm to check the hash file (default value is: sha256)
:return: ImageResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['director_id', 'file', 'hash', 'hash_algorithm']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method upload_director_cover" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'director_id' is set
if ('director_id' not in params) or (params['director_id'] is None):
raise ValueError("Missing the required parameter `director_id` when calling `upload_director_cover`")
collection_formats = {}
resource_path = '/directors/{director_id}/cover'.replace('{format}', 'json')
path_params = {}
if 'director_id' in params:
path_params['director_id'] = params['director_id']
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
if 'file' in params:
local_var_files['file'] = params['file']
self.api_client.set_default_header('Content-Type', 'application/x-www-form-urlencoded')
if 'hash' in params:
form_params.append(('hash', params['hash']))
self.api_client.set_default_header('Content-Type', 'application/x-www-form-urlencoded')
if 'hash_algorithm' in params:
form_params.append(('hash_algorithm', params['hash_algorithm']))
self.api_client.set_default_header('Content-Type', 'application/x-www-form-urlencoded')
body_params = None
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['multipart/form-data'])
# Authentication setting
auth_settings = ['ApiClientId', 'ApiClientSecret']
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='ImageResponse',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)<|fim▁end|>
|
This method makes a synchronous HTTP request by default. To make an
|
<|file_name|>showdesktop.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="en_US">
<context>
<name>ShowDesktop</name>
<message>
<location filename="../showdesktop.cpp" line="48"/>
<source>Show desktop</source>
<translation type="unfinished"></translation><|fim▁hole|> <location filename="../showdesktop.cpp" line="58"/>
<source>Show Desktop: Global shortcut '%1' cannot be registered</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../showdesktop.cpp" line="63"/>
<source>Show Desktop</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS><|fim▁end|>
|
</message>
<message>
|
<|file_name|>TargetPolicy.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2005 JBoss 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,<|fim▁hole|>
package org.drools.modelcompiler.domain;
public class TargetPolicy {
private String customerCode;
private String productCode;
private int coefficient;
public String getCustomerCode() {
return customerCode;
}
public void setCustomerCode(String customerCode) {
this.customerCode = customerCode;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public int getCoefficient() {
return coefficient;
}
public void setCoefficient(int coefficient) {
this.coefficient = coefficient;
}
}<|fim▁end|>
|
* 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.
*/
|
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>import struct
def validate_transaction_id(request_mbap, response):<|fim▁hole|> """ Check if Transaction id in request and response is equal. """
assert struct.unpack('>H', request_mbap[:2]) == \
struct.unpack('>H', response[:2])
def validate_protocol_id(request_mbap, response):
""" Check if Protocol id in request and response is equal. """
assert struct.unpack('>H', request_mbap[2:4]) == \
struct.unpack('>H', response[2:4])
def validate_length(response):
""" Check if Length field contains actual length of response. """
assert struct.unpack('>H', response[4:6])[0] == len(response[6:])
def validate_unit_id(request_mbap, response):
""" Check if Unit id in request and response is equal. """
assert struct.unpack('>B', request_mbap[6:7]) == \
struct.unpack('>B', response[6:7])
def validate_response_mbap(request_mbap, response):
""" Validate if fields in response MBAP contain correct values. """
validate_transaction_id(request_mbap, response)
validate_protocol_id(request_mbap, response)
validate_length(response)
validate_unit_id(request_mbap, response)
def validate_function_code(request, response):
""" Validate if Function code in request and response equal. """
assert struct.unpack('>B', request[7:8])[0] == \
struct.unpack('>B', response[7:8])[0]
def validate_single_bit_value_byte_count(request, response):
""" Check of byte count field contains actual byte count and if byte count
matches with the amount of requests quantity.
"""
byte_count = struct.unpack('>B', response[8:9])[0]
quantity = struct.unpack('>H', request[-2:])[0]
expected_byte_count = quantity // 8
if quantity % 8 != 0:
expected_byte_count = (quantity // 8) + 1
assert byte_count == len(response[9:])
assert byte_count == expected_byte_count
def validate_multi_bit_value_byte_count(request, response):
""" Check of byte count field contains actual byte count and if byte count
matches with the amount of requests quantity.
"""
byte_count = struct.unpack('>B', response[8:9])[0]
quantity = struct.unpack('>H', request[-2:])[0]
expected_byte_count = quantity * 2
assert byte_count == len(response[9:])
assert byte_count == expected_byte_count<|fim▁end|>
| |
<|file_name|>NameDatabase.hpp<|end_file_name|><|fim▁begin|>/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2016 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
#ifndef XCSOAR_FLARM_NAME_DATABASE_HPP
#define XCSOAR_FLARM_NAME_DATABASE_HPP
#include "Util/StaticString.hxx"
#include "Util/StaticArray.hxx"
#include "FlarmId.hpp"
#include "Util/Compiler.h"
#include <cassert>
#include <tchar.h>
class FlarmNameDatabase {
public:
struct Record {
FlarmId id;
StaticString<21> name;
Record() = default;
Record(FlarmId _id, const TCHAR *_name)
:id(_id), name(_name) {}
};
private:
typedef StaticArray<Record, 200> Array;
typedef Array::iterator iterator;
Array data;
public:
typedef Array::const_iterator const_iterator;
gcc_pure
const_iterator begin() const {
return data.begin();
}
gcc_pure
const_iterator end() const {
return data.end();
}
gcc_pure
const TCHAR *Get(FlarmId id) const;
gcc_pure
FlarmId Get(const TCHAR *name) const;
/**
* Look up all records with the specified name.
*
* @param max the maximum size of the given buffer
* @return the number of items copied to the given buffer
*/
unsigned Get(const TCHAR *name, FlarmId *buffer, unsigned max) const;
bool Set(FlarmId id, const TCHAR *name);
protected:
gcc_pure<|fim▁hole|> int Find(const TCHAR *name) const;
};
#endif<|fim▁end|>
|
int Find(FlarmId id) const;
gcc_pure
|
<|file_name|>index.ts<|end_file_name|><|fim▁begin|><|fim▁hole|>export * from './number-spinner.component';<|fim▁end|>
| |
<|file_name|>data_source_obmcs_identity_group_test.go<|end_file_name|><|fim▁begin|>// Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
package main
import (
"testing"
"time"
"github.com/MustWin/baremetal-sdk-go"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/terraform"
"github.com/stretchr/testify/suite"
)
type ResourceIdentityGroupsTestSuite struct {
suite.Suite
Client mockableClient
Config string
Provider terraform.ResourceProvider
Providers map[string]terraform.ResourceProvider
ResourceName string
List *baremetal.ListGroups
}
func (s *ResourceIdentityGroupsTestSuite) SetupTest() {
s.Client = GetTestProvider()
s.Provider = Provider(func(d *schema.ResourceData) (interface{}, error) {
return s.Client, nil
})
s.Providers = map[string]terraform.ResourceProvider{
"baremetal": s.Provider,
}
s.Config = `
resource "baremetal_identity_group" "t" {
name = "groupname"
description = "group desc!"
}
`
s.Config += testProviderConfig()
s.ResourceName = "data.baremetal_identity_groups.t"
b1 := baremetal.Group{
ID: "id",
Name: "groupname",
CompartmentID: "compartment",
Description: "blah",
State: baremetal.ResourceActive,
TimeCreated: time.Now(),
}
b2 := b1
b2.ID = "id2"
s.List = &baremetal.ListGroups{
Groups: []baremetal.Group{b1, b2},
}
}
func (s *ResourceIdentityGroupsTestSuite) TestReadGroups() {
<|fim▁hole|> PreventPostDestroyRefresh: true,
Providers: s.Providers,
Steps: []resource.TestStep{
{
ImportState: true,
ImportStateVerify: true,
Config: s.Config,
},
{
Config: s.Config + `
data "baremetal_identity_groups" "t" {
compartment_id = "${var.compartment_id}"
}`,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttrSet(s.ResourceName, "groups.0.id"),
resource.TestCheckResourceAttrSet(s.ResourceName, "groups.#"),
),
},
},
},
)
}
func TestResourceIdentityGroupsTestSuite(t *testing.T) {
suite.Run(t, new(ResourceIdentityGroupsTestSuite))
}<|fim▁end|>
|
resource.UnitTest(s.T(), resource.TestCase{
|
<|file_name|>version.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-<|fim▁hole|><|fim▁end|>
|
__version__ = "1.2.3"
|
<|file_name|>get_bucket_location.go<|end_file_name|><|fim▁begin|>/**
* Author: CZ [email protected]
*/
package bucket
import (
"encoding/xml"
"github.com/cz-it/aliyun-oss-golang-sdk/ossapi"
"path"
"strconv"
)
// LocationInfo is locaiton struct<|fim▁hole|>type LocationInfo struct {
XMLName xml.Name `xml:"LocationConstraint"`
Location string `xml:",chardata"`
}
// QueryLocation Query bucket's location
// @param name: name of bucket
// @return location : location name of bucket
// @return ossapiError : nil on success
func QueryLocation(name string) (location string, ossapiError *ossapi.Error) {
host := name + ".oss.aliyuncs.com"
resource := path.Join("/", name) + "/"
req := &ossapi.Request{
Host: host,
Path: "/?location",
Method: "GET",
Resource: resource,
SubRes: []string{"location"}}
rsp, err := req.Send()
if err != nil {
if _, ok := err.(*ossapi.Error); !ok {
ossapi.Logger.Error("GetService's Send Error:%s", err.Error())
ossapiError = ossapi.OSSAPIError
return
}
}
if rsp.Result != ossapi.ErrSUCC {
ossapiError = err.(*ossapi.Error)
return
}
bodyLen, err := strconv.Atoi(rsp.HTTPRsp.Header["Content-Length"][0])
if err != nil {
ossapi.Logger.Error("GetService's Send Error:%s", err.Error())
ossapiError = ossapi.OSSAPIError
return
}
body := make([]byte, bodyLen)
rsp.HTTPRsp.Body.Read(body)
locationInfo := new(LocationInfo)
err = xml.Unmarshal(body, locationInfo)
if err != nil {
ossapi.Logger.Error("GetService's Send Error:%s", err.Error())
ossapiError = ossapi.OSSAPIError
return
}
location = locationInfo.Location
return
}<|fim▁end|>
| |
<|file_name|>runserver.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
import errno
import os
import re
import socket
import sys
from datetime import datetime
<|fim▁hole|>from django.db import DEFAULT_DB_ALIAS, connections
from django.db.migrations.executor import MigrationExecutor
from django.utils import autoreload, six
from django.utils.encoding import force_text, get_system_encoding
naiveip_re = re.compile(r"""^(?:
(?P<addr>
(?P<ipv4>\d{1,3}(?:\.\d{1,3}){3}) | # IPv4 address
(?P<ipv6>\[[a-fA-F0-9:]+\]) | # IPv6 address
(?P<fqdn>[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*) # FQDN
):)?(?P<port>\d+)$""", re.X)
DEFAULT_PORT = "8000"
class Command(BaseCommand):
help = "Starts a lightweight Web server for development."
# Validation is called explicitly each time the server is reloaded.
requires_system_checks = False
def add_arguments(self, parser):
parser.add_argument('addrport', nargs='?',
help='Optional port number, or ipaddr:port')
parser.add_argument('--ipv6', '-6', action='store_true', dest='use_ipv6', default=False,
help='Tells Django to use an IPv6 address.')
parser.add_argument('--nothreading', action='store_false', dest='use_threading', default=True,
help='Tells Django to NOT use threading.')
parser.add_argument('--noreload', action='store_false', dest='use_reloader', default=True,
help='Tells Django to NOT use the auto-reloader.')
def execute(self, *args, **options):
if options.get('no_color'):
# We rely on the environment because it's currently the only
# way to reach WSGIRequestHandler. This seems an acceptable
# compromise considering `runserver` runs indefinitely.
os.environ[str("DJANGO_COLORS")] = str("nocolor")
super(Command, self).execute(*args, **options)
def get_handler(self, *args, **options):
"""
Returns the default WSGI handler for the runner.
"""
return get_internal_wsgi_application()
def handle(self, *args, **options):
from django.conf import settings
if not settings.DEBUG and not settings.ALLOWED_HOSTS:
raise CommandError('You must set settings.ALLOWED_HOSTS if DEBUG is False.')
self.use_ipv6 = options.get('use_ipv6')
if self.use_ipv6 and not socket.has_ipv6:
raise CommandError('Your Python does not support IPv6.')
self._raw_ipv6 = False
if not options.get('addrport'):
self.addr = ''
self.port = DEFAULT_PORT
else:
m = re.match(naiveip_re, options['addrport'])
if m is None:
raise CommandError('"%s" is not a valid port number '
'or address:port pair.' % options['addrport'])
self.addr, _ipv4, _ipv6, _fqdn, self.port = m.groups()
if not self.port.isdigit():
raise CommandError("%r is not a valid port number." % self.port)
if self.addr:
if _ipv6:
self.addr = self.addr[1:-1]
self.use_ipv6 = True
self._raw_ipv6 = True
elif self.use_ipv6 and not _fqdn:
raise CommandError('"%s" is not a valid IPv6 address.' % self.addr)
if not self.addr:
self.addr = '::1' if self.use_ipv6 else '127.0.0.1'
self._raw_ipv6 = bool(self.use_ipv6)
self.run(**options)
def run(self, **options):
"""
Runs the server, using the autoreloader if needed
"""
use_reloader = options.get('use_reloader')
if use_reloader:
autoreload.main(self.inner_run, None, options)
else:
self.inner_run(None, **options)
def inner_run(self, *args, **options):
from django.conf import settings
from django.utils import translation
# If an exception was silenced in ManagementUtility.execute in order
# to be raised in the child process, raise it now.
autoreload.raise_last_exception()
threading = options.get('use_threading')
shutdown_message = options.get('shutdown_message', '')
quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'
self.stdout.write("Performing system checks...\n\n")
self.validate(display_num_errors=True)
try:
self.check_migrations()
except ImproperlyConfigured:
pass
now = datetime.now().strftime('%B %d, %Y - %X')
if six.PY2:
now = now.decode(get_system_encoding())
self.stdout.write((
"%(started_at)s\n"
"Django version %(version)s, using settings %(settings)r\n"
"Starting development server at http://%(addr)s:%(port)s/\n"
"Quit the server with %(quit_command)s.\n"
) % {
"started_at": now,
"version": self.get_version(),
"settings": settings.SETTINGS_MODULE,
"addr": '[%s]' % self.addr if self._raw_ipv6 else self.addr,
"port": self.port,
"quit_command": quit_command,
})
# django.core.management.base forces the locale to en-us. We should
# set it up correctly for the first request (particularly important
# in the "--noreload" case).
translation.activate(settings.LANGUAGE_CODE)
try:
handler = self.get_handler(*args, **options)
run(self.addr, int(self.port), handler,
ipv6=self.use_ipv6, threading=threading)
except socket.error as e:
# Use helpful error messages instead of ugly tracebacks.
ERRORS = {
errno.EACCES: "You don't have permission to access that port.",
errno.EADDRINUSE: "That port is already in use.",
errno.EADDRNOTAVAIL: "That IP address can't be assigned-to.",
}
try:
error_text = ERRORS[e.errno]
except KeyError:
error_text = force_text(e)
self.stderr.write("Error: %s" % error_text)
# Need to use an OS exit because sys.exit doesn't work in a thread
os._exit(1)
except KeyboardInterrupt:
if shutdown_message:
self.stdout.write(shutdown_message)
sys.exit(0)
def check_migrations(self):
"""
Checks to see if the set of migrations on disk matches the
migrations in the database. Prints a warning if they don't match.
"""
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
plan = executor.migration_plan(executor.loader.graph.leaf_nodes())
if plan:
self.stdout.write(self.style.NOTICE(
"\nYou have unapplied migrations; your app may not work properly until they are applied."
))
self.stdout.write(self.style.NOTICE("Run 'python manage.py migrate' to apply them.\n"))
# Kept for backward compatibility
BaseRunserverCommand = Command<|fim▁end|>
|
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import BaseCommand, CommandError
from django.core.servers.basehttp import get_internal_wsgi_application, run
|
<|file_name|>en-gb.py<|end_file_name|><|fim▁begin|># coding: utf8
{
' Assessment Series Details': ' Assessment Series Details',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN',
'# of International Staff': '# of International Staff',
'# of National Staff': '# of National Staff',
'# of Vehicles': '# of Vehicles',
'%(module)s not installed': '%(module)s not installed',
'%(system_name)s - Verify Email': '%(system_name)s - Verify Email',
'%.1f km': '%.1f km',
'%Y-%m-%d': '%Y-%m-%d',
'%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S',
'%s rows deleted': '%s rows deleted',
'%s rows updated': '%s rows updated',
'& then click on the map below to adjust the Lat/Lon fields': '& then click on the map below to adjust the Lat/Lon fields',
"'Cancel' will indicate an asset log entry did not occur": "'Cancel' will indicate an asset log entry did not occur",
'* Required Fields': '* Required Fields',
'0-15 minutes': '0-15 minutes',
'1 Assessment': '1 Assessment',
'1 location, shorter time, can contain multiple Tasks': '1 location, shorter time, can contain multiple Tasks',
'1-3 days': '1-3 days',
'15-30 minutes': '15-30 minutes',
'2 different options are provided here currently:': '2 different options are provided here currently:',
'2x4 Car': '2x4 Car',
'30-60 minutes': '30-60 minutes',
'4-7 days': '4-7 days',
'4x4 Car': '4x4 Car',
'8-14 days': '8-14 days',
'A Marker assigned to an individual Location is set if there is a need to override the Marker assigned to the Feature Class.': 'A Marker assigned to an individual Location is set if there is a need to override the Marker assigned to the Feature Class.',
'A Reference Document such as a file, URL or contact person to verify this data.': 'A Reference Document such as a file, URL or contact person to verify this data.',
'A brief description of the group (optional)': 'A brief description of the group (optional)',
'A catalog of different Assessment Templates including summary information': 'A catalogue of different Assessment Templates including summary information',
'A file in GPX format taken from a GPS.': 'A file in GPX format taken from a GPS.',
'A library of digital resources, such as photos, documents and reports': 'A library of digital resources, such as photos, documents and reports',
'A location group can be used to define the extent of an affected area, if it does not fall within one administrative region.': 'A location group can be used to define the extent of an affected area, if it does not fall within one administrative region.',
'A location group is a set of locations (often, a set of administrative regions representing a combined area).': 'A location group is a set of locations (often, a set of administrative regions representing a combined area).',
'A location group must have at least one member.': 'A location group must have at least one member.',
"A location that specifies the geographic area for this region. This can be a location from the location hierarchy, or a 'group location', or a location that has a boundary for the area.": "A location that specifies the geographic area for this region. This can be a location from the location hierarchy, or a 'group location', or a location that has a boundary for the area.",
'A portal for volunteers allowing them to amend their own data & view assigned tasks.': 'A portal for volunteers allowing them to amend their own data & view assigned tasks.',
'A task is a piece of work that an individual or team can do in 1-2 days': 'A task is a piece of work that an individual or team can do in 1-2 days',
'ABOUT THIS MODULE': 'ABOUT THIS MODULE',
'ACCESS DATA': 'ACCESS DATA',
'ACTION REQUIRED': 'ACTION REQUIRED',
'ANY': 'ANY',
'API Key': 'API Key',
'API is documented here': 'API is documented here',
'ATC-20 Rapid Evaluation modified for New Zealand': 'ATC-20 Rapid Evaluation modified for New Zealand',
'Abbreviation': 'Abbreviation',
'Ability to customize the list of details tracked at a Shelter': 'Ability to customize the list of details tracked at a Shelter',
'Ability to customize the list of human resource tracked at a Shelter': 'Ability to customize the list of human resource tracked at a Shelter',
'Ability to customize the list of important facilities needed at a Shelter': 'Ability to customize the list of important facilities needed at a Shelter',
'About': 'About',
'Accept Push': 'Accept Push',
'Accept Pushes': 'Accept Pushes',
'Access denied': 'Access denied',
'Access to Shelter': 'Access to Shelter',
'Access to education services': 'Access to education services',
'Accessibility of Affected Location': 'Accessibility of Affected Location',
'Accompanying Relative': 'Accompanying Relative',
'Account Registered - Please Check Your Email': 'Account Registered - Please Check Your Email',
'Acronym': 'Acronym',
"Acronym of the organization's name, eg. IFRC.": "Acronym of the organisation's name, eg. IFRC.",
'Actionable by all targeted recipients': 'Actionable by all targeted recipients',
'Actionable only by designated exercise participants; exercise identifier SHOULD appear in <note>': 'Actionable only by designated exercise participants; exercise identifier SHOULD appear in <note>',
'Actioned?': 'Actioned?',
'Actions': 'Actions',
'Actions taken as a result of this request.': 'Actions taken as a result of this request.',
'Activate Events from Scenario templates for allocation of appropriate Resources (Human, Assets & Facilities).': 'Activate Events from Scenario templates for allocation of appropriate Resources (Human, Assets & Facilities).',
'Active': 'Active',
'Active Problems': 'Active Problems',
'Activities': 'Activities',
'Activities matching Assessments:': 'Activities matching Assessments:',
'Activities of boys 13-17yrs before disaster': 'Activities of boys 13-17yrs before disaster',
'Activities of boys 13-17yrs now': 'Activities of boys 13-17yrs now',
'Activities of boys <12yrs before disaster': 'Activities of boys <12yrs before disaster',
'Activities of boys <12yrs now': 'Activities of boys <12yrs now',
'Activities of children': 'Activities of children',
'Activities of girls 13-17yrs before disaster': 'Activities of girls 13-17yrs before disaster',
'Activities of girls 13-17yrs now': 'Activities of girls 13-17yrs now',
'Activities of girls <12yrs before disaster': 'Activities of girls <12yrs before disaster',
'Activities of girls <12yrs now': 'Activities of girls <12yrs now',
'Activities:': 'Activities:',
'Activity': 'Activity',
'Activity Added': 'Activity Added',
'Activity Deleted': 'Activity Deleted',
'Activity Details': 'Activity Details',
'Activity Report': 'Activity Report',
'Activity Reports': 'Activity Reports',
'Activity Type': 'Activity Type',
'Activity Types': 'Activity Types',
'Activity Updated': 'Activity Updated',
'Activity added': 'Activity added',
'Activity removed': 'Activity removed',
'Activity updated': 'Activity updated',
'Add': 'Add',
'Add Activity': 'Add Activity',
'Add Activity Report': 'Add Activity Report',
'Add Activity Type': 'Add Activity Type',
'Add Address': 'Add Address',
'Add Alternative Item': 'Add Alternative Item',
'Add Assessment': 'Add Assessment',
'Add Assessment Answer': 'Add Assessment Answer',
'Add Assessment Series': 'Add Assessment Series',
'Add Assessment Summary': 'Add Assessment Summary',
'Add Assessment Template': 'Add Assessment Template',
'Add Asset': 'Add Asset',
'Add Asset Log Entry - Change Label': 'Add Asset Log Entry - Change Label',
'Add Availability': 'Add Availability',
'Add Baseline': 'Add Baseline',
'Add Baseline Type': 'Add Baseline Type',
'Add Bed Type': 'Add Bed Type',
'Add Brand': 'Add Brand',
'Add Budget': 'Add Budget',
'Add Bundle': 'Add Bundle',
'Add Camp': 'Add Camp',
'Add Camp Service': 'Add Camp Service',
'Add Camp Type': 'Add Camp Type',
'Add Catalog': 'Add Catalogue',
'Add Catalog Item': 'Add Catalogue Item',
'Add Certificate': 'Add Certificate',
'Add Certification': 'Add Certification',
'Add Cholera Treatment Capability Information': 'Add Cholera Treatment Capability Information',
'Add Cluster': 'Add Cluster',
'Add Cluster Subsector': 'Add Cluster Subsector',
'Add Competency Rating': 'Add Competency Rating',
'Add Contact': 'Add Contact',
'Add Contact Information': 'Add Contact Information',
'Add Course': 'Add Course',
'Add Course Certificate': 'Add Course Certificate',
'Add Credential': 'Add Credential',
'Add Credentials': 'Add Credentials',
'Add Dead Body Report': 'Add Dead Body Report',
'Add Disaster Victims': 'Add Disaster Victims',
'Add Distribution.': 'Add Distribution.',
'Add Document': 'Add Document',
'Add Donor': 'Add Donor',
'Add Facility': 'Add Facility',
'Add Feature Class': 'Add Feature Class',
'Add Feature Layer': 'Add Feature Layer',
'Add Flood Report': 'Add Flood Report',
'Add GPS data': 'Add GPS data',
'Add Group': 'Add Group',
'Add Group Member': 'Add Group Member',
'Add Home Address': 'Add Home Address',
'Add Hospital': 'Add Hospital',
'Add Human Resource': 'Add Human Resource',
'Add Identification Report': 'Add Identification Report',
'Add Identity': 'Add Identity',
'Add Image': 'Add Image',
'Add Impact': 'Add Impact',
'Add Impact Type': 'Add Impact Type',
'Add Incident': 'Add Incident',
'Add Incident Report': 'Add Incident Report',
'Add Item': 'Add Item',
'Add Item Category': 'Add Item Category',
'Add Item Pack': 'Add Item Pack',
'Add Item to Catalog': 'Add Item to Catalogue',
'Add Item to Commitment': 'Add Item to Commitment',
'Add Item to Inventory': 'Add Item to Inventory',
'Add Item to Order': 'Add Item to Order',
'Add Item to Request': 'Add Item to Request',
'Add Item to Shipment': 'Add Item to Shipment',
'Add Job': 'Add Job',
'Add Job Role': 'Add Job Role',
'Add Kit': 'Add Kit',
'Add Layer': 'Add Layer',
'Add Level 1 Assessment': 'Add Level 1 Assessment',
'Add Level 2 Assessment': 'Add Level 2 Assessment',
'Add Location': 'Add Location',
'Add Log Entry': 'Add Log Entry',
'Add Map Configuration': 'Add Map Configuration',
'Add Marker': 'Add Marker',
'Add Member': 'Add Member',
'Add Membership': 'Add Membership',
'Add Message': 'Add Message',
'Add Mission': 'Add Mission',
'Add Need': 'Add Need',
'Add Need Type': 'Add Need Type',
'Add New': 'Add New',
'Add New Activity': 'Add New Activity',
'Add New Activity Type': 'Add New Activity Type',
'Add New Address': 'Add New Address',
'Add New Alternative Item': 'Add New Alternative Item',
'Add New Assessment': 'Add New Assessment',
'Add New Assessment Summary': 'Add New Assessment Summary',
'Add New Asset': 'Add New Asset',
'Add New Baseline': 'Add New Baseline',
'Add New Baseline Type': 'Add New Baseline Type',
'Add New Brand': 'Add New Brand',
'Add New Budget': 'Add New Budget',
'Add New Bundle': 'Add New Bundle',
'Add New Camp': 'Add New Camp',
'Add New Camp Service': 'Add New Camp Service',
'Add New Camp Type': 'Add New Camp Type',
'Add New Catalog': 'Add New Catalogue',
'Add New Cluster': 'Add New Cluster',
'Add New Cluster Subsector': 'Add New Cluster Subsector',
'Add New Commitment Item': 'Add New Commitment Item',
'Add New Contact': 'Add New Contact',
'Add New Credential': 'Add New Credential',
'Add New Document': 'Add New Document',
'Add New Donor': 'Add New Donor',
'Add New Entry': 'Add New Entry',
'Add New Event': 'Add New Event',
'Add New Facility': 'Add New Facility',
'Add New Feature Class': 'Add New Feature Class',
'Add New Feature Layer': 'Add New Feature Layer',
'Add New Flood Report': 'Add New Flood Report',
'Add New Group': 'Add New Group',
'Add New Home': 'Add New Home',
'Add New Hospital': 'Add New Hospital',
'Add New Human Resource': 'Add New Human Resource',
'Add New Identity': 'Add New Identity',
'Add New Image': 'Add New Image',
'Add New Impact': 'Add New Impact',
'Add New Impact Type': 'Add New Impact Type',
'Add New Incident': 'Add New Incident',
'Add New Incident Report': 'Add New Incident Report',
'Add New Item': 'Add New Item',
'Add New Item Category': 'Add New Item Category',
'Add New Item Pack': 'Add New Item Pack',
'Add New Item to Kit': 'Add New Item to Kit',
'Add New Item to Order': 'Add New Item to Order',
'Add New Kit': 'Add New Kit',
'Add New Layer': 'Add New Layer',
'Add New Level 1 Assessment': 'Add New Level 1 Assessment',
'Add New Level 2 Assessment': 'Add New Level 2 Assessment',
'Add New Location': 'Add New Location',
'Add New Log Entry': 'Add New Log Entry',
'Add New Map Configuration': 'Add New Map Configuration',
'Add New Marker': 'Add New Marker',
'Add New Member': 'Add New Member',
'Add New Membership': 'Add New Membership',
'Add New Need': 'Add New Need',
'Add New Need Type': 'Add New Need Type',
'Add New Office': 'Add New Office',
'Add New Order': 'Add New Order',
'Add New Organization': 'Add New Organisation',
'Add New Organization Domain': 'Add New Organisation Domain',
'Add New Patient': 'Add New Patient',
'Add New Person to Commitment': 'Add New Person to Commitment',
'Add New Photo': 'Add New Photo',
'Add New Population Statistic': 'Add New Population Statistic',
'Add New Problem': 'Add New Problem',
'Add New Project': 'Add New Project',
'Add New Project Site': 'Add New Project Site',
'Add New Projection': 'Add New Projection',
'Add New Rapid Assessment': 'Add New Rapid Assessment',
'Add New Received Item': 'Add New Received Item',
'Add New Record': 'Add New Record',
'Add New Relative': 'Add New Relative',
'Add New Report': 'Add New Report',
'Add New Request': 'Add New Request',
'Add New Request Item': 'Add New Request Item',
'Add New Resource': 'Add New Resource',
'Add New River': 'Add New River',
'Add New Role': 'Add New Role',
'Add New Role to User': 'Add New Role to User',
'Add New Room': 'Add New Room',
'Add New Scenario': 'Add New Scenario',
'Add New Sector': 'Add New Sector',
'Add New Sent Item': 'Add New Sent Item',
'Add New Setting': 'Add New Setting',
'Add New Shelter': 'Add New Shelter',
'Add New Shelter Service': 'Add New Shelter Service',
'Add New Shelter Type': 'Add New Shelter Type',
'Add New Skill': 'Add New Skill',
'Add New Solution': 'Add New Solution',
'Add New Staff Member': 'Add New Staff Member',
'Add New Staff Type': 'Add New Staff Type',
'Add New Subsector': 'Add New Subsector',
'Add New Task': 'Add New Task',
'Add New Team': 'Add New Team',
'Add New Theme': 'Add New Theme',
'Add New Ticket': 'Add New Ticket',
'Add New User': 'Add New User',
'Add New User to Role': 'Add New User to Role',
'Add New Vehicle': 'Add New Vehicle',
'Add New Volunteer': 'Add New Volunteer',
'Add New Warehouse': 'Add New Warehouse',
'Add Office': 'Add Office',
'Add Order': 'Add Order',
'Add Organization': 'Add Organisation',
'Add Organization Domain': 'Add Organisation Domain',
'Add Organization to Project': 'Add Organisation to Project',
'Add Person': 'Add Person',
'Add Person to Commitment': 'Add Person to Commitment',
'Add Personal Effects': 'Add Personal Effects',
'Add Photo': 'Add Photo',
'Add Point': 'Add Point',
'Add Polygon': 'Add Polygon',
'Add Population Statistic': 'Add Population Statistic',
'Add Position': 'Add Position',
'Add Problem': 'Add Problem',
'Add Project': 'Add Project',
'Add Project Site': 'Add Project Site',
'Add Projection': 'Add Projection',
'Add Question Meta-Data': 'Add Question Meta-Data',
'Add Rapid Assessment': 'Add Rapid Assessment',
'Add Record': 'Add Record',
'Add Reference Document': 'Add Reference Document',
'Add Report': 'Add Report',
'Add Repository': 'Add Repository',
'Add Request': 'Add Request',
'Add Resource': 'Add Resource',
'Add River': 'Add River',
'Add Role': 'Add Role',
'Add Room': 'Add Room',
'Add Saved Search': 'Add Saved Search',
'Add Section': 'Add Section',
'Add Sector': 'Add Sector',
'Add Service Profile': 'Add Service Profile',
'Add Setting': 'Add Setting',
'Add Shelter': 'Add Shelter',
'Add Shelter Service': 'Add Shelter Service',
'Add Shelter Type': 'Add Shelter Type',
'Add Skill': 'Add Skill',
'Add Skill Equivalence': 'Add Skill Equivalence',
'Add Skill Provision': 'Add Skill Provision',
'Add Skill Type': 'Add Skill Type',
'Add Skill to Request': 'Add Skill to Request',
'Add Solution': 'Add Solution',
'Add Staff Member': 'Add Staff Member',
'Add Staff Type': 'Add Staff Type',
'Add Status': 'Add Status',
'Add Subscription': 'Add Subscription',
'Add Subsector': 'Add Subsector',
'Add Task': 'Add Task',
'Add Team': 'Add Team',
'Add Template Section': 'Add Template Section',
'Add Theme': 'Add Theme',
'Add Ticket': 'Add Ticket',
'Add Training': 'Add Training',
'Add Unit': 'Add Unit',
'Add User': 'Add User',
'Add Vehicle': 'Add Vehicle',
'Add Vehicle Detail': 'Add Vehicle Detail',
'Add Vehicle Details': 'Add Vehicle Details',
'Add Volunteer': 'Add Volunteer',
'Add Volunteer Availability': 'Add Volunteer Availability',
'Add Warehouse': 'Add Warehouse',
'Add a Person': 'Add a Person',
'Add a Reference Document such as a file, URL or contact person to verify this data. If you do not enter a Reference Document, your email will be displayed instead.': 'Add a Reference Document such as a file, URL or contact person to verify this data. If you do not enter a Reference Document, your email will be displayed instead.',
'Add a new Assessment Answer': 'Add a new Assessment Answer',
'Add a new Assessment Question': 'Add a new Assessment Question',
'Add a new Assessment Series': 'Add a new Assessment Series',
'Add a new Assessment Template': 'Add a new Assessment Template',
'Add a new Completed Assessment': 'Add a new Completed Assessment',
'Add a new Template Section': 'Add a new Template Section',
'Add a new certificate to the catalog.': 'Add a new certificate to the catalogue.',
'Add a new competency rating to the catalog.': 'Add a new competency rating to the catalogue.',
'Add a new job role to the catalog.': 'Add a new job role to the catalogue.',
'Add a new skill provision to the catalog.': 'Add a new skill provision to the catalogue.',
'Add a new skill type to the catalog.': 'Add a new skill type to the catalogue.',
'Add all organizations which are involved in different roles in this project': 'Add all organisations which are involved in different roles in this project',
'Add an Assessment Question': 'Add an Assessment Question',
'Add new Group': 'Add new Group',
'Add new Individual': 'Add new Individual',
'Add new Patient': 'Add new Patient',
'Add new Question Meta-Data': 'Add new Question Meta-Data',
'Add new project.': 'Add new project.',
'Add staff members': 'Add staff members',
'Add to Bundle': 'Add to Bundle',
'Add to budget': 'Add to budget',
'Add volunteers': 'Add volunteers',
'Add/Edit/Remove Layers': 'Add/Edit/Remove Layers',
'Additional Beds / 24hrs': 'Additional Beds / 24hrs',
'Address': 'Address',
'Address Details': 'Address Details',
'Address Type': 'Address Type',
'Address added': 'Address added',
'Address deleted': 'Address deleted',
'Address updated': 'Address updated',
'Addresses': 'Addresses',
'Adequate': 'Adequate',
'Adequate food and water available': 'Adequate food and water available',
'Admin Email': 'Admin Email',
'Admin Name': 'Admin Name',
'Admin Tel': 'Admin Tel',
'Administration': 'Administration',
'Admissions/24hrs': 'Admissions/24hrs',
'Adolescent (12-20)': 'Adolescent (12-20)',
'Adolescent participating in coping activities': 'Adolescent participating in coping activities',
'Adult (21-50)': 'Adult (21-50)',
'Adult ICU': 'Adult ICU',
'Adult Psychiatric': 'Adult Psychiatric',
'Adult female': 'Adult female',
'Adult male': 'Adult male',
'Adults in prisons': 'Adults in prisons',
'Advanced:': 'Advanced:',
'Advisory': 'Advisory',
'After clicking on the button, a set of paired items will be shown one by one. Please select the one solution from each pair that you prefer over the other.': 'After clicking on the button, a set of paired items will be shown one by one. Please select the one solution from each pair that you prefer over the other.',
'Age Group': 'Age Group',
'Age group': 'Age group',
'Age group does not match actual age.': 'Age group does not match actual age.',
'Aggravating factors': 'Aggravating factors',
'Agriculture': 'Agriculture',
'Air Transport Service': 'Air Transport Service',
'Air tajin': 'Air tajin',
'Aircraft Crash': 'Aircraft Crash',
'Aircraft Hijacking': 'Aircraft Hijacking',
'Airport Closure': 'Airport Closure',
'Airspace Closure': 'Airspace Closure',
'Alcohol': 'Alcohol',
'Alert': 'Alert',
'All': 'All',
'All Inbound & Outbound Messages are stored here': 'All Inbound & Outbound Messages are stored here',
'All Resources': 'All Resources',
'All data provided by the Sahana Software Foundation from this site is licensed under a Creative Commons Attribution license. However, not all data originates here. Please consult the source field of each entry.': 'All data provided by the Sahana Software Foundation from this site is licensed under a Creative Commons Attribution license. However, not all data originates here. Please consult the source field of each entry.',
'Allows a Budget to be drawn up': 'Allows a Budget to be drawn up',
'Alternative Item': 'Alternative Item',
'Alternative Item Details': 'Alternative Item Details',
'Alternative Item added': 'Alternative Item added',
'Alternative Item deleted': 'Alternative Item deleted',
'Alternative Item updated': 'Alternative Item updated',
'Alternative Items': 'Alternative Items',
'Alternative places for studying': 'Alternative places for studying',
'Ambulance Service': 'Ambulance Service',
'An Assessment Template can be selected to create an Event Assessment. Within an Event Assessment responses can be collected and results can analyzed as tables, charts and maps': 'An Assessment Template can be selected to create an Event Assessment. Within an Event Assessment responses can be collected and results can analysed as tables, charts and maps',
'An item which can be used in place of another item': 'An item which can be used in place of another item',
'Analysis': 'Analysis',
'Analysis of assessments': 'Analysis of assessments',
'Animal Die Off': 'Animal Die Off',
'Animal Feed': 'Animal Feed',
'Answer': 'Answer',
'Anthropolgy': 'Anthropolgy',
'Antibiotics available': 'Antibiotics available',
'Antibiotics needed per 24h': 'Antibiotics needed per 24h',
'Apparent Age': 'Apparent Age',
'Apparent Gender': 'Apparent Gender',
'Application Deadline': 'Application Deadline',
'Approve': 'Approve',
'Approved': 'Approved',
'Approved By': 'Approved By',
'Approver': 'Approver',
'Arabic': 'Arabic',
'Arctic Outflow': 'Arctic Outflow',
'Are you sure you want to delete this record?': 'Are you sure you want to delete this record?',
'Areas inspected': 'Areas inspected',
'As of yet, no completed surveys have been added to this series.': 'As of yet, no completed surveys have been added to this series.',
'As of yet, no sections have been added to this template.': 'As of yet, no sections have been added to this template.',
'Assessment': 'Assessment',
'Assessment Answer': 'Assessment Answer',
'Assessment Answer Details': 'Assessment Answer Details',
'Assessment Answer added': 'Assessment Answer added',
'Assessment Answer deleted': 'Assessment Answer deleted',
'Assessment Answer updated': 'Assessment Answer updated',
'Assessment Details': 'Assessment Details',
'Assessment Question Details': 'Assessment Question Details',
'Assessment Question added': 'Assessment Question added',
'Assessment Question deleted': 'Assessment Question deleted',
'Assessment Question updated': 'Assessment Question updated',
'Assessment Reported': 'Assessment Reported',
'Assessment Series': 'Assessment Series',
'Assessment Series added': 'Assessment Series added',
'Assessment Series deleted': 'Assessment Series deleted',
'Assessment Series updated': 'Assessment Series updated',
'Assessment Summaries': 'Assessment Summaries',
'Assessment Summary Details': 'Assessment Summary Details',
'Assessment Summary added': 'Assessment Summary added',
'Assessment Summary deleted': 'Assessment Summary deleted',
'Assessment Summary updated': 'Assessment Summary updated',
'Assessment Template Details': 'Assessment Template Details',
'Assessment Template added': 'Assessment Template added',
'Assessment Template deleted': 'Assessment Template deleted',
'Assessment Template updated': 'Assessment Template updated',
'Assessment Templates': 'Assessment Templates',
'Assessment added': 'Assessment added',
'Assessment admin level': 'Assessment admin level',
'Assessment deleted': 'Assessment deleted',
'Assessment timeline': 'Assessment timeline',
'Assessment updated': 'Assessment updated',
'Assessments': 'Assessments',
'Assessments Needs vs. Activities': 'Assessments Needs vs. Activities',
'Assessments and Activities': 'Assessments and Activities',
'Assessments:': 'Assessments:',
'Assessor': 'Assessor',
'Asset': 'Asset',
'Asset Details': 'Asset Details',
'Asset Log': 'Asset Log',
'Asset Log Details': 'Asset Log Details',
'Asset Log Empty': 'Asset Log Empty',
'Asset Log Entry Added - Change Label': 'Asset Log Entry Added - Change Label',
'Asset Log Entry deleted': 'Asset Log Entry deleted',
'Asset Log Entry updated': 'Asset Log Entry updated',
'Asset Management': 'Asset Management',
'Asset Number': 'Asset Number',
'Asset added': 'Asset added',
'Asset deleted': 'Asset deleted',
'Asset removed': 'Asset removed',
'Asset updated': 'Asset updated',
'Assets': 'Assets',
'Assets are resources which are not consumable but are expected back, so they need tracking.': 'Assets are resources which are not consumable but are expected back, so they need tracking.',
'Assign': 'Assign',
'Assign to Org.': 'Assign to Org.',
'Assign to Organization': 'Assign to Organisation',
'Assign to Person': 'Assign to Person',
'Assign to Site': 'Assign to Site',
'Assigned': 'Assigned',
'Assigned By': 'Assigned By',
'Assigned To': 'Assigned To',
'Assigned to Organization': 'Assigned to Organisation',
'Assigned to Person': 'Assigned to Person',
'Assigned to Site': 'Assigned to Site',
'Assignment': 'Assignment',
'Assignments': 'Assignments',
'At/Visited Location (not virtual)': 'At/Visited Location (not virtual)',
'Attend to information sources as described in <instruction>': 'Attend to information sources as described in <instruction>',
'Attribution': 'Attribution',
"Authenticate system's Twitter account": "Authenticate system's Twitter account",
'Author': 'Author',
'Available Alternative Inventories': 'Available Alternative Inventories',
'Available Beds': 'Available Beds',
'Available Forms': 'Available Forms',
'Available Inventories': 'Available Inventories',
'Available Messages': 'Available Messages',
'Available Records': 'Available Records',
'Available databases and tables': 'Available databases and tables',
'Available for Location': 'Available for Location',
'Available from': 'Available from',
'Available in Viewer?': 'Available in Viewer?',
'Available until': 'Available until',
'Avalanche': 'Avalanche',
'Avoid the subject event as per the <instruction>': 'Avoid the subject event as per the <instruction>',
'Background Color': 'Background Colour',
'Background Color for Text blocks': 'Background Colour for Text blocks',
'Bahai': 'Bahai',
'Baldness': 'Baldness',
'Banana': 'Banana',
'Bank/micro finance': 'Bank/micro finance',
'Barricades are needed': 'Barricades are needed',
'Base Layer?': 'Base Layer?',
'Base Layers': 'Base Layers',
'Base Location': 'Base Location',
'Base Site Set': 'Base Site Set',
'Base URL of the remote Sahana-Eden site': 'Base URL of the remote Sahana-Eden site',
'Baseline Data': 'Baseline Data',
'Baseline Number of Beds': 'Baseline Number of Beds',
'Baseline Type': 'Baseline Type',
'Baseline Type Details': 'Baseline Type Details',
'Baseline Type added': 'Baseline Type added',
'Baseline Type deleted': 'Baseline Type deleted',
'Baseline Type updated': 'Baseline Type updated',
'Baseline Types': 'Baseline Types',
'Baseline added': 'Baseline added',
'Baseline deleted': 'Baseline deleted',
'Baseline number of beds of that type in this unit.': 'Baseline number of beds of that type in this unit.',
'Baseline updated': 'Baseline updated',
'Baselines': 'Baselines',
'Baselines Details': 'Baselines Details',
'Basic Assessment': 'Basic Assessment',
'Basic Assessment Reported': 'Basic Assessment Reported',
'Basic Details': 'Basic Details',
'Basic reports on the Shelter and drill-down by region': 'Basic reports on the Shelter and drill-down by region',
'Baud': 'Baud',
'Baud rate to use for your modem - The default is safe for most cases': 'Baud rate to use for your modem - The default is safe for most cases',
'Beam': 'Beam',
'Bed Capacity': 'Bed Capacity',
'Bed Capacity per Unit': 'Bed Capacity per Unit',
'Bed Type': 'Bed Type',
'Bed type already registered': 'Bed type already registered',
'Below ground level': 'Below ground level',
'Beneficiary Type': 'Beneficiary Type',
"Bing Layers cannot be displayed if there isn't a valid API Key": "Bing Layers cannot be displayed if there isn't a valid API Key",
'Biological Hazard': 'Biological Hazard',
'Biscuits': 'Biscuits',
'Blizzard': 'Blizzard',
'Blood Type (AB0)': 'Blood Type (AB0)',
'Blowing Snow': 'Blowing Snow',
'Boat': 'Boat',
'Bodies': 'Bodies',
'Bodies found': 'Bodies found',
'Bodies recovered': 'Bodies recovered',
'Body': 'Body',
'Body Recovery': 'Body Recovery',
'Body Recovery Request': 'Body Recovery Request',
'Body Recovery Requests': 'Body Recovery Requests',
'Bomb': 'Bomb',
'Bomb Explosion': 'Bomb Explosion',
'Bomb Threat': 'Bomb Threat',
'Border Color for Text blocks': 'Border Colour for Text blocks',
'Brand': 'Brand',
'Brand Details': 'Brand Details',
'Brand added': 'Brand added',
'Brand deleted': 'Brand deleted',
'Brand updated': 'Brand updated',
'Brands': 'Brands',
'Bricks': 'Bricks',
'Bridge Closed': 'Bridge Closed',
'Bucket': 'Bucket',
'Buddhist': 'Buddhist',
'Budget': 'Budget',
'Budget Details': 'Budget Details',
'Budget Updated': 'Budget Updated',
'Budget added': 'Budget added',
'Budget deleted': 'Budget deleted',
'Budget updated': 'Budget updated',
'Budgeting Module': 'Budgeting Module',
'Budgets': 'Budgets',
'Buffer': 'Buffer',
'Bug': 'Bug',
'Building Assessments': 'Building Assessments',
'Building Collapsed': 'Building Collapsed',
'Building Name': 'Building Name',
'Building Safety Assessments': 'Building Safety Assessments',
'Building Short Name/Business Name': 'Building Short Name/Business Name',
'Building or storey leaning': 'Building or storey leaning',
'Built using the Template agreed by a group of NGOs working together as the': 'Built using the Template agreed by a group of NGOs working together as the',
'Bulk Uploader': 'Bulk Uploader',
'Bundle': 'Bundle',
'Bundle Contents': 'Bundle Contents',
'Bundle Details': 'Bundle Details',
'Bundle Updated': 'Bundle Updated',
'Bundle added': 'Bundle added',
'Bundle deleted': 'Bundle deleted',
'Bundle updated': 'Bundle updated',
'Bundles': 'Bundles',
'Burn': 'Burn',
'Burn ICU': 'Burn ICU',
'Burned/charred': 'Burned/charred',
'By Facility': 'By Facility',
'By Inventory': 'By Inventory',
'CBA Women': 'CBA Women',
'CLOSED': 'CLOSED',
'CN': 'CN',
'CSS file %s not writable - unable to apply theme!': 'CSS file %s not writable - unable to apply theme!',
'Calculate': 'Calculate',
'Camp': 'Camp',
'Camp Coordination/Management': 'Camp Coordination/Management',
'Camp Details': 'Camp Details',
'Camp Service': 'Camp Service',
'Camp Service Details': 'Camp Service Details',
'Camp Service added': 'Camp Service added',
'Camp Service deleted': 'Camp Service deleted',
'Camp Service updated': 'Camp Service updated',
'Camp Services': 'Camp Services',
'Camp Type': 'Camp Type',
'Camp Type Details': 'Camp Type Details',
'Camp Type added': 'Camp Type added',
'Camp Type deleted': 'Camp Type deleted',
'Camp Type updated': 'Camp Type updated',
'Camp Types': 'Camp Types',
'Camp Types and Services': 'Camp Types and Services',
'Camp added': 'Camp added',
'Camp deleted': 'Camp deleted',
'Camp updated': 'Camp updated',
'Camps': 'Camps',
'Can only approve 1 record at a time!': 'Can only approve 1 record at a time!',
'Can only disable 1 record at a time!': 'Can only disable 1 record at a time!',
'Can only enable 1 record at a time!': 'Can only enable 1 record at a time!',
"Can't import tweepy": "Can't import tweepy",
'Cancel': 'Cancel',
'Cancel Log Entry': 'Cancel Log Entry',
'Cancel Shipment': 'Cancel Shipment',
'Canceled': 'Canceled',
'Candidate Matches for Body %s': 'Candidate Matches for Body %s',
'Canned Fish': 'Canned Fish',
'Cannot be empty': 'Cannot be empty',
'Cannot disable your own account!': 'Cannot disable your own account!',
'Capacity (Max Persons)': 'Capacity (Max Persons)',
'Capture Information on Disaster Victim groups (Tourists, Passengers, Families, etc.)': 'Capture Information on Disaster Victim groups (Tourists, Passengers, Families, etc.)',
'Capture Information on each disaster victim': 'Capture Information on each disaster victim',
'Capturing the projects each organization is providing and where': 'Capturing the projects each organisation is providing and where',
'Cardiology': 'Cardiology',
'Cassava': 'Cassava',
'Casual Labor': 'Casual Labor',
'Casualties': 'Casualties',
'Catalog': 'Catalogue',
'Catalog Details': 'Catalogue Details',
'Catalog Item added': 'Catalogue Item added',
'Catalog Item deleted': 'Catalogue Item deleted',
'Catalog Item updated': 'Catalogue Item updated',
'Catalog Items': 'Catalogue Items',
'Catalog added': 'Catalogue added',
'Catalog deleted': 'Catalogue deleted',
'Catalog updated': 'Catalogue updated',
'Catalogs': 'Catalogues',
'Categories': 'Categories',
'Category': 'Category',
"Caution: doesn't respect the framework rules!": "Caution: doesn't respect the framework rules!",
'Ceilings, light fixtures': 'Ceilings, light fixtures',
'Cell Phone': 'Cell Phone',
'Central point to record details on People': 'Central point to record details on People',
'Certificate': 'Certificate',
'Certificate Catalog': 'Certificate Catalogue',
'Certificate Details': 'Certificate Details',
'Certificate Status': 'Certificate Status',
'Certificate added': 'Certificate added',
'Certificate deleted': 'Certificate deleted',
'Certificate updated': 'Certificate updated',
'Certificates': 'Certificates',
'Certification': 'Certification',
'Certification Details': 'Certification Details',
'Certification added': 'Certification added',
'Certification deleted': 'Certification deleted',
'Certification updated': 'Certification updated',
'Certifications': 'Certifications',
'Certifying Organization': 'Certifying Organisation',
'Change Password': 'Change Password',
'Check': 'Check',
'Check Request': 'Check Request',
'Check for errors in the URL, maybe the address was mistyped.': 'Check for errors in the URL, maybe the address was mistyped.',
'Check if the URL is pointing to a directory instead of a webpage.': 'Check if the URL is pointing to a directory instead of a webpage.',
'Check outbox for the message status': 'Check outbox for the message status',
'Check to delete': 'Check to delete',
'Check to delete:': 'Check to delete:',
'Check-in at Facility': 'Check-in at Facility',
'Checked': 'Checked',
'Checklist': 'Checklist',
'Checklist created': 'Checklist created',
'Checklist deleted': 'Checklist deleted',
'Checklist of Operations': 'Checklist of Operations',
'Checklist updated': 'Checklist updated',
'Chemical Hazard': 'Chemical Hazard',
'Chemical, Biological, Radiological, Nuclear or High-Yield Explosive threat or attack': 'Chemical, Biological, Radiological, Nuclear or High-Yield Explosive threat or attack',
'Chicken': 'Chicken',
'Child': 'Child',
'Child (2-11)': 'Child (2-11)',
'Child (< 18 yrs)': 'Child (< 18 yrs)',
'Child Abduction Emergency': 'Child Abduction Emergency',
'Child headed households (<18 yrs)': 'Child headed households (<18 yrs)',
'Children (2-5 years)': 'Children (2-5 years)',
'Children (5-15 years)': 'Children (5-15 years)',
'Children (< 2 years)': 'Children (< 2 years)',
'Children in adult prisons': 'Children in adult prisons',
'Children in boarding schools': 'Children in boarding schools',
'Children in homes for disabled children': 'Children in homes for disabled children',
'Children in juvenile detention': 'Children in juvenile detention',
'Children in orphanages': 'Children in orphanages',
'Children living on their own (without adults)': 'Children living on their own (without adults)',
'Children not enrolled in new school': 'Children not enrolled in new school',
'Children orphaned by the disaster': 'Children orphaned by the disaster',
'Children separated from their parents/caregivers': 'Children separated from their parents/caregivers',
'Children that have been sent to safe places': 'Children that have been sent to safe places',
'Children who have disappeared since the disaster': 'Children who have disappeared since the disaster',
'Chinese (Simplified)': 'Chinese (Simplified)',
'Chinese (Traditional)': 'Chinese (Traditional)',
'Cholera Treatment': 'Cholera Treatment',
'Cholera Treatment Capability': 'Cholera Treatment Capability',
'Cholera Treatment Center': 'Cholera Treatment Center',
'Cholera-Treatment-Center': 'Cholera-Treatment-Center',
'Choose a new posting based on the new evaluation and team judgement. Severe conditions affecting the whole building are grounds for an UNSAFE posting. Localised Severe and overall Moderate conditions may require a RESTRICTED USE. Place INSPECTED placard at main entrance. Post all other placards at every significant entrance.': 'Choose a new posting based on the new evaluation and team judgement. Severe conditions affecting the whole building are grounds for an UNSAFE posting. Localised Severe and overall Moderate conditions may require a RESTRICTED USE. Place INSPECTED placard at main entrance. Post all other placards at every significant entrance.',
'Christian': 'Christian',
'Church': 'Church',
'City': 'City',
'Civil Emergency': 'Civil Emergency',
'Cladding, glazing': 'Cladding, glazing',
'Click on the link': 'Click on the link',
'Client IP': 'Client IP',
'Climate': 'Climate',
'Clinical Laboratory': 'Clinical Laboratory',
'Clinical Operations': 'Clinical Operations',
'Clinical Status': 'Clinical Status',
'Close map': 'Close map',
'Closed': 'Closed',
'Clothing': 'Clothing',
'Cluster': 'Cluster',
'Cluster Details': 'Cluster Details',
'Cluster Distance': 'Cluster Distance',
'Cluster Subsector': 'Cluster Subsector',
'Cluster Subsector Details': 'Cluster Subsector Details',
'Cluster Subsector added': 'Cluster Subsector added',
'Cluster Subsector deleted': 'Cluster Subsector deleted',
'Cluster Subsector updated': 'Cluster Subsector updated',
'Cluster Subsectors': 'Cluster Subsectors',
'Cluster Threshold': 'Cluster Threshold',
'Cluster added': 'Cluster added',
'Cluster deleted': 'Cluster deleted',
'Cluster updated': 'Cluster updated',
'Cluster(s)': 'Cluster(s)',
'Clusters': 'Clusters',
'Code': 'Code',
'Cold Wave': 'Cold Wave',
'Collapse, partial collapse, off foundation': 'Collapse, partial collapse, off foundation',
'Collective center': 'Collective center',
'Color for Underline of Subheadings': 'Colour for Underline of Subheadings',
'Color of Buttons when hovering': 'Colour of Buttons when hovering',
'Color of bottom of Buttons when not pressed': 'Colour of bottom of Buttons when not pressed',
'Color of bottom of Buttons when pressed': 'Colour of bottom of Buttons when pressed',
'Color of dropdown menus': 'Colour of dropdown menus',
'Color of selected Input fields': 'Colour of selected Input fields',
'Color of selected menu items': 'Colour of selected menu items',
'Columns, pilasters, corbels': 'Columns, pilasters, corbels',
'Combined Method': 'Combined Method',
'Come back later.': 'Come back later.',
'Come back later. Everyone visiting this site is probably experiencing the same problem as you.': 'Come back later. Everyone visiting this site is probably experiencing the same problem as you.',
'Comments': 'Comments',
'Commercial/Offices': 'Commercial/Offices',
'Commit': 'Commit',
'Commit Date': 'Commit Date',
'Commit from %s': 'Commit from %s',
'Commit. Status': 'Commit. Status',
'Commiting a changed spreadsheet to the database': 'Commiting a changed spreadsheet to the database',
'Commitment': 'Commitment',
'Commitment Added': 'Commitment Added',
'Commitment Canceled': 'Commitment Canceled',
'Commitment Details': 'Commitment Details',
'Commitment Item Details': 'Commitment Item Details',
'Commitment Item added': 'Commitment Item added',
'Commitment Item deleted': 'Commitment Item deleted',
'Commitment Item updated': 'Commitment Item updated',
'Commitment Items': 'Commitment Items',
'Commitment Status': 'Commitment Status',
'Commitment Updated': 'Commitment Updated',
'Commitments': 'Commitments',
'Committed': 'Committed',
'Committed By': 'Committed By',
'Committed People': 'Committed People',
'Committed Person Details': 'Committed Person Details',
'Committed Person updated': 'Committed Person updated',
'Committing Inventory': 'Committing Inventory',
'Committing Organization': 'Committing Organisation',
'Committing Person': 'Committing Person',
'Communication problems': 'Communication problems',
'Community Centre': 'Community Centre',
'Community Health Center': 'Community Health Center',
'Community Member': 'Community Member',
'Competency': 'Competency',
'Competency Rating Catalog': 'Competency Rating Catalogue',
'Competency Rating Details': 'Competency Rating Details',
'Competency Rating added': 'Competency Rating added',
'Competency Rating deleted': 'Competency Rating deleted',
'Competency Rating updated': 'Competency Rating updated',
'Competency Ratings': 'Competency Ratings',
'Complete': 'Complete',
'Complete a new Assessment': 'Complete a new Assessment',
'Completed': 'Completed',
'Completed Assessment': 'Completed Assessment',
'Completed Assessment Details': 'Completed Assessment Details',
'Completed Assessment added': 'Completed Assessment added',
'Completed Assessment deleted': 'Completed Assessment deleted',
'Completed Assessment updated': 'Completed Assessment updated',
'Completed Assessments': 'Completed Assessments',
'Completed surveys of this Series:': 'Completed surveys of this Series:',
'Complexion': 'Complexion',
'Compose': 'Compose',
'Compromised': 'Compromised',
'Concrete frame': 'Concrete frame',
'Concrete shear wall': 'Concrete shear wall',
'Condition': 'Condition',
'Configuration': 'Configuration',
'Configurations': 'Configurations',
'Configure Run-time Settings': 'Configure Run-time Settings',
'Configure connection details and authentication': 'Configure connection details and authentication',
'Configure resources to synchronize, update methods and policies': 'Configure resources to synchronise, update methods and policies',
'Configure the default proxy server to connect to remote repositories': 'Configure the default proxy server to connect to remote repositories',
'Confirm Shipment Received': 'Confirm Shipment Received',
'Confirmed': 'Confirmed',
'Confirming Organization': 'Confirming Organisation',
'Conflict Policy': 'Conflict Policy',
'Conflict policy': 'Conflict policy',
'Conflicts': 'Conflicts',
'Consignment Note': 'Consignment Note',
'Constraints Only': 'Constraints Only',
'Consumable': 'Consumable',
'Contact': 'Contact',
'Contact Data': 'Contact Data',
'Contact Details': 'Contact Details',
'Contact Info': 'Contact Info',
'Contact Information': 'Contact Information',
'Contact Information Added': 'Contact Information Added',
'Contact Information Deleted': 'Contact Information Deleted',
'Contact Information Updated': 'Contact Information Updated',
'Contact Method': 'Contact Method',
'Contact Name': 'Contact Name',
'Contact Person': 'Contact Person',
'Contact Phone': 'Contact Phone',
'Contact information added': 'Contact information added',
'Contact information deleted': 'Contact information deleted',
'Contact information updated': 'Contact information updated',
'Contact us': 'Contact us',
'Contacts': 'Contacts',
'Contents': 'Contents',
'Contributor': 'Contributor',
'Conversion Tool': 'Conversion Tool',
'Cooking NFIs': 'Cooking NFIs',
'Cooking Oil': 'Cooking Oil',
'Coordinate Conversion': 'Coordinate Conversion',
'Coping Activities': 'Coping Activities',
'Copy': 'Copy',
'Corn': 'Corn',
'Cost Type': 'Cost Type',
'Cost per Megabyte': 'Cost per Megabyte',
'Cost per Minute': 'Cost per Minute',
'Country': 'Country',
'Country is required!': 'Country is required!',
'Country of Residence': 'Country of Residence',
'County': 'County',
'Course': 'Course',
'Course Catalog': 'Course Catalogue',
'Course Certificate Details': 'Course Certificate Details',
'Course Certificate added': 'Course Certificate added',
'Course Certificate deleted': 'Course Certificate deleted',
'Course Certificate updated': 'Course Certificate updated',
'Course Certificates': 'Course Certificates',
'Course Details': 'Course Details',
'Course added': 'Course added',
'Course deleted': 'Course deleted',
'Course updated': 'Course updated',
'Courses': 'Courses',
'Create & manage Distribution groups to receive Alerts': 'Create & manage Distribution groups to receive Alerts',
'Create Checklist': 'Create Checklist',
'Create Group Entry': 'Create Group Entry',
'Create Impact Assessment': 'Create Impact Assessment',
'Create Mobile Impact Assessment': 'Create Mobile Impact Assessment',
'Create New Asset': 'Create New Asset',
'Create New Catalog': 'Create New Catalogue',
'Create New Catalog Item': 'Create New Catalogue Item',
'Create New Event': 'Create New Event',
'Create New Item': 'Create New Item',
'Create New Item Category': 'Create New Item Category',
'Create New Location': 'Create New Location',
'Create New Request': 'Create New Request',
'Create New Scenario': 'Create New Scenario',
'Create New Vehicle': 'Create New Vehicle',
'Create Rapid Assessment': 'Create Rapid Assessment',
'Create Request': 'Create Request',
'Create Task': 'Create Task',
'Create a group entry in the registry.': 'Create a group entry in the registry.',
'Create new Office': 'Create new Office',
'Create new Organization': 'Create new Organisation',
'Create, enter, and manage surveys.': 'Create, enter, and manage surveys.',
'Creation of assessments': 'Creation of assessments',
'Credential Details': 'Credential Details',
'Credential added': 'Credential added',
'Credential deleted': 'Credential deleted',
'Credential updated': 'Credential updated',
'Credentialling Organization': 'Credentialling Organisation',
'Credentials': 'Credentials',
'Credit Card': 'Credit Card',
'Crime': 'Crime',
'Criteria': 'Criteria',
'Currency': 'Currency',
'Current Entries': 'Current Entries',
'Current Group Members': 'Current Group Members',
'Current Identities': 'Current Identities',
'Current Location': 'Current Location',
'Current Location Country': 'Current Location Country',
'Current Location Phone Number': 'Current Location Phone Number',
'Current Location Treating Hospital': 'Current Location Treating Hospital',
'Current Log Entries': 'Current Log Entries',
'Current Memberships': 'Current Memberships',
'Current Mileage': 'Current Mileage',
'Current Records': 'Current Records',
'Current Registrations': 'Current Registrations',
'Current Status': 'Current Status',
'Current Team Members': 'Current Team Members',
'Current Twitter account': 'Current Twitter account',
'Current community priorities': 'Current community priorities',
'Current general needs': 'Current general needs',
'Current greatest needs of vulnerable groups': 'Current greatest needs of vulnerable groups',
'Current health problems': 'Current health problems',
'Current number of patients': 'Current number of patients',
'Current problems, categories': 'Current problems, categories',
'Current problems, details': 'Current problems, details',
'Current request': 'Current request',
'Current response': 'Current response',
'Current session': 'Current session',
'Currently Configured Jobs': 'Currently Configured Jobs',
'Currently Configured Repositories': 'Currently Configured Repositories',
'Currently Configured Resources': 'Currently Configured Resources',
'Currently no Certifications registered': 'Currently no Certifications registered',
'Currently no Course Certificates registered': 'Currently no Course Certificates registered',
'Currently no Credentials registered': 'Currently no Credentials registered',
'Currently no Missions registered': 'Currently no Missions registered',
'Currently no Skill Equivalences registered': 'Currently no Skill Equivalences registered',
'Currently no Skills registered': 'Currently no Skills registered',
'Currently no Trainings registered': 'Currently no Trainings registered',
'Currently no entries in the catalog': 'Currently no entries in the catalogue',
'DC': 'DC',
'DNA Profile': 'DNA Profile',
'DNA Profiling': 'DNA Profiling',
'DVI Navigator': 'DVI Navigator',
'Dam Overflow': 'Dam Overflow',
'Damage': 'Damage',
'Dangerous Person': 'Dangerous Person',
'Dashboard': 'Dashboard',
'Data': 'Data',
'Data uploaded': 'Data uploaded',
'Database': 'Database',
'Date': 'Date',
'Date & Time': 'Date & Time',
'Date Available': 'Date Available',
'Date Delivered': 'Date Delivered',
'Date Expected': 'Date Expected',
'Date Received': 'Date Received',
'Date Requested': 'Date Requested',
'Date Required': 'Date Required',
'Date Required Until': 'Date Required Until',
'Date Sent': 'Date Sent',
'Date Until': 'Date Until',
'Date and Time': 'Date and Time',
'Date and time this report relates to.': 'Date and time this report relates to.',
'Date of Birth': 'Date of Birth',
'Date of Latest Information on Beneficiaries Reached': 'Date of Latest Information on Beneficiaries Reached',
'Date of Report': 'Date of Report',
'Date of Treatment': 'Date of Treatment',
'Date/Time': 'Date/Time',
'Date/Time of Find': 'Date/Time of Find',
'Date/Time when found': 'Date/Time when found',
'Date/Time when last seen': 'Date/Time when last seen',
'De-duplicator': 'De-duplicator',
'Dead Bodies': 'Dead Bodies',
'Dead Body': 'Dead Body',
'Dead Body Details': 'Dead Body Details',
'Dead Body Reports': 'Dead Body Reports',
'Dead body report added': 'Dead body report added',
'Dead body report deleted': 'Dead body report deleted',
'Dead body report updated': 'Dead body report updated',
'Deaths in the past 24h': 'Deaths in the past 24h',
'Deaths/24hrs': 'Deaths/24hrs',
'Decimal Degrees': 'Decimal Degrees',
'Decomposed': 'Decomposed',
'Default Height of the map window.': 'Default Height of the map window.',
'Default Location': 'Default Location',
'Default Map': 'Default Map',
'Default Marker': 'Default Marker',
'Default Width of the map window.': 'Default Width of the map window.',
'Defecation area for animals': 'Defecation area for animals',
'Define Scenarios for allocation of appropriate Resources (Human, Assets & Facilities).': 'Define Scenarios for allocation of appropriate Resources (Human, Assets & Facilities).',
'Defines the icon used for display of features on handheld GPS.': 'Defines the icon used for display of features on handheld GPS.',
'Defines the icon used for display of features on interactive map & KML exports.': 'Defines the icon used for display of features on interactive map & KML exports.',
'Defines the marker used for display & the attributes visible in the popup.': 'Defines the marker used for display & the attributes visible in the popup.',
'Degrees must be a number between -180 and 180': 'Degrees must be a number between -180 and 180',
'Dehydration': 'Dehydration',
'Delete': 'Delete',
'Delete Alternative Item': 'Delete Alternative Item',
'Delete Assessment': 'Delete Assessment',
'Delete Assessment Summary': 'Delete Assessment Summary',
'Delete Asset': 'Delete Asset',
'Delete Asset Log Entry': 'Delete Asset Log Entry',
'Delete Baseline': 'Delete Baseline',
'Delete Baseline Type': 'Delete Baseline Type',
'Delete Brand': 'Delete Brand',
'Delete Budget': 'Delete Budget',
'Delete Bundle': 'Delete Bundle',
'Delete Catalog': 'Delete Catalogue',
'Delete Catalog Item': 'Delete Catalogue Item',
'Delete Certificate': 'Delete Certificate',
'Delete Certification': 'Delete Certification',
'Delete Cluster': 'Delete Cluster',
'Delete Cluster Subsector': 'Delete Cluster Subsector',
'Delete Commitment': 'Delete Commitment',
'Delete Commitment Item': 'Delete Commitment Item',
'Delete Competency Rating': 'Delete Competency Rating',
'Delete Contact Information': 'Delete Contact Information',
'Delete Course': 'Delete Course',
'Delete Course Certificate': 'Delete Course Certificate',
'Delete Credential': 'Delete Credential',
'Delete Document': 'Delete Document',
'Delete Donor': 'Delete Donor',
'Delete Event': 'Delete Event',
'Delete Feature Class': 'Delete Feature Class',
'Delete Feature Layer': 'Delete Feature Layer',
'Delete GPS data': 'Delete GPS data',
'Delete Group': 'Delete Group',
'Delete Home': 'Delete Home',
'Delete Hospital': 'Delete Hospital',
'Delete Image': 'Delete Image',
'Delete Impact': 'Delete Impact',
'Delete Impact Type': 'Delete Impact Type',
'Delete Incident Report': 'Delete Incident Report',
'Delete Item': 'Delete Item',
'Delete Item Category': 'Delete Item Category',
'Delete Item Pack': 'Delete Item Pack',
'Delete Job Role': 'Delete Job Role',
'Delete Kit': 'Delete Kit',
'Delete Layer': 'Delete Layer',
'Delete Level 1 Assessment': 'Delete Level 1 Assessment',
'Delete Level 2 Assessment': 'Delete Level 2 Assessment',
'Delete Location': 'Delete Location',
'Delete Map Configuration': 'Delete Map Configuration',
'Delete Marker': 'Delete Marker',
'Delete Membership': 'Delete Membership',
'Delete Message': 'Delete Message',
'Delete Mission': 'Delete Mission',
'Delete Need': 'Delete Need',
'Delete Need Type': 'Delete Need Type',
'Delete Office': 'Delete Office',
'Delete Order': 'Delete Order',
'Delete Organization': 'Delete Organisation',
'Delete Organization Domain': 'Delete Organisation Domain',
'Delete Patient': 'Delete Patient',
'Delete Person': 'Delete Person',
'Delete Photo': 'Delete Photo',
'Delete Population Statistic': 'Delete Population Statistic',
'Delete Position': 'Delete Position',
'Delete Project': 'Delete Project',
'Delete Projection': 'Delete Projection',
'Delete Rapid Assessment': 'Delete Rapid Assessment',
'Delete Received Shipment': 'Delete Received Shipment',
'Delete Record': 'Delete Record',
'Delete Relative': 'Delete Relative',
'Delete Report': 'Delete Report',
'Delete Request': 'Delete Request',
'Delete Request Item': 'Delete Request Item',
'Delete Request for Donations': 'Delete Request for Donations',
'Delete Request for Volunteers': 'Delete Request for Volunteers',
'Delete Resource': 'Delete Resource',
'Delete Room': 'Delete Room',
'Delete Saved Search': 'Delete Saved Search',
'Delete Scenario': 'Delete Scenario',
'Delete Section': 'Delete Section',
'Delete Sector': 'Delete Sector',
'Delete Sent Item': 'Delete Sent Item',
'Delete Sent Shipment': 'Delete Sent Shipment',
'Delete Service Profile': 'Delete Service Profile',
'Delete Skill': 'Delete Skill',
'Delete Skill Equivalence': 'Delete Skill Equivalence',
'Delete Skill Provision': 'Delete Skill Provision',
'Delete Skill Type': 'Delete Skill Type',
'Delete Staff Type': 'Delete Staff Type',
'Delete Status': 'Delete Status',
'Delete Subscription': 'Delete Subscription',
'Delete Subsector': 'Delete Subsector',
'Delete Training': 'Delete Training',
'Delete Unit': 'Delete Unit',
'Delete User': 'Delete User',
'Delete Vehicle': 'Delete Vehicle',
'Delete Vehicle Details': 'Delete Vehicle Details',
'Delete Warehouse': 'Delete Warehouse',
'Delete from Server?': 'Delete from Server?',
'Delete this Assessment Answer': 'Delete this Assessment Answer',
'Delete this Assessment Question': 'Delete this Assessment Question',
'Delete this Assessment Series': 'Delete this Assessment Series',
'Delete this Assessment Template': 'Delete this Assessment Template',
'Delete this Completed Assessment': 'Delete this Completed Assessment',
'Delete this Question Meta-Data': 'Delete this Question Meta-Data',
'Delete this Template Section': 'Delete this Template Section',
'Deliver To': 'Deliver To',
'Delivered To': 'Delivered To',
'Delphi Decision Maker': 'Delphi Decision Maker',
'Demographic': 'Demographic',
'Demonstrations': 'Demonstrations',
'Dental Examination': 'Dental Examination',
'Dental Profile': 'Dental Profile',
'Deployment Location': 'Deployment Location',
'Describe the condition of the roads to your hospital.': 'Describe the condition of the roads to your hospital.',
'Describe the procedure which this record relates to (e.g. "medical examination")': 'Describe the procedure which this record relates to (e.g. "medical examination")',
'Description': 'Description',
'Description of Contacts': 'Description of Contacts',
'Description of defecation area': 'Description of defecation area',
'Description of drinking water source': 'Description of drinking water source',
'Description of sanitary water source': 'Description of sanitary water source',
'Description of water source before the disaster': 'Description of water source before the disaster',
'Design, deploy & analyze surveys.': 'Design, deploy & analyse surveys.',
'Desire to remain with family': 'Desire to remain with family',
'Destination': 'Destination',
'Destroyed': 'Destroyed',
'Details': 'Details',
'Details field is required!': 'Details field is required!',
'Dialysis': 'Dialysis',
'Diaphragms, horizontal bracing': 'Diaphragms, horizontal bracing',
'Diarrhea': 'Diarrhea',
'Dignitary Visit': 'Dignitary Visit',
'Direction': 'Direction',
'Disable': 'Disable',
'Disabled': 'Disabled',
'Disabled participating in coping activities': 'Disabled participating in coping activities',
'Disabled?': 'Disabled?',
'Disaster Victim Identification': 'Disaster Victim Identification',
'Disaster Victim Registry': 'Disaster Victim Registry',
'Disaster clean-up/repairs': 'Disaster clean-up/repairs',
'Discharge (cusecs)': 'Discharge (cusecs)',
'Discharges/24hrs': 'Discharges/24hrs',
'Discussion Forum': 'Discussion Forum',
'Discussion Forum on item': 'Discussion Forum on item',
'Disease vectors': 'Disease vectors',
'Dispensary': 'Dispensary',
'Displaced': 'Displaced',
'Displaced Populations': 'Displaced Populations',
'Display': 'Display',
'Display Polygons?': 'Display Polygons?',
'Display Routes?': 'Display Routes?',
'Display Tracks?': 'Display Tracks?',
'Display Waypoints?': 'Display Waypoints?',
'Distance between defecation area and water source': 'Distance between defecation area and water source',
'Distance from %s:': 'Distance from %s:',
'Distance(Kms)': 'Distance(Kms)',
'Distribution': 'Distribution',
'Distribution groups': 'Distribution groups',
'District': 'District',
'Do you really want to delete these records?': 'Do you really want to delete these records?',
'Do you want to cancel this received shipment? The items will be removed from the Inventory. This action CANNOT be undone!': 'Do you want to cancel this received shipment? The items will be removed from the Inventory. This action CANNOT be undone!',
'Do you want to cancel this sent shipment? The items will be returned to the Inventory. This action CANNOT be undone!': 'Do you want to cancel this sent shipment? The items will be returned to the Inventory. This action CANNOT be undone!',
'Do you want to receive this shipment?': 'Do you want to receive this shipment?',
'Do you want to send these Committed items?': 'Do you want to send these Committed items?',
'Do you want to send this shipment?': 'Do you want to send this shipment?',
'Document Details': 'Document Details',
'Document Scan': 'Document Scan',
'Document added': 'Document added',
'Document deleted': 'Document deleted',
'Document removed': 'Document removed',
'Document updated': 'Document updated',
'Documents': 'Documents',
'Documents and Photos': 'Documents and Photos',
'Does this facility provide a cholera treatment center?': 'Does this facility provide a cholera treatment center?',
'Doing nothing (no structured activity)': 'Doing nothing (no structured activity)',
'Domain': 'Domain',
'Domestic chores': 'Domestic chores',
'Donated': 'Donated',
'Donation Certificate': 'Donation Certificate',
'Donation Phone #': 'Donation Phone #',
'Donations': 'Donations',
'Donor': 'Donor',
'Donor Details': 'Donor Details',
'Donor added': 'Donor added',
'Donor deleted': 'Donor deleted',
'Donor updated': 'Donor updated',
'Donors': 'Donors',
'Donors Report': 'Donors Report',
'Door frame': 'Door frame',
'Download OCR-able PDF Form': 'Download OCR-able PDF Form',
'Download Template': 'Download Template',
'Download last build': 'Download last build',
'Draft': 'Draft',
'Draft Features': 'Draft Features',
'Drainage': 'Drainage',
'Drawing up a Budget for Staff & Equipment across various Locations.': 'Drawing up a Budget for Staff & Equipment across various Locations.',
'Drill Down by Group': 'Drill Down by Group',
'Drill Down by Incident': 'Drill Down by Incident',
'Drill Down by Shelter': 'Drill Down by Shelter',
'Driving License': 'Driving License',
'Drought': 'Drought',
'Drugs': 'Drugs',
'Dug Well': 'Dug Well',
'Dummy': 'Dummy',
'Duplicate?': 'Duplicate?',
'Duration': 'Duration',
'Dust Storm': 'Dust Storm',
'Dwelling': 'Dwelling',
'E-mail': 'E-mail',
'EMS Reason': 'EMS Reason',
'EMS Status': 'EMS Status',
'ER Status': 'ER Status',
'ER Status Reason': 'ER Status Reason',
'EXERCISE': 'EXERCISE',
'Early Recovery': 'Early Recovery',
'Earth Enabled?': 'Earth Enabled?',
'Earthquake': 'Earthquake',
'Edit': 'Edit',
'Edit Activity': 'Edit Activity',
'Edit Address': 'Edit Address',
'Edit Alternative Item': 'Edit Alternative Item',
'Edit Application': 'Edit Application',
'Edit Assessment': 'Edit Assessment',
'Edit Assessment Answer': 'Edit Assessment Answer',
'Edit Assessment Question': 'Edit Assessment Question',
'Edit Assessment Series': 'Edit Assessment Series',
'Edit Assessment Summary': 'Edit Assessment Summary',
'Edit Assessment Template': 'Edit Assessment Template',
'Edit Asset': 'Edit Asset',
'Edit Asset Log Entry': 'Edit Asset Log Entry',
'Edit Baseline': 'Edit Baseline',
'Edit Baseline Type': 'Edit Baseline Type',
'Edit Brand': 'Edit Brand',
'Edit Budget': 'Edit Budget',
'Edit Bundle': 'Edit Bundle',
'Edit Camp': 'Edit Camp',
'Edit Camp Service': 'Edit Camp Service',
'Edit Camp Type': 'Edit Camp Type',
'Edit Catalog': 'Edit Catalogue',
'Edit Catalog Item': 'Edit Catalogue Item',
'Edit Certificate': 'Edit Certificate',
'Edit Certification': 'Edit Certification',
'Edit Cluster': 'Edit Cluster',
'Edit Cluster Subsector': 'Edit Cluster Subsector',
'Edit Commitment': 'Edit Commitment',
'Edit Commitment Item': 'Edit Commitment Item',
'Edit Committed Person': 'Edit Committed Person',
'Edit Competency Rating': 'Edit Competency Rating',
'Edit Completed Assessment': 'Edit Completed Assessment',
'Edit Contact': 'Edit Contact',
'Edit Contact Information': 'Edit Contact Information',
'Edit Contents': 'Edit Contents',
'Edit Course': 'Edit Course',
'Edit Course Certificate': 'Edit Course Certificate',
'Edit Credential': 'Edit Credential',
'Edit Dead Body Details': 'Edit Dead Body Details',
'Edit Description': 'Edit Description',
'Edit Details': 'Edit Details',
'Edit Disaster Victims': 'Edit Disaster Victims',
'Edit Document': 'Edit Document',
'Edit Donor': 'Edit Donor',
'Edit Email Settings': 'Edit Email Settings',
'Edit Entry': 'Edit Entry',
'Edit Event': 'Edit Event',
'Edit Facility': 'Edit Facility',
'Edit Feature Class': 'Edit Feature Class',
'Edit Feature Layer': 'Edit Feature Layer',
'Edit Flood Report': 'Edit Flood Report',
'Edit GPS data': 'Edit GPS data',
'Edit Group': 'Edit Group',
'Edit Home': 'Edit Home',
'Edit Home Address': 'Edit Home Address',
'Edit Hospital': 'Edit Hospital',
'Edit Human Resource': 'Edit Human Resource',
'Edit Identification Report': 'Edit Identification Report',
'Edit Identity': 'Edit Identity',
'Edit Image Details': 'Edit Image Details',
'Edit Impact': 'Edit Impact',
'Edit Impact Type': 'Edit Impact Type',
'Edit Import File': 'Edit Import File',
'Edit Incident': 'Edit Incident',
'Edit Incident Report': 'Edit Incident Report',
'Edit Inventory Item': 'Edit Inventory Item',
'Edit Item': 'Edit Item',
'Edit Item Category': 'Edit Item Category',
'Edit Item Pack': 'Edit Item Pack',
'Edit Job': 'Edit Job',
'Edit Job Role': 'Edit Job Role',
'Edit Kit': 'Edit Kit',
'Edit Layer': 'Edit Layer',
'Edit Level %d Locations?': 'Edit Level %d Locations?',
'Edit Level 1 Assessment': 'Edit Level 1 Assessment',
'Edit Level 2 Assessment': 'Edit Level 2 Assessment',
'Edit Location': 'Edit Location',
'Edit Location Details': 'Edit Location Details',
'Edit Log Entry': 'Edit Log Entry',
'Edit Map Configuration': 'Edit Map Configuration',
'Edit Marker': 'Edit Marker',
'Edit Membership': 'Edit Membership',
'Edit Message': 'Edit Message',
'Edit Mission': 'Edit Mission',
'Edit Modem Settings': 'Edit Modem Settings',
'Edit Need': 'Edit Need',
'Edit Need Type': 'Edit Need Type',
'Edit Office': 'Edit Office',
'Edit Options': 'Edit Options',
'Edit Order': 'Edit Order',
'Edit Order Item': 'Edit Order Item',
'Edit Organization': 'Edit Organisation',
'Edit Organization Domain': 'Edit Organisation Domain',
'Edit Parameters': 'Edit Parameters',
'Edit Patient': 'Edit Patient',
'Edit Person Details': 'Edit Person Details',
'Edit Personal Effects Details': 'Edit Personal Effects Details',
'Edit Photo': 'Edit Photo',
'Edit Population Statistic': 'Edit Population Statistic',
'Edit Position': 'Edit Position',
'Edit Problem': 'Edit Problem',
'Edit Project': 'Edit Project',
'Edit Project Organization': 'Edit Project Organization',
'Edit Projection': 'Edit Projection',
'Edit Question Meta-Data': 'Edit Question Meta-Data',
'Edit Rapid Assessment': 'Edit Rapid Assessment',
'Edit Received Item': 'Edit Received Item',
'Edit Received Shipment': 'Edit Received Shipment',
'Edit Record': 'Edit Record',
'Edit Registration': 'Edit Registration',
'Edit Relative': 'Edit Relative',
'Edit Repository Configuration': 'Edit Repository Configuration',
'Edit Request': 'Edit Request',
'Edit Request Item': 'Edit Request Item',
'Edit Request for Donations': 'Edit Request for Donations',
'Edit Request for Volunteers': 'Edit Request for Volunteers',
'Edit Requested Skill': 'Edit Requested Skill',
'Edit Resource': 'Edit Resource',
'Edit Resource Configuration': 'Edit Resource Configuration',
'Edit River': 'Edit River',
'Edit Role': 'Edit Role',
'Edit Room': 'Edit Room',
'Edit SMS Settings': 'Edit SMS Settings',
'Edit SMTP to SMS Settings': 'Edit SMTP to SMS Settings',
'Edit Saved Search': 'Edit Saved Search',
'Edit Scenario': 'Edit Scenario',
'Edit Sector': 'Edit Sector',
'Edit Sent Item': 'Edit Sent Item',
'Edit Setting': 'Edit Setting',
'Edit Settings': 'Edit Settings',
'Edit Shelter': 'Edit Shelter',
'Edit Shelter Service': 'Edit Shelter Service',
'Edit Shelter Type': 'Edit Shelter Type',
'Edit Skill': 'Edit Skill',
'Edit Skill Equivalence': 'Edit Skill Equivalence',
'Edit Skill Provision': 'Edit Skill Provision',
'Edit Skill Type': 'Edit Skill Type',
'Edit Solution': 'Edit Solution',
'Edit Staff Type': 'Edit Staff Type',
'Edit Subscription': 'Edit Subscription',
'Edit Subsector': 'Edit Subsector',
'Edit Synchronization Settings': 'Edit Synchronisation Settings',
'Edit Task': 'Edit Task',
'Edit Team': 'Edit Team',
'Edit Template Section': 'Edit Template Section',
'Edit Theme': 'Edit Theme',
'Edit Themes': 'Edit Themes',
'Edit Ticket': 'Edit Ticket',
'Edit Training': 'Edit Training',
'Edit Tropo Settings': 'Edit Tropo Settings',
'Edit User': 'Edit User',
'Edit Vehicle': 'Edit Vehicle',
'Edit Vehicle Details': 'Edit Vehicle Details',
'Edit Volunteer Availability': 'Edit Volunteer Availability',
'Edit Warehouse': 'Edit Warehouse',
'Edit Web API Settings': 'Edit Web API Settings',
'Edit current record': 'Edit current record',
'Edit message': 'Edit message',
'Edit the OpenStreetMap data for this area': 'Edit the OpenStreetMap data for this area',
'Editable?': 'Editable?',
'Education': 'Education',
'Education materials received': 'Education materials received',
'Education materials, source': 'Education materials, source',
'Effects Inventory': 'Effects Inventory',
'Eggs': 'Eggs',
'Either a shelter or a location must be specified': 'Either a shelter or a location must be specified',
'Either file upload or document URL required.': 'Either file upload or document URL required.',
'Either file upload or image URL required.': 'Either file upload or image URL required.',
'Elderly person headed households (>60 yrs)': 'Elderly person headed households (>60 yrs)',
'Electrical': 'Electrical',
'Electrical, gas, sewerage, water, hazmats': 'Electrical, gas, sewerage, water, hazmats',
'Elevated': 'Elevated',
'Elevators': 'Elevators',
'Email': 'Email',
'Email Address to which to send SMS messages. Assumes sending to phonenumber@address': 'Email Address to which to send SMS messages. Assumes sending to phonenumber@address',
'Email Settings': 'Email Settings',
'Email and SMS': 'Email and SMS',
'Email settings updated': 'Email settings updated',
'Embalming': 'Embalming',
'Embassy': 'Embassy',
'Emergency Capacity Building project': 'Emergency Capacity Building project',
'Emergency Department': 'Emergency Department',
'Emergency Shelter': 'Emergency Shelter',
'Emergency Support Facility': 'Emergency Support Facility',
'Emergency Support Service': 'Emergency Support Service',
'Emergency Telecommunications': 'Emergency Telecommunications',
'Enable': 'Enable',
'Enable/Disable Layers': 'Enable/Disable Layers',
'Enabled': 'Enabled',
'Enabled?': 'Enabled?',
'Enabling MapMaker layers disables the StreetView functionality': 'Enabling MapMaker layers disables the StreetView functionality',
'End Date': 'End Date',
'End date': 'End date',
'End date should be after start date': 'End date should be after start date',
'English': 'English',
'Enter Coordinates:': 'Enter Coordinates:',
'Enter a GPS Coord': 'Enter a GPS Coord',
'Enter a name for the spreadsheet you are uploading.': 'Enter a name for the spreadsheet you are uploading.',
'Enter a new support request.': 'Enter a new support request.',
'Enter a unique label!': 'Enter a unique label!',
'Enter a valid date before': 'Enter a valid date before',
'Enter a valid email': 'Enter a valid email',
'Enter a valid future date': 'Enter a valid future date',
'Enter a valid past date': 'Enter a valid past date',
'Enter some characters to bring up a list of possible matches': 'Enter some characters to bring up a list of possible matches',
'Enter some characters to bring up a list of possible matches.': 'Enter some characters to bring up a list of possible matches.',
'Enter tags separated by commas.': 'Enter tags separated by commas.',
'Enter the data for an assessment': 'Enter the data for an assessment',
'Enter the same password as above': 'Enter the same password as above',
'Enter your firstname': 'Enter your firstname',
'Enter your organization': 'Enter your organisation',
'Entered': 'Entered',
'Entering a phone number is optional, but doing so allows you to subscribe to receive SMS messages.': 'Entering a phone number is optional, but doing so allows you to subscribe to receive SMS messages.',
'Environment': 'Environment',
'Equipment': 'Equipment',
'Error encountered while applying the theme.': 'Error encountered while applying the theme.',
'Error in message': 'Error in message',
'Error logs for "%(app)s"': 'Error logs for "%(app)s"',
'Est. Delivery Date': 'Est. Delivery Date',
'Estimated # of households who are affected by the emergency': 'Estimated # of households who are affected by the emergency',
'Estimated # of people who are affected by the emergency': 'Estimated # of people who are affected by the emergency',
'Estimated Overall Building Damage': 'Estimated Overall Building Damage',
'Estimated total number of people in institutions': 'Estimated total number of people in institutions',
'Euros': 'Euros',
'Evacuating': 'Evacuating',
'Evaluate the information in this message. (This value SHOULD NOT be used in public warning applications.)': 'Evaluate the information in this message. (This value SHOULD NOT be used in public warning applications.)',
'Event': 'Event',
'Event Details': 'Event Details',
'Event added': 'Event added',
'Event deleted': 'Event deleted',
'Event updated': 'Event updated',
'Events': 'Events',
'Example': 'Example',
'Exceeded': 'Exceeded',
'Excel': 'Excel',
'Excellent': 'Excellent',
'Exclude contents': 'Exclude contents',
'Excreta disposal': 'Excreta disposal',
'Execute a pre-planned activity identified in <instruction>': 'Execute a pre-planned activity identified in <instruction>',
'Exercise': 'Exercise',
'Exercise?': 'Exercise?',
'Exercises mean all screens have a watermark & all notifications have a prefix.': 'Exercises mean all screens have a watermark & all notifications have a prefix.',
'Existing Placard Type': 'Existing Placard Type',
'Existing Sections': 'Existing Sections',
'Existing food stocks': 'Existing food stocks',
'Existing location cannot be converted into a group.': 'Existing location cannot be converted into a group.',
'Exits': 'Exits',
'Expected Return Home': 'Expected Return Home',
'Experience': 'Experience',
'Expiry Date': 'Expiry Date',
'Explosive Hazard': 'Explosive Hazard',
'Export': 'Export',
'Export Data': 'Export Data',
'Export Database as CSV': 'Export Database as CSV',
'Export in GPX format': 'Export in GPX format',
'Export in KML format': 'Export in KML format',
'Export in OSM format': 'Export in OSM format',
'Export in PDF format': 'Export in PDF format',
'Export in RSS format': 'Export in RSS format',
'Export in XLS format': 'Export in XLS format',
'Exterior Only': 'Exterior Only',
'Exterior and Interior': 'Exterior and Interior',
'Eye Color': 'Eye Colour',
'Facial hair, color': 'Facial hair, colour',
'Facial hair, type': 'Facial hair, type',
'Facial hear, length': 'Facial hear, length',
'Facilities': 'Facilities',
'Facility': 'Facility',
'Facility Details': 'Facility Details',
'Facility Operations': 'Facility Operations',
'Facility Status': 'Facility Status',
'Facility Type': 'Facility Type',
'Facility added': 'Facility added',
'Facility or Location': 'Facility or Location',
'Facility removed': 'Facility removed',
'Facility updated': 'Facility updated',
'Fail': 'Fail',
'Failed!': 'Failed!',
'Fair': 'Fair',
'Falling Object Hazard': 'Falling Object Hazard',
'Families/HH': 'Families/HH',
'Family': 'Family',
'Family tarpaulins received': 'Family tarpaulins received',
'Family tarpaulins, source': 'Family tarpaulins, source',
'Family/friends': 'Family/friends',
'Farmland/fishing material assistance, Rank': 'Farmland/fishing material assistance, Rank',
'Fatalities': 'Fatalities',
'Fax': 'Fax',
'Feature Class': 'Feature Class',
'Feature Class Details': 'Feature Class Details',
'Feature Class added': 'Feature Class added',
'Feature Class deleted': 'Feature Class deleted',
'Feature Class updated': 'Feature Class updated',
'Feature Classes': 'Feature Classes',
'Feature Classes are collections of Locations (Features) of the same type': 'Feature Classes are collections of Locations (Features) of the same type',
'Feature Layer Details': 'Feature Layer Details',
'Feature Layer added': 'Feature Layer added',
'Feature Layer deleted': 'Feature Layer deleted',
'Feature Layer updated': 'Feature Layer updated',
'Feature Layers': 'Feature Layers',
'Feature Namespace': 'Feature Namespace',
'Feature Request': 'Feature Request',
'Feature Type': 'Feature Type',
'Features Include': 'Features Include',
'Female': 'Female',
'Female headed households': 'Female headed households',
'Few': 'Few',
'Field': 'Field',
'Field Hospital': 'Field Hospital',
'File': 'File',
'File Imported': 'File Imported',
'File Importer': 'File Importer',
'File name': 'File name',
'Fill in Latitude': 'Fill in Latitude',
'Fill in Longitude': 'Fill in Longitude',
'Filter': 'Filter',
'Filter Field': 'Filter Field',
'Filter Value': 'Filter Value',
'Find': 'Find',
'Find Dead Body Report': 'Find Dead Body Report',
'Find Hospital': 'Find Hospital',
'Find Person Record': 'Find Person Record',
'Find a Person Record': 'Find a Person Record',
'Finder': 'Finder',
'Fingerprint': 'Fingerprint',
'Fingerprinting': 'Fingerprinting',
'Fingerprints': 'Fingerprints',
'Fire': 'Fire',
'Fire suppression and rescue': 'Fire suppression and rescue',
'First Name': 'First Name',
'First name': 'First name',
'Fishing': 'Fishing',
'Flash Flood': 'Flash Flood',
'Flash Freeze': 'Flash Freeze',
'Flexible Impact Assessments': 'Flexible Impact Assessments',
'Flood': 'Flood',
'Flood Alerts': 'Flood Alerts',
'Flood Alerts show water levels in various parts of the country': 'Flood Alerts show water levels in various parts of the country',
'Flood Report': 'Flood Report',
'Flood Report Details': 'Flood Report Details',
'Flood Report added': 'Flood Report added',
'Flood Report deleted': 'Flood Report deleted',
'Flood Report updated': 'Flood Report updated',
'Flood Reports': 'Flood Reports',
'Flow Status': 'Flow Status',
'Fog': 'Fog',
'Food': 'Food',
'Food Supply': 'Food Supply',
'Food assistance': 'Food assistance',
'Footer': 'Footer',
'Footer file %s missing!': 'Footer file %s missing!',
'For': 'For',
'For POP-3 this is usually 110 (995 for SSL), for IMAP this is usually 143 (993 for IMAP).': 'For POP-3 this is usually 110 (995 for SSL), for IMAP this is usually 143 (993 for IMAP).',
'For a country this would be the ISO2 code, for a Town, it would be the Airport Locode.': 'For a country this would be the ISO2 code, for a Town, it would be the Airport Locode.',
'For messages that support alert network internal functions': 'For messages that support alert network internal functions',
'Forest Fire': 'Forest Fire',
'Formal camp': 'Formal camp',
'Format': 'Format',
"Format the list of attribute values & the RGB value to use for these as a JSON object, e.g.: {Red: '#FF0000', Green: '#00FF00', Yellow: '#FFFF00'}": "Format the list of attribute values & the RGB value to use for these as a JSON object, e.g.: {Red: '#FF0000', Green: '#00FF00', Yellow: '#FFFF00'}",
'Forms': 'Forms',
'Found': 'Found',
'Foundations': 'Foundations',
'Freezing Drizzle': 'Freezing Drizzle',
'Freezing Rain': 'Freezing Rain',
'Freezing Spray': 'Freezing Spray',
'French': 'French',
'Friday': 'Friday',
'From': 'From',
'From Facility': 'From Facility',
'From Inventory': 'From Inventory',
'From Location': 'From Location',
'From Organization': 'From Organisation',
'Frost': 'Frost',
'Fulfil. Status': 'Fulfil. Status',
'Fulfillment Status': 'Fulfillment Status',
'Full': 'Full',
'Full beard': 'Full beard',
'Fullscreen Map': 'Fullscreen Map',
'Functions available': 'Functions available',
'Funding Organization': 'Funding Organisation',
'Funds Contributed by this Organization': 'Funds Contributed by this Organisation',
'Funeral': 'Funeral',
'Further Action Recommended': 'Further Action Recommended',
'GIS Reports of Shelter': 'GIS Reports of Shelter',
'GIS integration to view location details of the Shelter': 'GIS integration to view location details of the Shelter',
'GPS': 'GPS',
'GPS Data': 'GPS Data',
'GPS ID': 'GPS ID',
'GPS Marker': 'GPS Marker',
'GPS Track': 'GPS Track',
'GPS Track File': 'GPS Track File',
'GPS data': 'GPS data',
'GPS data added': 'GPS data added',
'GPS data deleted': 'GPS data deleted',
'GPS data updated': 'GPS data updated',
'GRN': 'GRN',
'GRN Status': 'GRN Status',
'Gale Wind': 'Gale Wind',
'Gap Analysis': 'Gap Analysis',
'Gap Analysis Map': 'Gap Analysis Map',
'Gap Analysis Report': 'Gap Analysis Report',
'Gender': 'Gender',
'General Comment': 'General Comment',
'General Medical/Surgical': 'General Medical/Surgical',
'General emergency and public safety': 'General emergency and public safety',
'General information on demographics': 'General information on demographics',
'Generate portable application': 'Generate portable application',
'Generator': 'Generator',
'Geocode': 'Geocode',
'Geocoder Selection': 'Geocoder Selection',
'Geometry Name': 'Geometry Name',
'Geonames.org search requires Internet connectivity!': 'Geonames.org search requires Internet connectivity!',
'Geophysical (inc. landslide)': 'Geophysical (inc. landslide)',
'Geotechnical': 'Geotechnical',
'Geotechnical Hazards': 'Geotechnical Hazards',
'German': 'German',
'Get incoming recovery requests as RSS feed': 'Get incoming recovery requests as RSS feed',
'Give a brief description of the image, e.g. what can be seen where on the picture (optional).': 'Give a brief description of the image, e.g. what can be seen where on the picture (optional).',
'Give information about where and when you have seen them': 'Give information about where and when you have seen them',
'Go to Request': 'Go to Request',
'Goatee': 'Goatee',
'Good': 'Good',
'Good Condition': 'Good Condition',
'Goods Received Note': 'Goods Received Note',
"Google Layers cannot be displayed if there isn't a valid API Key": "Google Layers cannot be displayed if there isn't a valid API Key",
'Government': 'Government',
'Government UID': 'Government UID',
'Government building': 'Government building',
'Grade': 'Grade',
'Great British Pounds': 'Great British Pounds',
'Greater than 10 matches. Please refine search further': 'Greater than 10 matches. Please refine search further',
'Greek': 'Greek',
'Green': 'Green',
'Ground movement, fissures': 'Ground movement, fissures',
'Ground movement, settlement, slips': 'Ground movement, settlement, slips',
'Group': 'Group',
'Group Description': 'Group Description',
'Group Details': 'Group Details',
'Group ID': 'Group ID',
'Group Member added': 'Group Member added',
'Group Members': 'Group Members',
'Group Memberships': 'Group Memberships',
'Group Name': 'Group Name',
'Group Title': 'Group Title',
'Group Type': 'Group Type',
'Group added': 'Group added',
'Group deleted': 'Group deleted',
'Group description': 'Group description',
'Group updated': 'Group updated',
'Groups': 'Groups',
'Groups removed': 'Groups removed',
'Guest': 'Guest',
'HFA Priorities': 'HFA Priorities',
'Hail': 'Hail',
'Hair Color': 'Hair Colour',
'Hair Length': 'Hair Length',
'Hair Style': 'Hair Style',
'Has data from this Reference Document been entered into Sahana?': 'Has data from this Reference Document been entered into Sahana?',
'Has the Certificate for receipt of the shipment been given to the sender?': 'Has the Certificate for receipt of the shipment been given to the sender?',
'Has the GRN (Goods Received Note) been completed?': 'Has the GRN (Goods Received Note) been completed?',
'Hazard Pay': 'Hazard Pay',
'Hazardous Material': 'Hazardous Material',
'Hazardous Road Conditions': 'Hazardous Road Conditions',
'Hazards': 'Hazards',
'Header Background': 'Header Background',
'Header background file %s missing!': 'Header background file %s missing!',
'Headquarters': 'Headquarters',
'Health': 'Health',
'Health care assistance, Rank': 'Health care assistance, Rank',
'Health center': 'Health center',
'Health center with beds': 'Health center with beds',
'Health center without beds': 'Health center without beds',
'Health services status': 'Health services status',
'Healthcare Worker': 'Healthcare Worker',
'Heat Wave': 'Heat Wave',
'Heat and Humidity': 'Heat and Humidity',
'Height': 'Height',
'Height (cm)': 'Height (cm)',
'Height (m)': 'Height (m)',
'Help': 'Help',
'Helps to monitor status of hospitals': 'Helps to monitor status of hospitals',
'Helps to report and search for missing persons': 'Helps to report and search for missing persons',
'Here are the solution items related to the problem.': 'Here are the solution items related to the problem.',
'Heritage Listed': 'Heritage Listed',
'Hierarchy Level 0 Name (i.e. Country)': 'Hierarchy Level 0 Name (i.e. Country)',
'Hierarchy Level 1 Name (e.g. State or Province)': 'Hierarchy Level 1 Name (e.g. State or Province)',
'Hierarchy Level 2 Name (e.g. District or County)': 'Hierarchy Level 2 Name (e.g. District or County)',
'Hierarchy Level 3 Name (e.g. City / Town / Village)': 'Hierarchy Level 3 Name (e.g. City / Town / Village)',
'Hierarchy Level 4 Name (e.g. Neighbourhood)': 'Hierarchy Level 4 Name (e.g. Neighbourhood)',
'Hierarchy Level 5 Name': 'Hierarchy Level 5 Name',
'High': 'High',
'High Water': 'High Water',
'Hindu': 'Hindu',
'Hit the back button on your browser to try again.': 'Hit the back button on your browser to try again.',
'Holiday Address': 'Holiday Address',
'Home': 'Home',
'Home Address': 'Home Address',
'Home City': 'Home City',
'Home Country': 'Home Country',
'Home Crime': 'Home Crime',
'Home Details': 'Home Details',
'Home Phone Number': 'Home Phone Number',
'Home Relative': 'Home Relative',
'Home added': 'Home added',
'Home deleted': 'Home deleted',
'Home updated': 'Home updated',
'Homes': 'Homes',
'Hospital': 'Hospital',
'Hospital Details': 'Hospital Details',
'Hospital Status Report': 'Hospital Status Report',
'Hospital information added': 'Hospital information added',
'Hospital information deleted': 'Hospital information deleted',
'Hospital information updated': 'Hospital information updated',
'Hospital status assessment.': 'Hospital status assessment.',
'Hospitals': 'Hospitals',
'Host National Society': 'Host National Society',
'Hot Spot': 'Hot Spot',
'Hour': 'Hour',
'Hours': 'Hours',
'Household kits received': 'Household kits received',
'Household kits, source': 'Household kits, source',
'How data shall be transferred': 'How data shall be transferred',
'How is this person affected by the disaster? (Select all that apply)': 'How is this person affected by the disaster? (Select all that apply)',
'How local records shall be updated': 'How local records shall be updated',
'How long will the food last?': 'How long will the food last?',
'How many Boys (0-17 yrs) are Dead due to the crisis': 'How many Boys (0-17 yrs) are Dead due to the crisis',
'How many Boys (0-17 yrs) are Injured due to the crisis': 'How many Boys (0-17 yrs) are Injured due to the crisis',
'How many Boys (0-17 yrs) are Missing due to the crisis': 'How many Boys (0-17 yrs) are Missing due to the crisis',
'How many Girls (0-17 yrs) are Dead due to the crisis': 'How many Girls (0-17 yrs) are Dead due to the crisis',
'How many Girls (0-17 yrs) are Injured due to the crisis': 'How many Girls (0-17 yrs) are Injured due to the crisis',
'How many Girls (0-17 yrs) are Missing due to the crisis': 'How many Girls (0-17 yrs) are Missing due to the crisis',
'How many Men (18 yrs+) are Dead due to the crisis': 'How many Men (18 yrs+) are Dead due to the crisis',
'How many Men (18 yrs+) are Injured due to the crisis': 'How many Men (18 yrs+) are Injured due to the crisis',
'How many Men (18 yrs+) are Missing due to the crisis': 'How many Men (18 yrs+) are Missing due to the crisis',
'How many Women (18 yrs+) are Dead due to the crisis': 'How many Women (18 yrs+) are Dead due to the crisis',
'How many Women (18 yrs+) are Injured due to the crisis': 'How many Women (18 yrs+) are Injured due to the crisis',
'How many Women (18 yrs+) are Missing due to the crisis': 'How many Women (18 yrs+) are Missing due to the crisis',
'How many days will the supplies last?': 'How many days will the supplies last?',
'How many new cases have been admitted to this facility in the past 24h?': 'How many new cases have been admitted to this facility in the past 24h?',
'How many of the patients with the disease died in the past 24h at this facility?': 'How many of the patients with the disease died in the past 24h at this facility?',
'How many patients with the disease are currently hospitalized at this facility?': 'How many patients with the disease are currently hospitalized at this facility?',
'How much detail is seen. A high Zoom level means lot of detail, but not a wide area. A low Zoom level means seeing a wide area, but not a high level of detail.': 'How much detail is seen. A high Zoom level means lot of detail, but not a wide area. A low Zoom level means seeing a wide area, but not a high level of detail.',
'Human Resource': 'Human Resource',
'Human Resource Details': 'Human Resource Details',
'Human Resource Management': 'Human Resource Management',
'Human Resource added': 'Human Resource added',
'Human Resource removed': 'Human Resource removed',
'Human Resource updated': 'Human Resource updated',
'Human Resources': 'Human Resources',
'Human Resources Management': 'Human Resources Management',
'Humanitarian NGO': 'Humanitarian NGO',
'Hurricane': 'Hurricane',
'Hurricane Force Wind': 'Hurricane Force Wind',
'Hybrid Layer': 'Hybrid Layer',
'Hygiene': 'Hygiene',
'Hygiene NFIs': 'Hygiene NFIs',
'Hygiene kits received': 'Hygiene kits received',
'Hygiene kits, source': 'Hygiene kits, source',
'Hygiene practice': 'Hygiene practice',
'Hygiene problems': 'Hygiene problems',
'I accept. Create my account.': 'I accept. Create my account.',
'ID Tag': 'ID Tag',
'ID Tag Number': 'ID Tag Number',
'ID type': 'ID type',
'Ice Pressure': 'Ice Pressure',
'Iceberg': 'Iceberg',
'Identification': 'Identification',
'Identification Report': 'Identification Report',
'Identification Reports': 'Identification Reports',
'Identification Status': 'Identification Status',
'Identified as': 'Identified as',
'Identified by': 'Identified by',
'Identifier which the repository identifies itself with when sending synchronization requests.': 'Identifier which the repository identifies itself with when sending synchronisation requests.',
'Identity': 'Identity',
'Identity Details': 'Identity Details',
'Identity added': 'Identity added',
'Identity deleted': 'Identity deleted',
'Identity updated': 'Identity updated',
'If a ticket was issued then please provide the Ticket ID.': 'If a ticket was issued then please provide the Ticket ID.',
'If a user verifies that they own an Email Address with this domain, the Approver field is used to determine whether & by whom further approval is required.': 'If a user verifies that they own an Email Address with this domain, the Approver field is used to determine whether & by whom further approval is required.',
'If it is a URL leading to HTML, then this will downloaded.': 'If it is a URL leading to HTML, then this will downloaded.',
'If neither are defined, then the Default Marker is used.': 'If neither are defined, then the Default Marker is used.',
'If no marker defined then the system default marker is used': 'If no marker defined then the system default marker is used',
'If no, specify why': 'If no, specify why',
'If none are selected, then all are searched.': 'If none are selected, then all are searched.',
'If not found, you can have a new location created.': 'If not found, you can have a new location created.',
"If selected, then this Asset's Location will be updated whenever the Person's Location is updated.": "If selected, then this Asset's Location will be updated whenever the Person's Location is updated.",
'If the location is a geographic area, then state at what level here.': 'If the location is a geographic area, then state at what level here.',
'If the request is for %s, please enter the details on the next screen.': 'If the request is for %s, please enter the details on the next screen.',
'If the request type is "Other", please enter request details here.': 'If the request type is "Other", please enter request details here.',
"If this configuration represents a region for the Regions menu, give it a name to use in the menu. The name for a personal map configuration will be set to the user's name.": "If this configuration represents a region for the Regions menu, give it a name to use in the menu. The name for a personal map configuration will be set to the user's name.",
"If this field is populated then a user who specifies this Organization when signing up will be assigned as a Staff of this Organization unless their domain doesn't match the domain field.": "If this field is populated then a user who specifies this Organisation when signing up will be assigned as a Staff of this Organisation unless their domain doesn't match the domain field.",
'If this field is populated then a user with the Domain specified will automatically be assigned as a Staff of this Organization': 'If this field is populated then a user with the Domain specified will automatically be assigned as a Staff of this Organisation',
'If this is set to True then mails will be deleted from the server after downloading.': 'If this is set to True then mails will be deleted from the server after downloading.',
'If this record should be restricted then select which role is required to access the record here.': 'If this record should be restricted then select which role is required to access the record here.',
'If this record should be restricted then select which role(s) are permitted to access the record here.': 'If this record should be restricted then select which role(s) are permitted to access the record here.',
'If yes, specify what and by whom': 'If yes, specify what and by whom',
'If yes, which and how': 'If yes, which and how',
'If you do not enter a Reference Document, your email will be displayed to allow this data to be verified.': 'If you do not enter a Reference Document, your email will be displayed to allow this data to be verified.',
"If you don't see the Hospital in the list, you can add a new one by clicking link 'Add Hospital'.": "If you don't see the Hospital in the list, you can add a new one by clicking link 'Add Hospital'.",
"If you don't see the Office in the list, you can add a new one by clicking link 'Add Office'.": "If you don't see the Office in the list, you can add a new one by clicking link 'Add Office'.",
"If you don't see the Organization in the list, you can add a new one by clicking link 'Add Organization'.": "If you don't see the Organisation in the list, you can add a new one by clicking link 'Add Organisation'.",
"If you don't see the site in the list, you can add a new one by clicking link 'Add Project Site'.": "If you don't see the site in the list, you can add a new one by clicking link 'Add Project Site'.",
'If you have any questions or need support, please see': 'If you have any questions or need support, please see',
'If you know what the Geonames ID of this location is then you can enter it here.': 'If you know what the Geonames ID of this location is then you can enter it here.',
'If you know what the OSM ID of this location is then you can enter it here.': 'If you know what the OSM ID of this location is then you can enter it here.',
'If you need to add a new document then you can click here to attach one.': 'If you need to add a new document then you can click here to attach one.',
'If you want several values, then separate with': 'If you want several values, then separate with',
'If you would like to help, then please': 'If you would like to help, then please',
'Illegal Immigrant': 'Illegal Immigrant',
'Image': 'Image',
'Image Details': 'Image Details',
'Image File(s), one image per page': 'Image File(s), one image per page',
'Image Tags': 'Image Tags',
'Image Type': 'Image Type',
'Image Upload': 'Image Upload',
'Image added': 'Image added',
'Image deleted': 'Image deleted',
'Image updated': 'Image updated',
'Imagery': 'Imagery',
'Images': 'Images',
'Impact Assessments': 'Impact Assessments',
'Impact Details': 'Impact Details',
'Impact Type': 'Impact Type',
'Impact Type Details': 'Impact Type Details',
'Impact Type added': 'Impact Type added',
'Impact Type deleted': 'Impact Type deleted',
'Impact Type updated': 'Impact Type updated',
'Impact Types': 'Impact Types',
'Impact added': 'Impact added',
'Impact deleted': 'Impact deleted',
'Impact updated': 'Impact updated',
'Impacts': 'Impacts',
'Import': 'Import',
'Import Completed Responses': 'Import Completed Responses',
'Import Data': 'Import Data',
'Import File': 'Import File',
'Import File Details': 'Import File Details',
'Import File deleted': 'Import File deleted',
'Import Files': 'Import Files',
'Import Job Count': 'Import Job Count',
'Import Jobs': 'Import Jobs',
'Import New File': 'Import New File',
'Import Offices': 'Import Offices',
'Import Organizations': 'Import Organisations',
'Import Project Organizations': 'Import Project Organisations',
'Import Questions': 'Import Questions',
'Import Staff & Volunteers': 'Import Staff & Volunteers',
'Import Templates': 'Import Templates',
'Import from Ushahidi Instance': 'Import from Ushahidi Instance',
'Import multiple tables as CSV': 'Import multiple tables as CSV',
'Import/Export': 'Import/Export',
'Importantly where there are no aid services being provided': 'Importantly where there are no aid services being provided',
'Imported': 'Imported',
'Importing data from spreadsheets': 'Importing data from spreadsheets',
'Improper decontamination': 'Improper decontamination',
'Improper handling of dead bodies': 'Improper handling of dead bodies',
'In Catalogs': 'In Catalogues',
'In Inventories': 'In Inventories',
'In Process': 'In Process',
'In Progress': 'In Progress',
'In Window layout the map maximises to fill the window, so no need to set a large value here.': 'In Window layout the map maximises to fill the window, so no need to set a large value here.',
'Inbound Mail Settings': 'Inbound Mail Settings',
'Incident': 'Incident',
'Incident Categories': 'Incident Categories',
'Incident Details': 'Incident Details',
'Incident Report': 'Incident Report',
'Incident Report Details': 'Incident Report Details',
'Incident Report added': 'Incident Report added',
'Incident Report deleted': 'Incident Report deleted',
'Incident Report updated': 'Incident Report updated',
'Incident Reporting': 'Incident Reporting',
'Incident Reporting System': 'Incident Reporting System',
'Incident Reports': 'Incident Reports',
'Incident added': 'Incident added',
'Incident removed': 'Incident removed',
'Incident updated': 'Incident updated',
'Incidents': 'Incidents',
'Include any special requirements such as equipment which they need to bring.': 'Include any special requirements such as equipment which they need to bring.',
'Incoming': 'Incoming',
'Incoming Shipment canceled': 'Incoming Shipment canceled',
'Incoming Shipment updated': 'Incoming Shipment updated',
'Incomplete': 'Incomplete',
'Individuals': 'Individuals',
'Industrial': 'Industrial',
'Industrial Crime': 'Industrial Crime',
'Industry Fire': 'Industry Fire',
'Infant (0-1)': 'Infant (0-1)',
'Infectious Disease': 'Infectious Disease',
'Infectious Disease (Hazardous Material)': 'Infectious Disease (Hazardous Material)',
'Infectious Diseases': 'Infectious Diseases',
'Infestation': 'Infestation',
'Informal Leader': 'Informal Leader',
'Informal camp': 'Informal camp',
'Information gaps': 'Information gaps',
'Infusion catheters available': 'Infusion catheters available',
'Infusion catheters need per 24h': 'Infusion catheters need per 24h',
'Infusion catheters needed per 24h': 'Infusion catheters needed per 24h',
'Infusions available': 'Infusions available',
'Infusions needed per 24h': 'Infusions needed per 24h',
'Inspected': 'Inspected',
'Inspection Date': 'Inspection Date',
'Inspection date and time': 'Inspection date and time',
'Inspection time': 'Inspection time',
'Inspector ID': 'Inspector ID',
'Instant Porridge': 'Instant Porridge',
'Institution': 'Institution',
'Insufficient': 'Insufficient',
'Insufficient privileges': 'Insufficient privileges',
'Insufficient vars: Need module, resource, jresource, instance': 'Insufficient vars: Need module, resource, jresource, instance',
'Insurance Renewal Due': 'Insurance Renewal Due',
'Intergovernmental Organization': 'Intergovernmental Organisation',
'Interior walls, partitions': 'Interior walls, partitions',
'Internal State': 'Internal State',
'International NGO': 'International NGO',
'International Organization': 'International Organisation',
'Interview taking place at': 'Interview taking place at',
'Invalid': 'Invalid',
'Invalid Query': 'Invalid Query',
'Invalid email': 'Invalid email',
'Invalid phone number': 'Invalid phone number',
'Invalid phone number!': 'Invalid phone number!',
'Invalid request!': 'Invalid request!',
'Invalid ticket': 'Invalid ticket',
'Inventories': 'Inventories',
'Inventory': 'Inventory',
'Inventory Item': 'Inventory Item',
'Inventory Item Details': 'Inventory Item Details',
'Inventory Item updated': 'Inventory Item updated',
'Inventory Items': 'Inventory Items',
'Inventory Items include both consumable supplies & those which will get turned into Assets at their destination.': 'Inventory Items include both consumable supplies & those which will get turned into Assets at their destination.',
'Inventory Management': 'Inventory Management',
'Inventory Stock Position': 'Inventory Stock Position',
'Inventory functionality is available for': 'Inventory functionality is available for',
'Inventory of Effects': 'Inventory of Effects',
'Is editing level L%d locations allowed?': 'Is editing level L%d locations allowed?',
'Is it safe to collect water?': 'Is it safe to collect water?',
'Is this a strict hierarchy?': 'Is this a strict hierarchy?',
'Issuing Authority': 'Issuing Authority',
'It captures not only the places where they are active, but also captures information on the range of projects they are providing in each area.': 'It captures not only the places where they are active, but also captures information on the range of projects they are providing in each area.',
'Italian': 'Italian',
'Item': 'Item',
'Item Added to Shipment': 'Item Added to Shipment',
'Item Catalog Details': 'Item Catalogue Details',
'Item Catalogs': 'Item Catalogues',
'Item Categories': 'Item Categories',
'Item Category': 'Item Category',
'Item Category Details': 'Item Category Details',
'Item Category added': 'Item Category added',
'Item Category deleted': 'Item Category deleted',
'Item Category updated': 'Item Category updated',
'Item Details': 'Item Details',
'Item Pack Details': 'Item Pack Details',
'Item Pack added': 'Item Pack added',
'Item Pack deleted': 'Item Pack deleted',
'Item Pack updated': 'Item Pack updated',
'Item Packs': 'Item Packs',
'Item added': 'Item added',
'Item added to Inventory': 'Item added to Inventory',
'Item added to order': 'Item added to order',
'Item added to shipment': 'Item added to shipment',
'Item already in Bundle!': 'Item already in Bundle!',
'Item already in Kit!': 'Item already in Kit!',
'Item already in budget!': 'Item already in budget!',
'Item deleted': 'Item deleted',
'Item removed from Inventory': 'Item removed from Inventory',
'Item removed from order': 'Item removed from order',
'Item removed from shipment': 'Item removed from shipment',
'Item updated': 'Item updated',
'Items': 'Items',
'Items in Category can be Assets': 'Items in Category can be Assets',
'Japanese': 'Japanese',
'Jerry can': 'Jerry can',
'Jew': 'Jew',
'Job Role': 'Job Role',
'Job Role Catalog': 'Job Role Catalogue',
'Job Role Details': 'Job Role Details',
'Job Role added': 'Job Role added',
'Job Role deleted': 'Job Role deleted',
'Job Role updated': 'Job Role updated',
'Job Roles': 'Job Roles',
'Job Title': 'Job Title',
'Job added': 'Job added',
'Job deleted': 'Job deleted',
'Job updated updated': 'Job updated updated',
'Journal': 'Journal',
'Journal Entry Details': 'Journal Entry Details',
'Journal entry added': 'Journal entry added',
'Journal entry deleted': 'Journal entry deleted',
'Journal entry updated': 'Journal entry updated',
'Kit': 'Kit',
'Kit Contents': 'Kit Contents',
'Kit Details': 'Kit Details',
'Kit Updated': 'Kit Updated',
'Kit added': 'Kit added',
'Kit deleted': 'Kit deleted',
'Kit updated': 'Kit updated',
'Kits': 'Kits',
'Known Identities': 'Known Identities',
'Known incidents of violence against women/girls': 'Known incidents of violence against women/girls',
'Known incidents of violence since disaster': 'Known incidents of violence since disaster',
'Korean': 'Korean',
'LICENSE': 'LICENSE',
'Label Question:': 'Label Question:',
'Lack of material': 'Lack of material',
'Lack of school uniform': 'Lack of school uniform',
'Lack of supplies at school': 'Lack of supplies at school',
'Lack of transport to school': 'Lack of transport to school',
'Lactating women': 'Lactating women',
'Lahar': 'Lahar',
'Landslide': 'Landslide',
'Language': 'Language',
'Last Name': 'Last Name',
'Last Synchronization': 'Last Synchronisation',
'Last known location': 'Last known location',
'Last name': 'Last name',
'Last status': 'Last status',
'Last synchronized on': 'Last synchronised on',
'Last updated ': 'Last updated ',
'Last updated by': 'Last updated by',
'Last updated on': 'Last updated on',
'Latitude': 'Latitude',
'Latitude & Longitude': 'Latitude & Longitude',
'Latitude is North-South (Up-Down).': 'Latitude is North-South (Up-Down).',
'Latitude is zero on the equator and positive in the northern hemisphere and negative in the southern hemisphere.': 'Latitude is zero on the equator and positive in the northern hemisphere and negative in the southern hemisphere.',
'Latitude of Map Center': 'Latitude of Map Center',
'Latitude of far northern end of the region of interest.': 'Latitude of far northern end of the region of interest.',
'Latitude of far southern end of the region of interest.': 'Latitude of far southern end of the region of interest.',
'Latitude should be between': 'Latitude should be between',
'Latrines': 'Latrines',
'Law enforcement, military, homeland and local/private security': 'Law enforcement, military, homeland and local/private security',
'Layer Details': 'Layer Details',
'Layer ID': 'Layer ID',
'Layer Name': 'Layer Name',
'Layer Type': 'Layer Type',
'Layer added': 'Layer added',
'Layer deleted': 'Layer deleted',
'Layer has been Disabled': 'Layer has been Disabled',
'Layer has been Enabled': 'Layer has been Enabled',
'Layer updated': 'Layer updated',
'Layers': 'Layers',
'Layers updated': 'Layers updated',
'Leader': 'Leader',
'Leave blank to request an unskilled person': 'Leave blank to request an unskilled person',
'Legend Format': 'Legend Format',
'Length (m)': 'Length (m)',
'Level': 'Level',
'Level 1': 'Level 1',
'Level 1 Assessment Details': 'Level 1 Assessment Details',
'Level 1 Assessment added': 'Level 1 Assessment added',
'Level 1 Assessment deleted': 'Level 1 Assessment deleted',
'Level 1 Assessment updated': 'Level 1 Assessment updated',
'Level 1 Assessments': 'Level 1 Assessments',
'Level 2': 'Level 2',
'Level 2 Assessment Details': 'Level 2 Assessment Details',
'Level 2 Assessment added': 'Level 2 Assessment added',
'Level 2 Assessment deleted': 'Level 2 Assessment deleted',
'Level 2 Assessment updated': 'Level 2 Assessment updated',
'Level 2 Assessments': 'Level 2 Assessments',
'Level 2 or detailed engineering evaluation recommended': 'Level 2 or detailed engineering evaluation recommended',
"Level is higher than parent's": "Level is higher than parent's",
'Library support not available for OpenID': 'Library support not available for OpenID',
'License Number': 'License Number',
'License Plate': 'License Plate',
'LineString': 'LineString',
'List': 'List',
'List / Add Baseline Types': 'List / Add Baseline Types',
'List / Add Impact Types': 'List / Add Impact Types',
'List / Add Services': 'List / Add Services',
'List / Add Types': 'List / Add Types',
'List Activities': 'List Activities',
'List All': 'List All',
'List All Activity Types': 'List All Activity Types',
'List All Assets': 'List All Assets',
'List All Catalog Items': 'List All Catalogue Items',
'List All Catalogs & Add Items to Catalogs': 'List All Catalogues & Add Items to Catalogues',
'List All Commitments': 'List All Commitments',
'List All Entries': 'List All Entries',
'List All Item Categories': 'List All Item Categories',
'List All Items': 'List All Items',
'List All Memberships': 'List All Memberships',
'List All Orders': 'List All Orders',
'List All Project Sites': 'List All Project Sites',
'List All Projects': 'List All Projects',
'List All Received Shipments': 'List All Received Shipments',
'List All Records': 'List All Records',
'List All Requested Items': 'List All Requested Items',
'List All Requested Skills': 'List All Requested Skills',
'List All Requests': 'List All Requests',
'List All Sent Shipments': 'List All Sent Shipments',
'List All Vehicles': 'List All Vehicles',
'List Alternative Items': 'List Alternative Items',
'List Assessment Summaries': 'List Assessment Summaries',
'List Assessments': 'List Assessments',
'List Assets': 'List Assets',
'List Availability': 'List Availability',
'List Baseline Types': 'List Baseline Types',
'List Baselines': 'List Baselines',
'List Brands': 'List Brands',
'List Budgets': 'List Budgets',
'List Bundles': 'List Bundles',
'List Camp Services': 'List Camp Services',
'List Camp Types': 'List Camp Types',
'List Camps': 'List Camps',
'List Catalog Items': 'List Catalogue Items',
'List Catalogs': 'List Catalogues',
'List Certificates': 'List Certificates',
'List Certifications': 'List Certifications',
'List Checklists': 'List Checklists',
'List Cluster Subsectors': 'List Cluster Subsectors',
'List Clusters': 'List Clusters',
'List Commitment Items': 'List Commitment Items',
'List Commitments': 'List Commitments',
'List Committed People': 'List Committed People',
'List Competency Ratings': 'List Competency Ratings',
'List Contact Information': 'List Contact Information',
'List Contacts': 'List Contacts',
'List Course Certificates': 'List Course Certificates',
'List Courses': 'List Courses',
'List Credentials': 'List Credentials',
'List Current': 'List Current',
'List Documents': 'List Documents',
'List Donors': 'List Donors',
'List Events': 'List Events',
'List Facilities': 'List Facilities',
'List Feature Classes': 'List Feature Classes',
'List Feature Layers': 'List Feature Layers',
'List Flood Reports': 'List Flood Reports',
'List GPS data': 'List GPS data',
'List Groups': 'List Groups',
'List Groups/View Members': 'List Groups/View Members',
'List Homes': 'List Homes',
'List Hospitals': 'List Hospitals',
'List Human Resources': 'List Human Resources',
'List Identities': 'List Identities',
'List Images': 'List Images',
'List Impact Assessments': 'List Impact Assessments',
'List Impact Types': 'List Impact Types',
'List Impacts': 'List Impacts',
'List Import Files': 'List Import Files',
'List Incident Reports': 'List Incident Reports',
'List Incidents': 'List Incidents',
'List Item Categories': 'List Item Categories',
'List Item Packs': 'List Item Packs',
'List Items': 'List Items',
'List Items in Inventory': 'List Items in Inventory',
'List Job Roles': 'List Job Roles',
'List Jobs': 'List Jobs',
'List Kits': 'List Kits',
'List Layers': 'List Layers',
'List Level 1 Assessments': 'List Level 1 Assessments',
'List Level 1 assessments': 'List Level 1 assessments',
'List Level 2 Assessments': 'List Level 2 Assessments',
'List Level 2 assessments': 'List Level 2 assessments',
'List Locations': 'List Locations',
'List Log Entries': 'List Log Entries',
'List Map Configurations': 'List Map Configurations',
'List Markers': 'List Markers',
'List Members': 'List Members',
'List Memberships': 'List Memberships',
'List Messages': 'List Messages',
'List Missing Persons': 'List Missing Persons',
'List Missions': 'List Missions',
'List Need Types': 'List Need Types',
'List Needs': 'List Needs',
'List Offices': 'List Offices',
'List Order Items': 'List Order Items',
'List Orders': 'List Orders',
'List Organization Domains': 'List Organisation Domains',
'List Organizations': 'List Organisations',
'List Patients': 'List Patients',
'List Personal Effects': 'List Personal Effects',
'List Persons': 'List Persons',
'List Photos': 'List Photos',
'List Population Statistics': 'List Population Statistics',
'List Positions': 'List Positions',
'List Problems': 'List Problems',
'List Project Organizations': 'List Project Organisations',
'List Project Sites': 'List Project Sites',
'List Projections': 'List Projections',
'List Projects': 'List Projects',
'List Rapid Assessments': 'List Rapid Assessments',
'List Received Items': 'List Received Items',
'List Received Shipments': 'List Received Shipments',
'List Records': 'List Records',
'List Registrations': 'List Registrations',
'List Relatives': 'List Relatives',
'List Reports': 'List Reports',
'List Repositories': 'List Repositories',
'List Request Items': 'List Request Items',
'List Requested Skills': 'List Requested Skills',
'List Requests': 'List Requests',
'List Requests for Donations': 'List Requests for Donations',
'List Requests for Volunteers': 'List Requests for Volunteers',
'List Resources': 'List Resources',
'List Rivers': 'List Rivers',
'List Roles': 'List Roles',
'List Rooms': 'List Rooms',
'List Saved Searches': 'List Saved Searches',
'List Scenarios': 'List Scenarios',
'List Sections': 'List Sections',
'List Sectors': 'List Sectors',
'List Sent Items': 'List Sent Items',
'List Sent Shipments': 'List Sent Shipments',
'List Service Profiles': 'List Service Profiles',
'List Settings': 'List Settings',
'List Shelter Services': 'List Shelter Services',
'List Shelter Types': 'List Shelter Types',
'List Shelters': 'List Shelters',
'List Skill Equivalences': 'List Skill Equivalences',
'List Skill Provisions': 'List Skill Provisions',
'List Skill Types': 'List Skill Types',
'List Skills': 'List Skills',
'List Solutions': 'List Solutions',
'List Staff Types': 'List Staff Types',
'List Status': 'List Status',
'List Subscriptions': 'List Subscriptions',
'List Subsectors': 'List Subsectors',
'List Support Requests': 'List Support Requests',
'List Tasks': 'List Tasks',
'List Teams': 'List Teams',
'List Themes': 'List Themes',
'List Tickets': 'List Tickets',
'List Trainings': 'List Trainings',
'List Units': 'List Units',
'List Users': 'List Users',
'List Vehicle Details': 'List Vehicle Details',
'List Vehicles': 'List Vehicles',
'List Warehouses': 'List Warehouses',
'List all': 'List all',
'List all Assessment Answer': 'List all Assessment Answer',
'List all Assessment Questions': 'List all Assessment Questions',
'List all Assessment Series': 'List all Assessment Series',
'List all Assessment Templates': 'List all Assessment Templates',
'List all Completed Assessment': 'List all Completed Assessment',
'List all Question Meta-Data': 'List all Question Meta-Data',
'List all Template Sections': 'List all Template Sections',
'List available Scenarios': 'List available Scenarios',
'List of Assessment Answers': 'List of Assessment Answers',
'List of Assessment Questions': 'List of Assessment Questions',
'List of Assessment Series': 'List of Assessment Series',
'List of Assessment Templates': 'List of Assessment Templates',
'List of CSV files': 'List of CSV files',
'List of CSV files uploaded': 'List of CSV files uploaded',
'List of Completed Assessments': 'List of Completed Assessments',
'List of Items': 'List of Items',
'List of Missing Persons': 'List of Missing Persons',
'List of Question Meta-Data': 'List of Question Meta-Data',
'List of Reports': 'List of Reports',
'List of Requests': 'List of Requests',
'List of Selected Answers': 'List of Selected Answers',
'List of Spreadsheets': 'List of Spreadsheets',
'List of Spreadsheets uploaded': 'List of Spreadsheets uploaded',
'List of Template Sections': 'List of Template Sections',
'List of addresses': 'List of addresses',
'List unidentified': 'List unidentified',
'List/Add': 'List/Add',
'Lists "who is doing what & where". Allows relief agencies to coordinate their activities': 'Lists "who is doing what & where". Allows relief agencies to coordinate their activities',
'Live Help': 'Live Help',
'Livelihood': 'Livelihood',
'Load Cleaned Data into Database': 'Load Cleaned Data into Database',
'Load Raw File into Grid': 'Load Raw File into Grid',
'Load Search': 'Load Search',
'Loading': 'Loading',
'Local Name': 'Local Name',
'Local Names': 'Local Names',
'Location': 'Location',
'Location 1': 'Location 1',
'Location 2': 'Location 2',
'Location Details': 'Location Details',
'Location Hierarchy Level 0 Name': 'Location Hierarchy Level 0 Name',
'Location Hierarchy Level 1 Name': 'Location Hierarchy Level 1 Name',
'Location Hierarchy Level 2 Name': 'Location Hierarchy Level 2 Name',
'Location Hierarchy Level 3 Name': 'Location Hierarchy Level 3 Name',
'Location Hierarchy Level 4 Name': 'Location Hierarchy Level 4 Name',
'Location Hierarchy Level 5 Name': 'Location Hierarchy Level 5 Name',
'Location added': 'Location added',
'Location deleted': 'Location deleted',
'Location group cannot be a parent.': 'Location group cannot be a parent.',
'Location group cannot have a parent.': 'Location group cannot have a parent.',
'Location groups can be used in the Regions menu.': 'Location groups can be used in the Regions menu.',
'Location groups may be used to filter what is shown on the map and in search results to only entities covered by locations in the group.': 'Location groups may be used to filter what is shown on the map and in search results to only entities covered by locations in the group.',
'Location updated': 'Location updated',
'Location: ': 'Location: ',
'Locations': 'Locations',
'Locations of this level need to have a parent of level': 'Locations of this level need to have a parent of level',
'Lockdown': 'Lockdown',
'Log': 'Log',
'Log Entry': 'Log Entry',
'Log Entry Deleted': 'Log Entry Deleted',
'Log Entry Details': 'Log Entry Details',
'Log entry added': 'Log entry added',
'Log entry deleted': 'Log entry deleted',
'Log entry updated': 'Log entry updated',
'Login': 'Login',
'Logistics': 'Logistics',
'Logo': 'Logo',
'Logo file %s missing!': 'Logo file %s missing!',
'Logout': 'Logout',
'Longitude': 'Longitude',
'Longitude is West - East (sideways).': 'Longitude is West - East (sideways).',
'Longitude is West-East (sideways).': 'Longitude is West-East (sideways).',
'Longitude is zero on the prime meridian (Greenwich Mean Time) and is positive to the east, across Europe and Asia. Longitude is negative to the west, across the Atlantic and the Americas.': 'Longitude is zero on the prime meridian (Greenwich Mean Time) and is positive to the east, across Europe and Asia. Longitude is negative to the west, across the Atlantic and the Americas.',
'Longitude is zero on the prime meridian (through Greenwich, United Kingdom) and is positive to the east, across Europe and Asia. Longitude is negative to the west, across the Atlantic and the Americas.': 'Longitude is zero on the prime meridian (through Greenwich, United Kingdom) and is positive to the east, across Europe and Asia. Longitude is negative to the west, across the Atlantic and the Americas.',
'Longitude of Map Center': 'Longitude of Map Center',
'Longitude of far eastern end of the region of interest.': 'Longitude of far eastern end of the region of interest.',
'Longitude of far western end of the region of interest.': 'Longitude of far western end of the region of interest.',
'Longitude should be between': 'Longitude should be between',
'Looting': 'Looting',
'Lost': 'Lost',
'Lost Password': 'Lost Password',
'Low': 'Low',
'Magnetic Storm': 'Magnetic Storm',
'Major Damage': 'Major Damage',
'Major expenses': 'Major expenses',
'Major outward damage': 'Major outward damage',
'Make Commitment': 'Make Commitment',
'Make New Commitment': 'Make New Commitment',
'Make Request': 'Make Request',
'Make a Request for Donations': 'Make a Request for Donations',
'Make a Request for Volunteers': 'Make a Request for Volunteers',
'Make preparations per the <instruction>': 'Make preparations per the <instruction>',
'Male': 'Male',
'Manage Events': 'Manage Events',
'Manage Users & Roles': 'Manage Users & Roles',
'Manage Vehicles': 'Manage Vehicles',
'Manage requests for supplies, assets, staff or other resources. Matches against Inventories where supplies are requested.': 'Manage requests for supplies, assets, staff or other resources. Matches against Inventories where supplies are requested.',
'Manage requests of hospitals for assistance.': 'Manage requests of hospitals for assistance.',
'Manager': 'Manager',
'Mandatory. In GeoServer, this is the Layer Name. Within the WFS getCapabilities, this is the FeatureType Name part after the colon(:).': 'Mandatory. In GeoServer, this is the Layer Name. Within the WFS getCapabilities, this is the FeatureType Name part after the colon(:).',
'Mandatory. The URL to access the service.': 'Mandatory. The URL to access the service.',
'Manual Synchronization': 'Manual Synchronisation',
'Many': 'Many',
'Map': 'Map',
'Map Center Latitude': 'Map Center Latitude',
'Map Center Longitude': 'Map Center Longitude',
'Map Configuration': 'Map Configuration',
'Map Configuration Details': 'Map Configuration Details',
'Map Configuration added': 'Map Configuration added',
'Map Configuration deleted': 'Map Configuration deleted',
'Map Configuration removed': 'Map Configuration removed',
'Map Configuration updated': 'Map Configuration updated',
'Map Configurations': 'Map Configurations',
'Map Height': 'Map Height',
'Map Service Catalog': 'Map Service Catalogue',
'Map Settings': 'Map Settings',
'Map Viewing Client': 'Map Viewing Client',
'Map Width': 'Map Width',
'Map Zoom': 'Map Zoom',
'Map of Hospitals': 'Map of Hospitals',
'MapMaker Hybrid Layer': 'MapMaker Hybrid Layer',
'MapMaker Layer': 'MapMaker Layer',
'Maps': 'Maps',
'Marine Security': 'Marine Security',
'Marital Status': 'Marital Status',
'Marker': 'Marker',
'Marker Details': 'Marker Details',
'Marker added': 'Marker added',
'Marker deleted': 'Marker deleted',
'Marker updated': 'Marker updated',
'Markers': 'Markers',
'Master': 'Master',
'Master Message Log': 'Master Message Log',
'Master Message Log to process incoming reports & requests': 'Master Message Log to process incoming reports & requests',
'Match Percentage': 'Match Percentage',
'Match Requests': 'Match Requests',
'Match percentage indicates the % match between these two records': 'Match percentage indicates the % match between these two records',
'Match?': 'Match?',
'Matching Catalog Items': 'Matching Catalogue Items',
'Matching Items': 'Matching Items',
'Matching Records': 'Matching Records',
'Maximum Location Latitude': 'Maximum Location Latitude',
'Maximum Location Longitude': 'Maximum Location Longitude',
'Measure Area: Click the points around the polygon & end with a double-click': 'Measure Area: Click the points around the polygon & end with a double-click',
'Measure Length: Click the points along the path & end with a double-click': 'Measure Length: Click the points along the path & end with a double-click',
'Medical and public health': 'Medical and public health',
'Medium': 'Medium',
'Megabytes per Month': 'Megabytes per Month',
'Members': 'Members',
'Membership': 'Membership',
'Membership Details': 'Membership Details',
'Membership added': 'Membership added',
'Membership deleted': 'Membership deleted',
'Membership updated': 'Membership updated',
'Memberships': 'Memberships',
'Message': 'Message',
'Message Details': 'Message Details',
'Message Variable': 'Message Variable',
'Message added': 'Message added',
'Message deleted': 'Message deleted',
'Message updated': 'Message updated',
'Message variable': 'Message variable',
'Messages': 'Messages',
'Messaging': 'Messaging',
'Meteorite': 'Meteorite',
'Meteorological (inc. flood)': 'Meteorological (inc. flood)',
'Method used': 'Method used',
'Middle Name': 'Middle Name',
'Migrants or ethnic minorities': 'Migrants or ethnic minorities',
'Mileage': 'Mileage',
'Military': 'Military',
'Minimum Location Latitude': 'Minimum Location Latitude',
'Minimum Location Longitude': 'Minimum Location Longitude',
'Minimum shift time is 6 hours': 'Minimum shift time is 6 hours',
'Minor Damage': 'Minor Damage',
'Minor/None': 'Minor/None',
'Minorities participating in coping activities': 'Minorities participating in coping activities',
'Minute': 'Minute',
'Minutes must be a number between 0 and 60': 'Minutes must be a number between 0 and 60',
'Minutes per Month': 'Minutes per Month',
'Minutes should be a number greater than 0 and less than 60': 'Minutes should be a number greater than 0 and less than 60',
'Miscellaneous': 'Miscellaneous',
'Missing': 'Missing',
'Missing Person': 'Missing Person',
'Missing Person Details': 'Missing Person Details',
'Missing Person Registry': 'Missing Person Registry',
'Missing Persons': 'Missing Persons',
'Missing Persons Registry': 'Missing Persons Registry',
'Missing Persons Report': 'Missing Persons Report',
'Missing Report': 'Missing Report',
'Missing Senior Citizen': 'Missing Senior Citizen',
'Missing Vulnerable Person': 'Missing Vulnerable Person',
'Mission Details': 'Mission Details',
'Mission Record': 'Mission Record',
'Mission added': 'Mission added',
'Mission deleted': 'Mission deleted',
'Mission updated': 'Mission updated',
'Missions': 'Missions',
'Mobile': 'Mobile',
'Mobile Basic Assessment': 'Mobile Basic Assessment',
'Mobile Phone': 'Mobile Phone',
'Mode': 'Mode',
'Model/Type': 'Model/Type',
'Modem settings updated': 'Modem settings updated',
'Moderate': 'Moderate',
'Moderator': 'Moderator',
'Modify Information on groups and individuals': 'Modify Information on groups and individuals',
'Modifying data in spreadsheet before importing it to the database': 'Modifying data in spreadsheet before importing it to the database',
'Module': 'Module',
'Module provides access to information on current Flood Levels.': 'Module provides access to information on current Flood Levels.',
'Monday': 'Monday',
'Monthly Cost': 'Monthly Cost',
'Monthly Salary': 'Monthly Salary',
'Months': 'Months',
'Morgue': 'Morgue',
'Morgue Details': 'Morgue Details',
'Morgue Status': 'Morgue Status',
'Morgue Units Available': 'Morgue Units Available',
'Morgues': 'Morgues',
'Mosque': 'Mosque',
'Motorcycle': 'Motorcycle',
'Moustache': 'Moustache',
'MultiPolygon': 'MultiPolygon',
'Multiple': 'Multiple',
'Multiple Matches': 'Multiple Matches',
'Muslim': 'Muslim',
'Must a location have a parent location?': 'Must a location have a parent location?',
'My Cedar Bluff AL': 'My Cedar Bluff AL',
'My Details': 'My Details',
'My Tasks': 'My Tasks',
'N/A': 'N/A',
'NO': 'NO',
'NZSEE Level 1': 'NZSEE Level 1',
'NZSEE Level 2': 'NZSEE Level 2',
'Name': 'Name',
'Name and/or ID': 'Name and/or ID',
'Name field is required!': 'Name field is required!',
'Name of the file (& optional sub-path) located in static which should be used for the background of the header.': 'Name of the file (& optional sub-path) located in static which should be used for the background of the header.',
'Name of the file (& optional sub-path) located in static which should be used for the top-left image.': 'Name of the file (& optional sub-path) located in static which should be used for the top-left image.',
'Name of the file (& optional sub-path) located in views which should be used for footer.': 'Name of the file (& optional sub-path) located in views which should be used for footer.',
'Name of the person in local language and script (optional).': 'Name of the person in local language and script (optional).',
'Name of the repository (for you own reference)': 'Name of the repository (for you own reference)',
'Name, Org and/or ID': 'Name, Org and/or ID',
'Names can be added in multiple languages': 'Names can be added in multiple languages',
'National': 'National',
'National ID Card': 'National ID Card',
'National NGO': 'National NGO',
'Nationality': 'Nationality',
'Nationality of the person.': 'Nationality of the person.',
'Nautical Accident': 'Nautical Accident',
'Nautical Hijacking': 'Nautical Hijacking',
'Need Type': 'Need Type',
'Need Type Details': 'Need Type Details',
'Need Type added': 'Need Type added',
'Need Type deleted': 'Need Type deleted',
'Need Type updated': 'Need Type updated',
'Need Types': 'Need Types',
"Need a 'url' argument!": "Need a 'url' argument!",
'Need added': 'Need added',
'Need deleted': 'Need deleted',
'Need to be logged-in to be able to submit assessments': 'Need to be logged-in to be able to submit assessments',
'Need to configure Twitter Authentication': 'Need to configure Twitter Authentication',
'Need to specify a Budget!': 'Need to specify a Budget!',
'Need to specify a Kit!': 'Need to specify a Kit!',
'Need to specify a Resource!': 'Need to specify a Resource!',
'Need to specify a bundle!': 'Need to specify a bundle!',
'Need to specify a group!': 'Need to specify a group!',
'Need to specify a location to search for.': 'Need to specify a location to search for.',
'Need to specify a role!': 'Need to specify a role!',
'Need to specify a table!': 'Need to specify a table!',
'Need to specify a user!': 'Need to specify a user!',
'Need updated': 'Need updated',
'Needs': 'Needs',
'Needs Details': 'Needs Details',
'Needs Maintenance': 'Needs Maintenance',
'Needs to reduce vulnerability to violence': 'Needs to reduce vulnerability to violence',
'Negative Flow Isolation': 'Negative Flow Isolation',
'Neighborhood': 'Neighborhood',
'Neighbourhood': 'Neighbourhood',
'Neighbouring building hazard': 'Neighbouring building hazard',
'Neonatal ICU': 'Neonatal ICU',
'Neonatology': 'Neonatology',
'Network': 'Network',
'Neurology': 'Neurology',
'New': 'New',
'New Assessment': 'New Assessment',
'New Assessment reported from': 'New Assessment reported from',
'New Certificate': 'New Certificate',
'New Checklist': 'New Checklist',
'New Entry': 'New Entry',
'New Event': 'New Event',
'New Home': 'New Home',
'New Item Category': 'New Item Category',
'New Job Role': 'New Job Role',
'New Location': 'New Location',
'New Location Group': 'New Location Group',
'New Patient': 'New Patient',
'New Record': 'New Record',
'New Relative': 'New Relative',
'New Request': 'New Request',
'New Scenario': 'New Scenario',
'New Skill': 'New Skill',
'New Solution Choice': 'New Solution Choice',
'New Staff Member': 'New Staff Member',
'New Support Request': 'New Support Request',
'New Team': 'New Team',
'New Ticket': 'New Ticket',
'New Training Course': 'New Training Course',
'New Volunteer': 'New Volunteer',
'New cases in the past 24h': 'New cases in the past 24h',
'Next': 'Next',
'Next View': 'Next View',
'No': 'No',
'No Activities Found': 'No Activities Found',
'No Activities currently registered in this event': 'No Activities currently registered in this event',
'No Alternative Items currently registered': 'No Alternative Items currently registered',
'No Assessment Answers currently registered': 'No Assessment Answers currently registered',
'No Assessment Question currently registered': 'No Assessment Question currently registered',
'No Assessment Series currently registered': 'No Assessment Series currently registered',
'No Assessment Summaries currently registered': 'No Assessment Summaries currently registered',
'No Assessment Template currently registered': 'No Assessment Template currently registered',
'No Assessments currently registered': 'No Assessments currently registered',
'No Assets currently registered': 'No Assets currently registered',
'No Assets currently registered in this event': 'No Assets currently registered in this event',
'No Assets currently registered in this scenario': 'No Assets currently registered in this scenario',
'No Baseline Types currently registered': 'No Baseline Types currently registered',
'No Baselines currently registered': 'No Baselines currently registered',
'No Brands currently registered': 'No Brands currently registered',
'No Budgets currently registered': 'No Budgets currently registered',
'No Bundles currently registered': 'No Bundles currently registered',
'No Camp Services currently registered': 'No Camp Services currently registered',
'No Camp Types currently registered': 'No Camp Types currently registered',
'No Camps currently registered': 'No Camps currently registered',
'No Catalog Items currently registered': 'No Catalogue Items currently registered',
'No Catalogs currently registered': 'No Catalogues currently registered',
'No Checklist available': 'No Checklist available',
'No Cluster Subsectors currently registered': 'No Cluster Subsectors currently registered',
'No Clusters currently registered': 'No Clusters currently registered',
'No Commitment Items currently registered': 'No Commitment Items currently registered',
'No Commitments': 'No Commitments',
'No Completed Assessments currently registered': 'No Completed Assessments currently registered',
'No Credentials currently set': 'No Credentials currently set',
'No Details currently registered': 'No Details currently registered',
'No Documents currently attached to this request': 'No Documents currently attached to this request',
'No Documents found': 'No Documents found',
'No Donors currently registered': 'No Donors currently registered',
'No Events currently registered': 'No Events currently registered',
'No Facilities currently registered in this event': 'No Facilities currently registered in this event',
'No Facilities currently registered in this scenario': 'No Facilities currently registered in this scenario',
'No Feature Classes currently defined': 'No Feature Classes currently defined',
'No Feature Layers currently defined': 'No Feature Layers currently defined',
'No Flood Reports currently registered': 'No Flood Reports currently registered',
'No GPS data currently registered': 'No GPS data currently registered',
'No Groups currently defined': 'No Groups currently defined',
'No Groups currently registered': 'No Groups currently registered',
'No Homes currently registered': 'No Homes currently registered',
'No Hospitals currently registered': 'No Hospitals currently registered',
'No Human Resources currently registered in this event': 'No Human Resources currently registered in this event',
'No Human Resources currently registered in this scenario': 'No Human Resources currently registered in this scenario',
'No Identification Report Available': 'No Identification Report Available',
'No Identities currently registered': 'No Identities currently registered',
'No Image': 'No Image',
'No Images currently registered': 'No Images currently registered',
'No Impact Types currently registered': 'No Impact Types currently registered',
'No Impacts currently registered': 'No Impacts currently registered',
'No Import Files currently uploaded': 'No Import Files currently uploaded',
'No Incident Reports currently registered': 'No Incident Reports currently registered',
'No Incidents currently registered in this event': 'No Incidents currently registered in this event',
'No Incoming Shipments': 'No Incoming Shipments',
'No Inventories currently have suitable alternative items in stock': 'No Inventories currently have suitable alternative items in stock',
'No Inventories currently have this item in stock': 'No Inventories currently have this item in stock',
'No Item Categories currently registered': 'No Item Categories currently registered',
'No Item Packs currently registered': 'No Item Packs currently registered',
'No Items currently registered': 'No Items currently registered',
'No Items currently registered in this Inventory': 'No Items currently registered in this Inventory',
'No Kits currently registered': 'No Kits currently registered',
'No Level 1 Assessments currently registered': 'No Level 1 Assessments currently registered',
'No Level 2 Assessments currently registered': 'No Level 2 Assessments currently registered',
'No Locations currently available': 'No Locations currently available',
'No Locations currently registered': 'No Locations currently registered',
'No Map Configurations currently defined': 'No Map Configurations currently defined',
'No Map Configurations currently registered in this event': 'No Map Configurations currently registered in this event',
'No Map Configurations currently registered in this scenario': 'No Map Configurations currently registered in this scenario',
'No Markers currently available': 'No Markers currently available',
'No Match': 'No Match',
'No Matching Catalog Items': 'No Matching Catalogue Items',
'No Matching Items': 'No Matching Items',
'No Matching Records': 'No Matching Records',
'No Members currently registered': 'No Members currently registered',
'No Memberships currently defined': 'No Memberships currently defined',
'No Memberships currently registered': 'No Memberships currently registered',
'No Messages currently in Outbox': 'No Messages currently in Outbox',
'No Need Types currently registered': 'No Need Types currently registered',
'No Needs currently registered': 'No Needs currently registered',
'No Offices currently registered': 'No Offices currently registered',
'No Order Items currently registered': 'No Order Items currently registered',
'No Orders registered': 'No Orders registered',
'No Organization Domains currently registered': 'No Organisation Domains currently registered',
'No Organizations currently registered': 'No Organisations currently registered',
'No Organizations for this Project': 'No Organisations for this Project',
'No Packs for Item': 'No Packs for Item',
'No Patients currently registered': 'No Patients currently registered',
'No People currently committed': 'No People currently committed',
'No People currently registered in this camp': 'No People currently registered in this camp',
'No People currently registered in this shelter': 'No People currently registered in this shelter',
'No Persons currently registered': 'No Persons currently registered',
'No Persons currently reported missing': 'No Persons currently reported missing',
'No Persons found': 'No Persons found',
'No Photos found': 'No Photos found',
'No Picture': 'No Picture',
'No Population Statistics currently registered': 'No Population Statistics currently registered',
'No Presence Log Entries currently registered': 'No Presence Log Entries currently registered',
'No Problems currently defined': 'No Problems currently defined',
'No Projections currently defined': 'No Projections currently defined',
'No Projects currently registered': 'No Projects currently registered',
'No Question Meta-Data currently registered': 'No Question Meta-Data currently registered',
'No Rapid Assessments currently registered': 'No Rapid Assessments currently registered',
'No Ratings for Skill Type': 'No Ratings for Skill Type',
'No Received Items currently registered': 'No Received Items currently registered',
'No Received Shipments': 'No Received Shipments',
'No Records currently available': 'No Records currently available',
'No Relatives currently registered': 'No Relatives currently registered',
'No Request Items currently registered': 'No Request Items currently registered',
'No Requests': 'No Requests',
'No Requests for Donations': 'No Requests for Donations',
'No Requests for Volunteers': 'No Requests for Volunteers',
'No Rivers currently registered': 'No Rivers currently registered',
'No Roles currently defined': 'No Roles currently defined',
'No Rooms currently registered': 'No Rooms currently registered',
'No Scenarios currently registered': 'No Scenarios currently registered',
'No Search saved': 'No Search saved',
'No Sections currently registered': 'No Sections currently registered',
'No Sectors currently registered': 'No Sectors currently registered',
'No Sent Items currently registered': 'No Sent Items currently registered',
'No Sent Shipments': 'No Sent Shipments',
'No Settings currently defined': 'No Settings currently defined',
'No Shelter Services currently registered': 'No Shelter Services currently registered',
'No Shelter Types currently registered': 'No Shelter Types currently registered',
'No Shelters currently registered': 'No Shelters currently registered',
'No Skills currently requested': 'No Skills currently requested',
'No Solutions currently defined': 'No Solutions currently defined',
'No Staff Types currently registered': 'No Staff Types currently registered',
'No Subscription available': 'No Subscription available',
'No Subsectors currently registered': 'No Subsectors currently registered',
'No Support Requests currently registered': 'No Support Requests currently registered',
'No Tasks currently registered in this event': 'No Tasks currently registered in this event',
'No Tasks currently registered in this scenario': 'No Tasks currently registered in this scenario',
'No Teams currently registered': 'No Teams currently registered',
'No Template Section currently registered': 'No Template Section currently registered',
'No Themes currently defined': 'No Themes currently defined',
'No Tickets currently registered': 'No Tickets currently registered',
'No Users currently registered': 'No Users currently registered',
'No Vehicle Details currently defined': 'No Vehicle Details currently defined',
'No Vehicles currently registered': 'No Vehicles currently registered',
'No Warehouses currently registered': 'No Warehouses currently registered',
'No access at all': 'No access at all',
'No access to this record!': 'No access to this record!',
'No action recommended': 'No action recommended',
'No contact information available': 'No contact information available',
'No contact method found': 'No contact method found',
'No contacts currently registered': 'No contacts currently registered',
'No data in this table - cannot create PDF!': 'No data in this table - cannot create PDF!',
'No databases in this application': 'No databases in this application',
'No dead body reports available': 'No dead body reports available',
'No entries found': 'No entries found',
'No entry available': 'No entry available',
'No forms to the corresponding resource have been downloaded yet.': 'No forms to the corresponding resource have been downloaded yet.',
'No jobs configured': 'No jobs configured',
'No jobs configured yet': 'No jobs configured yet',
'No match': 'No match',
'No matching records found': 'No matching records found',
'No messages in the system': 'No messages in the system',
'No person record found for current user.': 'No person record found for current user.',
'No problem group defined yet': 'No problem group defined yet',
'No reports available.': 'No reports available.',
'No reports currently available': 'No reports currently available',
'No repositories configured': 'No repositories configured',
'No requests found': 'No requests found',
'No resources configured yet': 'No resources configured yet',
'No resources currently reported': 'No resources currently reported',
'No service profile available': 'No service profile available',
'No skills currently set': 'No skills currently set',
'No staff or volunteers currently registered': 'No staff or volunteers currently registered',
'No status information available': 'No status information available',
'No tasks currently assigned': 'No tasks currently assigned',
'No tasks currently registered': 'No tasks currently registered',
'No units currently registered': 'No units currently registered',
'No volunteer availability registered': 'No volunteer availability registered',
'Non-structural Hazards': 'Non-structural Hazards',
'None': 'None',
'None (no such record)': 'None (no such record)',
'Noodles': 'Noodles',
'Normal': 'Normal',
'Not Applicable': 'Not Applicable',
'Not Authorised!': 'Not Authorised!',
'Not Possible': 'Not Possible',
'Not authorised!': 'Not authorised!',
'Not installed or incorrectly configured.': 'Not installed or incorrectly configured.',
'Note that this list only shows active volunteers. To see all people registered in the system, search from this screen instead': 'Note that this list only shows active volunteers. To see all people registered in the system, search from this screen instead',
'Notes': 'Notes',
'Notice to Airmen': 'Notice to Airmen',
'Number of Patients': 'Number of Patients',
'Number of People Required': 'Number of People Required',
'Number of additional beds of that type expected to become available in this unit within the next 24 hours.': 'Number of additional beds of that type expected to become available in this unit within the next 24 hours.',
'Number of alternative places for studying': 'Number of alternative places for studying',
'Number of available/vacant beds of that type in this unit at the time of reporting.': 'Number of available/vacant beds of that type in this unit at the time of reporting.',
'Number of bodies found': 'Number of bodies found',
'Number of deaths during the past 24 hours.': 'Number of deaths during the past 24 hours.',
'Number of discharged patients during the past 24 hours.': 'Number of discharged patients during the past 24 hours.',
'Number of doctors': 'Number of doctors',
'Number of in-patients at the time of reporting.': 'Number of in-patients at the time of reporting.',
'Number of newly admitted patients during the past 24 hours.': 'Number of newly admitted patients during the past 24 hours.',
'Number of non-medical staff': 'Number of non-medical staff',
'Number of nurses': 'Number of nurses',
'Number of private schools': 'Number of private schools',
'Number of public schools': 'Number of public schools',
'Number of religious schools': 'Number of religious schools',
'Number of residential units': 'Number of residential units',
'Number of residential units not habitable': 'Number of residential units not habitable',
'Number of vacant/available beds in this hospital. Automatically updated from daily reports.': 'Number of vacant/available beds in this hospital. Automatically updated from daily reports.',
'Number of vacant/available units to which victims can be transported immediately.': 'Number of vacant/available units to which victims can be transported immediately.',
'Number or Label on the identification tag this person is wearing (if any).': 'Number or Label on the identification tag this person is wearing (if any).',
'Number or code used to mark the place of find, e.g. flag code, grid coordinates, site reference number or similar (if available)': 'Number or code used to mark the place of find, e.g. flag code, grid coordinates, site reference number or similar (if available)',
'Number/Percentage of affected population that is Female & Aged 0-5': 'Number/Percentage of affected population that is Female & Aged 0-5',
'Number/Percentage of affected population that is Female & Aged 13-17': 'Number/Percentage of affected population that is Female & Aged 13-17',
'Number/Percentage of affected population that is Female & Aged 18-25': 'Number/Percentage of affected population that is Female & Aged 18-25',
'Number/Percentage of affected population that is Female & Aged 26-60': 'Number/Percentage of affected population that is Female & Aged 26-60',
'Number/Percentage of affected population that is Female & Aged 6-12': 'Number/Percentage of affected population that is Female & Aged 6-12',
'Number/Percentage of affected population that is Female & Aged 61+': 'Number/Percentage of affected population that is Female & Aged 61+',
'Number/Percentage of affected population that is Male & Aged 0-5': 'Number/Percentage of affected population that is Male & Aged 0-5',
'Number/Percentage of affected population that is Male & Aged 13-17': 'Number/Percentage of affected population that is Male & Aged 13-17',
'Number/Percentage of affected population that is Male & Aged 18-25': 'Number/Percentage of affected population that is Male & Aged 18-25',
'Number/Percentage of affected population that is Male & Aged 26-60': 'Number/Percentage of affected population that is Male & Aged 26-60',
'Number/Percentage of affected population that is Male & Aged 6-12': 'Number/Percentage of affected population that is Male & Aged 6-12',
'Number/Percentage of affected population that is Male & Aged 61+': 'Number/Percentage of affected population that is Male & Aged 61+',
'Numeric Question:': 'Numeric Question:',
'Nursery Beds': 'Nursery Beds',
'Nutrition': 'Nutrition',
'Nutrition problems': 'Nutrition problems',
'OCR Form Review': 'OCR Form Review',
'OK': 'OK',
'OR Reason': 'OR Reason',
'OR Status': 'OR Status',
'OR Status Reason': 'OR Status Reason',
'Objectives': 'Objectives',
'Observer': 'Observer',
'Obsolete': 'Obsolete',
'Obstetrics/Gynecology': 'Obstetrics/Gynecology',
'Office': 'Office',
'Office Address': 'Office Address',
'Office Details': 'Office Details',
'Office Phone': 'Office Phone',
'Office added': 'Office added',
'Office deleted': 'Office deleted',
'Office updated': 'Office updated',
'Offices': 'Offices',
'Older people as primary caregivers of children': 'Older people as primary caregivers of children',
'Older people in care homes': 'Older people in care homes',
'Older people participating in coping activities': 'Older people participating in coping activities',
'Older person (>60 yrs)': 'Older person (>60 yrs)',
'On by default?': 'On by default?',
'On by default? (only applicable to Overlays)': 'On by default? (only applicable to Overlays)',
'One Time Cost': 'One Time Cost',
'One time cost': 'One time cost',
'One-time': 'One-time',
'One-time costs': 'One-time costs',
'Oops! Something went wrong...': 'Oops! Something went wrong...',
'Oops! something went wrong on our side.': 'Oops! something went wrong on our side.',
'Opacity (1 for opaque, 0 for fully-transparent)': 'Opacity (1 for opaque, 0 for fully-transparent)',
'Open': 'Open',
'Open area': 'Open area',
'Open recent': 'Open recent',
'Operating Rooms': 'Operating Rooms',
'Optical Character Recognition': 'Optical Character Recognition',
'Optical Character Recognition for reading the scanned handwritten paper forms.': 'Optical Character Recognition for reading the scanned handwritten paper forms.',
'Optional': 'Optional',
'Optional Subject to put into Email - can be used as a Security Password by the service provider': 'Optional Subject to put into Email - can be used as a Security Password by the service provider',
'Optional link to an Incident which this Assessment was triggered by.': 'Optional link to an Incident which this Assessment was triggered by.',
'Optional selection of a MapServer map.': 'Optional selection of a MapServer map.',
'Optional selection of a background color.': 'Optional selection of a background colour.',
'Optional selection of an alternate style.': 'Optional selection of an alternate style.',
'Optional. If you wish to style the features based on values of an attribute, select the attribute to use here.': 'Optional. If you wish to style the features based on values of an attribute, select the attribute to use here.',
'Optional. In GeoServer, this is the Workspace Namespace URI (not the name!). Within the WFS getCapabilities, this is the FeatureType Name part before the colon(:).': 'Optional. In GeoServer, this is the Workspace Namespace URI (not the name!). Within the WFS getCapabilities, this is the FeatureType Name part before the colon(:).',
'Optional. The name of an element whose contents should be a URL of an Image file put into Popups.': 'Optional. The name of an element whose contents should be a URL of an Image file put into Popups.',
'Optional. The name of an element whose contents should be put into Popups.': 'Optional. The name of an element whose contents should be put into Popups.',
"Optional. The name of the geometry column. In PostGIS this defaults to 'the_geom'.": "Optional. The name of the geometry column. In PostGIS this defaults to 'the_geom'.",
'Optional. The name of the schema. In Geoserver this has the form http://host_name/geoserver/wfs/DescribeFeatureType?version=1.1.0&;typename=workspace_name:layer_name.': 'Optional. The name of the schema. In Geoserver this has the form http://host_name/geoserver/wfs/DescribeFeatureType?version=1.1.0&;typename=workspace_name:layer_name.',
'Options': 'Options',
'Order': 'Order',
'Order Created': 'Order Created',
'Order Details': 'Order Details',
'Order Item Details': 'Order Item Details',
'Order Item updated': 'Order Item updated',
'Order Items': 'Order Items',
'Order canceled': 'Order canceled',
'Order updated': 'Order updated',
'Orders': 'Orders',
'Organization': 'Organisation',
'Organization Details': 'Organisation Details',
'Organization Domain Details': 'Organisation Domain Details',
'Organization Domain added': 'Organisation Domain added',
'Organization Domain deleted': 'Organisation Domain deleted',
'Organization Domain updated': 'Organisation Domain updated',
'Organization Domains': 'Organisation Domains',
'Organization Registry': 'Organisation Registry',
'Organization added': 'Organisation added',
'Organization added to Project': 'Organisation added to Project',
'Organization deleted': 'Organisation deleted',
'Organization removed from Project': 'Organisation removed from Project',
'Organization updated': 'Organisation updated',
'Organizational Development': 'Organisational Development',
'Organizations': 'Organisations',
'Origin': 'Origin',
'Origin of the separated children': 'Origin of the separated children',
'Other': 'Other',
'Other (describe)': 'Other (describe)',
'Other (specify)': 'Other (specify)',
'Other Evidence': 'Other Evidence',
'Other Faucet/Piped Water': 'Other Faucet/Piped Water',
'Other Isolation': 'Other Isolation',
'Other Name': 'Other Name',
'Other activities of boys 13-17yrs': 'Other activities of boys 13-17yrs',
'Other activities of boys 13-17yrs before disaster': 'Other activities of boys 13-17yrs before disaster',
'Other activities of boys <12yrs': 'Other activities of boys <12yrs',
'Other activities of boys <12yrs before disaster': 'Other activities of boys <12yrs before disaster',
'Other activities of girls 13-17yrs': 'Other activities of girls 13-17yrs',
'Other activities of girls 13-17yrs before disaster': 'Other activities of girls 13-17yrs before disaster',
'Other activities of girls<12yrs': 'Other activities of girls<12yrs',
'Other activities of girls<12yrs before disaster': 'Other activities of girls<12yrs before disaster',
'Other alternative infant nutrition in use': 'Other alternative infant nutrition in use',
'Other alternative places for study': 'Other alternative places for study',
'Other assistance needed': 'Other assistance needed',
'Other assistance, Rank': 'Other assistance, Rank',
'Other current health problems, adults': 'Other current health problems, adults',
'Other current health problems, children': 'Other current health problems, children',
'Other events': 'Other events',
'Other factors affecting school attendance': 'Other factors affecting school attendance',
'Other major expenses': 'Other major expenses',
'Other non-food items': 'Other non-food items',
'Other recommendations': 'Other recommendations',
'Other residential': 'Other residential',
'Other school assistance received': 'Other school assistance received',
'Other school assistance, details': 'Other school assistance, details',
'Other school assistance, source': 'Other school assistance, source',
'Other settings can only be set by editing a file on the server': 'Other settings can only be set by editing a file on the server',
'Other side dishes in stock': 'Other side dishes in stock',
'Other types of water storage containers': 'Other types of water storage containers',
'Other ways to obtain food': 'Other ways to obtain food',
'Outbound Mail settings are configured in models/000_config.py.': 'Outbound Mail settings are configured in models/000_config.py.',
'Outbox': 'Outbox',
'Outgoing SMS Handler': 'Outgoing SMS Handler',
'Outgoing SMS handler': 'Outgoing SMS handler',
'Overall Hazards': 'Overall Hazards',
'Overhead falling hazard': 'Overhead falling hazard',
'Overland Flow Flood': 'Overland Flow Flood',
'Overlays': 'Overlays',
'Owned Resources': 'Owned Resources',
'PAHO UID': 'PAHO UID',
'PDAM': 'PDAM',
'PDF File': 'PDF File',
'PIN': 'PIN',
'PIN number ': 'PIN number ',
'PL Women': 'PL Women',
'Pack': 'Pack',
'Packs': 'Packs',
'Page': 'Page',
'Pan Map: keep the left mouse button pressed and drag the map': 'Pan Map: keep the left mouse button pressed and drag the map',
'Parameters': 'Parameters',
'Parapets, ornamentation': 'Parapets, ornamentation',
'Parent': 'Parent',
'Parent Office': 'Parent Office',
"Parent level should be higher than this record's level. Parent level is": "Parent level should be higher than this record's level. Parent level is",
'Parent needs to be of the correct level': 'Parent needs to be of the correct level',
'Parent needs to be set': 'Parent needs to be set',
'Parent needs to be set for locations of level': 'Parent needs to be set for locations of level',
'Parents/Caregivers missing children': 'Parents/Caregivers missing children',
'Parking Area': 'Parking Area',
'Partial': 'Partial',
'Participant': 'Participant',
'Partner National Society': 'Partner National Society',
'Pass': 'Pass',
'Passport': 'Passport',
'Password': 'Password',
"Password fields don't match": "Password fields don't match",
'Password to use for authentication at the remote site': 'Password to use for authentication at the remote site',
'Path': 'Path',
'Pathology': 'Pathology',
'Patient': 'Patient',
'Patient Details': 'Patient Details',
'Patient Tracking': 'Patient Tracking',
'Patient added': 'Patient added',
'Patient deleted': 'Patient deleted',
'Patient updated': 'Patient updated',
'Patients': 'Patients',
'Pediatric ICU': 'Pediatric ICU',
'Pediatric Psychiatric': 'Pediatric Psychiatric',
'Pediatrics': 'Pediatrics',
'Pending': 'Pending',
'People': 'People',
'People Needing Food': 'People Needing Food',
'People Needing Shelter': 'People Needing Shelter',
'People Needing Water': 'People Needing Water',
'People Trapped': 'People Trapped',
'Performance Rating': 'Performance Rating',
'Person': 'Person',
'Person 1': 'Person 1',
'Person 1, Person 2 are the potentially duplicate records': 'Person 1, Person 2 are the potentially duplicate records',
'Person 2': 'Person 2',
'Person De-duplicator': 'Person De-duplicator',
'Person Details': 'Person Details',
'Person Name': 'Person Name',
'Person Registry': 'Person Registry',
'Person added': 'Person added',
'Person added to Commitment': 'Person added to Commitment',
'Person deleted': 'Person deleted',
'Person details updated': 'Person details updated',
'Person interviewed': 'Person interviewed',
'Person must be specified!': 'Person must be specified!',
'Person removed from Commitment': 'Person removed from Commitment',
'Person who has actually seen the person/group.': 'Person who has actually seen the person/group.',
'Person/Group': 'Person/Group',
'Personal Data': 'Personal Data',
'Personal Effects': 'Personal Effects',
'Personal Effects Details': 'Personal Effects Details',
'Personal Map': 'Personal Map',
'Personal Profile': 'Personal Profile',
'Personal impact of disaster': 'Personal impact of disaster',
'Persons': 'Persons',
'Persons in institutions': 'Persons in institutions',
'Persons with disability (mental)': 'Persons with disability (mental)',
'Persons with disability (physical)': 'Persons with disability (physical)',
'Phone': 'Phone',
'Phone 1': 'Phone 1',
'Phone 2': 'Phone 2',
'Phone number is required': 'Phone number is required',
"Phone number to donate to this organization's relief efforts.": "Phone number to donate to this organization's relief efforts.",
'Phone/Business': 'Phone/Business',
'Phone/Emergency': 'Phone/Emergency',
'Phone/Exchange (Switchboard)': 'Phone/Exchange (Switchboard)',
'Photo': 'Photo',
'Photo Details': 'Photo Details',
'Photo Taken?': 'Photo Taken?',
'Photo added': 'Photo added',
'Photo deleted': 'Photo deleted',
'Photo updated': 'Photo updated',
'Photograph': 'Photograph',
'Photos': 'Photos',
'Physical Description': 'Physical Description',
'Physical Safety': 'Physical Safety',
'Picture': 'Picture',
'Picture upload and finger print upload facility': 'Picture upload and finger print upload facility',
'Place': 'Place',
'Place of Recovery': 'Place of Recovery',
'Place on Map': 'Place on Map',
'Places for defecation': 'Places for defecation',
'Places the children have been sent to': 'Places the children have been sent to',
'Playing': 'Playing',
"Please come back after sometime if that doesn't help.": "Please come back after sometime if that doesn't help.",
'Please enter a first name': 'Please enter a first name',
'Please enter a number only': 'Please enter a number only',
'Please enter a site OR a location': 'Please enter a site OR a location',
'Please enter a valid email address': 'Please enter a valid email address',
'Please enter the first few letters of the Person/Group for the autocomplete.': 'Please enter the first few letters of the Person/Group for the autocomplete.',
'Please enter the recipient': 'Please enter the recipient',
'Please fill this!': 'Please fill this!',
'Please give an estimated figure about how many bodies have been found.': 'Please give an estimated figure about how many bodies have been found.',
'Please provide the URL of the page you are referring to, a description of what you expected to happen & what actually happened.': 'Please provide the URL of the page you are referring to, a description of what you expected to happen & what actually happened.',
'Please report here where you are:': 'Please report here where you are:',
'Please select': 'Please select',
'Please select another level': 'Please select another level',
'Please specify any problems and obstacles with the proper handling of the disease, in detail (in numbers, where appropriate). You may also add suggestions the situation could be improved.': 'Please specify any problems and obstacles with the proper handling of the disease, in detail (in numbers, where appropriate). You may also add suggestions the situation could be improved.',
'Please use this field to record any additional information, including a history of the record if it is updated.': 'Please use this field to record any additional information, including a history of the record if it is updated.',
'Please use this field to record any additional information, including any Special Needs.': 'Please use this field to record any additional information, including any Special Needs.',
'Please use this field to record any additional information, such as Ushahidi instance IDs. Include a history of the record if it is updated.': 'Please use this field to record any additional information, such as Ushahidi instance IDs. Include a history of the record if it is updated.',
'Pledge Support': 'Pledge Support',
'Point': 'Point',
'Poisoning': 'Poisoning',
'Poisonous Gas': 'Poisonous Gas',
'Police': 'Police',
'Pollution and other environmental': 'Pollution and other environmental',
'Polygon': 'Polygon',
'Polygon reference of the rating unit': 'Polygon reference of the rating unit',
'Poor': 'Poor',
'Population': 'Population',
'Population Statistic Details': 'Population Statistic Details',
'Population Statistic added': 'Population Statistic added',
'Population Statistic deleted': 'Population Statistic deleted',
'Population Statistic updated': 'Population Statistic updated',
'Population Statistics': 'Population Statistics',
'Population and number of households': 'Population and number of households',
'Popup Fields': 'Popup Fields',
'Popup Label': 'Popup Label',
'Porridge': 'Porridge',
'Port': 'Port',
'Port Closure': 'Port Closure',
'Portable App': 'Portable App',
'Portal at': 'Portal at',
'Portuguese': 'Portuguese',
'Portuguese (Brazil)': 'Portuguese (Brazil)',
'Position': 'Position',
'Position Catalog': 'Position Catalogue',
'Position Details': 'Position Details',
'Position added': 'Position added',
'Position deleted': 'Position deleted',
'Position updated': 'Position updated',
'Positions': 'Positions',
'Postcode': 'Postcode',
'Poultry': 'Poultry',
'Poultry restocking, Rank': 'Poultry restocking, Rank',
'Power Failure': 'Power Failure',
'Powered by Sahana Eden': 'Powered by Sahana Eden',
'Pre-cast connections': 'Pre-cast connections',
'Preferred Name': 'Preferred Name',
'Pregnant women': 'Pregnant women',
'Preliminary': 'Preliminary',
'Presence': 'Presence',
'Presence Condition': 'Presence Condition',
'Presence Log': 'Presence Log',
'Previous View': 'Previous View',
'Primary Occupancy': 'Primary Occupancy',
'Priority': 'Priority',
'Priority from 1 to 9. 1 is most preferred.': 'Priority from 1 to 9. 1 is most preferred.',
'Privacy': 'Privacy',
'Private': 'Private',
'Problem': 'Problem',
'Problem Administration': 'Problem Administration',
'Problem Details': 'Problem Details',
'Problem Group': 'Problem Group',
'Problem Title': 'Problem Title',
'Problem added': 'Problem added',
'Problem connecting to twitter.com - please refresh': 'Problem connecting to twitter.com - please refresh',
'Problem deleted': 'Problem deleted',
'Problem updated': 'Problem updated',
'Problems': 'Problems',
'Procedure': 'Procedure',
'Process Received Shipment': 'Process Received Shipment',
'Process Shipment to Send': 'Process Shipment to Send',
'Profile': 'Profile',
'Project': 'Project',
'Project Details': 'Project Details',
'Project Details including organizations': 'Project Details including organisations',
'Project Details including organizations and communities': 'Project Details including organisations and communities',
'Project Organization Details': 'Project Organisation Details',
'Project Organization updated': 'Project Organisation updated',
'Project Organizations': 'Project Organisations',
'Project Site': 'Project Site',
'Project Sites': 'Project Sites',
'Project Status': 'Project Status',
'Project Tracking': 'Project Tracking',
'Project added': 'Project added',
'Project deleted': 'Project deleted',
'Project updated': 'Project updated',
'Projection': 'Projection',
'Projection Details': 'Projection Details',
'Projection added': 'Projection added',
'Projection deleted': 'Projection deleted',
'Projection updated': 'Projection updated',
'Projections': 'Projections',
'Projects': 'Projects',
'Property reference in the council system': 'Property reference in the council system',
'Protection': 'Protection',
'Provide Metadata for your media files': 'Provide Metadata for your media files',
'Provide a password': 'Provide a password',
'Provide an optional sketch of the entire building or damage points. Indicate damage points.': 'Provide an optional sketch of the entire building or damage points. Indicate damage points.',
'Proxy Server URL': 'Proxy Server URL',
'Psychiatrics/Adult': 'Psychiatrics/Adult',
'Psychiatrics/Pediatric': 'Psychiatrics/Pediatric',
'Public': 'Public',
'Public Event': 'Public Event',
'Public and private transportation': 'Public and private transportation',
'Public assembly': 'Public assembly',
'Pull tickets from external feed': 'Pull tickets from external feed',
'Purchase Date': 'Purchase Date',
'Purpose': 'Purpose',
'Push tickets to external system': 'Push tickets to external system',
'Pyroclastic Flow': 'Pyroclastic Flow',
'Pyroclastic Surge': 'Pyroclastic Surge',
'Python Serial module not available within the running Python - this needs installing to activate the Modem': 'Python Serial module not available within the running Python - this needs installing to activate the Modem',
'Quantity': 'Quantity',
'Quantity Committed': 'Quantity Committed',
'Quantity Fulfilled': 'Quantity Fulfilled',
"Quantity in %s's Inventory": "Quantity in %s's Inventory",
'Quantity in Transit': 'Quantity in Transit',
'Quarantine': 'Quarantine',
'Queries': 'Queries',
'Query': 'Query',
'Queryable?': 'Queryable?',
'Question': 'Question',
'Question Details': 'Question Details',
'Question Meta-Data': 'Question Meta-Data',
'Question Meta-Data Details': 'Question Meta-Data Details',
'Question Meta-Data added': 'Question Meta-Data added',
'Question Meta-Data deleted': 'Question Meta-Data deleted',
'Question Meta-Data updated': 'Question Meta-Data updated',
'Question Summary': 'Question Summary',
'RC frame with masonry infill': 'RC frame with masonry infill',
'RECORD A': 'RECORD A',
'RECORD B': 'RECORD B',
'RMS': 'RMS',
'RMS Team': 'RMS Team',
'Race': 'Race',
'Radio': 'Radio',
'Radio Details': 'Radio Details',
'Radiological Hazard': 'Radiological Hazard',
'Radiology': 'Radiology',
'Railway Accident': 'Railway Accident',
'Railway Hijacking': 'Railway Hijacking',
'Rain Fall': 'Rain Fall',
'Rapid Assessment': 'Rapid Assessment',
'Rapid Assessment Details': 'Rapid Assessment Details',
'Rapid Assessment added': 'Rapid Assessment added',
'Rapid Assessment deleted': 'Rapid Assessment deleted',
'Rapid Assessment updated': 'Rapid Assessment updated',
'Rapid Assessments': 'Rapid Assessments',
'Rapid Assessments & Flexible Impact Assessments': 'Rapid Assessments & Flexible Impact Assessments',
'Rapid Close Lead': 'Rapid Close Lead',
'Rapid Data Entry': 'Rapid Data Entry',
'Raw Database access': 'Raw Database access',
'Receive': 'Receive',
'Receive New Shipment': 'Receive New Shipment',
'Receive Shipment': 'Receive Shipment',
'Receive this shipment?': 'Receive this shipment?',
'Received': 'Received',
'Received By': 'Received By',
'Received By Person': 'Received By Person',
'Received Item Details': 'Received Item Details',
'Received Item updated': 'Received Item updated',
'Received Shipment Details': 'Received Shipment Details',
'Received Shipment canceled': 'Received Shipment canceled',
'Received Shipment canceled and items removed from Inventory': 'Received Shipment canceled and items removed from Inventory',
'Received Shipment updated': 'Received Shipment updated',
'Received Shipments': 'Received Shipments',
'Receiving and Sending Items': 'Receiving and Sending Items',
'Recipient': 'Recipient',
'Recipients': 'Recipients',
'Recommendations for Repair and Reconstruction or Demolition': 'Recommendations for Repair and Reconstruction or Demolition',
'Record': 'Record',
'Record Details': 'Record Details',
'Record Saved': 'Record Saved',
'Record added': 'Record added',
'Record any restriction on use or entry': 'Record any restriction on use or entry',
'Record created': 'Record created',
'Record deleted': 'Record deleted',
'Record last updated': 'Record last updated',
'Record not found': 'Record not found',
'Record not found!': 'Record not found!',
'Record updated': 'Record updated',
'Recording and Assigning Assets': 'Recording and Assigning Assets',
'Recovery': 'Recovery',
'Recovery Request': 'Recovery Request',
'Recovery Request added': 'Recovery Request added',
'Recovery Request deleted': 'Recovery Request deleted',
'Recovery Request updated': 'Recovery Request updated',
'Recurring': 'Recurring',
'Recurring Cost': 'Recurring Cost',
'Recurring cost': 'Recurring cost',
'Recurring costs': 'Recurring costs',
'Red': 'Red',
'Red Cross / Red Crescent': 'Red Cross / Red Crescent',
'Reference Document': 'Reference Document',
'Refresh Rate (seconds)': 'Refresh Rate (seconds)',
'Region': 'Region',
'Region Location': 'Region Location',
'Regional': 'Regional',
'Register': 'Register',
'Register Person': 'Register Person',
'Register Person into this Camp': 'Register Person into this Camp',
'Register Person into this Shelter': 'Register Person into this Shelter',
'Register them as a volunteer': 'Register them as a volunteer',
'Registered People': 'Registered People',
'Registered users can': 'Registered users can',
'Registration': 'Registration',
'Registration Details': 'Registration Details',
'Registration added': 'Registration added',
'Registration entry deleted': 'Registration entry deleted',
'Registration is still pending approval from Approver (%s) - please wait until confirmation received.': 'Registration is still pending approval from Approver (%s) - please wait until confirmation received.',
'Registration key': 'Registration key',
'Registration updated': 'Registration updated',
'Rehabilitation/Long Term Care': 'Rehabilitation/Long Term Care',
'Reinforced masonry': 'Reinforced masonry',
'Rejected': 'Rejected',
'Relative Details': 'Relative Details',
'Relative added': 'Relative added',
'Relative deleted': 'Relative deleted',
'Relative updated': 'Relative updated',
'Relatives': 'Relatives',
'Relief': 'Relief',
'Relief Team': 'Relief Team',
'Religion': 'Religion',
'Religious': 'Religious',
'Religious Leader': 'Religious Leader',
'Relocate as instructed in the <instruction>': 'Relocate as instructed in the <instruction>',
'Remote Error': 'Remote Error',
'Remove': 'Remove',
'Remove Activity from this event': 'Remove Activity from this event',
'Remove Asset from this event': 'Remove Asset from this event',
'Remove Asset from this scenario': 'Remove Asset from this scenario',
'Remove Document from this request': 'Remove Document from this request',
'Remove Facility from this event': 'Remove Facility from this event',
'Remove Facility from this scenario': 'Remove Facility from this scenario',
'Remove Human Resource from this event': 'Remove Human Resource from this event',
'Remove Human Resource from this scenario': 'Remove Human Resource from this scenario',
'Remove Incident from this event': 'Remove Incident from this event',
'Remove Item from Inventory': 'Remove Item from Inventory',
'Remove Item from Order': 'Remove Item from Order',
'Remove Item from Shipment': 'Remove Item from Shipment',
'Remove Map Configuration from this event': 'Remove Map Configuration from this event',
'Remove Map Configuration from this scenario': 'Remove Map Configuration from this scenario',
'Remove Organization from Project': 'Remove Organisation from Project',
'Remove Person from Commitment': 'Remove Person from Commitment',
'Remove Skill': 'Remove Skill',
'Remove Skill from Request': 'Remove Skill from Request',
'Remove Task from this event': 'Remove Task from this event',
'Remove Task from this scenario': 'Remove Task from this scenario',
'Remove this asset from this event': 'Remove this asset from this event',
'Remove this asset from this scenario': 'Remove this asset from this scenario',
'Remove this facility from this event': 'Remove this facility from this event',
'Remove this facility from this scenario': 'Remove this facility from this scenario',
'Remove this human resource from this event': 'Remove this human resource from this event',
'Remove this human resource from this scenario': 'Remove this human resource from this scenario',
'Remove this task from this event': 'Remove this task from this event',
'Remove this task from this scenario': 'Remove this task from this scenario',
'Repair': 'Repair',
'Repaired': 'Repaired',
'Repeat your password': 'Repeat your password',
'Report': 'Report',
'Report Another Assessment...': 'Report Another Assessment...',
'Report Details': 'Report Details',
'Report Resource': 'Report Resource',
'Report To': 'Report To',
'Report Types Include': 'Report Types Include',
'Report added': 'Report added',
'Report deleted': 'Report deleted',
'Report my location': 'Report my location',
'Report the contributing factors for the current EMS status.': 'Report the contributing factors for the current EMS status.',
'Report the contributing factors for the current OR status.': 'Report the contributing factors for the current OR status.',
'Report them as found': 'Report them as found',
'Report them missing': 'Report them missing',
'Report updated': 'Report updated',
'ReportLab module not available within the running Python - this needs installing for PDF output!': 'ReportLab module not available within the running Python - this needs installing for PDF output!',
'Reported To': 'Reported To',
'Reporter': 'Reporter',
'Reporter Name': 'Reporter Name',
'Reporting on the projects in the region': 'Reporting on the projects in the region',
'Reports': 'Reports',
'Repositories': 'Repositories',
'Repository': 'Repository',
'Repository Base URL': 'Repository Base URL',
'Repository Configuration': 'Repository Configuration',
'Repository Name': 'Repository Name',
'Repository UUID': 'Repository UUID',
'Repository configuration deleted': 'Repository configuration deleted',
'Repository configuration updated': 'Repository configuration updated',
'Repository configured': 'Repository configured',
'Request': 'Request',
'Request Added': 'Request Added',
'Request Canceled': 'Request Canceled',
'Request Details': 'Request Details',
'Request From': 'Request From',
'Request Item': 'Request Item',
'Request Item Details': 'Request Item Details',
'Request Item added': 'Request Item added',
'Request Item deleted': 'Request Item deleted',
'Request Item from Available Inventory': 'Request Item from Available Inventory',
'Request Item updated': 'Request Item updated',
'Request Items': 'Request Items',
'Request New People': 'Request New People',
'Request Number': 'Request Number',
'Request Status': 'Request Status',
'Request Type': 'Request Type',
'Request Updated': 'Request Updated',
'Request added': 'Request added',
'Request deleted': 'Request deleted',
'Request for Account': 'Request for Account',
'Request for Donations Added': 'Request for Donations Added',
'Request for Donations Canceled': 'Request for Donations Canceled',
'Request for Donations Details': 'Request for Donations Details',
'Request for Donations Updated': 'Request for Donations Updated',
'Request for Role Upgrade': 'Request for Role Upgrade',
'Request for Volunteers Added': 'Request for Volunteers Added',
'Request for Volunteers Canceled': 'Request for Volunteers Canceled',
'Request for Volunteers Details': 'Request for Volunteers Details',
'Request for Volunteers Updated': 'Request for Volunteers Updated',
'Request updated': 'Request updated',
'Request, Response & Session': 'Request, Response & Session',
'Requested': 'Requested',
'Requested By': 'Requested By',
'Requested By Facility': 'Requested By Facility',
'Requested For': 'Requested For',
'Requested For Facility': 'Requested For Facility',
'Requested From': 'Requested From',
'Requested Items': 'Requested Items',
'Requested Skill Details': 'Requested Skill Details',
'Requested Skill updated': 'Requested Skill updated',
'Requested Skills': 'Requested Skills',
'Requester': 'Requester',
'Requests': 'Requests',
'Requests Management': 'Requests Management',
'Requests for Donations': 'Requests for Donations',
'Requests for Volunteers': 'Requests for Volunteers',
'Required Skills': 'Required Skills',
'Requires Login': 'Requires Login',
'Requires Login!': 'Requires Login!',
'Rescue and recovery': 'Rescue and recovery',
'Reset': 'Reset',
'Reset Password': 'Reset Password',
'Resolve': 'Resolve',
'Resolve link brings up a new screen which helps to resolve these duplicate records and update the database.': 'Resolve link brings up a new screen which helps to resolve these duplicate records and update the database.',
'Resource': 'Resource',
'Resource Configuration': 'Resource Configuration',
'Resource Details': 'Resource Details',
'Resource Mapping System': 'Resource Mapping System',
'Resource Mapping System account has been activated': 'Resource Mapping System account has been activated',
'Resource Name': 'Resource Name',
'Resource added': 'Resource added',
'Resource configuration deleted': 'Resource configuration deleted',
'Resource configuration updated': 'Resource configuration updated',
'Resource configured': 'Resource configured',
'Resource deleted': 'Resource deleted',
'Resource updated': 'Resource updated',
'Resources': 'Resources',
'Respiratory Infections': 'Respiratory Infections',
'Response': 'Response',
'Restricted Access': 'Restricted Access',
'Restricted Use': 'Restricted Use',
'Results': 'Results',
'Retail Crime': 'Retail Crime',
'Retrieve Password': 'Retrieve Password',
'Return': 'Return',
'Return to Request': 'Return to Request',
'Returned': 'Returned',
'Returned From': 'Returned From',
'Review Incoming Shipment to Receive': 'Review Incoming Shipment to Receive',
'Rice': 'Rice',
'Riot': 'Riot',
'River': 'River',
'River Details': 'River Details',
'River added': 'River added',
'River deleted': 'River deleted',
'River updated': 'River updated',
'Rivers': 'Rivers',
'Road Accident': 'Road Accident',
'Road Closed': 'Road Closed',
'Road Conditions': 'Road Conditions',
'Road Delay': 'Road Delay',
'Road Hijacking': 'Road Hijacking',
'Road Usage Condition': 'Road Usage Condition',
'Roads Layer': 'Roads Layer',
'Role': 'Role',
'Role Details': 'Role Details',
'Role Required': 'Role Required',
'Role Updated': 'Role Updated',
'Role added': 'Role added',
'Role deleted': 'Role deleted',
'Role updated': 'Role updated',
'Roles': 'Roles',
'Roles Permitted': 'Roles Permitted',
'Roof tile': 'Roof tile',
'Roofs, floors (vertical load)': 'Roofs, floors (vertical load)',
'Room': 'Room',
'Room Details': 'Room Details',
'Room added': 'Room added',
'Room deleted': 'Room deleted',
'Room updated': 'Room updated',
'Rooms': 'Rooms',
'Rows in table': 'Rows in table',
'Rows selected': 'Rows selected',
'Running Cost': 'Running Cost',
'Russian': 'Russian',
'SMS': 'SMS',
'SMS Modems (Inbound & Outbound)': 'SMS Modems (Inbound & Outbound)',
'SMS Outbound': 'SMS Outbound',
'SMS Settings': 'SMS Settings',
'SMS settings updated': 'SMS settings updated',
'SMTP to SMS settings updated': 'SMTP to SMS settings updated',
'Safe environment for vulnerable groups': 'Safe environment for vulnerable groups',
'Safety Assessment Form': 'Safety Assessment Form',
'Safety of children and women affected by disaster?': 'Safety of children and women affected by disaster?',
'Sahana Eden': 'Sahana Eden',
'Sahana Eden Humanitarian Management Platform': 'Sahana Eden Humanitarian Management Platform',
'Sahana Eden portable application generator': 'Sahana Eden portable application generator',
'Salted Fish': 'Salted Fish',
'Sanitation problems': 'Sanitation problems',
'Satellite': 'Satellite',
'Satellite Layer': 'Satellite Layer',
'Saturday': 'Saturday',
'Save': 'Save',
'Save Search': 'Save Search',
'Save: Default Lat, Lon & Zoom for the Viewport': 'Save: Default Lat, Lon & Zoom for the Viewport',
'Saved Search Details': 'Saved Search Details',
'Saved Search added': 'Saved Search added',
'Saved Search deleted': 'Saved Search deleted',
'Saved Search updated': 'Saved Search updated',
'Saved Searches': 'Saved Searches',
'Saved.': 'Saved.',
'Saving...': 'Saving...',
'Scale of Results': 'Scale of Results',
'Scanned Copy': 'Scanned Copy',
'Scanned Forms Upload': 'Scanned Forms Upload',
'Scenario': 'Scenario',
'Scenario Details': 'Scenario Details',
'Scenario added': 'Scenario added',
'Scenario deleted': 'Scenario deleted',
'Scenario updated': 'Scenario updated',
'Scenarios': 'Scenarios',
'Schedule': 'Schedule',
'Schedule synchronization jobs': 'Schedule synchronisation jobs',
'Schema': 'Schema',
'School': 'School',
'School Closure': 'School Closure',
'School Lockdown': 'School Lockdown',
'School Teacher': 'School Teacher',
'School activities': 'School activities',
'School assistance': 'School assistance',
'School attendance': 'School attendance',
'School destroyed': 'School destroyed',
'School heavily damaged': 'School heavily damaged',
'School tents received': 'School tents received',
'School tents, source': 'School tents, source',
'School used for other purpose': 'School used for other purpose',
'School/studying': 'School/studying',
'Search': 'Search',
'Search Activities': 'Search Activities',
'Search Activity Report': 'Search Activity Report',
'Search Addresses': 'Search Addresses',
'Search Alternative Items': 'Search Alternative Items',
'Search Assessment Summaries': 'Search Assessment Summaries',
'Search Assessments': 'Search Assessments',
'Search Asset Log': 'Search Asset Log',
'Search Assets': 'Search Assets',
'Search Baseline Type': 'Search Baseline Type',
'Search Baselines': 'Search Baselines',
'Search Brands': 'Search Brands',
'Search Budgets': 'Search Budgets',
'Search Bundles': 'Search Bundles',
'Search Camp Services': 'Search Camp Services',
'Search Camp Types': 'Search Camp Types',
'Search Camps': 'Search Camps',
'Search Catalog Items': 'Search Catalogue Items',
'Search Catalogs': 'Search Catalogues',
'Search Certificates': 'Search Certificates',
'Search Certifications': 'Search Certifications',
'Search Checklists': 'Search Checklists',
'Search Cluster Subsectors': 'Search Cluster Subsectors',
'Search Clusters': 'Search Clusters',
'Search Commitment Items': 'Search Commitment Items',
'Search Commitments': 'Search Commitments',
'Search Committed People': 'Search Committed People',
'Search Competency Ratings': 'Search Competency Ratings',
'Search Contact Information': 'Search Contact Information',
'Search Contacts': 'Search Contacts',
'Search Course Certificates': 'Search Course Certificates',
'Search Courses': 'Search Courses',
'Search Credentials': 'Search Credentials',
'Search Criteria': 'Search Criteria',
'Search Documents': 'Search Documents',
'Search Donors': 'Search Donors',
'Search Entries': 'Search Entries',
'Search Events': 'Search Events',
'Search Facilities': 'Search Facilities',
'Search Feature Class': 'Search Feature Class',
'Search Feature Layers': 'Search Feature Layers',
'Search Flood Reports': 'Search Flood Reports',
'Search GPS data': 'Search GPS data',
'Search Geonames': 'Search Geonames',
'Search Groups': 'Search Groups',
'Search Homes': 'Search Homes',
'Search Human Resources': 'Search Human Resources',
'Search Identity': 'Search Identity',
'Search Images': 'Search Images',
'Search Impact Type': 'Search Impact Type',
'Search Impacts': 'Search Impacts',
'Search Import Files': 'Search Import Files',
'Search Incident Reports': 'Search Incident Reports',
'Search Incidents': 'Search Incidents',
'Search Inventory Items': 'Search Inventory Items',
'Search Inventory items': 'Search Inventory items',
'Search Item Categories': 'Search Item Categories',
'Search Item Packs': 'Search Item Packs',
'Search Items': 'Search Items',
'Search Job Roles': 'Search Job Roles',
'Search Kits': 'Search Kits',
'Search Layers': 'Search Layers',
'Search Level': 'Search Level',
'Search Level 1 Assessments': 'Search Level 1 Assessments',
'Search Level 2 Assessments': 'Search Level 2 Assessments',
'Search Locations': 'Search Locations',
'Search Log Entry': 'Search Log Entry',
'Search Map Configurations': 'Search Map Configurations',
'Search Markers': 'Search Markers',
'Search Member': 'Search Member',
'Search Membership': 'Search Membership',
'Search Memberships': 'Search Memberships',
'Search Missions': 'Search Missions',
'Search Need Type': 'Search Need Type',
'Search Needs': 'Search Needs',
'Search Offices': 'Search Offices',
'Search Order Items': 'Search Order Items',
'Search Orders': 'Search Orders',
'Search Organization Domains': 'Search Organisation Domains',
'Search Organizations': 'Search Organisations',
'Search Patients': 'Search Patients',
'Search Personal Effects': 'Search Personal Effects',
'Search Persons': 'Search Persons',
'Search Photos': 'Search Photos',
'Search Population Statistics': 'Search Population Statistics',
'Search Positions': 'Search Positions',
'Search Problems': 'Search Problems',
'Search Project Organizations': 'Search Project Organisations',
'Search Projections': 'Search Projections',
'Search Projects': 'Search Projects',
'Search Rapid Assessments': 'Search Rapid Assessments',
'Search Received Items': 'Search Received Items',
'Search Received Shipments': 'Search Received Shipments',
'Search Records': 'Search Records',
'Search Registations': 'Search Registations',
'Search Relatives': 'Search Relatives',
'Search Report': 'Search Report',
'Search Request': 'Search Request',
'Search Request Items': 'Search Request Items',
'Search Requested Items': 'Search Requested Items',
'Search Requested Skills': 'Search Requested Skills',
'Search Requests': 'Search Requests',
'Search Requests for Donations': 'Search Requests for Donations',
'Search Requests for Volunteers': 'Search Requests for Volunteers',
'Search Resources': 'Search Resources',
'Search Rivers': 'Search Rivers',
'Search Roles': 'Search Roles',
'Search Rooms': 'Search Rooms',
'Search Saved Searches': 'Search Saved Searches',
'Search Scenarios': 'Search Scenarios',
'Search Sections': 'Search Sections',
'Search Sectors': 'Search Sectors',
'Search Sent Items': 'Search Sent Items',
'Search Sent Shipments': 'Search Sent Shipments',
'Search Service Profiles': 'Search Service Profiles',
'Search Settings': 'Search Settings',
'Search Shelter Services': 'Search Shelter Services',
'Search Shelter Types': 'Search Shelter Types',
'Search Shelters': 'Search Shelters',
'Search Skill Equivalences': 'Search Skill Equivalences',
'Search Skill Provisions': 'Search Skill Provisions',
'Search Skill Types': 'Search Skill Types',
'Search Skills': 'Search Skills',
'Search Solutions': 'Search Solutions',
'Search Staff Types': 'Search Staff Types',
'Search Staff or Volunteer': 'Search Staff or Volunteer',
'Search Status': 'Search Status',
'Search Subscriptions': 'Search Subscriptions',
'Search Subsectors': 'Search Subsectors',
'Search Support Requests': 'Search Support Requests',
'Search Tasks': 'Search Tasks',
'Search Teams': 'Search Teams',
'Search Themes': 'Search Themes',
'Search Tickets': 'Search Tickets',
'Search Trainings': 'Search Trainings',
'Search Twitter Tags': 'Search Twitter Tags',
'Search Units': 'Search Units',
'Search Users': 'Search Users',
'Search Vehicle Details': 'Search Vehicle Details',
'Search Vehicles': 'Search Vehicles',
'Search Volunteer Availability': 'Search Volunteer Availability',
'Search Warehouses': 'Search Warehouses',
'Search and Edit Group': 'Search and Edit Group',
'Search and Edit Individual': 'Search and Edit Individual',
'Search by organization.': 'Search by organisation.',
'Search for Job': 'Search for Job',
'Search for Repository': 'Search for Repository',
'Search for Resource': 'Search for Resource',
'Search for Staff or Volunteers': 'Search for Staff or Volunteers',
'Search for a Location by name, including local names.': 'Search for a Location by name, including local names.',
'Search for a Person': 'Search for a Person',
'Search for a Project': 'Search for a Project',
'Search for a shipment by looking for text in any field.': 'Search for a shipment by looking for text in any field.',
'Search for a shipment received between these dates': 'Search for a shipment received between these dates',
'Search for a vehicle by text.': 'Search for a vehicle by text.',
'Search for an Organization by name or acronym': 'Search for an Organisation by name or acronym',
'Search for an Organization by name or acronym.': 'Search for an Organisation by name or acronym.',
'Search for an asset by text.': 'Search for an asset by text.',
'Search for an item by Year of Manufacture.': 'Search for an item by Year of Manufacture.',
'Search for an item by brand.': 'Search for an item by brand.',
'Search for an item by catalog.': 'Search for an item by catalogue.',
'Search for an item by category.': 'Search for an item by category.',
'Search for an item by its code, name, model and/or comment.': 'Search for an item by its code, name, model and/or comment.',
'Search for an item by text.': 'Search for an item by text.',
'Search for an order by looking for text in any field.': 'Search for an order by looking for text in any field.',
'Search for an order expected between these dates': 'Search for an order expected between these dates',
'Search for asset by location.': 'Search for asset by location.',
'Search for office by location.': 'Search for office by location.',
'Search for office by organization.': 'Search for office by organisation.',
'Search for office by text.': 'Search for office by text.',
'Search for vehicle by location.': 'Search for vehicle by location.',
'Search for warehouse by location.': 'Search for warehouse by location.',
'Search for warehouse by organization.': 'Search for warehouse by organisation.',
'Search for warehouse by text.': 'Search for warehouse by text.',
'Search here for a person record in order to:': 'Search here for a person record in order to:',
'Search messages': 'Search messages',
'Searching for different groups and individuals': 'Searching for different groups and individuals',
'Secondary Server (Optional)': 'Secondary Server (Optional)',
'Seconds must be a number between 0 and 60': 'Seconds must be a number between 0 and 60',
'Section': 'Section',
'Section Details': 'Section Details',
'Section deleted': 'Section deleted',
'Section updated': 'Section updated',
'Sections': 'Sections',
'Sections that are part of this template': 'Sections that are part of this template',
'Sections that can be selected': 'Sections that can be selected',
'Sector': 'Sector',
'Sector Details': 'Sector Details',
'Sector added': 'Sector added',
'Sector deleted': 'Sector deleted',
'Sector updated': 'Sector updated',
'Sector(s)': 'Sector(s)',
'Sectors': 'Sectors',
'Security Required': 'Security Required',
'Security Status': 'Security Status',
'Security problems': 'Security problems',
'See All Entries': 'See All Entries',
'See a detailed description of the module on the Sahana Eden wiki': 'See a detailed description of the module on the Sahana Eden wiki',
'See all': 'See all',
'See the universally unique identifier (UUID) of this repository': 'See the universally unique identifier (UUID) of this repository',
'See unassigned recovery requests': 'See unassigned recovery requests',
'Select Existing Location': 'Select Existing Location',
'Select Items from the Request': 'Select Items from the Request',
'Select Items from this Inventory': 'Select Items from this Inventory',
'Select This Location': 'Select This Location',
"Select a Room from the list or click 'Add Room'": "Select a Room from the list or click 'Add Room'",
'Select a location': 'Select a location',
"Select a manager for status 'assigned'": "Select a manager for status 'assigned'",
'Select a range for the number of total beds': 'Select a range for the number of total beds',
'Select all that apply': 'Select all that apply',
'Select an Organization to see a list of offices': 'Select an Organisation to see a list of offices',
'Select the overlays for Assessments and Activities relating to each Need to identify the gap.': 'Select the overlays for Assessments and Activities relating to each Need to identify the gap.',
'Select the person assigned to this role for this project.': 'Select the person assigned to this role for this project.',
"Select this if all specific locations need a parent at the deepest level of the location hierarchy. For example, if 'district' is the smallest division in the hierarchy, then all specific locations would be required to have a district as a parent.": "Select this if all specific locations need a parent at the deepest level of the location hierarchy. For example, if 'district' is the smallest division in the hierarchy, then all specific locations would be required to have a district as a parent.",
"Select this if all specific locations need a parent location in the location hierarchy. This can assist in setting up a 'region' representing an affected area.": "Select this if all specific locations need a parent location in the location hierarchy. This can assist in setting up a 'region' representing an affected area.",
'Select to show this configuration in the menu.': 'Select to show this configuration in the menu.',
'Selected Answers': 'Selected Answers',
'Selected Jobs': 'Selected Jobs',
'Selects what type of gateway to use for outbound SMS': 'Selects what type of gateway to use for outbound SMS',
'Send': 'Send',
'Send Alerts using Email &/or SMS': 'Send Alerts using Email &/or SMS',
'Send Commitment as Shipment': 'Send Commitment as Shipment',
'Send New Shipment': 'Send New Shipment',
'Send Notification': 'Send Notification',
'Send Shipment': 'Send Shipment',
'Send a message to this person': 'Send a message to this person',
'Send from %s': 'Send from %s',
'Send message': 'Send message',
'Send new message': 'Send new message',
'Sends & Receives Alerts via Email & SMS': 'Sends & Receives Alerts via Email & SMS',
'Senior (50+)': 'Senior (50+)',
'Sent': 'Sent',
'Sent By': 'Sent By',
'Sent By Person': 'Sent By Person',
'Sent Item Details': 'Sent Item Details',
'Sent Item deleted': 'Sent Item deleted',
'Sent Item updated': 'Sent Item updated',
'Sent Shipment Details': 'Sent Shipment Details',
'Sent Shipment canceled': 'Sent Shipment canceled',
'Sent Shipment canceled and items returned to Inventory': 'Sent Shipment canceled and items returned to Inventory',
'Sent Shipment updated': 'Sent Shipment updated',
'Sent Shipments': 'Sent Shipments',
'Separated children, caregiving arrangements': 'Separated children, caregiving arrangements',
'Serial Number': 'Serial Number',
'Series': 'Series',
'Series Analysis': 'Series Analysis',
'Series Details': 'Series Details',
'Series Map': 'Series Map',
'Series Summary': 'Series Summary',
'Server': 'Server',
'Service Catalog': 'Service Catalogue',
'Service Due': 'Service Due',
'Service or Facility': 'Service or Facility',
'Service profile added': 'Service profile added',
'Service profile deleted': 'Service profile deleted',
'Service profile updated': 'Service profile updated',
'Services': 'Services',
'Services Available': 'Services Available',
'Set Base Site': 'Set Base Site',
'Set By': 'Set By',
'Set True to allow editing this level of the location hierarchy by users who are not MapAdmins.': 'Set True to allow editing this level of the location hierarchy by users who are not MapAdmins.',
'Setting Details': 'Setting Details',
'Setting added': 'Setting added',
'Setting deleted': 'Setting deleted',
'Setting updated': 'Setting updated',
'Settings': 'Settings',
'Settings updated': 'Settings updated',
'Settings were reset because authenticating with Twitter failed': 'Settings were reset because authenticating with Twitter failed',
'Settings which can be configured through the web interface are available here.': 'Settings which can be configured through the web interface are available here.',
'Severe': 'Severe',
'Severity': 'Severity',
'Share a common Marker (unless over-ridden at the Feature level)': 'Share a common Marker (unless over-ridden at the Feature level)',
'Shelter': 'Shelter',
'Shelter & Essential NFIs': 'Shelter & Essential NFIs',
'Shelter Details': 'Shelter Details',
'Shelter Name': 'Shelter Name',
'Shelter Registry': 'Shelter Registry',
'Shelter Service': 'Shelter Service',
'Shelter Service Details': 'Shelter Service Details',
'Shelter Service added': 'Shelter Service added',
'Shelter Service deleted': 'Shelter Service deleted',
'Shelter Service updated': 'Shelter Service updated',
'Shelter Services': 'Shelter Services',
'Shelter Type': 'Shelter Type',
'Shelter Type Details': 'Shelter Type Details',
'Shelter Type added': 'Shelter Type added',
'Shelter Type deleted': 'Shelter Type deleted',
'Shelter Type updated': 'Shelter Type updated',
'Shelter Types': 'Shelter Types',
'Shelter Types and Services': 'Shelter Types and Services',
'Shelter added': 'Shelter added',
'Shelter deleted': 'Shelter deleted',
'Shelter updated': 'Shelter updated',
'Shelter/NFI Assistance': 'Shelter/NFI Assistance',
'Shelters': 'Shelters',
'Shipment Created': 'Shipment Created',
'Shipment Items': 'Shipment Items',
'Shipment Items received by Inventory': 'Shipment Items received by Inventory',
'Shipment Items sent from Inventory': 'Shipment Items sent from Inventory',
'Shipment to Send': 'Shipment to Send',
'Shipments': 'Shipments',
'Shipments To': 'Shipments To',
'Shooting': 'Shooting',
'Short Assessment': 'Short Assessment',
'Short Description': 'Short Description',
'Show Checklist': 'Show Checklist',
'Show Map': 'Show Map',
'Show in Menu?': 'Show in Menu?',
'Show on Map': 'Show on Map',
'Show on map': 'Show on map',
'Show selected answers': 'Show selected answers',
'Showing latest entries first': 'Showing latest entries first',
'Sign-up for Account': 'Sign-up for Account',
'Single PDF File': 'Single PDF File',
'Site': 'Site',
'Site Administration': 'Site Administration',
'Sites': 'Sites',
'Situation Awareness & Geospatial Analysis': 'Situation Awareness & Geospatial Analysis',
'Sketch': 'Sketch',
'Skill': 'Skill',
'Skill Catalog': 'Skill Catalogue',
'Skill Details': 'Skill Details',
'Skill Equivalence': 'Skill Equivalence',
'Skill Equivalence Details': 'Skill Equivalence Details',
'Skill Equivalence added': 'Skill Equivalence added',
'Skill Equivalence deleted': 'Skill Equivalence deleted',
'Skill Equivalence updated': 'Skill Equivalence updated',
'Skill Equivalences': 'Skill Equivalences',
'Skill Provision': 'Skill Provision',
'Skill Provision Catalog': 'Skill Provision Catalogue',
'Skill Provision Details': 'Skill Provision Details',
'Skill Provision added': 'Skill Provision added',
'Skill Provision deleted': 'Skill Provision deleted',
'Skill Provision updated': 'Skill Provision updated',
'Skill Provisions': 'Skill Provisions',
'Skill Type': 'Skill Type',
'Skill Type Catalog': 'Skill Type Catalogue',
'Skill Type added': 'Skill Type added',
'Skill Type deleted': 'Skill Type deleted',
'Skill Type updated': 'Skill Type updated',
'Skill Types': 'Skill Types',
'Skill added': 'Skill added',
'Skill added to Request': 'Skill added to Request',
'Skill deleted': 'Skill deleted',
'Skill removed': 'Skill removed',
'Skill removed from Request': 'Skill removed from Request',
'Skill updated': 'Skill updated',
'Skills': 'Skills',
'Skills Catalog': 'Skills Catalogue',
'Skills Management': 'Skills Management',
'Skype ID': 'Skype ID',
'Slope failure, debris': 'Slope failure, debris',
'Small Trade': 'Small Trade',
'Smoke': 'Smoke',
'Snapshot': 'Snapshot',
'Snapshot Report': 'Snapshot Report',
'Snow Fall': 'Snow Fall',
'Snow Squall': 'Snow Squall',
'Soil bulging, liquefaction': 'Soil bulging, liquefaction',
'Solid waste': 'Solid waste',
'Solution': 'Solution',
'Solution Details': 'Solution Details',
'Solution Item': 'Solution Item',
'Solution added': 'Solution added',
'Solution deleted': 'Solution deleted',
'Solution updated': 'Solution updated',
'Solutions': 'Solutions',
'Some': 'Some',
'Sorry - the server has a problem, please try again later.': 'Sorry - the server has a problem, please try again later.',
'Sorry that location appears to be outside the area of the Parent.': 'Sorry that location appears to be outside the area of the Parent.',
'Sorry that location appears to be outside the area supported by this deployment.': 'Sorry that location appears to be outside the area supported by this deployment.',
'Sorry, I could not understand your request': 'Sorry, I could not understand your request',
'Sorry, only users with the MapAdmin role are allowed to create location groups.': 'Sorry, only users with the MapAdmin role are allowed to create location groups.',
'Sorry, only users with the MapAdmin role are allowed to edit these locations': 'Sorry, only users with the MapAdmin role are allowed to edit these locations',
'Sorry, something went wrong.': 'Sorry, something went wrong.',
'Sorry, that page is forbidden for some reason.': 'Sorry, that page is forbidden for some reason.',
'Sorry, that service is temporary unavailable.': 'Sorry, that service is temporary unavailable.',
'Sorry, there are no addresses to display': 'Sorry, there are no addresses to display',
"Sorry, things didn't get done on time.": "Sorry, things didn't get done on time.",
"Sorry, we couldn't find that page.": "Sorry, we couldn't find that page.",
'Source': 'Source',
'Source ID': 'Source ID',
'Source Time': 'Source Time',
'Sources of income': 'Sources of income',
'Space Debris': 'Space Debris',
'Spanish': 'Spanish',
'Special Ice': 'Special Ice',
'Special Marine': 'Special Marine',
'Specialized Hospital': 'Specialized Hospital',
'Specific Area (e.g. Building/Room) within the Location that this Person/Group is seen.': 'Specific Area (e.g. Building/Room) within the Location that this Person/Group is seen.',
'Specific locations need to have a parent of level': 'Specific locations need to have a parent of level',
'Specify a descriptive title for the image.': 'Specify a descriptive title for the image.',
'Specify the bed type of this unit.': 'Specify the bed type of this unit.',
'Specify the number of available sets': 'Specify the number of available sets',
'Specify the number of available units (adult doses)': 'Specify the number of available units (adult doses)',
'Specify the number of available units (litres) of Ringer-Lactate or equivalent solutions': 'Specify the number of available units (litres) of Ringer-Lactate or equivalent solutions',
'Specify the number of sets needed per 24h': 'Specify the number of sets needed per 24h',
'Specify the number of units (adult doses) needed per 24h': 'Specify the number of units (adult doses) needed per 24h',
'Specify the number of units (litres) of Ringer-Lactate or equivalent solutions needed per 24h': 'Specify the number of units (litres) of Ringer-Lactate or equivalent solutions needed per 24h',
'Speed': 'Speed',
'Spherical Mercator?': 'Spherical Mercator?',
'Spreadsheet Importer': 'Spreadsheet Importer',
'Spreadsheet uploaded': 'Spreadsheet uploaded',
'Spring': 'Spring',
'Squall': 'Squall',
'Staff': 'Staff',
'Staff & Volunteers': 'Staff & Volunteers',
'Staff ID': 'Staff ID',
'Staff Member Details': 'Staff Member Details',
'Staff Members': 'Staff Members',
'Staff Record': 'Staff Record',
'Staff Type Details': 'Staff Type Details',
'Staff Type added': 'Staff Type added',
'Staff Type deleted': 'Staff Type deleted',
'Staff Type updated': 'Staff Type updated',
'Staff Types': 'Staff Types',
'Staff and Volunteers': 'Staff and Volunteers',
'Staff and volunteers': 'Staff and volunteers',
'Staff member added': 'Staff member added',
'Staff present and caring for residents': 'Staff present and caring for residents',
'Staff2': 'Staff2',
'Staffing': 'Staffing',
'Stairs': 'Stairs',
'Start Date': 'Start Date',
'Start date': 'Start date',
'Start date and end date should have valid date values': 'Start date and end date should have valid date values',
'State': 'State',
'Stationery': 'Stationery',
'Status': 'Status',
'Status Report': 'Status Report',
'Status Updated': 'Status Updated',
'Status added': 'Status added',
'Status deleted': 'Status deleted',
'Status of clinical operation of the facility.': 'Status of clinical operation of the facility.',
'Status of general operation of the facility.': 'Status of general operation of the facility.',
'Status of morgue capacity.': 'Status of morgue capacity.',
'Status of operations of the emergency department of this hospital.': 'Status of operations of the emergency department of this hospital.',
'Status of security procedures/access restrictions in the hospital.': 'Status of security procedures/access restrictions in the hospital.',
'Status of the operating rooms of this hospital.': 'Status of the operating rooms of this hospital.',
'Status updated': 'Status updated',
'Steel frame': 'Steel frame',
'Stolen': 'Stolen',
'Store spreadsheets in the Eden database': 'Store spreadsheets in the Eden database',
'Storeys at and above ground level': 'Storeys at and above ground level',
'Storm Force Wind': 'Storm Force Wind',
'Storm Surge': 'Storm Surge',
'Stowaway': 'Stowaway',
'Strategy': 'Strategy',
'Street Address': 'Street Address',
'Streetview Enabled?': 'Streetview Enabled?',
'Strong Wind': 'Strong Wind',
'Structural': 'Structural',
'Structural Hazards': 'Structural Hazards',
'Style': 'Style',
'Style Field': 'Style Field',
'Style Values': 'Style Values',
'Subject': 'Subject',
'Submission successful - please wait': 'Submission successful - please wait',
'Submit': 'Submit',
'Submit New': 'Submit New',
'Submit New (full form)': 'Submit New (full form)',
'Submit New (triage)': 'Submit New (triage)',
'Submit a request for recovery': 'Submit a request for recovery',
'Submit new Level 1 assessment (full form)': 'Submit new Level 1 assessment (full form)',
'Submit new Level 1 assessment (triage)': 'Submit new Level 1 assessment (triage)',
'Submit new Level 2 assessment': 'Submit new Level 2 assessment',
'Subscribe': 'Subscribe',
'Subscription Details': 'Subscription Details',
'Subscription added': 'Subscription added',
'Subscription deleted': 'Subscription deleted',
'Subscription updated': 'Subscription updated',
'Subscriptions': 'Subscriptions',
'Subsector': 'Subsector',
'Subsector Details': 'Subsector Details',
'Subsector added': 'Subsector added',
'Subsector deleted': 'Subsector deleted',
'Subsector updated': 'Subsector updated',
'Subsectors': 'Subsectors',
'Subsistence Cost': 'Subsistence Cost',
'Suburb': 'Suburb',
'Suggest not changing this field unless you know what you are doing.': 'Suggest not changing this field unless you know what you are doing.',
'Summary': 'Summary',
'Summary by Administration Level': 'Summary by Administration Level',
'Summary by Question Type': 'Summary by Question Type',
'Summary of Responses within Series': 'Summary of Responses within Series',
'Sunday': 'Sunday',
'Supply Chain Management': 'Supply Chain Management',
'Supply Item Categories': 'Supply Item Categories',
'Support Request': 'Support Request',
'Support Requests': 'Support Requests',
'Supports the decision making of large groups of Crisis Management Experts by helping the groups create ranked list.': 'Supports the decision making of large groups of Crisis Management Experts by helping the groups create ranked list.',
'Surgery': 'Surgery',
'Survey Module': 'Survey Module',
'Surveys': 'Surveys',
'Symbology': 'Symbology',
'Synchronization': 'Synchronisation',
'Synchronization Job': 'Synchronisation Job',
'Synchronization Log': 'Synchronisation Log',
'Synchronization Schedule': 'Synchronisation Schedule',
'Synchronization Settings': 'Synchronisation Settings',
'Synchronization mode': 'Synchronisation mode',
'Synchronization settings updated': 'Synchronisation settings updated',
'Synchronize now': 'Synchronise now',
"System's Twitter account updated": "System's Twitter account updated",
'Table name of the resource to synchronize': 'Table name of the resource to synchronise',
'Tags': 'Tags',
'Take shelter in place or per <instruction>': 'Take shelter in place or per <instruction>',
'Task': 'Task',
'Task Details': 'Task Details',
'Task List': 'Task List',
'Task Status': 'Task Status',
'Task added': 'Task added',
'Task deleted': 'Task deleted',
'Task removed': 'Task removed',
'Task updated': 'Task updated',
'Tasks': 'Tasks',
'Team Description': 'Team Description',
'Team Details': 'Team Details',
'Team ID': 'Team ID',
'Team Leader': 'Team Leader',
'Team Member added': 'Team Member added',
'Team Members': 'Team Members',
'Team Name': 'Team Name',
'Team Type': 'Team Type',
'Team added': 'Team added',
'Team deleted': 'Team deleted',
'Team updated': 'Team updated',
'Teams': 'Teams',
'Technical testing only, all recipients disregard': 'Technical testing only, all recipients disregard',
'Telecommunications': 'Telecommunications',
'Telephone': 'Telephone',
'Telephone Details': 'Telephone Details',
'Telephony': 'Telephony',
'Tells GeoServer to do MetaTiling which reduces the number of duplicate labels.': 'Tells GeoServer to do MetaTiling which reduces the number of duplicate labels.',
'Temp folder %s not writable - unable to apply theme!': 'Temp folder %s not writable - unable to apply theme!',
'Template': 'Template',
'Template Name': 'Template Name',
'Template Section Details': 'Template Section Details',
'Template Section added': 'Template Section added',
'Template Section deleted': 'Template Section deleted',
'Template Section updated': 'Template Section updated',
'Template Sections': 'Template Sections',
'Template Summary': 'Template Summary',
'Template file %s not readable - unable to apply theme!': 'Template file %s not readable - unable to apply theme!',
'Templates': 'Templates',
'Term for the fifth-level within-country administrative division (e.g. a voting or postcode subdivision). This level is not often used.': 'Term for the fifth-level within-country administrative division (e.g. a voting or postcode subdivision). This level is not often used.',
'Term for the fourth-level within-country administrative division (e.g. Village, Neighborhood or Precinct).': 'Term for the fourth-level within-country administrative division (e.g. Village, Neighborhood or Precinct).',
'Term for the primary within-country administrative division (e.g. State or Province).': 'Term for the primary within-country administrative division (e.g. State or Province).',
'Term for the secondary within-country administrative division (e.g. District or County).': 'Term for the secondary within-country administrative division (e.g. District or County).',
'Term for the third-level within-country administrative division (e.g. City or Town).': 'Term for the third-level within-country administrative division (e.g. City or Town).',
'Term for the top-level administrative division (i.e. Country).': 'Term for the top-level administrative division (i.e. Country).',
'Terms of Service\n\nYou have to be eighteen or over to register as a volunteer.': 'Terms of Service\n\nYou have to be eighteen or over to register as a volunteer.',
'Terms of Service:': 'Terms of Service:',
'Territorial Authority': 'Territorial Authority',
'Terrorism': 'Terrorism',
'Tertiary Server (Optional)': 'Tertiary Server (Optional)',
'Text': 'Text',
'Text Color for Text blocks': 'Text Colour for Text blocks',
'Thank you for validating your email. Your user account is still pending for approval by the system administator (%s).You will get a notification by email when your account is activated.': 'Thank you for validating your email. Your user account is still pending for approval by the system administator (%s).You will get a notification by email when your account is activated.',
'Thanks for your assistance': 'Thanks for your assistance',
'The': 'The',
'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1 == db.table2.field2" results in a SQL JOIN.': 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1 == db.table2.field2" results in a SQL JOIN.',
'The Area which this Site is located within.': 'The Area which this Site is located within.',
'The Assessment Module stores assessment templates and allows responses to assessments for specific events to be collected and analysed': 'The Assessment Module stores assessment templates and allows responses to assessments for specific events to be collected and analysed',
'The Assessments module allows field workers to send in assessments.': 'The Assessments module allows field workers to send in assessments.',
'The Author of this Document (optional)': 'The Author of this Document (optional)',
'The Building Asssesments module allows building safety to be assessed, e.g. after an Earthquake.': 'The Building Asssesments module allows building safety to be assessed, e.g. after an Earthquake.',
'The Camp this Request is from': 'The Camp this Request is from',
'The Camp this person is checking into.': 'The Camp this person is checking into.',
'The Current Location of the Person/Group, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.': 'The Current Location of the Person/Group, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.',
"The Donor(s) for this project. Multiple values can be selected by holding down the 'Control' key.": "The Donor(s) for this project. Multiple values can be selected by holding down the 'Control' key.",
'The Email Address to which approval requests are sent (normally this would be a Group mail rather than an individual). If the field is blank then requests are approved automatically if the domain matches.': 'The Email Address to which approval requests are sent (normally this would be a Group mail rather than an individual). If the field is blank then requests are approved automatically if the domain matches.',
'The Incident Reporting System allows the General Public to Report Incidents & have these Tracked.': 'The Incident Reporting System allows the General Public to Report Incidents & have these Tracked.',
'The Location the Person has come from, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.': 'The Location the Person has come from, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.',
'The Location the Person is going to, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.': 'The Location the Person is going to, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.',
'The Media Library provides a catalog of digital media.': 'The Media Library provides a catalogue of digital media.',
'The Messaging Module is the main communications hub of the Sahana system. It is used to send alerts and/or messages using SMS & Email to various groups and individuals before, during and after a disaster.': 'The Messaging Module is the main communications hub of the Sahana system. It is used to send alerts and/or messages using SMS & Email to various groups and individuals before, during and after a disaster.',
'The Organization Registry keeps track of all the relief organizations working in the area.': 'The Organisation Registry keeps track of all the relief organisations working in the area.',
'The Patient Tracking system keeps track of all the evacuated patients & their relatives.': 'The Patient Tracking system keeps track of all the evacuated patients & their relatives.',
"The Project Tool can be used to record project Information and generate Who's Doing What Where Reports.": "The Project Tool can be used to record project Information and generate Who's Doing What Where Reports.",
'The Project Tracking module allows the creation of Activities to meet Gaps in Needs Assessments.': 'The Project Tracking module allows the creation of Activities to meet Gaps in Needs Assessments.',
'The Role this person plays within this hospital.': 'The Role this person plays within this hospital.',
'The Shelter Registry tracks all shelters and stores basic details regarding them. It collaborates with other modules to track people associated with a shelter, the services available etc.': 'The Shelter Registry tracks all shelters and stores basic details regarding them. It collaborates with other modules to track people associated with a shelter, the services available etc.',
'The Shelter this Request is from': 'The Shelter this Request is from',
'The Shelter this person is checking into.': 'The Shelter this person is checking into.',
'The URL for the GetCapabilities page of a Web Map Service (WMS) whose layers you want available via the Browser panel on the Map.': 'The URL for the GetCapabilities page of a Web Map Service (WMS) whose layers you want available via the Browser panel on the Map.',
"The URL of the image file. If you don't upload an image file, then you must specify its location here.": "The URL of the image file. If you don't upload an image file, then you must specify its location here.",
'The URL of your web gateway without the post parameters': 'The URL of your web gateway without the post parameters',
'The URL to access the service.': 'The URL to access the service.',
'The Unique Identifier (UUID) as assigned to this facility by the government.': 'The Unique Identifier (UUID) as assigned to this facility by the government.',
'The area is': 'The area is',
'The asset must be assigned to a site OR location.': 'The asset must be assigned to a site OR location.',
'The attribute which is used for the title of popups.': 'The attribute which is used for the title of popups.',
'The attribute within the KML which is used for the title of popups.': 'The attribute within the KML which is used for the title of popups.',
'The attribute(s) within the KML which are used for the body of popups. (Use a space between attributes)': 'The attribute(s) within the KML which are used for the body of popups. (Use a space between attributes)',
'The body height (crown to heel) in cm.': 'The body height (crown to heel) in cm.',
'The country the person usually lives in.': 'The country the person usually lives in.',
'The default Facility for which this person is acting.': 'The default Facility for which this person is acting.',
'The default Facility for which you are acting.': 'The default Facility for which you are acting.',
'The default Organization for whom this person is acting.': 'The default Organisation for whom this person is acting.',
'The default Organization for whom you are acting.': 'The default Organisation for whom you are acting.',
'The duplicate record will be deleted': 'The duplicate record will be deleted',
'The first or only name of the person (mandatory).': 'The first or only name of the person (mandatory).',
'The form of the URL is http://your/web/map/service?service=WMS&request=GetCapabilities where your/web/map/service stands for the URL path to the WMS.': 'The form of the URL is http://your/web/map/service?service=WMS&request=GetCapabilities where your/web/map/service stands for the URL path to the WMS.',
'The language you wish the site to be displayed in.': 'The language you wish the site to be displayed in.',
'The length is': 'The length is',
'The level at which Searches are filtered.': 'The level at which Searches are filtered.',
'The list of Brands are maintained by the Administrators.': 'The list of Brands are maintained by the Administrators.',
'The list of Catalogs are maintained by the Administrators.': 'The list of Catalogues are maintained by the Administrators.',
'The map will be displayed initially with this latitude at the center.': 'The map will be displayed initially with this latitude at the center.',
'The map will be displayed initially with this longitude at the center.': 'The map will be displayed initially with this longitude at the center.',
'The minimum number of characters is ': 'The minimum number of characters is ',
'The minimum number of features to form a cluster.': 'The minimum number of features to form a cluster.',
'The name to be used when calling for or directly addressing the person (optional).': 'The name to be used when calling for or directly addressing the person (optional).',
'The next screen will allow you to detail the number of people here & their needs.': 'The next screen will allow you to detail the number of people here & their needs.',
'The number of Units of Measure of the Alternative Items which is equal to One Unit of Measure of the Item': 'The number of Units of Measure of the Alternative Items which is equal to One Unit of Measure of the Item',
'The number of pixels apart that features need to be before they are clustered.': 'The number of pixels apart that features need to be before they are clustered.',
'The number of tiles around the visible map to download. Zero means that the 1st page loads faster, higher numbers mean subsequent panning is faster.': 'The number of tiles around the visible map to download. Zero means that the 1st page loads faster, higher numbers mean subsequent panning is faster.',
'The person at the location who is reporting this incident (optional)': 'The person at the location who is reporting this incident (optional)',
'The post variable containing the phone number': 'The post variable containing the phone number',
'The post variable on the URL used for sending messages': 'The post variable on the URL used for sending messages',
'The post variables other than the ones containing the message and the phone number': 'The post variables other than the ones containing the message and the phone number',
'The serial port at which the modem is connected - /dev/ttyUSB0, etc on linux and com1, com2, etc on Windows': 'The serial port at which the modem is connected - /dev/ttyUSB0, etc on linux and com1, com2, etc on Windows',
'The server did not receive a timely response from another server that it was accessing to fill the request by the browser.': 'The server did not receive a timely response from another server that it was accessing to fill the request by the browser.',
'The server received an incorrect response from another server that it was accessing to fill the request by the browser.': 'The server received an incorrect response from another server that it was accessing to fill the request by the browser.',
'The site where this position is based.': 'The site where this position is based.',
'The staff responsibile for Facilities can make Requests for assistance. Commitments can be made against these Requests however the requests remain open until the requestor confirms that the request is complete.': 'The staff responsibile for Facilities can make Requests for assistance. Commitments can be made against these Requests however the requests remain open until the requestor confirms that the request is complete.',
'The subject event no longer poses a threat or concern and any follow on action is described in <instruction>': 'The subject event no longer poses a threat or concern and any follow on action is described in <instruction>',
'The synchronization module allows the synchronization of data resources between Sahana Eden instances.': 'The synchronisation module allows the synchronisation of data resources between Sahana Eden instances.',
'The time at which the Event started.': 'The time at which the Event started.',
'The time difference between UTC and your timezone, specify as +HHMM for eastern or -HHMM for western timezones.': 'The time difference between UTC and your timezone, specify as +HHMM for eastern or -HHMM for western timezones.',
'The token associated with this application on': 'The token associated with this application on',
'The way in which an item is normally distributed': 'The way in which an item is normally distributed',
'The weight in kg.': 'The weight in kg.',
'Theme': 'Theme',
'Theme Details': 'Theme Details',
'Theme added': 'Theme added',
'Theme deleted': 'Theme deleted',
'Theme updated': 'Theme updated',
'Themes': 'Themes',
'There are errors': 'There are errors',
'There are insufficient items in the Inventory to send this shipment': 'There are insufficient items in the Inventory to send this shipment',
'There are multiple records at this location': 'There are multiple records at this location',
'There is no address for this person yet. Add new address.': 'There is no address for this person yet. Add new address.',
'There was a problem, sorry, please try again later.': 'There was a problem, sorry, please try again later.',
'These are settings for Inbound Mail.': 'These are settings for Inbound Mail.',
'These are the Incident Categories visible to normal End-Users': 'These are the Incident Categories visible to normal End-Users',
'These need to be added in Decimal Degrees.': 'These need to be added in Decimal Degrees.',
'They': 'They',
'This appears to be a duplicate of ': 'This appears to be a duplicate of ',
'This email address is already in use': 'This email address is already in use',
'This file already exists on the server as': 'This file already exists on the server as',
'This is appropriate if this level is under construction. To prevent accidental modification after this level is complete, this can be set to False.': 'This is appropriate if this level is under construction. To prevent accidental modification after this level is complete, this can be set to False.',
'This is the way to transfer data between machines as it maintains referential integrity.': 'This is the way to transfer data between machines as it maintains referential integrity.',
'This is the way to transfer data between machines as it maintains referential integrity...duplicate data should be removed manually 1st!': 'This is the way to transfer data between machines as it maintains referential integrity...duplicate data should be removed manually 1st!',
'This level is not open for editing.': 'This level is not open for editing.',
'This might be due to a temporary overloading or maintenance of the server.': 'This might be due to a temporary overloading or maintenance of the server.',
'This module allows Inventory Items to be Requested & Shipped between the Inventories of Facilities.': 'This module allows Inventory Items to be Requested & Shipped between the Inventories of Facilities.',
'This module allows you to manage Events - whether pre-planned (e.g. exercises) or Live Incidents. You can allocate appropriate Resources (Human, Assets & Facilities) so that these can be mobilized easily.': 'This module allows you to manage Events - whether pre-planned (e.g. exercises) or Live Incidents. You can allocate appropriate Resources (Human, Assets & Facilities) so that these can be mobilized easily.',
'This module allows you to plan scenarios for both Exercises & Events. You can allocate appropriate Resources (Human, Assets & Facilities) so that these can be mobilized easily.': 'This module allows you to plan scenarios for both Exercises & Events. You can allocate appropriate Resources (Human, Assets & Facilities) so that these can be mobilized easily.',
'This resource is already configured for this repository': 'This resource is already configured for this repository',
'This screen allows you to upload a collection of photos to the server.': 'This screen allows you to upload a collection of photos to the server.',
'This setting can only be controlled by the Administrator.': 'This setting can only be controlled by the Administrator.',
'This shipment has already been received.': 'This shipment has already been received.',
'This shipment has already been sent.': 'This shipment has already been sent.',
'This shipment has not been received - it has NOT been canceled because can still be edited.': 'This shipment has not been received - it has NOT been canceled because can still be edited.',
'This shipment has not been sent - it has NOT been canceled because can still be edited.': 'This shipment has not been sent - it has NOT been canceled because can still be edited.',
'This shipment will be confirmed as received.': 'This shipment will be confirmed as received.',
'Thunderstorm': 'Thunderstorm',
'Thursday': 'Thursday',
'Ticket': 'Ticket',
'Ticket Details': 'Ticket Details',
'Ticket ID': 'Ticket ID',
'Ticket added': 'Ticket added',
'Ticket deleted': 'Ticket deleted',
'Ticket updated': 'Ticket updated',
'Ticketing Module': 'Ticketing Module',
'Tickets': 'Tickets',
'Tiled': 'Tiled',
'Tilt-up concrete': 'Tilt-up concrete',
'Timber frame': 'Timber frame',
'Timeline': 'Timeline',
'Timeline Report': 'Timeline Report',
'Timestamp': 'Timestamp',
'Timestamps can be correlated with the timestamps on the photos to locate them on the map.': 'Timestamps can be correlated with the timestamps on the photos to locate them on the map.',
'Title': 'Title',
'Title to show for the Web Map Service panel in the Tools panel.': 'Title to show for the Web Map Service panel in the Tools panel.',
'To': 'To',
'To Location': 'To Location',
'To Person': 'To Person',
'To create a personal map configuration, click ': 'To create a personal map configuration, click ',
'To edit OpenStreetMap, you need to edit the OpenStreetMap settings in models/000_config.py': 'To edit OpenStreetMap, you need to edit the OpenStreetMap settings in models/000_config.py',
'To search by job title, enter any portion of the title. You may use % as wildcard.': 'To search by job title, enter any portion of the title. You may use % as wildcard.',
"To search by person name, enter any of the first, middle or last names, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all persons.": "To search by person name, enter any of the first, middle or last names, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all persons.",
"To search for a body, enter the ID tag number of the body. You may use % as wildcard. Press 'Search' without input to list all bodies.": "To search for a body, enter the ID tag number of the body. You may use % as wildcard. Press 'Search' without input to list all bodies.",
"To search for a hospital, enter any of the names or IDs of the hospital, or the organisation name or acronym, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all hospitals.": "To search for a hospital, enter any of the names or IDs of the hospital, or the organisation name or acronym, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all hospitals.",
"To search for a hospital, enter any of the names or IDs of the hospital, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all hospitals.": "To search for a hospital, enter any of the names or IDs of the hospital, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all hospitals.",
"To search for a location, enter the name. You may use % as wildcard. Press 'Search' without input to list all locations.": "To search for a location, enter the name. You may use % as wildcard. Press 'Search' without input to list all locations.",
"To search for a patient, enter any of the first, middle or last names, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all patients.": "To search for a patient, enter any of the first, middle or last names, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all patients.",
"To search for a person, enter any of the first, middle or last names and/or an ID number of a person, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all persons.": "To search for a person, enter any of the first, middle or last names and/or an ID number of a person, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all persons.",
"To search for an assessment, enter any portion the ticket number of the assessment. You may use % as wildcard. Press 'Search' without input to list all assessments.": "To search for an assessment, enter any portion the ticket number of the assessment. You may use % as wildcard. Press 'Search' without input to list all assessments.",
'To variable': 'To variable',
'Tools': 'Tools',
'Tornado': 'Tornado',
'Total': 'Total',
'Total # of Target Beneficiaries': 'Total # of Target Beneficiaries',
'Total # of households of site visited': 'Total # of households of site visited',
'Total Beds': 'Total Beds',
'Total Beneficiaries': 'Total Beneficiaries',
'Total Cost per Megabyte': 'Total Cost per Megabyte',
'Total Cost per Minute': 'Total Cost per Minute',
'Total Monthly': 'Total Monthly',
'Total Monthly Cost': 'Total Monthly Cost',
'Total Monthly Cost: ': 'Total Monthly Cost: ',
'Total One-time Costs': 'Total One-time Costs',
'Total Persons': 'Total Persons',
'Total Recurring Costs': 'Total Recurring Costs',
'Total Unit Cost': 'Total Unit Cost',
'Total Unit Cost: ': 'Total Unit Cost: ',
'Total Units': 'Total Units',
'Total gross floor area (square meters)': 'Total gross floor area (square meters)',
'Total number of beds in this hospital. Automatically updated from daily reports.': 'Total number of beds in this hospital. Automatically updated from daily reports.',
'Total number of houses in the area': 'Total number of houses in the area',
'Total number of schools in affected area': 'Total number of schools in affected area',
'Total population of site visited': 'Total population of site visited',
'Totals for Budget:': 'Totals for Budget:',
'Totals for Bundle:': 'Totals for Bundle:',
'Totals for Kit:': 'Totals for Kit:',
'Tourist Group': 'Tourist Group',
'Town': 'Town',
'Traces internally displaced people (IDPs) and their needs': 'Traces internally displaced people (IDPs) and their needs',
'Track with this Person?': 'Track with this Person?',
'Tracking of Patients': 'Tracking of Patients',
'Tracking of Projects, Activities and Tasks': 'Tracking of Projects, Activities and Tasks',
'Tracking of basic information on the location, facilities and size of the Shelters': 'Tracking of basic information on the location, facilities and size of the Shelters',
'Tracks the location, capacity and breakdown of victims in Shelters': 'Tracks the location, capacity and breakdown of victims in Shelters',
'Traffic Report': 'Traffic Report',
'Training': 'Training',
'Training Course Catalog': 'Training Course Catalogue',
'Training Details': 'Training Details',
'Training added': 'Training added',
'Training deleted': 'Training deleted',
'Training updated': 'Training updated',
'Trainings': 'Trainings',
'Transit': 'Transit',
'Transit Status': 'Transit Status',
'Transition Effect': 'Transition Effect',
'Transparent?': 'Transparent?',
'Transportation Required': 'Transportation Required',
'Transportation assistance, Rank': 'Transportation assistance, Rank',
'Trauma Center': 'Trauma Center',
'Travel Cost': 'Travel Cost',
'Tropical Storm': 'Tropical Storm',
'Tropo Messaging Token': 'Tropo Messaging Token',
'Tropo Voice Token': 'Tropo Voice Token',
'Tropo settings updated': 'Tropo settings updated',
'Truck': 'Truck',
'Try checking the URL for errors, maybe it was mistyped.': 'Try checking the URL for errors, maybe it was mistyped.',
'Try hitting refresh/reload button or trying the URL from the address bar again.': 'Try hitting refresh/reload button or trying the URL from the address bar again.',
'Try refreshing the page or hitting the back button on your browser.': 'Try refreshing the page or hitting the back button on your browser.',
'Tsunami': 'Tsunami',
'Tuesday': 'Tuesday',
'Twitter': 'Twitter',
'Twitter ID or #hashtag': 'Twitter ID or #hashtag',
'Twitter Settings': 'Twitter Settings',
'Type': 'Type',
'Type of Construction': 'Type of Construction',
'Type of water source before the disaster': 'Type of water source before the disaster',
"Type the first few characters of one of the Person's names.": "Type the first few characters of one of the Person's names.",
'UN': 'UN',
'URL': 'URL',
'URL of the default proxy server to connect to remote repositories (if required). If only some of the repositories require the use of a proxy server, you can configure this in the respective repository configuration.': 'URL of the default proxy server to connect to remote repositories (if required). If only some of the repositories require the use of a proxy server, you can configure this in the respective repository configuration.',
'URL of the proxy server to connect to this repository (leave empty for default proxy)': 'URL of the proxy server to connect to this repository (leave empty for default proxy)',
'UTC Offset': 'UTC Offset',
'UUID': 'UUID',
'Un-Repairable': 'Un-Repairable',
'Unable to parse CSV file!': 'Unable to parse CSV file!',
'Under which condition a local record shall be updated if it also has been modified locally since the last synchronization': 'Under which condition a local record shall be updated if it also has been modified locally since the last synchronisation',
'Under which conditions local records shall be updated': 'Under which conditions local records shall be updated',
'Understaffed': 'Understaffed',
'Unidentified': 'Unidentified',
'Unique identifier which THIS repository identifies itself with when sending synchronization requests.': 'Unique identifier which THIS repository identifies itself with when sending synchronisation requests.',
'Unit Cost': 'Unit Cost',
'Unit added': 'Unit added',
'Unit deleted': 'Unit deleted',
'Unit of Measure': 'Unit of Measure',
'Unit updated': 'Unit updated',
'United States Dollars': 'United States Dollars',
'Units': 'Units',
'Universally unique identifier for the local repository, needed to register the local repository at remote instances to allow push-synchronization.': 'Universally unique identifier for the local repository, needed to register the local repository at remote instances to allow push-synchronisation.',
'Unknown': 'Unknown',
'Unknown type of facility': 'Unknown type of facility',
'Unreinforced masonry': 'Unreinforced masonry',
'Unsafe': 'Unsafe',
'Unselect to disable the modem': 'Unselect to disable the modem',
'Unselect to disable this API service': 'Unselect to disable this API service',
'Unselect to disable this SMTP service': 'Unselect to disable this SMTP service',
'Unsent': 'Unsent',
'Unsubscribe': 'Unsubscribe',
'Unsupported data format!': 'Unsupported data format!',
'Unsupported method!': 'Unsupported method!',
'Update': 'Update',
'Update Activity Report': 'Update Activity Report',
'Update Cholera Treatment Capability Information': 'Update Cholera Treatment Capability Information',
'Update Method': 'Update Method',
'Update Policy': 'Update Policy',
'Update Request': 'Update Request',
'Update Service Profile': 'Update Service Profile',
'Update Status': 'Update Status',
'Update Task Status': 'Update Task Status',
'Update Unit': 'Update Unit',
'Update your current ordered list': 'Update your current ordered list',
'Updated By': 'Updated By',
'Upload Comma Separated Value File': 'Upload Comma Separated Value File',
'Upload Format': 'Upload Format',
'Upload Photos': 'Upload Photos',
'Upload Scanned OCR Form': 'Upload Scanned OCR Form',
'Upload Spreadsheet': 'Upload Spreadsheet',
'Upload Web2py portable build as a zip file': 'Upload Web2py portable build as a zip file',
'Upload a Assessment Template import file': 'Upload a Assessment Template import file',
'Upload a CSV file': 'Upload a CSV file',
'Upload a CSV file formatted according to the Template.': 'Upload a CSV file formatted according to the Template.',
'Upload a Question List import file': 'Upload a Question List import file',
'Upload a Spreadsheet': 'Upload a Spreadsheet',
'Upload an image file (bmp, gif, jpeg or png), max. 300x300 pixels!': 'Upload an image file (bmp, gif, jpeg or png), max. 300x300 pixels!',
'Upload an image file here.': 'Upload an image file here.',
"Upload an image file here. If you don't upload an image file, then you must specify its location in the URL field.": "Upload an image file here. If you don't upload an image file, then you must specify its location in the URL field.",
'Upload an image, such as a photo': 'Upload an image, such as a photo',
'Upload the Completed Assessments import file': 'Upload the Completed Assessments import file',
'Uploaded': 'Uploaded',
'Urban Fire': 'Urban Fire',
'Urban area': 'Urban area',
'Urdu': 'Urdu',
'Urgent': 'Urgent',
'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.',
'Use Geocoder for address lookups?': 'Use Geocoder for address lookups?',
'Use default': 'Use default',
'Use these links to download data that is currently in the database.': 'Use these links to download data that is currently in the database.',
'Use this to set the starting location for the Location Selector.': 'Use this to set the starting location for the Location Selector.',
'Used by IRS & Assess': 'Used by IRS & Assess',
'Used in onHover Tooltip & Cluster Popups to differentiate between types.': 'Used in onHover Tooltip & Cluster Popups to differentiate between types.',
'Used to build onHover Tooltip & 1st field also used in Cluster Popups to differentiate between records.': 'Used to build onHover Tooltip & 1st field also used in Cluster Popups to differentiate between records.',
'Used to check that latitude of entered locations is reasonable. May be used to filter lists of resources that have locations.': 'Used to check that latitude of entered locations is reasonable. May be used to filter lists of resources that have locations.',
'Used to check that longitude of entered locations is reasonable. May be used to filter lists of resources that have locations.': 'Used to check that longitude of entered locations is reasonable. May be used to filter lists of resources that have locations.',
'Used to import data from spreadsheets into the database': 'Used to import data from spreadsheets into the database',
'Used within Inventory Management, Request Management and Asset Management': 'Used within Inventory Management, Request Management and Asset Management',
'User': 'User',
'User %(id)s Logged-in': 'User %(id)s Logged-in',
'User %(id)s Registered': 'User %(id)s Registered',
'User Account has been Approved': 'User Account has been Approved',
'User Account has been Disabled': 'User Account has been Disabled',
'User Details': 'User Details',
'User Guidelines Synchronization': 'User Guidelines Synchronisation',
'User ID': 'User ID',
'User Management': 'User Management',
'User Profile': 'User Profile',
'User Requests': 'User Requests',
'User Updated': 'User Updated',
'User added': 'User added',
'User already has this role': 'User already has this role',
'User deleted': 'User deleted',
'User updated': 'User updated',
'Username': 'Username',
'Username to use for authentication at the remote site': 'Username to use for authentication at the remote site',
'Users': 'Users',
'Users removed': 'Users removed',
'Uses the REST Query Format defined in': 'Uses the REST Query Format defined in',
'Utilities': 'Utilities',
'Utility, telecommunication, other non-transport infrastructure': 'Utility, telecommunication, other non-transport infrastructure',
'Value': 'Value',
'Value per Pack': 'Value per Pack',
'Various Reporting functionalities': 'Various Reporting functionalities',
'Vehicle': 'Vehicle',
'Vehicle Crime': 'Vehicle Crime',
'Vehicle Details': 'Vehicle Details',
'Vehicle Details added': 'Vehicle Details added',
'Vehicle Details deleted': 'Vehicle Details deleted',
'Vehicle Details updated': 'Vehicle Details updated',
'Vehicle Management': 'Vehicle Management',
'Vehicle Types': 'Vehicle Types',
'Vehicle added': 'Vehicle added',
'Vehicle deleted': 'Vehicle deleted',
'Vehicle updated': 'Vehicle updated',
'Vehicles': 'Vehicles',
'Vehicles are assets with some extra details.': 'Vehicles are assets with some extra details.',
'Verification Status': 'Verification Status',
'Verified?': 'Verified?',
'Verify Password': 'Verify Password',
'Verify password': 'Verify password',
'Version': 'Version',
'Very Good': 'Very Good',
'Very High': 'Very High',
'Vietnamese': 'Vietnamese',
'View Alerts received using either Email or SMS': 'View Alerts received using either Email or SMS',
'View All': 'View All',
'View All Tickets': 'View All Tickets',
'View Error Tickets': 'View Error Tickets',
'View Fullscreen Map': 'View Fullscreen Map',
'View Image': 'View Image',
'View Items': 'View Items',
'View Location Details': 'View Location Details',
'View Outbox': 'View Outbox',
'View Picture': 'View Picture',
'View Results of completed and/or partially completed assessments': 'View Results of completed and/or partially completed assessments',
'View Settings': 'View Settings',
'View Tickets': 'View Tickets',
'View all log entries': 'View all log entries',
'View and/or update their details': 'View and/or update their details',
'View log entries per repository': 'View log entries per repository',
'View on Map': 'View on Map',
'View or update the status of a hospital.': 'View or update the status of a hospital.',
'View pending requests and pledge support.': 'View pending requests and pledge support.',
'View the hospitals on a map.': 'View the hospitals on a map.',
'View/Edit the Database directly': 'View/Edit the Database directly',
'Village': 'Village',
'Village Leader': 'Village Leader',
'Visual Recognition': 'Visual Recognition',
'Volcanic Ash Cloud': 'Volcanic Ash Cloud',
'Volcanic Event': 'Volcanic Event',
'Volume (m3)': 'Volume (m3)',
'Volunteer Availability': 'Volunteer Availability',
'Volunteer Details': 'Volunteer Details',
'Volunteer Information': 'Volunteer Information',
'Volunteer Management': 'Volunteer Management',
'Volunteer Project': 'Volunteer Project',
'Volunteer Record': 'Volunteer Record',
'Volunteer Request': 'Volunteer Request',
'Volunteer added': 'Volunteer added',
'Volunteer availability added': 'Volunteer availability added',
'Volunteer availability deleted': 'Volunteer availability deleted',
'Volunteer availability updated': 'Volunteer availability updated',
'Volunteers': 'Volunteers',
'Vote': 'Vote',
'Votes': 'Votes',
'WARNING': 'WARNING',
'WASH': 'WASH',
'Walking Only': 'Walking Only',
'Wall or other structural damage': 'Wall or other structural damage',
'Warehouse': 'Warehouse',
'Warehouse Details': 'Warehouse Details',
'Warehouse added': 'Warehouse added',
'Warehouse deleted': 'Warehouse deleted',
'Warehouse updated': 'Warehouse updated',
'Warehouses': 'Warehouses',
'WatSan': 'WatSan',
'Water Sanitation Hygiene': 'Water Sanitation Hygiene',
'Water collection': 'Water collection',
'Water gallon': 'Water gallon',
'Water storage containers in households': 'Water storage containers in households',
'Water supply': 'Water supply',
'Waterspout': 'Waterspout',
'We have tried': 'We have tried',
'Web API settings updated': 'Web API settings updated',
'Web Map Service Browser Name': 'Web Map Service Browser Name',
'Web Map Service Browser URL': 'Web Map Service Browser URL',
'Web2py executable zip file found - Upload to replace the existing file': 'Web2py executable zip file found - Upload to replace the existing file',
'Web2py executable zip file needs to be uploaded to use this function.': 'Web2py executable zip file needs to be uploaded to use this function.',
'Website': 'Website',
'Wednesday': 'Wednesday',
'Weight': 'Weight',
'Weight (kg)': 'Weight (kg)',
'Welcome to the': 'Welcome to the',
'Well-Known Text': 'Well-Known Text',
'What order to be contacted in.': 'What order to be contacted in.',
'What the Items will be used for': 'What the Items will be used for',
'Wheat': 'Wheat',
'When reports were entered': 'When reports were entered',
'Where Project is implemented, including activities and beneficiaries': 'Where Project is implemented, including activities and beneficiaries',
'Whether to accept unsolicited data transmissions from the repository': 'Whether to accept unsolicited data transmissions from the repository',
'Which methods to apply when importing data to the local repository': 'Which methods to apply when importing data to the local repository',
'Whiskers': 'Whiskers',
'Who is doing what and where': 'Who is doing what and where',
'Who usually collects water for the family?': 'Who usually collects water for the family?',
'Width (m)': 'Width (m)',
'Wild Fire': 'Wild Fire',<|fim▁hole|>'With best regards': 'With best regards',
'Women of Child Bearing Age': 'Women of Child Bearing Age',
'Women participating in coping activities': 'Women participating in coping activities',
'Women who are Pregnant or in Labour': 'Women who are Pregnant or in Labour',
'Womens Focus Groups': 'Womens Focus Groups',
'Wooden plank': 'Wooden plank',
'Wooden poles': 'Wooden poles',
'Working hours end': 'Working hours end',
'Working hours start': 'Working hours start',
'Working or other to provide money/food': 'Working or other to provide money/food',
'X-Ray': 'X-Ray',
'YES': 'YES',
"Yahoo Layers cannot be displayed if there isn't a valid API Key": "Yahoo Layers cannot be displayed if there isn't a valid API Key",
'Year': 'Year',
'Year built': 'Year built',
'Year of Manufacture': 'Year of Manufacture',
'Yellow': 'Yellow',
'Yes': 'Yes',
'You are a recovery team?': 'You are a recovery team?',
'You are attempting to delete your own account - are you sure you want to proceed?': 'You are attempting to delete your own account - are you sure you want to proceed?',
'You are currently reported missing!': 'You are currently reported missing!',
'You can click on the map below to select the Lat/Lon fields': 'You can click on the map below to select the Lat/Lon fields',
'You can select the Draw tool': 'You can select the Draw tool',
'You can set the modem settings for SMS here.': 'You can set the modem settings for SMS here.',
'You can use the Conversion Tool to convert from either GPS coordinates or Degrees/Minutes/Seconds.': 'You can use the Conversion Tool to convert from either GPS coordinates or Degrees/Minutes/Seconds.',
'You do not have permission for any facility to add an order.': 'You do not have permission for any facility to add an order.',
'You do not have permission for any facility to make a commitment.': 'You do not have permission for any facility to make a commitment.',
'You do not have permission for any facility to make a request.': 'You do not have permission for any facility to make a request.',
'You do not have permission for any facility to receive a shipment.': 'You do not have permission for any facility to receive a shipment.',
'You do not have permission for any facility to send a shipment.': 'You do not have permission for any facility to send a shipment.',
'You do not have permission for any site to add an inventory item.': 'You do not have permission for any site to add an inventory item.',
'You do not have permission to cancel this received shipment.': 'You do not have permission to cancel this received shipment.',
'You do not have permission to cancel this sent shipment.': 'You do not have permission to cancel this sent shipment.',
'You do not have permission to make this commitment.': 'You do not have permission to make this commitment.',
'You do not have permission to receive this shipment.': 'You do not have permission to receive this shipment.',
'You do not have permission to send a shipment from this site.': 'You do not have permission to send a shipment from this site.',
'You do not have permission to send this shipment.': 'You do not have permission to send this shipment.',
'You have a personal map configuration. To change your personal configuration, click ': 'You have a personal map configuration. To change your personal configuration, click ',
'You have found a dead body?': 'You have found a dead body?',
"You have unsaved changes. Click Cancel now, then 'Save' to save them. Click OK now to discard them.": "You have unsaved changes. Click Cancel now, then 'Save' to save them. Click OK now to discard them.",
"You haven't made any calculations": "You haven't made any calculations",
'You must be logged in to register volunteers.': 'You must be logged in to register volunteers.',
'You must be logged in to report persons missing or found.': 'You must be logged in to report persons missing or found.',
'You should edit Twitter settings in models/000_config.py': 'You should edit Twitter settings in models/000_config.py',
'Your current ordered list of solution items is shown below. You can change it by voting again.': 'Your current ordered list of solution items is shown below. You can change it by voting again.',
'Your post was added successfully.': 'Your post was added successfully.',
'Your request for Red Cross and Red Crescent Resource Mapping System (RMS) has been approved and you can now access the system at': 'Your request for Red Cross and Red Crescent Resource Mapping System (RMS) has been approved and you can now access the system at',
'ZIP Code': 'ZIP Code',
'Zero Hour': 'Zero Hour',
'Zinc roof': 'Zinc roof',
'Zoom': 'Zoom',
'Zoom In: click in the map or use the left mouse button and drag to create a rectangle': 'Zoom In: click in the map or use the left mouse button and drag to create a rectangle',
'Zoom Levels': 'Zoom Levels',
'Zoom Out: click in the map or use the left mouse button and drag to create a rectangle': 'Zoom Out: click in the map or use the left mouse button and drag to create a rectangle',
'Zoom to Current Location': 'Zoom to Current Location',
'Zoom to maximum map extent': 'Zoom to maximum map extent',
'access granted': 'access granted',
'active': 'active',
'added': 'added',
'allows a budget to be developed based on staff & equipment costs, including any admin overheads.': 'allows a budget to be developed based on staff & equipment costs, including any admin overheads.',
'allows for creation and management of assessments.': 'allows for creation and management of assessments.',
'always update': 'always update',
'an individual/team to do in 1-2 days': 'an individual/team to do in 1-2 days',
'assigned': 'assigned',
'average': 'average',
'black': 'black',
'blond': 'blond',
'blue': 'blue',
'brown': 'brown',
'business_damaged': 'business_damaged',
'by': 'by',
'by %(person)s': 'by %(person)s',
'c/o Name': 'c/o Name',
'can be used to extract data from spreadsheets and put them into database tables.': 'can be used to extract data from spreadsheets and put them into database tables.',
'cancelled': 'cancelled',
'caucasoid': 'caucasoid',
'check all': 'check all',
'click for more details': 'click for more details',
'click here': 'click here',
'completed': 'completed',
'consider': 'consider',
'curly': 'curly',
'currently registered': 'currently registered',
'dark': 'dark',
'data uploaded': 'data uploaded',
'database': 'database',
'database %s select': 'database %s select',
'days': 'days',
'db': 'db',
'deceased': 'deceased',
'delete all checked': 'delete all checked',
'deleted': 'deleted',
'design': 'design',
'diseased': 'diseased',
'displaced': 'displaced',
'divorced': 'divorced',
'done!': 'done!',
'duplicate': 'duplicate',
'edit': 'edit',
'eg. gas, electricity, water': 'eg. gas, electricity, water',
'enclosed area': 'enclosed area',
'enter a number between %(min)g and %(max)g': 'enter a number between %(min)g and %(max)g',
'enter an integer between %(min)g and %(max)g': 'enter an integer between %(min)g and %(max)g',
'export as csv file': 'export as csv file',
'fat': 'fat',
'feedback': 'feedback',
'female': 'female',
'flush latrine with septic tank': 'flush latrine with septic tank',
'food_sources': 'food_sources',
'forehead': 'forehead',
'form data': 'form data',
'found': 'found',
'from Twitter': 'from Twitter',
'getting': 'getting',
'green': 'green',
'grey': 'grey',
'here': 'here',
'hours': 'hours',
'households': 'households',
'identified': 'identified',
'ignore': 'ignore',
'in Deg Min Sec format': 'in Deg Min Sec format',
'in GPS format': 'in GPS format',
'in Inv.': 'in Inv.',
'inactive': 'inactive',
'injured': 'injured',
'insert new': 'insert new',
'insert new %s': 'insert new %s',
'invalid': 'invalid',
'invalid request': 'invalid request',
'is a central online repository where information on all the disaster victims and families, especially identified casualties, evacuees and displaced people can be stored. Information like name, age, contact number, identity card number, displaced location, and other details are captured. Picture and finger print details of the people can be uploaded to the system. People can also be captured by group for efficiency and convenience.': 'is a central online repository where information on all the disaster victims and families, especially identified casualties, evacuees and displaced people can be stored. Information like name, age, contact number, identity card number, displaced location, and other details are captured. Picture and finger print details of the people can be uploaded to the system. People can also be captured by group for efficiency and convenience.',
'keeps track of all incoming tickets allowing them to be categorised & routed to the appropriate place for actioning.': 'keeps track of all incoming tickets allowing them to be categorised & routed to the appropriate place for actioning.',
'latrines': 'latrines',
'leave empty to detach account': 'leave empty to detach account',
'legend URL': 'legend URL',
'light': 'light',
'login': 'login',
'long': 'long',
'long>12cm': 'long>12cm',
'male': 'male',
'married': 'married',
'maxExtent': 'maxExtent',
'maxResolution': 'maxResolution',
'medium': 'medium',
'medium<12cm': 'medium<12cm',
'meters': 'meters',
'minutes': 'minutes',
'missing': 'missing',
'module allows the site administrator to configure various options.': 'module allows the site administrator to configure various options.',
'module helps monitoring the status of hospitals.': 'module helps monitoring the status of hospitals.',
'mongoloid': 'mongoloid',
'more': 'more',
'negroid': 'negroid',
'never': 'never',
'never update': 'never update',
'new': 'new',
'new record inserted': 'new record inserted',
'next 100 rows': 'next 100 rows',
'no': 'no',
'none': 'none',
'not specified': 'not specified',
'obsolete': 'obsolete',
'on': 'on',
'on %(date)s': 'on %(date)s',
'open defecation': 'open defecation',
'optional': 'optional',
'or import from csv file': 'or import from csv file',
'other': 'other',
'over one hour': 'over one hour',
'people': 'people',
'piece': 'piece',
'pit': 'pit',
'pit latrine': 'pit latrine',
'postponed': 'postponed',
'preliminary template or draft, not actionable in its current form': 'preliminary template or draft, not actionable in its current form',
'previous 100 rows': 'previous 100 rows',
'pull': 'pull',
'pull and push': 'pull and push',
'push': 'push',
'record does not exist': 'record does not exist',
'record id': 'record id',
'red': 'red',
'replace': 'replace',
'reports successfully imported.': 'reports successfully imported.',
'representation of the Polygon/Line.': 'representation of the Polygon/Line.',
'retired': 'retired',
'retry': 'retry',
'river': 'river',
'see comment': 'see comment',
'selected': 'selected',
'separated': 'separated',
'separated from family': 'separated from family',
'shaved': 'shaved',
'short': 'short',
'short<6cm': 'short<6cm',
'sides': 'sides',
'sign-up now': 'sign-up now',
'single': 'single',
'slim': 'slim',
'specify': 'specify',
'staff': 'staff',
'staff members': 'staff members',
'state': 'state',
'state location': 'state location',
'straight': 'straight',
'suffered financial losses': 'suffered financial losses',
'table': 'table',
'tall': 'tall',
'times and it is still not working. We give in. Sorry.': 'times and it is still not working. We give in. Sorry.',
'to access the system': 'to access the system',
'to download a OCR Form.': 'to download a OCR Form.',
'to reset your password': 'to reset your password',
'to verify your email': 'to verify your email',
'tonsure': 'tonsure',
'total': 'total',
'tweepy module not available within the running Python - this needs installing for non-Tropo Twitter support!': 'tweepy module not available within the running Python - this needs installing for non-Tropo Twitter support!',
'unable to parse csv file': 'unable to parse csv file',
'uncheck all': 'uncheck all',
'unidentified': 'unidentified',
'unknown': 'unknown',
'unspecified': 'unspecified',
'unverified': 'unverified',
'update': 'update',
'update if master': 'update if master',
'update if newer': 'update if newer',
'updated': 'updated',
'verified': 'verified',
'volunteer': 'volunteer',
'volunteers': 'volunteers',
'wavy': 'wavy',
'weeks': 'weeks',
'white': 'white',
'wider area, longer term, usually contain multiple Activities': 'wider area, longer term, usually contain multiple Activities',
'widowed': 'widowed',
'within human habitat': 'within human habitat',
'xlwt module not available within the running Python - this needs installing for XLS output!': 'xlwt module not available within the running Python - this needs installing for XLS output!',
'yes': 'yes',
}<|fim▁end|>
|
'Wind Chill': 'Wind Chill',
'Window frame': 'Window frame',
'Winter Storm': 'Winter Storm',
|
<|file_name|>email_test.py<|end_file_name|><|fim▁begin|>import bountyfunding
from bountyfunding.core.const import *
from bountyfunding.core.data import clean_database
from test import to_object
from nose.tools import *
USER = "bountyfunding"
class Email_Test:
def setup(self):
self.app = bountyfunding.app.test_client()
clean_database()
def test_email(self):
eq_(len(self.get_emails()), 0)
r = self.app.post('/issues', data=dict(ref=1, status='READY',
title='Title', link='/issue/1'))
eq_(r.status_code, 200)
r = self.app.post('/issue/1/sponsorships',
data=dict(user=USER, amount=10))
eq_(r.status_code, 200)
r = self.app.get("/issue/1")
eq_(r.status_code, 200)
r = self.app.put('/issue/1', data=dict(
status=IssueStatus.to_string(IssueStatus.STARTED)))
eq_(r.status_code, 200)
emails = self.get_emails()
eq_(len(emails), 1)
email = emails[0]
eq_(email.recipient, USER)
ok_(email.issue_id)
ok_(email.body)
<|fim▁hole|> eq_(r.status_code, 200)
def get_emails(self):
r = self.app.get("/emails")
eq_(r.status_code, 200)
return to_object(r).data<|fim▁end|>
|
r = self.app.delete("/email/%s" % email.id)
|
<|file_name|>SemiLagrangianExpression.cpp<|end_file_name|><|fim▁begin|>// Copyright (C) 2013 Columbia University in the City of New York and others.
//
// Please see the AUTHORS file in the main source directory for a full list
// of contributors.
//
// This file is part of TerraFERMA.
//
// TerraFERMA is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// TerraFERMA is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TerraFERMA. If not, see <http://www.gnu.org/licenses/>.
#include "SemiLagrangianExpression.h"
#include "BoostTypes.h"
#include "Bucket.h"
#include "Logger.h"
#include <dolfin.h>
using namespace buckettools;
//*******************************************************************|************************************************************//
// specific constructor (scalar)
//*******************************************************************|************************************************************//
SemiLagrangianExpression::SemiLagrangianExpression(const Bucket *bucket, const double_ptr time,
const std::pair< std::string, std::pair< std::string, std::string > > &function,
const std::pair< std::string, std::pair< std::string, std::string > > &velocity,
const std::pair< std::string, std::pair< std::string, std::string > > &outside) :
dolfin::Expression(),
bucket_(bucket),
time_(time),
funcname_(function),
velname_(velocity),
outname_(outside),
initialized_(false)
{
tf_not_parallelized("SemiLagrangianExpression");
}
//*******************************************************************|************************************************************//
// specific constructor (vector)
//*******************************************************************|************************************************************//
SemiLagrangianExpression::SemiLagrangianExpression(const std::size_t &dim,
const Bucket *bucket, const double_ptr time,
const std::pair< std::string, std::pair< std::string, std::string > > &function,
const std::pair< std::string, std::pair< std::string, std::string > > &velocity,
const std::pair< std::string, std::pair< std::string, std::string > > &outside) :
dolfin::Expression(dim),
bucket_(bucket),
time_(time),
funcname_(function),
velname_(velocity),
outname_(outside),
initialized_(false)
{
tf_not_parallelized("SemiLagrangianExpression");
}
//*******************************************************************|************************************************************//
// specific constructor (tensor)
//*******************************************************************|************************************************************//
SemiLagrangianExpression::SemiLagrangianExpression(const std::vector<std::size_t> &value_shape,
const Bucket *bucket, const double_ptr time,
const std::pair< std::string, std::pair< std::string, std::string > > &function,
const std::pair< std::string, std::pair< std::string, std::string > > &velocity,
const std::pair< std::string, std::pair< std::string, std::string > > &outside) :
dolfin::Expression(value_shape),
bucket_(bucket),
time_(time),
funcname_(function),
velname_(velocity),
outname_(outside),
initialized_(false)
{
tf_not_parallelized("SemiLagrangianExpression");
}
//*******************************************************************|************************************************************//
// default destructor
//*******************************************************************|************************************************************//
SemiLagrangianExpression::~SemiLagrangianExpression()
{
delete ufccellstar_;
ufccellstar_ = NULL;
delete[] xstar_;
xstar_ = NULL;
delete v_;
v_ = NULL;
delete oldv_;
oldv_ = NULL;
delete vstar_;
vstar_ = NULL;
delete cellcache_;
cellcache_ = NULL;
}
//*******************************************************************|************************************************************//
// initialize the expression
//*******************************************************************|************************************************************//
void SemiLagrangianExpression::init()
{
if (!initialized_)
{
initialized_ = true;
if(funcname_.second.first=="field")
{
func_ = (*(*(*bucket()).fetch_system(funcname_.first)).
fetch_field(funcname_.second.second)).
genericfunction_ptr(time());
}
else
{
func_ = (*(*(*bucket()).fetch_system(funcname_.first)).
fetch_coeff(funcname_.second.second)).
genericfunction_ptr(time());
}
if(velname_.second.first=="field")
{
vel_ = (*(*(*bucket()).fetch_system(velname_.first)).
fetch_field(velname_.second.second)).
genericfunction_ptr((*bucket()).current_time_ptr());
oldvel_ = (*(*(*bucket()).fetch_system(velname_.first)).
fetch_field(velname_.second.second)).
genericfunction_ptr((*bucket()).old_time_ptr());
}
else
{
vel_ = (*(*(*bucket()).fetch_system(velname_.first)).
fetch_coeff(velname_.second.second)).
genericfunction_ptr((*bucket()).current_time_ptr());
oldvel_ = (*(*(*bucket()).fetch_system(velname_.first)).
fetch_coeff(velname_.second.second)).
genericfunction_ptr((*bucket()).old_time_ptr());
}
if(outname_.second.first=="field")
{
out_ = (*(*(*bucket()).fetch_system(outname_.first)).
fetch_field(outname_.second.second)).
genericfunction_ptr(time());
}
else
{
out_ = (*(*(*bucket()).fetch_system(outname_.first)).
fetch_coeff(outname_.second.second)).
genericfunction_ptr(time());
}
assert(value_rank()==(*func_).value_rank());
assert(value_rank()==(*out_).value_rank());
for (uint i = 0; i < value_rank(); i++)
{
assert(value_dimension(i)==(*func_).value_dimension(i));
assert(value_dimension(i)==(*out_).value_dimension(i));
}
mesh_ = (*(*bucket()).fetch_system(funcname_.first)).mesh();// use the mesh from the function system
dim_ = (*mesh_).geometry().dim();
assert((*vel_).value_rank()<2);
if((*vel_).value_rank()==0)
{
assert(dim_==1);
}
else
{
assert((*vel_).value_dimension(0)==dim_);
}
ufccellstar_ = new ufc::cell;
xstar_ = new double[dim_];
v_ = new dolfin::Array<double>(dim_);
oldv_ = new dolfin::Array<double>(dim_);
vstar_ = new dolfin::Array<double>(dim_);
cellcache_ = new dolfin::MeshFunction< point_map >(mesh_, dim_);
}
}
//*******************************************************************|************************************************************//
// overload dolfin expression eval
//*******************************************************************|************************************************************//
void SemiLagrangianExpression::eval(dolfin::Array<double>& values,
const dolfin::Array<double>& x,
const ufc::cell &cell) const
{
const bool outside = findpoint_(x, cell);
dolfin::Array<double> xstar(dim_, xstar_);
if (outside)
{
(*out_).eval(values, xstar, *ufccellstar_);
}
else
{
(*func_).eval(values, xstar, *ufccellstar_);
}
}
//*******************************************************************|************************************************************//
// find the launch point
//*******************************************************************|************************************************************//
const bool SemiLagrangianExpression::findpoint_(const dolfin::Array<double>& x,
const ufc::cell &cell) const
{
bool outside = false;
point_map &points = (*cellcache_)[cell.index];
dolfin::Point lp(x.size(), x.data());
point_iterator p_it = points.find(lp);
findvstar_(x, cell);
for (uint k = 0; k < 2; k++)
{
for (uint i = 0; i < dim_; i++)
{
xstar_[i] = x[i] - ((*bucket()).timestep()/2.0)*(*vstar_)[i];
}
outside = checkpoint_(0, p_it, points, lp);
if (outside)
{
return true;
}
dolfin::Array<double> xstar(dim_, xstar_);
findvstar_(xstar, *ufccellstar_);
}
for (uint i = 0; i < dim_; i++)
{
xstar_[i] = x[i] - ((*bucket()).timestep())*(*vstar_)[i];
}
outside = checkpoint_(1, p_it, points, lp);
if (outside)
{
return true;
}
return false;
}
//*******************************************************************|************************************************************//
// find the time weighted velocity at the requested point, x
//*******************************************************************|************************************************************//
void SemiLagrangianExpression::findvstar_(const dolfin::Array<double>& x,
const ufc::cell &cell) const
{
(*vel_).eval(*v_, x, cell);
(*oldvel_).eval(*oldv_, x, cell);
for (uint i = 0; i < dim_; i++)
{
(*vstar_)[i] = 0.5*( (*v_)[i] + (*oldv_)[i] );
}
}
//*******************************************************************|************************************************************//<|fim▁hole|>const bool SemiLagrangianExpression::checkpoint_(const int &index,
point_iterator &p_it,
point_map &points,
const dolfin::Point &lp) const
{
std::vector<unsigned int> cell_indices;
int cell_index;
const dolfin::Point p(dim_, xstar_);
if (p_it != points.end())
{
cell_index = (*p_it).second[index];
bool update = false;
if (cell_index < 0)
{
update = true;
}
else
{
dolfin::Cell dolfincell(*mesh_, cell_index);
if (!dolfincell.collides(p))
{
update = true;
}
}
if (update)
{
cell_indices = (*(*mesh_).bounding_box_tree()).compute_entity_collisions(p);
if (cell_indices.size()==0)
{
cell_index = -1;
}
else
{
cell_index = cell_indices[0];
}
(*p_it).second[index] = cell_index;
}
}
else
{
cell_indices = (*(*mesh_).bounding_box_tree()).compute_entity_collisions(p);
if (cell_indices.size()==0)
{
cell_index = -1;
}
else
{
cell_index = cell_indices[0];
}
std::vector<int> cells(2, -1);
cells[index] = cell_index;
points[lp] = cells;
}
if (cell_index<0)
{
return true;
}
dolfin::Cell dolfincell(*mesh_, cell_index);
dolfincell.get_cell_data(*ufccellstar_);
return false;
}<|fim▁end|>
|
// check if the current xstar_ is in the cache and/or is valid
//*******************************************************************|************************************************************//
|
<|file_name|>custom.py<|end_file_name|><|fim▁begin|>#This is a cell with a custom comment as marker
x=10<|fim▁hole|>print(x+y)<|fim▁end|>
|
y=11
|
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>import { RNGeth as Geth, Hooks } from './packages/geth';
export default Geth;
export const useKeyStore = Hooks.useKeyStore;<|fim▁hole|><|fim▁end|>
|
export const useEthereumClient = Hooks.useEthereumClient;
|
<|file_name|>test_migrations.py<|end_file_name|><|fim▁begin|># Copyright 2010-2011 OpenStack Foundation
# Copyright 2012-2013 IBM Corp.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mock
from oslotest import base as test_base
from oslo.db.sqlalchemy import test_migrations as migrate
class TestWalkVersions(test_base.BaseTestCase, migrate.WalkVersionsMixin):
def setUp(self):<|fim▁hole|> self.INIT_VERSION = 4
def test_migrate_up(self):
self.migration_api.db_version.return_value = 141
self._migrate_up(self.engine, 141)
self.migration_api.upgrade.assert_called_with(
self.engine, self.REPOSITORY, 141)
self.migration_api.db_version.assert_called_with(
self.engine, self.REPOSITORY)
def test_migrate_up_with_data(self):
test_value = {"a": 1, "b": 2}
self.migration_api.db_version.return_value = 141
self._pre_upgrade_141 = mock.MagicMock()
self._pre_upgrade_141.return_value = test_value
self._check_141 = mock.MagicMock()
self._migrate_up(self.engine, 141, True)
self._pre_upgrade_141.assert_called_with(self.engine)
self._check_141.assert_called_with(self.engine, test_value)
def test_migrate_down(self):
self.migration_api.db_version.return_value = 42
self.assertTrue(self._migrate_down(self.engine, 42))
self.migration_api.db_version.assert_called_with(
self.engine, self.REPOSITORY)
def test_migrate_down_not_implemented(self):
self.migration_api.downgrade.side_effect = NotImplementedError
self.assertFalse(self._migrate_down(self.engine, 42))
def test_migrate_down_with_data(self):
self._post_downgrade_043 = mock.MagicMock()
self.migration_api.db_version.return_value = 42
self._migrate_down(self.engine, 42, True)
self._post_downgrade_043.assert_called_with(self.engine)
@mock.patch.object(migrate.WalkVersionsMixin, '_migrate_up')
@mock.patch.object(migrate.WalkVersionsMixin, '_migrate_down')
def test_walk_versions_all_default(self, _migrate_up, _migrate_down):
self.REPOSITORY.latest = 20
self.migration_api.db_version.return_value = self.INIT_VERSION
self._walk_versions()
self.migration_api.version_control.assert_called_with(
None, self.REPOSITORY, self.INIT_VERSION)
self.migration_api.db_version.assert_called_with(
None, self.REPOSITORY)
versions = range(self.INIT_VERSION + 1, self.REPOSITORY.latest + 1)
upgraded = [mock.call(None, v, with_data=True) for v in versions]
self.assertEqual(self._migrate_up.call_args_list, upgraded)
downgraded = [mock.call(None, v - 1) for v in reversed(versions)]
self.assertEqual(self._migrate_down.call_args_list, downgraded)
@mock.patch.object(migrate.WalkVersionsMixin, '_migrate_up')
@mock.patch.object(migrate.WalkVersionsMixin, '_migrate_down')
def test_walk_versions_all_true(self, _migrate_up, _migrate_down):
self.REPOSITORY.latest = 20
self.migration_api.db_version.return_value = self.INIT_VERSION
self._walk_versions(self.engine, snake_walk=True, downgrade=True)
versions = range(self.INIT_VERSION + 1, self.REPOSITORY.latest + 1)
upgraded = []
for v in versions:
upgraded.append(mock.call(self.engine, v, with_data=True))
upgraded.append(mock.call(self.engine, v))
upgraded.extend(
[mock.call(self.engine, v) for v in reversed(versions)]
)
self.assertEqual(upgraded, self._migrate_up.call_args_list)
downgraded_1 = [
mock.call(self.engine, v - 1, with_data=True) for v in versions
]
downgraded_2 = []
for v in reversed(versions):
downgraded_2.append(mock.call(self.engine, v - 1))
downgraded_2.append(mock.call(self.engine, v - 1))
downgraded = downgraded_1 + downgraded_2
self.assertEqual(self._migrate_down.call_args_list, downgraded)
@mock.patch.object(migrate.WalkVersionsMixin, '_migrate_up')
@mock.patch.object(migrate.WalkVersionsMixin, '_migrate_down')
def test_walk_versions_true_false(self, _migrate_up, _migrate_down):
self.REPOSITORY.latest = 20
self.migration_api.db_version.return_value = self.INIT_VERSION
self._walk_versions(self.engine, snake_walk=True, downgrade=False)
versions = range(self.INIT_VERSION + 1, self.REPOSITORY.latest + 1)
upgraded = []
for v in versions:
upgraded.append(mock.call(self.engine, v, with_data=True))
upgraded.append(mock.call(self.engine, v))
self.assertEqual(upgraded, self._migrate_up.call_args_list)
downgraded = [
mock.call(self.engine, v - 1, with_data=True) for v in versions
]
self.assertEqual(self._migrate_down.call_args_list, downgraded)
@mock.patch.object(migrate.WalkVersionsMixin, '_migrate_up')
@mock.patch.object(migrate.WalkVersionsMixin, '_migrate_down')
def test_walk_versions_all_false(self, _migrate_up, _migrate_down):
self.REPOSITORY.latest = 20
self.migration_api.db_version.return_value = self.INIT_VERSION
self._walk_versions(self.engine, snake_walk=False, downgrade=False)
versions = range(self.INIT_VERSION + 1, self.REPOSITORY.latest + 1)
upgraded = [
mock.call(self.engine, v, with_data=True) for v in versions
]
self.assertEqual(upgraded, self._migrate_up.call_args_list)<|fim▁end|>
|
super(TestWalkVersions, self).setUp()
self.migration_api = mock.MagicMock()
self.engine = mock.MagicMock()
self.REPOSITORY = mock.MagicMock()
|
<|file_name|>ExampleInterface.java<|end_file_name|><|fim▁begin|><|fim▁hole|>package org.edtoktay.dynamic.compiler;
/**
* @author deniz.toktay
*
*/
public interface ExampleInterface {
void addObject(String arg1, String arg2);
Object getObject(String arg1);
}<|fim▁end|>
|
/**
*
*/
|
<|file_name|>languages.py<|end_file_name|><|fim▁begin|># coding=utf-8
from __future__ import unicode_literals
c_lang_config = {
"name": "c",
"compile": {
"group_memory": True,
"src_name": "main.c",
"exe_name": "main",
"max_cpu_time": 5.0,
"max_real_time": 10.0,
"max_memory": 512 * 1024, # 512M compile memory
"compile_command": "/usr/bin/gcc -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c99 {src_path} -lm -o {exe_path}",
},
"run": {
"exe_name": "main",
"max_cpu_time": 1.0,
"max_real_time": 5.0,
"max_memory": 10 * 1024, # 10M compile memory
"command": "{exe_path}",
}
}
cpp_lang_config = {
"name": "c++",
"compile": {
"group_memory": True,
"src_name": "main.cpp",
"exe_name": "main",
"max_cpu_time": 5.0,
"max_real_time": 10.0,
"max_memory": 512 * 1024, # 512M compile memory
"compile_command": "/usr/bin/g++ -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c++11 {src_path} -lm -o {exe_path}",
},
"run": {
"exe_name": "main",
"max_cpu_time": 1.0,
"max_real_time": 5.0,
"max_memory": 10 * 1024, # 10M compile memory
"command": "{exe_path}",
}
}
java_lang_config = {
"name": "java",
"compile": {
"group_memory": True,
"src_name": "Main.java",
"exe_name": "Main",
"max_cpu_time": 3.0,
"max_real_time": 5.0,
"max_memory": -1,
"compile_command": "/usr/bin/javac {src_path} -d {exe_name} -encoding UTF8"
},
"run": {
"group_memory": True,
"exe_name": "Main",
"max_cpu_time": 1.0,
"max_real_time": 5.0,
"max_memory": 10 * 1024, # 10M compile memory
"command": "/usr/bin/java -cp {exe_name} Main",
}
}
<|fim▁hole|>
py2_lang_config = {
"name": "python2",
"compile": {
"src_name": "solution.py",
"exe_name": "solution.pyc",
"max_cpu_time": 3000,
"max_real_time": 5000,
"max_memory": 128 * 1024 ,
"compile_command": "/usr/bin/python -m py_compile {src_path}",
},
"run": {
"exe_name": "solution.pyc",
"command": "/usr/bin/python {exe_path}",
}
}<|fim▁end|>
| |
<|file_name|>sqrl_xcu1525.py<|end_file_name|><|fim▁begin|>#
# This file is part of LiteX-Boards.
#
# Copyright (c) 2020 David Shah <[email protected]>
# Copyright (c) 2020 Florent Kermarrec <[email protected]>
# SPDX-License-Identifier: BSD-2-Clause
from litex.build.generic_platform import Pins, Subsignal, IOStandard, Misc
from litex.build.xilinx import XilinxPlatform, VivadoProgrammer
# IOs ----------------------------------------------------------------------------------------------
_io = [
# Clk / Rst
("clk300", 0,
Subsignal("n", Pins("AY38"), IOStandard("DIFF_SSTL12")),
Subsignal("p", Pins("AY37"), IOStandard("DIFF_SSTL12")),
),
("clk300", 1,
Subsignal("n", Pins("AW19"), IOStandard("DIFF_SSTL12")),
Subsignal("p", Pins("AW20"), IOStandard("DIFF_SSTL12")),
),
("clk300", 2,
Subsignal("n", Pins("E32"), IOStandard("DIFF_SSTL12")),
Subsignal("p", Pins("F32"), IOStandard("DIFF_SSTL12")),
),
("clk300", 3,
Subsignal("n", Pins("H16"), IOStandard("DIFF_SSTL12")),
Subsignal("p", Pins("J16"), IOStandard("DIFF_SSTL12")),
),
# Leds
("user_led", 0, Pins("BC21"), IOStandard("LVCMOS12")),
("user_led", 1, Pins("BB21"), IOStandard("LVCMOS12")),
("user_led", 2, Pins("BA20"), IOStandard("LVCMOS12")),
# Serial
("serial", 0,
Subsignal("rx", Pins("BF18"), IOStandard("LVCMOS12")),
Subsignal("tx", Pins("BB20"), IOStandard("LVCMOS12")),
),
# PCIe
("pcie_x2", 0,
Subsignal("rst_n", Pins("BD21"), IOStandard("LVCMOS12")),
Subsignal("clk_n", Pins("AM10")),
Subsignal("clk_p", Pins("AM11")),
Subsignal("rx_n", Pins("AF1 AG3")),
Subsignal("rx_p", Pins("AF2 AG4")),
Subsignal("tx_n", Pins("AF6 AG8")),
Subsignal("tx_p", Pins("AF7 AG9")),
),
("pcie_x4", 0,
Subsignal("rst_n", Pins("BD21"), IOStandard("LVCMOS12")),
Subsignal("clk_n", Pins("AM10")),
Subsignal("clk_p", Pins("AM11")),
Subsignal("rx_n", Pins("AF1 AG3 AH1 AJ3")),
Subsignal("rx_p", Pins("AF2 AG4 AH2 AJ4")),
Subsignal("tx_n", Pins("AF6 AG8 AH6 AJ8")),
Subsignal("tx_p", Pins("AF7 AG9 AH7 AJ9")),
),
("pcie_x8", 0,
Subsignal("rst_n", Pins("BD21"), IOStandard("LVCMOS12")),
Subsignal("clk_n", Pins("AM10")),
Subsignal("clk_p", Pins("AM11")),
Subsignal("rx_n", Pins("AF1 AG3 AH1 AJ3 AK1 AL3 AM1 AN3")),
Subsignal("rx_p", Pins("AF2 AG4 AH2 AJ4 AK2 AL4 AM2 AN4")),
Subsignal("tx_n", Pins("AF6 AG8 AH6 AJ8 AK6 AL8 AM6 AN8")),
Subsignal("tx_p", Pins("AF7 AG9 AH7 AJ9 AK7 AL9 AM7 AN9")),
),
("pcie_x16", 0,
Subsignal("rst_n", Pins("BD21"), IOStandard("LVCMOS12")),
Subsignal("clk_n", Pins("AM10")),
Subsignal("clk_p", Pins("AM11")),
Subsignal("rx_n", Pins("AF1 AG3 AH1 AJ3 AK1 AL3 AM1 AN3 AP1 AR3 AT1 AU3 AV1 AW3 BA1 BC1")),
Subsignal("rx_p", Pins("AF2 AG4 AH2 AJ4 AK2 AL4 AM2 AN4 AP2 AR4 AT2 AU4 AV2 AW4 BA2 BC2")),
Subsignal("tx_n", Pins("AF6 AG8 AH6 AJ8 AK6 AL8 AM6 AN8 AP6 AR8 AT6 AU8 AV6 BB4 BD4 BF4")),
Subsignal("tx_p", Pins("AF7 AG9 AH7 AJ9 AK7 AL9 AM7 AN9 AP7 AR9 AT7 AU9 AV7 BB5 BD5 BF5")),
),
# DDR4 SDRAM
("ddram", 0,
Subsignal("a", Pins(
"AT36 AV36 AV37 AW35 AW36 AY36 AY35 BA40",
"BA37 BB37 AR35 BA39 BB40 AN36"),
IOStandard("SSTL12_DCI")),
Subsignal("act_n", Pins("BB39"), IOStandard("SSTL12_DCI")),
Subsignal("ba", Pins("AT35 AT34"), IOStandard("SSTL12_DCI")),
Subsignal("bg", Pins("BC37 BC39"), IOStandard("SSTL12_DCI")),
Subsignal("ras_n", Pins("AR36"), IOStandard("SSTL12_DCI")), # A16
Subsignal("cas_n", Pins("AP36"), IOStandard("SSTL12_DCI")), # A15
Subsignal("we_n", Pins("AP35"), IOStandard("SSTL12_DCI")), # A14
Subsignal("cke", Pins("BC38"), IOStandard("SSTL12_DCI")),
Subsignal("clk_n", Pins("AW38"), IOStandard("DIFF_SSTL12_DCI")),
Subsignal("clk_p", Pins("AV38"), IOStandard("DIFF_SSTL12_DCI")),
Subsignal("cs_n", Pins("AR33"), IOStandard("SSTL12_DCI")),
Subsignal("dm", Pins("BC31 AY27 BB26 BD26 AP30 BF39 AR30 BA32"),
IOStandard("POD12_DCI")),
Subsignal("dq", Pins(
"BB31 BB32 AY33 AY32 BC33 BC32 BB34 BC34",
"AT28 AT27 AU27 AV27 AV28 AV29 AW30 AY30",
"BA28 BA27 AW28 AW29 BC27 BB27 BA29 BB29",
"BE28 BF28 BE30 BD30 BF27 BE27 BF29 BF30",
"AT32 AU32 AM30 AL30 AR31 AN31 AR32 AN32",
"BD40 BD39 BF42 BF43 BF41 BE40 BE37 BF37",
"AM27 AN27 AP28 AP29 AM29 AN29 AR28 AR27",
"AW34 AV32 AV31 AV34 BA35 BA34 AW31 AY31"),
IOStandard("POD12_DCI"),
Misc("OUTPUT_IMPEDANCE=RDRV_40_40"),
Misc("PRE_EMPHASIS=RDRV_240"),
Misc("EQUALIZATION=EQ_LEVEL2")),
Subsignal("dqs_n", Pins("BB36 AU30 BB30 BD29 AM32 BF38 AL29 AW33"),
IOStandard("DIFF_POD12"),
Misc("OUTPUT_IMPEDANCE=RDRV_40_40"),
Misc("PRE_EMPHASIS=RDRV_240"),
Misc("EQUALIZATION=EQ_LEVEL2")),
Subsignal("dqs_p", Pins("BB35 AU29 BA30 BD28 AM31 BE38 AL28 AV33"),
IOStandard("DIFF_POD12"),
Misc("OUTPUT_IMPEDANCE=RDRV_40_40"),
Misc("PRE_EMPHASIS=RDRV_240"),
Misc("EQUALIZATION=EQ_LEVEL2")),
Subsignal("odt", Pins("AP34"), IOStandard("SSTL12_DCI")),
Subsignal("reset_n", Pins("AU31"), IOStandard("LVCMOS12")),
Misc("SLEW=FAST")
),
("ddram", 1,
Subsignal("a", Pins(
"AN24 AT24 AW24 AN26 AY22 AY23 AV24 BA22",
"AY25 BA23 AM26 BA25 BB22 AL24"),
IOStandard("SSTL12_DCI")),
Subsignal("act_n", Pins("AW25"), IOStandard("SSTL12_DCI")),
Subsignal("ba", Pins("AU24 AP26"), IOStandard("SSTL12_DCI")),
Subsignal("bg", Pins("BC22 AW26"), IOStandard("SSTL12_DCI")),
Subsignal("ras_n", Pins("AN23"), IOStandard("SSTL12_DCI")), # A16
Subsignal("cas_n", Pins("AM25"), IOStandard("SSTL12_DCI")), # A15
Subsignal("we_n", Pins("AL25"), IOStandard("SSTL12_DCI")), # A14
Subsignal("cke", Pins("BB25"), IOStandard("SSTL12_DCI")),
Subsignal("clk_n", Pins("AU25"), IOStandard("DIFF_SSTL12_DCI")),
Subsignal("clk_p", Pins("AT25"), IOStandard("DIFF_SSTL12_DCI")),
Subsignal("cs_n", Pins("AV23"), IOStandard("SSTL12_DCI")),
Subsignal("dm", Pins("BE8 BE15 BE22 BA10 AY13 BB14 AN14 AW16"),
IOStandard("POD12_DCI")),
Subsignal("dq", Pins(
" BC7 BD7 BD8 BD9 BF7 BE7 BD10 BE10",
"BF12 BE13 BD14 BD13 BF14 BF13 BD16 BD15",
"BF25 BE25 BF24 BD25 BC23 BD23 BF23 BE23",
"BA14 BA13 BA12 BB12 BC9 BB9 BA7 BA8",
"AU13 AW14 AW13 AV13 AU14 BA11 AY11 AV14",
"BA18 BA17 AY18 AY17 BD11 BC11 BA15 BB15",
"AR13 AP13 AN13 AM13 AT15 AR15 AM14 AL14",
"AV16 AV17 AU17 AU16 BB17 BB16 AT17 AT18"),
IOStandard("POD12_DCI"),<|fim▁hole|> Misc("OUTPUT_IMPEDANCE=RDRV_40_40"),
Misc("PRE_EMPHASIS=RDRV_240"),
Misc("EQUALIZATION=EQ_LEVEL2")),
Subsignal("dqs_n", Pins("BF9 BE11 BD24 BB10 AY15 BC12 AT13 AW18"),
IOStandard("DIFF_POD12"),
Misc("OUTPUT_IMPEDANCE=RDRV_40_40"),
Misc("PRE_EMPHASIS=RDRV_240"),
Misc("EQUALIZATION=EQ_LEVEL2")),
Subsignal("dqs_p", Pins("BF10 BE12 BC24 BB11 AW15 BC13 AT14 AV18"),
IOStandard("DIFF_POD12"),
Misc("OUTPUT_IMPEDANCE=RDRV_40_40"),
Misc("PRE_EMPHASIS=RDRV_240"),
Misc("EQUALIZATION=EQ_LEVEL2")),
Subsignal("odt", Pins("AW23"), IOStandard("SSTL12_DCI")),
Subsignal("reset_n", Pins("AR17"), IOStandard("LVCMOS12")),
Misc("SLEW=FAST")
),
("ddram", 2,
Subsignal("a", Pins(
"L29 A33 C33 J29 H31 G31 C32 B32",
"A32 D31 A34 E31 M30 F33"),
IOStandard("SSTL12_DCI")),
Subsignal("act_n", Pins("B31"), IOStandard("SSTL12_DCI")),
Subsignal("ba", Pins("D33 B36"), IOStandard("SSTL12_DCI")),
Subsignal("bg", Pins("C31 J30"), IOStandard("SSTL12_DCI")),
Subsignal("ras_n", Pins("K30"), IOStandard("SSTL12_DCI")), # A16
Subsignal("cas_n", Pins("G32"), IOStandard("SSTL12_DCI")), # A15
Subsignal("we_n", Pins("A35"), IOStandard("SSTL12_DCI")), # A14
Subsignal("cke", Pins("G30"), IOStandard("SSTL12_DCI")),
Subsignal("clk_n", Pins("B34"), IOStandard("DIFF_SSTL12_DCI")),
Subsignal("clk_p", Pins("C34"), IOStandard("DIFF_SSTL12_DCI")),
Subsignal("cs_n", Pins("B35"), IOStandard("SSTL12_DCI")),
Subsignal("dm", Pins("T30 M27 R28 H26 C37 H33 G37 M34"),
IOStandard("POD12_DCI")),
Subsignal("dq", Pins(
"P29 P30 R30 N29 N32 M32 P31 L32",
"H29 G29 J28 H28 K27 L27 K26 K25",
"P25 R25 L25 M25 P26 R26 N27 N28",
"F27 D28 E27 E28 G26 F29 G27 F28",
"A38 A37 B37 C36 B40 C39 A40 D39",
"G36 H36 H37 J36 G34 G35 K37 K38",
"E38 D38 E35 F35 E36 E37 F38 G38",
"K35 J35 K33 L33 J33 J34 N34 P34"),
IOStandard("POD12_DCI"),
Misc("OUTPUT_IMPEDANCE=RDRV_40_40"),
Misc("PRE_EMPHASIS=RDRV_240"),
Misc("EQUALIZATION=EQ_LEVEL2")),
Subsignal("dqs_n", Pins("M31 J26 M26 D30 A39 H38 E40 L36"),
IOStandard("DIFF_POD12"),
Misc("OUTPUT_IMPEDANCE=RDRV_40_40"),
Misc("PRE_EMPHASIS=RDRV_240"),
Misc("EQUALIZATION=EQ_LEVEL2")),
Subsignal("dqs_p", Pins("N31 J25 N26 D29 B39 J38 E39 L35"),
IOStandard("DIFF_POD12"),
Misc("OUTPUT_IMPEDANCE=RDRV_40_40"),
Misc("PRE_EMPHASIS=RDRV_240"),
Misc("EQUALIZATION=EQ_LEVEL2")),
Subsignal("odt", Pins("E33"), IOStandard("SSTL12_DCI")),
Subsignal("reset_n", Pins("D36"), IOStandard("LVCMOS12")),
Misc("SLEW=FAST")
),
("ddram", 3,
Subsignal("a", Pins(
"K15 B15 F14 A15 C14 A14 B14 E13",
"F13 A13 D14 C13 B13 K16"),
IOStandard("SSTL12_DCI")),
Subsignal("act_n", Pins("H13"), IOStandard("SSTL12_DCI")),
Subsignal("ba", Pins("J15 H14"), IOStandard("SSTL12_DCI")),
Subsignal("bg", Pins("D13 J13"), IOStandard("SSTL12_DCI")),
Subsignal("ras_n", Pins("F15"), IOStandard("SSTL12_DCI")), # A16
Subsignal("cas_n", Pins("E15"), IOStandard("SSTL12_DCI")), # A15
Subsignal("cke", Pins("K13"), IOStandard("SSTL12_DCI")), # A14
Subsignal("we_n", Pins("D15"), IOStandard("SSTL12_DCI")),
Subsignal("clk_n", Pins("L13"), IOStandard("DIFF_SSTL12_DCI")),
Subsignal("clk_p", Pins("L14"), IOStandard("DIFF_SSTL12_DCI")),
Subsignal("cs_n", Pins("B16"), IOStandard("SSTL12_DCI")),
Subsignal("dm", Pins("T13 N17 D24 B19 H19 H23 M22 N22"),
IOStandard("POD12_DCI")),
Subsignal("dq", Pins(
"M16 N16 N14 N13 R15 T15 P13 P14",
"R17 R18 M20 M19 N18 N19 R20 T20",
"B24 A23 A22 B25 C24 C23 C22 B22",
"C18 C19 C21 B21 A17 A18 B20 A20",
"E18 E17 E20 F20 D19 H18 D20 J18",
"G21 E22 G22 F22 G25 F24 E25 F25",
"J24 G24 J23 H24 L23 K21 L24 K22",
"P24 N24 R23 T24 N23 P21 P23 R21"),
IOStandard("POD12_DCI"),
Misc("OUTPUT_IMPEDANCE=RDRV_40_40"),
Misc("PRE_EMPHASIS=RDRV_240"),
Misc("EQUALIZATION=EQ_LEVEL2")),
Subsignal("dqs_n", Pins("P15 P18 A24 B17 F17 E23 H21 R22"),
IOStandard("DIFF_POD12"),
Misc("OUTPUT_IMPEDANCE=RDRV_40_40"),
Misc("PRE_EMPHASIS=RDRV_240"),
Misc("EQUALIZATION=EQ_LEVEL2")),
Subsignal("dqs_p", Pins("R16 P19 A25 C17 F18 F23 J21 T22"),
IOStandard("DIFF_POD12"),
Misc("OUTPUT_IMPEDANCE=RDRV_40_40"),
Misc("PRE_EMPHASIS=RDRV_240"),
Misc("EQUALIZATION=EQ_LEVEL2")),
Subsignal("odt", Pins("C16"), IOStandard("SSTL12_DCI")),
Subsignal("reset_n", Pins("D21"), IOStandard("LVCMOS12")),
Misc("SLEW=FAST")
),
]
# Connectors ---------------------------------------------------------------------------------------
_connectors = []
# Platform -----------------------------------------------------------------------------------------
class Platform(XilinxPlatform):
default_clk_name = "clk300"
default_clk_period = 1e9/300e6
def __init__(self, toolchain="vivado"):
XilinxPlatform.__init__(self, "xcvu9p-fsgd2104-2l-e", _io, _connectors, toolchain=toolchain)
def create_programmer(self):
return VivadoProgrammer()
def do_finalize(self, fragment):
XilinxPlatform.do_finalize(self, fragment)
# For passively cooled boards, overheating is a significant risk if airflow isn't sufficient
self.add_platform_command("set_property BITSTREAM.CONFIG.OVERTEMPSHUTDOWN ENABLE [current_design]")
# Reduce programming time
self.add_platform_command("set_property BITSTREAM.GENERAL.COMPRESS TRUE [current_design]")
# DDR4 memory channel C0 Clock constraint / Internal Vref
self.add_period_constraint(self.lookup_request("clk300", 0, loose=True), 1e9/300e6)
self.add_platform_command("set_property INTERNAL_VREF 0.84 [get_iobanks 40]")
self.add_platform_command("set_property INTERNAL_VREF 0.84 [get_iobanks 41]")
self.add_platform_command("set_property INTERNAL_VREF 0.84 [get_iobanks 42]")
# DDR4 memory channel C1 Clock constraint / Internal Vref
self.add_period_constraint(self.lookup_request("clk300", 1, loose=True), 1e9/300e6)
self.add_platform_command("set_property INTERNAL_VREF 0.84 [get_iobanks 65]")
self.add_platform_command("set_property INTERNAL_VREF 0.84 [get_iobanks 66]")
self.add_platform_command("set_property INTERNAL_VREF 0.84 [get_iobanks 67]")
# DDR4 memory channel C2 Clock constraint / Internal Vref
self.add_period_constraint(self.lookup_request("clk300", 2, loose=True), 1e9/300e6)
self.add_platform_command("set_property INTERNAL_VREF 0.84 [get_iobanks 46]")
self.add_platform_command("set_property INTERNAL_VREF 0.84 [get_iobanks 47]")
self.add_platform_command("set_property INTERNAL_VREF 0.84 [get_iobanks 48]")
# DDR4 memory channel C3 Clock constraint / Internal Vref
self.add_period_constraint(self.lookup_request("clk300", 3, loose=True), 1e9/300e6)
self.add_platform_command("set_property INTERNAL_VREF 0.84 [get_iobanks 70]")
self.add_platform_command("set_property INTERNAL_VREF 0.84 [get_iobanks 71]")
self.add_platform_command("set_property INTERNAL_VREF 0.84 [get_iobanks 72]")<|fim▁end|>
| |
<|file_name|>AccountUtil.java<|end_file_name|><|fim▁begin|>/*
* Project: NextGIS Mobile
* Purpose: Mobile GIS for Android.
* Author: Dmitry Baryshnikov (aka Bishop), [email protected]
* Author: NikitaFeodonit, [email protected]
* Author: Stanislav Petriakov, [email protected]
* *****************************************************************************
* Copyright (c) 2015-2017, 2019 NextGIS, [email protected]
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextgis.maplib.util;
import android.accounts.Account;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SyncInfo;
import android.os.Build;
import android.util.Base64;
import com.nextgis.maplib.api.IGISApplication;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import static com.nextgis.maplib.util.Constants.JSON_END_DATE_KEY;
import static com.nextgis.maplib.util.Constants.JSON_SIGNATURE_KEY;
import static com.nextgis.maplib.util.Constants.JSON_START_DATE_KEY;
import static com.nextgis.maplib.util.Constants.JSON_SUPPORTED_KEY;
import static com.nextgis.maplib.util.Constants.JSON_USER_ID_KEY;
import static com.nextgis.maplib.util.Constants.SUPPORT;
public class AccountUtil {
public static boolean isProUser(Context context) {
File support = context.getExternalFilesDir(null);
if (support == null)
support = new File(context.getFilesDir(), SUPPORT);
else
support = new File(support, SUPPORT);
try {
String jsonString = FileUtil.readFromFile(support);
JSONObject json = new JSONObject(jsonString);
if (json.optBoolean(JSON_SUPPORTED_KEY)) {
final String id = json.getString(JSON_USER_ID_KEY);
final String start = json.getString(JSON_START_DATE_KEY);
final String end = json.getString(JSON_END_DATE_KEY);
final String data = id + start + end + "true";
final String signature = json.getString(JSON_SIGNATURE_KEY);
return verifySignature(data, signature);
}
} catch (JSONException | IOException ignored) { }<|fim▁hole|> return false;
}
private static boolean verifySignature(String data, String signature) {
try {
// add public key
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
String key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzbmnrTLjTLxqCnIqXgIJ\n" +
"jebXVOn4oV++8z5VsBkQwK+svDkGK/UcJ4YjXUuPqyiZwauHGy1wizGCgVIRcPNM\n" +
"I0n9W6797NMFaC1G6Rp04ISv7DAu0GIZ75uDxE/HHDAH48V4PqQeXMp01Uf4ttti\n" +
"XfErPKGio7+SL3GloEqtqGbGDj6Yx4DQwWyIi6VvmMsbXKmdMm4ErczWFDFHIxpV\n" +
"ln/VfX43r/YOFxqt26M7eTpaBIvAU6/yWkIsvidMNL/FekQVTiRCl/exPgioDGrf\n" +
"06z5a0sd3NDbS++GMCJstcKxkzk5KLQljAJ85Jciiuy2vv14WU621ves8S9cMISO\n" + "HwIDAQAB";
byte[] keyBytes = Base64.decode(key.getBytes("UTF-8"), Base64.DEFAULT);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
PublicKey publicKey = keyFactory.generatePublic(spec);
// verify signature
Signature signCheck = Signature.getInstance("SHA256withRSA");
signCheck.initVerify(publicKey);
signCheck.update(data.getBytes("UTF-8"));
byte[] sigBytes = Base64.decode(signature, Base64.DEFAULT);
return signCheck.verify(sigBytes);
} catch (Exception e) {
return false;
}
}
public static boolean isSyncActive(Account account, String authority) {
return isSyncActiveHoneycomb(account, authority);
}
public static boolean isSyncActiveHoneycomb(Account account, String authority) {
for (SyncInfo syncInfo : ContentResolver.getCurrentSyncs()) {
if (syncInfo.account.equals(account) && syncInfo.authority.equals(authority)) {
return true;
}
}
return false;
}
public static AccountData getAccountData(Context context, String accountName) throws IllegalStateException {
IGISApplication app = (IGISApplication) context.getApplicationContext();
Account account = app.getAccount(accountName);
if (null == account) {
throw new IllegalStateException("Account is null");
}
AccountData accountData = new AccountData();
accountData.url = app.getAccountUrl(account);
accountData.login = app.getAccountLogin(account);
accountData.password = app.getAccountPassword(account);
return accountData;
}
public static class AccountData {
public String url;
public String login;
public String password;
}
}<|fim▁end|>
| |
<|file_name|>prefs.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use basedir::default_config_dir;
use embedder_traits::resources::{self, Resource};
use num_cpus;
use opts;
use rustc_serialize::json::{Json, ToJson};
use std::borrow::ToOwned;
use std::cmp::max;
use std::collections::HashMap;
use std::fs::File;
use std::io::{Read, Write, stderr};
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
lazy_static! {
pub static ref PREFS: Preferences = {
let defaults = default_prefs();
if let Ok(prefs) = read_prefs(&resources::read_string(Resource::Preferences)) {
defaults.extend(prefs);
}
defaults
};
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub enum PrefValue {
Boolean(bool),
String(String),
Number(f64),
Missing,
}
impl PrefValue {
pub fn from_json(data: Json) -> Result<PrefValue, ()> {
let value = match data {
Json::Boolean(x) => PrefValue::Boolean(x),
Json::String(x) => PrefValue::String(x),
Json::F64(x) => PrefValue::Number(x),
Json::I64(x) => PrefValue::Number(x as f64),
Json::U64(x) => PrefValue::Number(x as f64),
_ => return Err(()),
};
Ok(value)
}
pub fn as_boolean(&self) -> Option<bool> {
match *self {
PrefValue::Boolean(value) => Some(value),
_ => None,
}
}
pub fn as_string(&self) -> Option<&str> {
match *self {
PrefValue::String(ref value) => Some(&value),
_ => None,
}
}
pub fn as_i64(&self) -> Option<i64> {
match *self {
PrefValue::Number(x) => Some(x as i64),
_ => None,
}
}
pub fn as_u64(&self) -> Option<u64> {
match *self {
PrefValue::Number(x) => Some(x as u64),
_ => None,
}
}
}
impl ToJson for PrefValue {
fn to_json(&self) -> Json {
match *self {
PrefValue::Boolean(x) => Json::Boolean(x),
PrefValue::String(ref x) => Json::String(x.clone()),
PrefValue::Number(x) => Json::F64(x),
PrefValue::Missing => Json::Null,
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum Pref {
NoDefault(Arc<PrefValue>),
WithDefault(Arc<PrefValue>, Option<Arc<PrefValue>>),
}
impl Pref {
pub fn new(value: PrefValue) -> Pref {
Pref::NoDefault(Arc::new(value))
}
fn new_default(value: PrefValue) -> Pref {
Pref::WithDefault(Arc::new(value), None)
}
fn from_json(data: Json) -> Result<Pref, ()> {
let value = PrefValue::from_json(data)?;
Ok(Pref::new_default(value))
}
pub fn value(&self) -> &Arc<PrefValue> {
match *self {
Pref::NoDefault(ref x) => x,
Pref::WithDefault(ref default, ref override_value) => match *override_value {
Some(ref x) => x,
None => default,
},
}
}
fn set(&mut self, value: PrefValue) {
// TODO - this should error if we try to override a pref of one type
// with a value of a different type
match *self {
Pref::NoDefault(ref mut pref_value) => *pref_value = Arc::new(value),
Pref::WithDefault(_, ref mut override_value) => *override_value = Some(Arc::new(value)),
}
}
}
impl ToJson for Pref {
fn to_json(&self) -> Json {
self.value().to_json()
}
}
pub fn default_prefs() -> Preferences {
let prefs = Preferences(Arc::new(RwLock::new(HashMap::new())));
prefs.set(
"layout.threads",
PrefValue::Number(max(num_cpus::get() * 3 / 4, 1) as f64),
);
prefs
}
pub fn read_prefs(txt: &str) -> Result<HashMap<String, Pref>, ()> {
let json = Json::from_str(txt).or_else(|e| {
println!("Ignoring invalid JSON in preferences: {:?}.", e);
Err(())
})?;
let mut prefs = HashMap::new();
if let Json::Object(obj) = json {
for (name, value) in obj.into_iter() {
match Pref::from_json(value) {
Ok(x) => {
prefs.insert(name, x);
},
Err(_) => println!(
"Ignoring non-boolean/string/i64 preference value for {:?}",
name
),
}
}
}
Ok(prefs)
}
pub fn add_user_prefs() {
match opts::get().config_dir {
Some(ref config_path) => {
let mut path = PathBuf::from(config_path);
init_user_prefs(&mut path);
},
None => {
if let Some(mut path) = default_config_dir() {
if path.join("prefs.json").exists() {
init_user_prefs(&mut path);
}
}
},
}
}
fn init_user_prefs(path: &mut PathBuf) {
path.push("prefs.json");
if let Ok(mut file) = File::open(path) {
let mut txt = String::new();
file.read_to_string(&mut txt).expect("Can't read use prefs");
if let Ok(prefs) = read_prefs(&txt) {
PREFS.extend(prefs);
}
} else {
writeln!(
&mut stderr(),
"Error opening prefs.json from config directory"
).expect("failed printing to stderr");
}
}
pub struct Preferences(Arc<RwLock<HashMap<String, Pref>>>);
impl Preferences {
pub fn get(&self, name: &str) -> Arc<PrefValue> {
self.0
.read()
.unwrap()
.get(name)
.map_or(Arc::new(PrefValue::Missing), |x| x.value().clone())
}
pub fn cloned(&self) -> HashMap<String, Pref> {
self.0.read().unwrap().clone()
}
pub fn set(&self, name: &str, value: PrefValue) {<|fim▁hole|> return;
}
prefs.insert(name.to_owned(), Pref::new(value));
}
pub fn reset(&self, name: &str) -> Arc<PrefValue> {
let mut prefs = self.0.write().unwrap();
let result = match prefs.get_mut(name) {
None => return Arc::new(PrefValue::Missing),
Some(&mut Pref::NoDefault(_)) => Arc::new(PrefValue::Missing),
Some(&mut Pref::WithDefault(ref default, ref mut set_value)) => {
*set_value = None;
default.clone()
},
};
if *result == PrefValue::Missing {
prefs.remove(name);
}
result
}
pub fn reset_all(&self) {
let names = {
self.0
.read()
.unwrap()
.keys()
.cloned()
.collect::<Vec<String>>()
};
for name in names.iter() {
self.reset(name);
}
}
pub fn extend(&self, extension: HashMap<String, Pref>) {
self.0.write().unwrap().extend(extension);
}
pub fn is_webvr_enabled(&self) -> bool {
self.get("dom.webvr.enabled").as_boolean().unwrap_or(false)
}
pub fn is_dom_to_texture_enabled(&self) -> bool {
self.get("dom.webgl.dom_to_texture.enabled")
.as_boolean()
.unwrap_or(false)
}
pub fn is_webgl2_enabled(&self) -> bool {
self.get("dom.webgl2.enabled").as_boolean().unwrap_or(false)
}
}<|fim▁end|>
|
let mut prefs = self.0.write().unwrap();
if let Some(pref) = prefs.get_mut(name) {
pref.set(value);
|
<|file_name|>test_replay.py<|end_file_name|><|fim▁begin|>import unittest
import time
import random<|fim▁hole|>import os
os.environ['USE_CALIENDO'] = 'True'
from caliendo.db import flatfiles
from caliendo.facade import patch
from caliendo.patch import replay
from caliendo.util import recache
from caliendo import Ignore
import caliendo
from test.api import callback
from test.api.callback import method_calling_method
from test.api.callback import method_with_callback
from test.api.callback import callback_for_method
from test.api.callback import CALLBACK_FILE
from test.api.callback import CACHED_METHOD_FILE
def run_n_times(func, n):
for i in range(n):
pid = os.fork()
if pid:
os.waitpid(pid, 0)
else:
func(i)
os._exit(0)
class ReplayTestCase(unittest.TestCase):
def setUp(self):
caliendo.util.register_suite()
recache()
flatfiles.CACHE_['stacks'] = {}
flatfiles.CACHE_['seeds'] = {}
flatfiles.CACHE_['cache'] = {}
with open(CALLBACK_FILE, 'w+') as f:
pass
with open(CACHED_METHOD_FILE, 'w+') as f:
pass
def test_replay(self):
def do_it(i):
@replay('test.api.callback.callback_for_method')
@patch('test.api.callback.method_with_callback')
def test(i):
cb_file = method_with_callback(callback_for_method, 0.5)
with open(cb_file, 'rb') as f:
contents = f.read()
assert contents == ('.' * (i+1)), "Got {0} was expecting {1}".format(contents, ('.' * (i+1)))
test(i)
os._exit(0)
for i in range(2):
pid = os.fork()
if pid:
os.waitpid(pid, 0)
else:
do_it(i)
with open(CACHED_METHOD_FILE, 'rb') as f:
assert f.read() == '.'
def test_replay_with_ignore(self):
def do_it(i):
@replay('test.api.callback.callback_for_method')
@patch('test.api.callback.method_with_callback', ignore=Ignore([1]))
def test_(i):
cb_file = method_with_callback(callback_for_method, random.random())
with open(cb_file, 'rb') as f:
contents = f.read()
assert contents == ('.' * (i+1)), "Got {0} was expecting {1}".format(contents, ('.' * (i+1)))
test_(i)
os._exit(0)
for i in range(2):
pid = os.fork()
if pid:
os.waitpid(pid, 0)
else:
do_it(i)
with open(CACHED_METHOD_FILE, 'rb') as f:
assert f.read() == '.'
if __name__ == '__main__':
unittest.main()<|fim▁end|>
| |
<|file_name|>teamcoco.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
import base64
import re
from .common import InfoExtractor
from ..utils import qualities
class TeamcocoIE(InfoExtractor):
_VALID_URL = r'http://teamcoco\.com/video/(?P<video_id>[0-9]+)?/?(?P<display_id>.*)'
_TESTS = [
{
'url': 'http://teamcoco.com/video/80187/conan-becomes-a-mary-kay-beauty-consultant',
'md5': '3f7746aa0dc86de18df7539903d399ea',
'info_dict': {
'id': '80187',
'ext': 'mp4',
'title': 'Conan Becomes A Mary Kay Beauty Consultant',
'description': 'Mary Kay is perhaps the most trusted name in female beauty, so of course Conan is a natural choice to sell their products.',
'age_limit': 0,
}
}, {
'url': 'http://teamcoco.com/video/louis-ck-interview-george-w-bush',
'md5': 'cde9ba0fa3506f5f017ce11ead928f9a',
'info_dict': {
'id': '19705',
'ext': 'mp4',
'description': 'Louis C.K. got starstruck by George W. Bush, so what? Part one.',
'title': 'Louis C.K. Interview Pt. 1 11/3/11',
'age_limit': 0,
}
}
]
_VIDEO_ID_REGEXES = (
r'"eVar42"\s*:\s*(\d+)',
r'Ginger\.TeamCoco\.openInApp\("video",\s*"([^"]+)"',
r'"id_not"\s*:\s*(\d+)'
)
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
display_id = mobj.group('display_id')
webpage = self._download_webpage(url, display_id)
video_id = mobj.group('video_id')
if not video_id:
video_id = self._html_search_regex(
self._VIDEO_ID_REGEXES, webpage, 'video id')
embed_url = 'http://teamcoco.com/embed/v/%s' % video_id
embed = self._download_webpage(
embed_url, video_id, 'Downloading embed page')
encoded_data = self._search_regex(
r'"preload"\s*:\s*"([^"]+)"', embed, 'encoded data')
data = self._parse_json(
base64.b64decode(encoded_data.encode('ascii')).decode('utf-8'), video_id)
formats = []
get_quality = qualities(['500k', '480p', '1000k', '720p', '1080p'])
for filed in data['files']:
m_format = re.search(r'(\d+(k|p))\.mp4', filed['url'])
if m_format is not None:
format_id = m_format.group(1)
else:
format_id = filed['bitrate']
tbr = (
int(filed['bitrate'])
if filed['bitrate'].isdigit()
else None)
formats.append({
'url': filed['url'],
'ext': 'mp4',
'tbr': tbr,
'format_id': format_id,
'quality': get_quality(format_id),
})
self._sort_formats(formats)
return {
'id': video_id,
'display_id': display_id,
'formats': formats,
'title': data['title'],
'thumbnail': data.get('thumb', {}).get('href'),
'description': data.get('teaser'),<|fim▁hole|> }<|fim▁end|>
|
'age_limit': self._family_friendly_search(webpage),
|
<|file_name|>magic-string.es.js<|end_file_name|><|fim▁begin|>import { encode } from 'vlq';
function Chunk ( start, end, content ) {
this.start = start;
this.end = end;
this.original = content;
this.intro = '';
this.outro = '';
this.content = content;
this.storeName = false;
this.edited = false;
// we make these non-enumerable, for sanity while debugging
Object.defineProperties( this, {
previous: { writable: true, value: null },
next: { writable: true, value: null }
});
}
Chunk.prototype = {
appendLeft: function appendLeft ( content ) {
this.outro += content;
},
appendRight: function appendRight ( content ) {
this.intro = this.intro + content;
},
clone: function clone () {
var chunk = new Chunk( this.start, this.end, this.original );
chunk.intro = this.intro;
chunk.outro = this.outro;
chunk.content = this.content;
chunk.storeName = this.storeName;
chunk.edited = this.edited;
return chunk;
},
contains: function contains ( index ) {
return this.start < index && index < this.end;
},
eachNext: function eachNext ( fn ) {
var chunk = this;
while ( chunk ) {
fn( chunk );
chunk = chunk.next;
}
},
eachPrevious: function eachPrevious ( fn ) {
var chunk = this;
while ( chunk ) {
fn( chunk );
chunk = chunk.previous;
}
},
edit: function edit ( content, storeName, contentOnly ) {
this.content = content;
if ( !contentOnly ) {
this.intro = '';
this.outro = '';
}
this.storeName = storeName;
this.edited = true;
return this;
},
prependLeft: function prependLeft ( content ) {
this.outro = content + this.outro;
},
prependRight: function prependRight ( content ) {
this.intro = content + this.intro;
},
split: function split ( index ) {
var sliceIndex = index - this.start;
var originalBefore = this.original.slice( 0, sliceIndex );
var originalAfter = this.original.slice( sliceIndex );
this.original = originalBefore;
var newChunk = new Chunk( index, this.end, originalAfter );
newChunk.outro = this.outro;
this.outro = '';
this.end = index;
if ( this.edited ) {
// TODO is this block necessary?...
newChunk.edit( '', false );
this.content = '';
} else {
this.content = originalBefore;
}
newChunk.next = this.next;
if ( newChunk.next ) { newChunk.next.previous = newChunk; }
newChunk.previous = this;
this.next = newChunk;
return newChunk;
},
toString: function toString () {
return this.intro + this.content + this.outro;
},
trimEnd: function trimEnd ( rx ) {
this.outro = this.outro.replace( rx, '' );
if ( this.outro.length ) { return true; }
var trimmed = this.content.replace( rx, '' );
if ( trimmed.length ) {
if ( trimmed !== this.content ) {
this.split( this.start + trimmed.length ).edit( '', false );
}
return true;
} else {
this.edit( '', false );
this.intro = this.intro.replace( rx, '' );
if ( this.intro.length ) { return true; }
}
},
trimStart: function trimStart ( rx ) {
this.intro = this.intro.replace( rx, '' );
if ( this.intro.length ) { return true; }
var trimmed = this.content.replace( rx, '' );
if ( trimmed.length ) {
if ( trimmed !== this.content ) {
this.split( this.end - trimmed.length );
this.edit( '', false );
}
return true;
} else {
this.edit( '', false );
this.outro = this.outro.replace( rx, '' );
if ( this.outro.length ) { return true; }
}
}
};
var _btoa;
if ( typeof window !== 'undefined' && typeof window.btoa === 'function' ) {
_btoa = window.btoa;
} else if ( typeof Buffer === 'function' ) {
_btoa = function (str) { return new Buffer( str ).toString( 'base64' ); };
} else {
_btoa = function () {
throw new Error( 'Unsupported environment: `window.btoa` or `Buffer` should be supported.' );
};
}
var btoa = _btoa;
function SourceMap ( properties ) {
this.version = 3;
this.file = properties.file;
this.sources = properties.sources;
this.sourcesContent = properties.sourcesContent;
this.names = properties.names;
this.mappings = properties.mappings;
}
SourceMap.prototype = {
toString: function toString () {
return JSON.stringify( this );
},
toUrl: function toUrl () {
return 'data:application/json;charset=utf-8;base64,' + btoa( this.toString() );
}
};
function guessIndent ( code ) {
var lines = code.split( '\n' );
var tabbed = lines.filter( function (line) { return /^\t+/.test( line ); } );
var spaced = lines.filter( function (line) { return /^ {2,}/.test( line ); } );
if ( tabbed.length === 0 && spaced.length === 0 ) {
return null;
}
// More lines tabbed than spaced? Assume tabs, and
// default to tabs in the case of a tie (or nothing
// to go on)
if ( tabbed.length >= spaced.length ) {
return '\t';
}
// Otherwise, we need to guess the multiple
var min = spaced.reduce( function ( previous, current ) {
var numSpaces = /^ +/.exec( current )[0].length;
return Math.min( numSpaces, previous );
}, Infinity );
return new Array( min + 1 ).join( ' ' );
}
function getRelativePath ( from, to ) {
var fromParts = from.split( /[\/\\]/ );
var toParts = to.split( /[\/\\]/ );
fromParts.pop(); // get dirname
while ( fromParts[0] === toParts[0] ) {
fromParts.shift();
toParts.shift();
}
if ( fromParts.length ) {
var i = fromParts.length;
while ( i-- ) { fromParts[i] = '..'; }
}
return fromParts.concat( toParts ).join( '/' );
}
var toString$1 = Object.prototype.toString;
function isObject ( thing ) {
return toString$1.call( thing ) === '[object Object]';
}
function getLocator ( source ) {
var originalLines = source.split( '\n' );
var start = 0;
var lineRanges = originalLines.map( function ( line, i ) {
var end = start + line.length + 1;
var range = { start: start, end: end, line: i };
start = end;
return range;
});
var i = 0;
function rangeContains ( range, index ) {
return range.start <= index && index < range.end;
}
function getLocation ( range, index ) {
return { line: range.line, column: index - range.start };
}
return function locate ( index ) {
var range = lineRanges[i];
var d = index >= range.end ? 1 : -1;
while ( range ) {
if ( rangeContains( range, index ) ) { return getLocation( range, index ); }
i += d;
range = lineRanges[i];
}
};
}
function Mappings ( hires ) {
var this$1 = this;
var offsets = {
generatedCodeColumn: 0,
sourceIndex: 0,
sourceCodeLine: 0,
sourceCodeColumn: 0,
sourceCodeName: 0
};
var generatedCodeLine = 0;
var generatedCodeColumn = 0;
this.raw = [];
var rawSegments = this.raw[ generatedCodeLine ] = [];
var pending = null;
this.addEdit = function ( sourceIndex, content, original, loc, nameIndex ) {
if ( content.length ) {
rawSegments.push([
generatedCodeColumn,
sourceIndex,
loc.line,
loc.column,
nameIndex ]);
} else if ( pending ) {
rawSegments.push( pending );
}
this$1.advance( content );
pending = null;
};
this.addUneditedChunk = function ( sourceIndex, chunk, original, loc, sourcemapLocations ) {
var originalCharIndex = chunk.start;
var first = true;
while ( originalCharIndex < chunk.end ) {
if ( hires || first || sourcemapLocations[ originalCharIndex ] ) {
rawSegments.push([
generatedCodeColumn,
sourceIndex,
loc.line,
loc.column,
-1
]);
}
if ( original[ originalCharIndex ] === '\n' ) {
loc.line += 1;
loc.column = 0;
generatedCodeLine += 1;
this$1.raw[ generatedCodeLine ] = rawSegments = [];
generatedCodeColumn = 0;
} else {
loc.column += 1;
generatedCodeColumn += 1;
}
originalCharIndex += 1;
first = false;
}
pending = [
generatedCodeColumn,
sourceIndex,
loc.line,
loc.column,
-1 ];
};
this.advance = function (str) {
if ( !str ) { return; }
var lines = str.split( '\n' );
var lastLine = lines.pop();
if ( lines.length ) {
generatedCodeLine += lines.length;
this$1.raw[ generatedCodeLine ] = rawSegments = [];
generatedCodeColumn = lastLine.length;
} else {
generatedCodeColumn += lastLine.length;
}
};
this.encode = function () {
return this$1.raw.map( function (segments) {
var generatedCodeColumn = 0;
return segments.map( function (segment) {
var arr = [
segment[0] - generatedCodeColumn,
segment[1] - offsets.sourceIndex,
segment[2] - offsets.sourceCodeLine,
segment[3] - offsets.sourceCodeColumn
];
generatedCodeColumn = segment[0];
offsets.sourceIndex = segment[1];
offsets.sourceCodeLine = segment[2];
offsets.sourceCodeColumn = segment[3];
if ( ~segment[4] ) {
arr.push( segment[4] - offsets.sourceCodeName );
offsets.sourceCodeName = segment[4];
}
return encode( arr );
}).join( ',' );
}).join( ';' );
};
}
var Stats = function Stats () {
Object.defineProperties( this, {
startTimes: { value: {} }
});
};
Stats.prototype.time = function time ( label ) {
this.startTimes[ label ] = process.hrtime();
};
Stats.prototype.timeEnd = function timeEnd ( label ) {
var elapsed = process.hrtime( this.startTimes[ label ] );
if ( !this[ label ] ) { this[ label ] = 0; }
this[ label ] += elapsed[0] * 1e3 + elapsed[1] * 1e-6;
};
var warned = {
insertLeft: false,
insertRight: false,
storeName: false
};
function MagicString$1 ( string, options ) {
if ( options === void 0 ) options = {};
var chunk = new Chunk( 0, string.length, string );
Object.defineProperties( this, {
original: { writable: true, value: string },
outro: { writable: true, value: '' },
intro: { writable: true, value: '' },
firstChunk: { writable: true, value: chunk },
lastChunk: { writable: true, value: chunk },
lastSearchedChunk: { writable: true, value: chunk },
byStart: { writable: true, value: {} },
byEnd: { writable: true, value: {} },
filename: { writable: true, value: options.filename },
indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
sourcemapLocations: { writable: true, value: {} },
storedNames: { writable: true, value: {} },
indentStr: { writable: true, value: guessIndent( string ) }
});
this.byStart[ 0 ] = chunk;
this.byEnd[ string.length ] = chunk;
}
MagicString$1.prototype = {
addSourcemapLocation: function addSourcemapLocation ( char ) {
this.sourcemapLocations[ char ] = true;
},
append: function append ( content ) {
if ( typeof content !== 'string' ) { throw new TypeError( 'outro content must be a string' ); }
this.outro += content;
return this;
},
appendLeft: function appendLeft ( index, content ) {
if ( typeof content !== 'string' ) { throw new TypeError( 'inserted content must be a string' ); }
this._split( index );
var chunk = this.byEnd[ index ];
if ( chunk ) {
chunk.appendLeft( content );
} else {
this.intro += content;
}
return this;
},
appendRight: function appendRight ( index, content ) {
if ( typeof content !== 'string' ) { throw new TypeError( 'inserted content must be a string' ); }
this._split( index );
var chunk = this.byStart[ index ];
if ( chunk ) {
chunk.appendRight( content );
} else {
this.outro += content;
}
return this;
},
clone: function clone () {
var cloned = new MagicString$1( this.original, { filename: this.filename });
var originalChunk = this.firstChunk;
var clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
while ( originalChunk ) {
cloned.byStart[ clonedChunk.start ] = clonedChunk;
cloned.byEnd[ clonedChunk.end ] = clonedChunk;
var nextOriginalChunk = originalChunk.next;
var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
if ( nextClonedChunk ) {
clonedChunk.next = nextClonedChunk;
nextClonedChunk.previous = clonedChunk;
clonedChunk = nextClonedChunk;
}
originalChunk = nextOriginalChunk;
}
cloned.lastChunk = clonedChunk;
if ( this.indentExclusionRanges ) {
cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
}
Object.keys( this.sourcemapLocations ).forEach( function (loc) {
cloned.sourcemapLocations[ loc ] = true;
});
return cloned;
},
generateMap: function generateMap ( options ) {
var this$1 = this;
options = options || {};
var sourceIndex = 0;
var names = Object.keys( this.storedNames );
var mappings = new Mappings( options.hires );
var locate = getLocator( this.original );
if ( this.intro ) {
mappings.advance( this.intro );
}
this.firstChunk.eachNext( function (chunk) {
var loc = locate( chunk.start );
if ( chunk.intro.length ) { mappings.advance( chunk.intro ); }
if ( chunk.edited ) {
mappings.addEdit( sourceIndex, chunk.content, chunk.original, loc, chunk.storeName ? names.indexOf( chunk.original ) : -1 );
} else {
mappings.addUneditedChunk( sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations );
}
if ( chunk.outro.length ) { mappings.advance( chunk.outro ); }
});
var map = new SourceMap({
file: ( options.file ? options.file.split( /[\/\\]/ ).pop() : null ),
sources: [ options.source ? getRelativePath( options.file || '', options.source ) : null ],
sourcesContent: options.includeContent ? [ this.original ] : [ null ],
names: names,
mappings: mappings.encode()
});
return map;
},
getIndentString: function getIndentString () {
return this.indentStr === null ? '\t' : this.indentStr;
},
indent: function indent ( indentStr, options ) {
var this$1 = this;
var pattern = /^[^\r\n]/gm;
if ( isObject( indentStr ) ) {
options = indentStr;
indentStr = undefined;
}
indentStr = indentStr !== undefined ? indentStr : ( this.indentStr || '\t' );
if ( indentStr === '' ) { return this; } // noop
options = options || {};
// Process exclusion ranges
var isExcluded = {};
if ( options.exclude ) {
var exclusions = typeof options.exclude[0] === 'number' ? [ options.exclude ] : options.exclude;
exclusions.forEach( function (exclusion) {
for ( var i = exclusion[0]; i < exclusion[1]; i += 1 ) {
isExcluded[i] = true;
}
});
}
var shouldIndentNextCharacter = options.indentStart !== false;
var replacer = function (match) {
if ( shouldIndentNextCharacter ) { return ("" + indentStr + match); }
shouldIndentNextCharacter = true;
return match;
};
this.intro = this.intro.replace( pattern, replacer );
var charIndex = 0;
var chunk = this.firstChunk;
while ( chunk ) {
var end = chunk.end;
if ( chunk.edited ) {
if ( !isExcluded[ charIndex ] ) {
chunk.content = chunk.content.replace( pattern, replacer );
if ( chunk.content.length ) {
shouldIndentNextCharacter = chunk.content[ chunk.content.length - 1 ] === '\n';
}
}
} else {
charIndex = chunk.start;
while ( charIndex < end ) {
if ( !isExcluded[ charIndex ] ) {
var char = this$1.original[ charIndex ];
if ( char === '\n' ) {
shouldIndentNextCharacter = true;
} else if ( char !== '\r' && shouldIndentNextCharacter ) {
shouldIndentNextCharacter = false;
if ( charIndex === chunk.start ) {
chunk.prependRight( indentStr );
} else {
var rhs = chunk.split( charIndex );
rhs.prependRight( indentStr );
this$1.byStart[ charIndex ] = rhs;
this$1.byEnd[ charIndex ] = chunk;
chunk = rhs;
}
}
}
charIndex += 1;
}
}
charIndex = chunk.end;
chunk = chunk.next;
}
this.outro = this.outro.replace( pattern, replacer );
return this;
},
insert: function insert () {
throw new Error( 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)' );
},
insertLeft: function insertLeft ( index, content ) {
if ( !warned.insertLeft ) {
console.warn( 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead' ); // eslint-disable-line no-console
warned.insertLeft = true;
}
return this.appendLeft( index, content );
},
insertRight: function insertRight ( index, content ) {
if ( !warned.insertRight ) {
console.warn( 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead' ); // eslint-disable-line no-console
warned.insertRight = true;
}
return this.prependRight( index, content );
},
move: function move ( start, end, index ) {
if ( index >= start && index <= end ) { throw new Error( 'Cannot move a selection inside itself' ); }
this._split( start );
this._split( end );
this._split( index );
var first = this.byStart[ start ];
var last = this.byEnd[ end ];
var oldLeft = first.previous;
var oldRight = last.next;
var newRight = this.byStart[ index ];
if ( !newRight && last === this.lastChunk ) { return this; }
var newLeft = newRight ? newRight.previous : this.lastChunk;
if ( oldLeft ) { oldLeft.next = oldRight; }
if ( oldRight ) { oldRight.previous = oldLeft; }
if ( newLeft ) { newLeft.next = first; }
if ( newRight ) { newRight.previous = last; }
if ( !first.previous ) { this.firstChunk = last.next; }
if ( !last.next ) {
this.lastChunk = first.previous;
this.lastChunk.next = null;
}
first.previous = newLeft;
last.next = newRight;
if ( !newLeft ) { this.firstChunk = first; }
if ( !newRight ) { this.lastChunk = last; }
return this;
},
overwrite: function overwrite ( start, end, content, options ) {
var this$1 = this;
if ( typeof content !== 'string' ) { throw new TypeError( 'replacement content must be a string' ); }
while ( start < 0 ) { start += this$1.original.length; }
while ( end < 0 ) { end += this$1.original.length; }
if ( end > this.original.length ) { throw new Error( 'end is out of bounds' ); }
if ( start === end ) { throw new Error( 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead' ); }
this._split( start );
this._split( end );
if ( options === true ) {
if ( !warned.storeName ) {
console.warn( 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string' ); // eslint-disable-line no-console
warned.storeName = true;
}
options = { storeName: true };
}
var storeName = options !== undefined ? options.storeName : false;
var contentOnly = options !== undefined ? options.contentOnly : false;
if ( storeName ) {
var original = this.original.slice( start, end );
this.storedNames[ original ] = true;
}
var first = this.byStart[ start ];
var last = this.byEnd[ end ];
if ( first ) {
if ( end > first.end && first.next !== this.byStart[ first.end ] ) {
throw new Error( 'Cannot overwrite across a split point' );
}
first.edit( content, storeName, contentOnly );
if ( last ) {
first.next = last.next;
} else {
first.next = null;
this.lastChunk = first;
}
first.original = this.original.slice( start, end );
first.end = end;
}
else {
// must be inserting at the end
var newChunk = new Chunk( start, end, '' ).edit( content, storeName );
// TODO last chunk in the array may not be the last chunk, if it's moved...
last.next = newChunk;
newChunk.previous = last;
}
return this;
},
prepend: function prepend ( content ) {
if ( typeof content !== 'string' ) { throw new TypeError( 'outro content must be a string' ); }
this.intro = content + this.intro;
return this;
},
prependLeft: function prependLeft ( index, content ) {
if ( typeof content !== 'string' ) { throw new TypeError( 'inserted content must be a string' ); }
this._split( index );
var chunk = this.byEnd[ index ];
if ( chunk ) {
chunk.prependLeft( content );
} else {
this.intro = content + this.intro;
}
return this;
},
prependRight: function prependRight ( index, content ) {
if ( typeof content !== 'string' ) { throw new TypeError( 'inserted content must be a string' ); }
this._split( index );
var chunk = this.byStart[ index ];
if ( chunk ) {
chunk.prependRight( content );
} else {
this.outro = content + this.outro;
}
return this;
},
remove: function remove ( start, end ) {
var this$1 = this;
while ( start < 0 ) { start += this$1.original.length; }
while ( end < 0 ) { end += this$1.original.length; }
if ( start === end ) { return this; }
if ( start < 0 || end > this.original.length ) { throw new Error( 'Character is out of bounds' ); }
if ( start > end ) { throw new Error( 'end must be greater than start' ); }
this._split( start );
this._split( end );
var chunk = this.byStart[ start ];
while ( chunk ) {
chunk.intro = '';
chunk.outro = '';
chunk.edit( '' );
chunk = end > chunk.end ? this$1.byStart[ chunk.end ] : null;
}
return this;
},
slice: function slice ( start, end ) {
var this$1 = this;
if ( start === void 0 ) start = 0;
if ( end === void 0 ) end = this.original.length;
while ( start < 0 ) { start += this$1.original.length; }
while ( end < 0 ) { end += this$1.original.length; }
var result = '';
// find start chunk
var chunk = this.firstChunk;
while ( chunk && ( chunk.start > start || chunk.end <= start ) ) {
// found end chunk before start
if ( chunk.start < end && chunk.end >= end ) {
return result;
}
chunk = chunk.next;
}
if ( chunk && chunk.edited && chunk.start !== start ) { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
var startChunk = chunk;
while ( chunk ) {
if ( chunk.intro && ( startChunk !== chunk || chunk.start === start ) ) {
result += chunk.intro;
}
var containsEnd = chunk.start < end && chunk.end >= end;
if ( containsEnd && chunk.edited && chunk.end !== end ) { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
var sliceStart = startChunk === chunk ? start - chunk.start : 0;
var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
result += chunk.content.slice( sliceStart, sliceEnd );
if ( chunk.outro && ( !containsEnd || chunk.end === end ) ) {
result += chunk.outro;
}
if ( containsEnd ) {
break;
}
chunk = chunk.next;
}
return result;
},
// TODO deprecate this? not really very useful
snip: function snip ( start, end ) {
var clone = this.clone();
clone.remove( 0, start );
clone.remove( end, clone.original.length );
return clone;
},
_split: function _split ( index ) {
var this$1 = this;
if ( this.byStart[ index ] || this.byEnd[ index ] ) { return; }
var chunk = this.lastSearchedChunk;
var searchForward = index > chunk.end;
while ( true ) {
if ( chunk.contains( index ) ) { return this$1._splitChunk( chunk, index ); }
chunk = searchForward ?
this$1.byStart[ chunk.end ] :
this$1.byEnd[ chunk.start ];
}
},
_splitChunk: function _splitChunk ( chunk, index ) {
if ( chunk.edited && chunk.content.length ) { // zero-length edited chunks are a special case (overlapping replacements)
var loc = getLocator( this.original )( index );
throw new Error( ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")") );
}
var newChunk = chunk.split( index );
this.byEnd[ index ] = chunk;
this.byStart[ index ] = newChunk;
this.byEnd[ newChunk.end ] = newChunk;
if ( chunk === this.lastChunk ) { this.lastChunk = newChunk; }
this.lastSearchedChunk = chunk;
return true;
},
toString: function toString () {
var str = this.intro;
var chunk = this.firstChunk;
while ( chunk ) {
str += chunk.toString();
chunk = chunk.next;
}
return str + this.outro;
},
trimLines: function trimLines () {
return this.trim('[\\r\\n]');
},
trim: function trim ( charType ) {
return this.trimStart( charType ).trimEnd( charType );
},
trimEnd: function trimEnd ( charType ) {
var this$1 = this;
var rx = new RegExp( ( charType || '\\s' ) + '+$' );
this.outro = this.outro.replace( rx, '' );
if ( this.outro.length ) { return this; }
var chunk = this.lastChunk;
do {
var end = chunk.end;
var aborted = chunk.trimEnd( rx );
// if chunk was trimmed, we have a new lastChunk
if ( chunk.end !== end ) {
this$1.lastChunk = chunk.next;
this$1.byEnd[ chunk.end ] = chunk;
this$1.byStart[ chunk.next.start ] = chunk.next;
}
if ( aborted ) { return this$1; }
chunk = chunk.previous;
} while ( chunk );
return this;
},
trimStart: function trimStart ( charType ) {
var this$1 = this;
var rx = new RegExp( '^' + ( charType || '\\s' ) + '+' );
this.intro = this.intro.replace( rx, '' );
if ( this.intro.length ) { return this; }
var chunk = this.firstChunk;
do {
var end = chunk.end;
var aborted = chunk.trimStart( rx );
if ( chunk.end !== end ) {
// special case...
if ( chunk === this$1.lastChunk ) { this$1.lastChunk = chunk.next; }
this$1.byEnd[ chunk.end ] = chunk;
this$1.byStart[ chunk.next.start ] = chunk.next;
}
if ( aborted ) { return this$1; }
chunk = chunk.next;
} while ( chunk );
return this;
}
};<|fim▁hole|>
function Bundle ( options ) {
if ( options === void 0 ) options = {};
this.intro = options.intro || '';
this.separator = options.separator !== undefined ? options.separator : '\n';
this.sources = [];
this.uniqueSources = [];
this.uniqueSourceIndexByFilename = {};
}
Bundle.prototype = {
addSource: function addSource ( source ) {
if ( source instanceof MagicString$1 ) {
return this.addSource({
content: source,
filename: source.filename,
separator: this.separator
});
}
if ( !isObject( source ) || !source.content ) {
throw new Error( 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`' );
}
[ 'filename', 'indentExclusionRanges', 'separator' ].forEach( function (option) {
if ( !hasOwnProp.call( source, option ) ) { source[ option ] = source.content[ option ]; }
});
if ( source.separator === undefined ) { // TODO there's a bunch of this sort of thing, needs cleaning up
source.separator = this.separator;
}
if ( source.filename ) {
if ( !hasOwnProp.call( this.uniqueSourceIndexByFilename, source.filename ) ) {
this.uniqueSourceIndexByFilename[ source.filename ] = this.uniqueSources.length;
this.uniqueSources.push({ filename: source.filename, content: source.content.original });
} else {
var uniqueSource = this.uniqueSources[ this.uniqueSourceIndexByFilename[ source.filename ] ];
if ( source.content.original !== uniqueSource.content ) {
throw new Error( ("Illegal source: same filename (" + (source.filename) + "), different contents") );
}
}
}
this.sources.push( source );
return this;
},
append: function append ( str, options ) {
this.addSource({
content: new MagicString$1( str ),
separator: ( options && options.separator ) || ''
});
return this;
},
clone: function clone () {
var bundle = new Bundle({
intro: this.intro,
separator: this.separator
});
this.sources.forEach( function (source) {
bundle.addSource({
filename: source.filename,
content: source.content.clone(),
separator: source.separator
});
});
return bundle;
},
generateMap: function generateMap ( options ) {
var this$1 = this;
if ( options === void 0 ) options = {};
var names = [];
this.sources.forEach( function (source) {
Object.keys( source.content.storedNames ).forEach( function (name) {
if ( !~names.indexOf( name ) ) { names.push( name ); }
});
});
var mappings = new Mappings( options.hires );
if ( this.intro ) {
mappings.advance( this.intro );
}
this.sources.forEach( function ( source, i ) {
if ( i > 0 ) {
mappings.advance( this$1.separator );
}
var sourceIndex = source.filename ? this$1.uniqueSourceIndexByFilename[ source.filename ] : -1;
var magicString = source.content;
var locate = getLocator( magicString.original );
if ( magicString.intro ) {
mappings.advance( magicString.intro );
}
magicString.firstChunk.eachNext( function (chunk) {
var loc = locate( chunk.start );
if ( chunk.intro.length ) { mappings.advance( chunk.intro ); }
if ( source.filename ) {
if ( chunk.edited ) {
mappings.addEdit( sourceIndex, chunk.content, chunk.original, loc, chunk.storeName ? names.indexOf( chunk.original ) : -1 );
} else {
mappings.addUneditedChunk( sourceIndex, chunk, magicString.original, loc, magicString.sourcemapLocations );
}
}
else {
mappings.advance( chunk.content );
}
if ( chunk.outro.length ) { mappings.advance( chunk.outro ); }
});
if ( magicString.outro ) {
mappings.advance( magicString.outro );
}
});
return new SourceMap({
file: ( options.file ? options.file.split( /[\/\\]/ ).pop() : null ),
sources: this.uniqueSources.map( function (source) {
return options.file ? getRelativePath( options.file, source.filename ) : source.filename;
}),
sourcesContent: this.uniqueSources.map( function (source) {
return options.includeContent ? source.content : null;
}),
names: names,
mappings: mappings.encode()
});
},
getIndentString: function getIndentString () {
var indentStringCounts = {};
this.sources.forEach( function (source) {
var indentStr = source.content.indentStr;
if ( indentStr === null ) { return; }
if ( !indentStringCounts[ indentStr ] ) { indentStringCounts[ indentStr ] = 0; }
indentStringCounts[ indentStr ] += 1;
});
return ( Object.keys( indentStringCounts ).sort( function ( a, b ) {
return indentStringCounts[a] - indentStringCounts[b];
})[0] ) || '\t';
},
indent: function indent ( indentStr ) {
var this$1 = this;
if ( !arguments.length ) {
indentStr = this.getIndentString();
}
if ( indentStr === '' ) { return this; } // noop
var trailingNewline = !this.intro || this.intro.slice( -1 ) === '\n';
this.sources.forEach( function ( source, i ) {
var separator = source.separator !== undefined ? source.separator : this$1.separator;
var indentStart = trailingNewline || ( i > 0 && /\r?\n$/.test( separator ) );
source.content.indent( indentStr, {
exclude: source.indentExclusionRanges,
indentStart: indentStart//: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
});
// TODO this is a very slow way to determine this
trailingNewline = source.content.toString().slice( 0, -1 ) === '\n';
});
if ( this.intro ) {
this.intro = indentStr + this.intro.replace( /^[^\n]/gm, function ( match, index ) {
return index > 0 ? indentStr + match : match;
});
}
return this;
},
prepend: function prepend ( str ) {
this.intro = str + this.intro;
return this;
},
toString: function toString () {
var this$1 = this;
var body = this.sources.map( function ( source, i ) {
var separator = source.separator !== undefined ? source.separator : this$1.separator;
var str = ( i > 0 ? separator : '' ) + source.content.toString();
return str;
}).join( '' );
return this.intro + body;
},
trimLines: function trimLines () {
return this.trim('[\\r\\n]');
},
trim: function trim ( charType ) {
return this.trimStart( charType ).trimEnd( charType );
},
trimStart: function trimStart ( charType ) {
var this$1 = this;
var rx = new RegExp( '^' + ( charType || '\\s' ) + '+' );
this.intro = this.intro.replace( rx, '' );
if ( !this.intro ) {
var source;
var i = 0;
do {
source = this$1.sources[i];
if ( !source ) {
break;
}
source.content.trimStart( charType );
i += 1;
} while ( source.content.toString() === '' ); // TODO faster way to determine non-empty source?
}
return this;
},
trimEnd: function trimEnd ( charType ) {
var this$1 = this;
var rx = new RegExp( ( charType || '\\s' ) + '+$' );
var source;
var i = this.sources.length - 1;
do {
source = this$1.sources[i];
if ( !source ) {
this$1.intro = this$1.intro.replace( rx, '' );
break;
}
source.content.trimEnd( charType );
i -= 1;
} while ( source.content.toString() === '' ); // TODO faster way to determine non-empty source?
return this;
}
};
export { Bundle };export default MagicString$1;
//# sourceMappingURL=magic-string.es.js.map<|fim▁end|>
|
var hasOwnProp = Object.prototype.hasOwnProperty;
|
<|file_name|>entity.js<|end_file_name|><|fim▁begin|>/* Copyright 2015 Dietrich Epp.
This file is part of Dash and the Jetpack Space Pirates. The Dash
and the Jetpack Space Pirates source code is distributed under the
terms of the MIT license. See LICENSE.txt for details. */
'use strict';
var glm = require('gl-matrix');
var vec2 = glm.vec2;
var color = require('./color');
var param = require('./param');
var physics = require('./physics');
function destroy(body) {
if (body.world) {
body.world.removeBody(body);
}
}
var Types = {};
/*
* Register entity types.
*
* category: The category name, or null.
* types: Mapping from type names to types
*/
function registerTypes(types, category) {
var prefix = category ? category + '.' : '';
_.forOwn(types, function(value, key) {<|fim▁hole|> }
delete value.inherit;
}
var tname = prefix + key;
if (Types.hasOwnProperty(tname)) {
console.error('Duplicate type registered: ' + tname);
return;
}
Types[tname] = value;
});
}
function getType(type) {
return Types[type];
}
module.exports = {
destroy: destroy,
registerTypes: registerTypes,
getType: getType,
};<|fim▁end|>
|
var inh = value.inherit, i;
if (inh) {
for (i = 0; i < inh.length; i++) {
_.defaults(value, inh[i]);
|
<|file_name|>xml-parse.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf8 -*-
import xml.etree.ElementTree as ET<|fim▁hole|>filename = 'GeoLogger.gpx'
def main():
tree = ET.parse(filename)
root = tree.getroot()
pprint(root.tag)
pprint(root.attrib)
pprint(root.findtext('.'))
if __name__ == "__main__":
main()<|fim▁end|>
|
from pprint import pprint
|
<|file_name|>test_std.py<|end_file_name|><|fim▁begin|># #!/usr/bin/env python
#
# import nlopt # THIS IS NOT A PACKAGE!
# import numpy as np
#
# print(('nlopt version='+nlopt.__version__))
#
# def f(x, grad):
# F=x[0]
# L=x[1]
# E=x[2]
# I=x[3]
# D=F*L**3/(3.*E*I)
# return D
#
# n = 4
# opt = nlopt.opt(nlopt.LN_COBYLA, n)<|fim▁hole|># ub = np.array([60., 60., 40e3, 10.])
# x = (lb+ub)/2.
# opt.set_lower_bounds(lb)
# opt.set_upper_bounds(ub)
# opt.set_xtol_rel(1e-3)
# opt.set_ftol_rel(1e-3)
# xopt = opt.optimize(x)
#
# opt_val = opt.last_optimum_value()
# result = opt.last_optimize_result()
# print(('opt_result='+str(result)))
# print(('optimizer='+str(xopt)))
# print(('opt_val='+str(opt_val)))<|fim▁end|>
|
# opt.set_min_objective(f)
# lb = np.array([40., 50., 30e3, 1.])
|
<|file_name|>_constraints.py<|end_file_name|><|fim▁begin|>"""Constraints definition for minimize."""
from __future__ import division, print_function, absolute_import
import numpy as np
from ._hessian_update_strategy import BFGS<|fim▁hole|>from scipy._lib._numpy_compat import suppress_warnings
from scipy.sparse import issparse
class NonlinearConstraint(object):
"""Nonlinear constraint on the variables.
The constraint has the general inequality form::
lb <= fun(x) <= ub
Here the vector of independent variables x is passed as ndarray of shape
(n,) and ``fun`` returns a vector with m components.
It is possible to use equal bounds to represent an equality constraint or
infinite bounds to represent a one-sided constraint.
Parameters
----------
fun : callable
The function defining the constraint.
The signature is ``fun(x) -> array_like, shape (m,)``.
lb, ub : array_like
Lower and upper bounds on the constraint. Each array must have the
shape (m,) or be a scalar, in the latter case a bound will be the same
for all components of the constraint. Use ``np.inf`` with an
appropriate sign to specify a one-sided constraint.
Set components of `lb` and `ub` equal to represent an equality
constraint. Note that you can mix constraints of different types:
interval, one-sided or equality, by setting different components of
`lb` and `ub` as necessary.
jac : {callable, '2-point', '3-point', 'cs'}, optional
Method of computing the Jacobian matrix (an m-by-n matrix,
where element (i, j) is the partial derivative of f[i] with
respect to x[j]). The keywords {'2-point', '3-point',
'cs'} select a finite difference scheme for the numerical estimation.
A callable must have the following signature:
``jac(x) -> {ndarray, sparse matrix}, shape (m, n)``.
Default is '2-point'.
hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy, None}, optional
Method for computing the Hessian matrix. The keywords
{'2-point', '3-point', 'cs'} select a finite difference scheme for
numerical estimation. Alternatively, objects implementing
`HessianUpdateStrategy` interface can be used to approximate the
Hessian. Currently available implementations are:
- `BFGS` (default option)
- `SR1`
A callable must return the Hessian matrix of ``dot(fun, v)`` and
must have the following signature:
``hess(x, v) -> {LinearOperator, sparse matrix, array_like}, shape (n, n)``.
Here ``v`` is ndarray with shape (m,) containing Lagrange multipliers.
keep_feasible : array_like of bool, optional
Whether to keep the constraint components feasible throughout
iterations. A single value set this property for all components.
Default is False. Has no effect for equality constraints.
finite_diff_rel_step: None or array_like, optional
Relative step size for the finite difference approximation. Default is
None, which will select a reasonable value automatically depending
on a finite difference scheme.
finite_diff_jac_sparsity: {None, array_like, sparse matrix}, optional
Defines the sparsity structure of the Jacobian matrix for finite
difference estimation, its shape must be (m, n). If the Jacobian has
only few non-zero elements in *each* row, providing the sparsity
structure will greatly speed up the computations. A zero entry means
that a corresponding element in the Jacobian is identically zero.
If provided, forces the use of 'lsmr' trust-region solver.
If None (default) then dense differencing will be used.
Notes
-----
Finite difference schemes {'2-point', '3-point', 'cs'} may be used for
approximating either the Jacobian or the Hessian. We, however, do not allow
its use for approximating both simultaneously. Hence whenever the Jacobian
is estimated via finite-differences, we require the Hessian to be estimated
using one of the quasi-Newton strategies.
The scheme 'cs' is potentially the most accurate, but requires the function
to correctly handles complex inputs and be analytically continuable to the
complex plane. The scheme '3-point' is more accurate than '2-point' but
requires twice as many operations.
"""
def __init__(self, fun, lb, ub, jac='2-point', hess=BFGS(),
keep_feasible=False, finite_diff_rel_step=None,
finite_diff_jac_sparsity=None):
self.fun = fun
self.lb = lb
self.ub = ub
self.finite_diff_rel_step = finite_diff_rel_step
self.finite_diff_jac_sparsity = finite_diff_jac_sparsity
self.jac = jac
self.hess = hess
self.keep_feasible = keep_feasible
class LinearConstraint(object):
"""Linear constraint on the variables.
The constraint has the general inequality form::
lb <= A.dot(x) <= ub
Here the vector of independent variables x is passed as ndarray of shape
(n,) and the matrix A has shape (m, n).
It is possible to use equal bounds to represent an equality constraint or
infinite bounds to represent a one-sided constraint.
Parameters
----------
A : {array_like, sparse matrix}, shape (m, n)
Matrix defining the constraint.
lb, ub : array_like
Lower and upper bounds on the constraint. Each array must have the
shape (m,) or be a scalar, in the latter case a bound will be the same
for all components of the constraint. Use ``np.inf`` with an
appropriate sign to specify a one-sided constraint.
Set components of `lb` and `ub` equal to represent an equality
constraint. Note that you can mix constraints of different types:
interval, one-sided or equality, by setting different components of
`lb` and `ub` as necessary.
keep_feasible : array_like of bool, optional
Whether to keep the constraint components feasible throughout
iterations. A single value set this property for all components.
Default is False. Has no effect for equality constraints.
"""
def __init__(self, A, lb, ub, keep_feasible=False):
self.A = A
self.lb = lb
self.ub = ub
self.keep_feasible = keep_feasible
class Bounds(object):
"""Bounds constraint on the variables.
The constraint has the general inequality form::
lb <= x <= ub
It is possible to use equal bounds to represent an equality constraint or
infinite bounds to represent a one-sided constraint.
Parameters
----------
lb, ub : array_like, optional
Lower and upper bounds on independent variables. Each array must
have the same size as x or be a scalar, in which case a bound will be
the same for all the variables. Set components of `lb` and `ub` equal
to fix a variable. Use ``np.inf`` with an appropriate sign to disable
bounds on all or some variables. Note that you can mix constraints of
different types: interval, one-sided or equality, by setting different
components of `lb` and `ub` as necessary.
keep_feasible : array_like of bool, optional
Whether to keep the constraint components feasible throughout
iterations. A single value set this property for all components.
Default is False. Has no effect for equality constraints.
"""
def __init__(self, lb, ub, keep_feasible=False):
self.lb = lb
self.ub = ub
self.keep_feasible = keep_feasible
def __repr__(self):
if np.any(self.keep_feasible):
return "{}({!r}, {!r}, keep_feasible={!r})".format(type(self).__name__, self.lb, self.ub, self.keep_feasible)
else:
return "{}({!r}, {!r})".format(type(self).__name__, self.lb, self.ub)
class PreparedConstraint(object):
"""Constraint prepared from a user defined constraint.
On creation it will check whether a constraint definition is valid and
the initial point is feasible. If created successfully, it will contain
the attributes listed below.
Parameters
----------
constraint : {NonlinearConstraint, LinearConstraint`, Bounds}
Constraint to check and prepare.
x0 : array_like
Initial vector of independent variables.
sparse_jacobian : bool or None, optional
If bool, then the Jacobian of the constraint will be converted
to the corresponded format if necessary. If None (default), such
conversion is not made.
finite_diff_bounds : 2-tuple, optional
Lower and upper bounds on the independent variables for the finite
difference approximation, if applicable. Defaults to no bounds.
Attributes
----------
fun : {VectorFunction, LinearVectorFunction, IdentityVectorFunction}
Function defining the constraint wrapped by one of the convenience
classes.
bounds : 2-tuple
Contains lower and upper bounds for the constraints --- lb and ub.
These are converted to ndarray and have a size equal to the number of
the constraints.
keep_feasible : ndarray
Array indicating which components must be kept feasible with a size
equal to the number of the constraints.
"""
def __init__(self, constraint, x0, sparse_jacobian=None,
finite_diff_bounds=(-np.inf, np.inf)):
if isinstance(constraint, NonlinearConstraint):
fun = VectorFunction(constraint.fun, x0,
constraint.jac, constraint.hess,
constraint.finite_diff_rel_step,
constraint.finite_diff_jac_sparsity,
finite_diff_bounds, sparse_jacobian)
elif isinstance(constraint, LinearConstraint):
fun = LinearVectorFunction(constraint.A, x0, sparse_jacobian)
elif isinstance(constraint, Bounds):
fun = IdentityVectorFunction(x0, sparse_jacobian)
else:
raise ValueError("`constraint` of an unknown type is passed.")
m = fun.m
lb = np.asarray(constraint.lb, dtype=float)
ub = np.asarray(constraint.ub, dtype=float)
if lb.ndim == 0:
lb = np.resize(lb, m)
if ub.ndim == 0:
ub = np.resize(ub, m)
keep_feasible = np.asarray(constraint.keep_feasible, dtype=bool)
if keep_feasible.ndim == 0:
keep_feasible = np.resize(keep_feasible, m)
if keep_feasible.shape != (m,):
raise ValueError("`keep_feasible` has a wrong shape.")
mask = keep_feasible & (lb != ub)
f0 = fun.f
if np.any(f0[mask] < lb[mask]) or np.any(f0[mask] > ub[mask]):
raise ValueError("`x0` is infeasible with respect to some "
"inequality constraint with `keep_feasible` "
"set to True.")
self.fun = fun
self.bounds = (lb, ub)
self.keep_feasible = keep_feasible
def violation(self, x):
"""How much the constraint is exceeded by.
Parameters
----------
x : array-like
Vector of independent variables
Returns
-------
excess : array-like
How much the constraint is exceeded by, for each of the
constraints specified by `PreparedConstraint.fun`.
"""
with suppress_warnings() as sup:
sup.filter(UserWarning)
ev = self.fun.fun(np.asarray(x))
excess_lb = np.maximum(self.bounds[0] - ev, 0)
excess_ub = np.maximum(ev - self.bounds[1], 0)
return excess_lb + excess_ub
def new_bounds_to_old(lb, ub, n):
"""Convert the new bounds representation to the old one.
The new representation is a tuple (lb, ub) and the old one is a list
containing n tuples, i-th containing lower and upper bound on a i-th
variable.
"""
lb = np.asarray(lb)
ub = np.asarray(ub)
if lb.ndim == 0:
lb = np.resize(lb, n)
if ub.ndim == 0:
ub = np.resize(ub, n)
lb = [x if x > -np.inf else None for x in lb]
ub = [x if x < np.inf else None for x in ub]
return list(zip(lb, ub))
def old_bound_to_new(bounds):
"""Convert the old bounds representation to the new one.
The new representation is a tuple (lb, ub) and the old one is a list
containing n tuples, i-th containing lower and upper bound on a i-th
variable.
"""
lb, ub = zip(*bounds)
lb = np.array([x if x is not None else -np.inf for x in lb])
ub = np.array([x if x is not None else np.inf for x in ub])
return lb, ub
def strict_bounds(lb, ub, keep_feasible, n_vars):
"""Remove bounds which are not asked to be kept feasible."""
strict_lb = np.resize(lb, n_vars).astype(float)
strict_ub = np.resize(ub, n_vars).astype(float)
keep_feasible = np.resize(keep_feasible, n_vars)
strict_lb[~keep_feasible] = -np.inf
strict_ub[~keep_feasible] = np.inf
return strict_lb, strict_ub
def new_constraint_to_old(con, x0):
"""
Converts new-style constraint objects to old-style constraint dictionaries.
"""
if isinstance(con, NonlinearConstraint):
if (con.finite_diff_jac_sparsity is not None or
con.finite_diff_rel_step is not None or
not isinstance(con.hess, BFGS) or # misses user specified BFGS
con.keep_feasible):
warn("Constraint options `finite_diff_jac_sparsity`, "
"`finite_diff_rel_step`, `keep_feasible`, and `hess`"
"are ignored by this method.", OptimizeWarning)
fun = con.fun
if callable(con.jac):
jac = con.jac
else:
jac = None
else: # LinearConstraint
if con.keep_feasible:
warn("Constraint option `keep_feasible` is ignored by this "
"method.", OptimizeWarning)
A = con.A
if issparse(A):
A = A.todense()
fun = lambda x: np.dot(A, x)
jac = lambda x: A
# FIXME: when bugs in VectorFunction/LinearVectorFunction are worked out,
# use pcon.fun.fun and pcon.fun.jac. Until then, get fun/jac above.
pcon = PreparedConstraint(con, x0)
lb, ub = pcon.bounds
i_eq = lb == ub
i_bound_below = np.logical_xor(lb != -np.inf, i_eq)
i_bound_above = np.logical_xor(ub != np.inf, i_eq)
i_unbounded = np.logical_and(lb == -np.inf, ub == np.inf)
if np.any(i_unbounded):
warn("At least one constraint is unbounded above and below. Such "
"constraints are ignored.", OptimizeWarning)
ceq = []
if np.any(i_eq):
def f_eq(x):
y = np.array(fun(x)).flatten()
return y[i_eq] - lb[i_eq]
ceq = [{"type": "eq", "fun": f_eq}]
if jac is not None:
def j_eq(x):
dy = jac(x)
if issparse(dy):
dy = dy.todense()
dy = np.atleast_2d(dy)
return dy[i_eq, :]
ceq[0]["jac"] = j_eq
cineq = []
n_bound_below = np.sum(i_bound_below)
n_bound_above = np.sum(i_bound_above)
if n_bound_below + n_bound_above:
def f_ineq(x):
y = np.zeros(n_bound_below + n_bound_above)
y_all = np.array(fun(x)).flatten()
y[:n_bound_below] = y_all[i_bound_below] - lb[i_bound_below]
y[n_bound_below:] = -(y_all[i_bound_above] - ub[i_bound_above])
return y
cineq = [{"type": "ineq", "fun": f_ineq}]
if jac is not None:
def j_ineq(x):
dy = np.zeros((n_bound_below + n_bound_above, len(x0)))
dy_all = jac(x)
if issparse(dy_all):
dy_all = dy_all.todense()
dy_all = np.atleast_2d(dy_all)
dy[:n_bound_below, :] = dy_all[i_bound_below]
dy[n_bound_below:, :] = -dy_all[i_bound_above]
return dy
cineq[0]["jac"] = j_ineq
old_constraints = ceq + cineq
if len(old_constraints) > 1:
warn("Equality and inequality constraints are specified in the same "
"element of the constraint list. For efficient use with this "
"method, equality and inequality constraints should be specified "
"in separate elements of the constraint list. ", OptimizeWarning)
return old_constraints
def old_constraint_to_new(ic, con):
"""
Converts old-style constraint dictionaries to new-style constraint objects.
"""
# check type
try:
ctype = con['type'].lower()
except KeyError:
raise KeyError('Constraint %d has no type defined.' % ic)
except TypeError:
raise TypeError('Constraints must be a sequence of dictionaries.')
except AttributeError:
raise TypeError("Constraint's type must be a string.")
else:
if ctype not in ['eq', 'ineq']:
raise ValueError("Unknown constraint type '%s'." % con['type'])
if 'fun' not in con:
raise ValueError('Constraint %d has no function defined.' % ic)
lb = 0
if ctype == 'eq':
ub = 0
else:
ub = np.inf
jac = '2-point'
if 'args' in con:
args = con['args']
fun = lambda x: con['fun'](x, *args)
if 'jac' in con:
jac = lambda x: con['jac'](x, *args)
else:
fun = con['fun']
if 'jac' in con:
jac = con['jac']
return NonlinearConstraint(fun, lb, ub, jac)<|fim▁end|>
|
from ._differentiable_functions import (
VectorFunction, LinearVectorFunction, IdentityVectorFunction)
from .optimize import OptimizeWarning
from warnings import warn
|
<|file_name|>mocha.d.ts<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
|
export * from "./src/mocha/testing";
|
<|file_name|>Launcher.java<|end_file_name|><|fim▁begin|>package me.streib.janis.nanhotline.web;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.InetSocketAddress;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.SessionManager;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
<|fim▁hole|> InputStream ins;
File confFile = new File("conf/nanhotline.properties");
if (confFile.exists()) {
ins = new FileInputStream(confFile);
} else {
ins = Launcher.class
.getResourceAsStream("nanhotline.properties");
}
conf = new NANHotlineConfiguration(ins);
} else {
conf = new NANHotlineConfiguration(new FileInputStream(new File(
args[0])));
}
DatabaseConnection.init(conf);
Server s = new Server(new InetSocketAddress(conf.getHostName(),
conf.getPort()));
((QueuedThreadPool) s.getThreadPool()).setMaxThreads(20);
ServletContextHandler h = new ServletContextHandler(
ServletContextHandler.SESSIONS);
h.setInitParameter(SessionManager.__SessionCookieProperty, "DB-Session");
h.addServlet(NANHotline.class, "/*");
HandlerList hl = new HandlerList();
hl.setHandlers(new Handler[] { generateStaticContext(), h });
s.setHandler(hl);
s.start();
}
private static Handler generateStaticContext() {
final ResourceHandler rh = new ResourceHandler();
rh.setResourceBase("static/");
ContextHandler ch = new ContextHandler("/static");
ch.setHandler(rh);
return ch;
}
}<|fim▁end|>
|
public class Launcher {
public static void main(String[] args) throws Exception {
NANHotlineConfiguration conf;
if (args.length != 1) {
|
<|file_name|>cvc.js<|end_file_name|><|fim▁begin|>/*
* ---------
* |.##> <##.| Open Smart Card Development Platform (www.openscdp.org)
* |# #|
* |# #| Copyright (c) 1999-2006 CardContact Software & System Consulting
* |'##> <##'| Andreas Schwier, 32429 Minden, Germany (www.cardcontact.de)
* ---------
*
* This file is part of OpenSCDP.
*
* OpenSCDP is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* OpenSCDP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenSCDP; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Support for card verifiable certificates
*
*/
//
// Constructor for CVC object from binary data
//
function CVC(value) {
this.value = new ASN1(value);
// print(this.value);
}
// Some static configuration tables
CVC.prototype.Profiles = new Array();
CVC.prototype.Profiles[3] = new Array();
CVC.prototype.Profiles[3][0] = { name:"CPI", length:1 };
CVC.prototype.Profiles[3][1] = { name:"CAR", length:8 };
CVC.prototype.Profiles[3][2] = { name:"CHR", length:12 };
CVC.prototype.Profiles[3][3] = { name:"CHA", length:7 };
CVC.prototype.Profiles[3][4] = { name:"OID", length:7 };
CVC.prototype.Profiles[3][5] = { name:"MOD", length:128 };
CVC.prototype.Profiles[3][6] = { name:"EXP", length:4 };
CVC.prototype.Profiles[4] = new Array();
CVC.prototype.Profiles[4][0] = { name:"CPI", length:1 };
CVC.prototype.Profiles[4][1] = { name:"CAR", length:8 };
CVC.prototype.Profiles[4][2] = { name:"CHR", length:12 };
CVC.prototype.Profiles[4][3] = { name:"CHA", length:7 };
CVC.prototype.Profiles[4][4] = { name:"OID", length:6 };
CVC.prototype.Profiles[4][5] = { name:"MOD", length:128 };
CVC.prototype.Profiles[4][6] = { name:"EXP", length:4 };
CVC.prototype.Profiles[33] = new Array();
CVC.prototype.Profiles[33][0] = { name:"CPI", length:1 };
CVC.prototype.Profiles[33][1] = { name:"MOD", length:256 };
CVC.prototype.Profiles[33][2] = { name:"EXP", length:4 };
CVC.prototype.Profiles[33][3] = { name:"OID", length:7 };
CVC.prototype.Profiles[33][4] = { name:"CHR", length:8 };
CVC.prototype.Profiles[33][5] = { name:"CAR", length:8 };
CVC.prototype.Profiles[34] = new Array();
CVC.prototype.Profiles[34][0] = { name:"CPI", length:1 };
CVC.prototype.Profiles[34][1] = { name:"MOD", length:256 };
CVC.prototype.Profiles[34][2] = { name:"EXP", length:4 };
CVC.prototype.Profiles[34][3] = { name:"OID", length:6 };
CVC.prototype.Profiles[34][4] = { name:"CHA", length:7 };
CVC.prototype.Profiles[34][5] = { name:"CHR", length:12 };
CVC.prototype.Profiles[34][6] = { name:"CAR", length:8 };
//
// Verify CVC certificate with public key
//
CVC.prototype.verifyWith = function(puk) {
// Get signed content
var signedContent = this.value.get(0).value;
// Decrypt with public key
var crypto = new Crypto();
var plain = crypto.decrypt(puk, Crypto.RSA_ISO9796_2, signedContent);
print("Plain value:");
print(plain);
// Check prefix and postfix byte
if ((plain.byteAt(0) != 0x6A) || (plain.byteAt(plain.length - 1) != 0xBC)) {
throw new GPError("CVC", GPError.CRYPTO_FAILED, -1, "Decrypted CVC shows invalid padding. Probably wrong public key.");
}
this.plainContent = plain;
var cpi = plain.byteAt(1);
var hashlen = (cpi >= 0x20 ? 32 : 20); // Starting with G2 SHA-256 is used
// Extract hash
this.hash = plain.bytes(plain.length - (hashlen + 1), hashlen);
var publicKeyRemainder = this.getPublicKeyRemainder();
// Input to hash is everything in the signed area plus the data in the public key remainder
var certdata = plain.bytes(1, plain.length - (hashlen + 2));
certdata = certdata.concat(publicKeyRemainder);
if (cpi >= 0x20) {
var refhash = crypto.digest(Crypto.SHA_256, certdata);
} else {
var refhash = crypto.digest(Crypto.SHA_1, certdata);
}
if (!refhash.equals(this.hash)) {
print(" Hash = " + this.hash);
print("RefHash = " + refhash);
throw new GPError("CVC", GPError.CRYPTO_FAILED, -2, "Hash value of certificate failed in verification");
}
// Split certificate data into components according to profile
var profile = certdata.byteAt(0);
var profileTemplate = this.Profiles[profile];
var offset = 0;
for (var i = 0; i < profileTemplate.length; i++) {
var name = profileTemplate[i].name;
var len = profileTemplate[i].length;
var val = certdata.bytes(offset, len);
// print(" " + name + " : " + val);
<|fim▁hole|>
if (cpi < 0x20) {
if (!this.CAR.equals(this.value.get(2).value)) {
print("Warning: CAR in signed area does not match outer CAR");
}
}
}
CVC.prototype.verifyWithOneOf = function(puklist) {
for (var i = 0; i < puklist.length; i++) {
try {
this.verifyWith(puklist[i]);
break;
}
catch(e) {
if ((e instanceof GPError) && (e.reason == -1)) {
print("Trying next key on the list...");
} else {
throw e;
}
}
}
if (i >= puklist.length) {
throw new GPError("CVC", GPError.CRYPTO_FAILED, -3, "List of possible public keys exhausted. CVC decryption failed.");
}
}
//
// Return signatur data object
//
CVC.prototype.getSignaturDataObject = function() {
return (this.value.get(0));
}
//
// Return the public key remainder
//
CVC.prototype.getPublicKeyRemainderDataObject = function() {
return (this.value.get(1));
}
//
// Return the public key remainder
//
CVC.prototype.getPublicKeyRemainder = function() {
return (this.value.get(1).value);
}
//
// Return the certification authority reference (CAR)
//
CVC.prototype.getCertificationAuthorityReference = function() {
if (this.value.elements > 2) {
return (this.value.get(2).value);
} else {
if (!this.CAR) {
throw new GPError("CVC", GPError.INVALID_USAGE, 0, "Must verify certificate before extracting CAR");
}
return this.CAR;
}
}
//
// Return the certificate holder reference (CHR)
//
CVC.prototype.getCertificateHolderReference = function() {
if (!this.CHR) {
throw new GPError("CVC", GPError.INVALID_USAGE, 0, "Must verify certificate before extracting CHR");
}
return this.CHR;
}
//
// Return public key from certificate
//
CVC.prototype.getPublicKey = function() {
if (!this.MOD) {
throw new GPError("CVC", GPError.INVALID_USAGE, 0, "Must verify certificate before extracting public key");
}
var key = new Key();
key.setType(Key.PUBLIC);
key.setComponent(Key.MODULUS, this.MOD);
key.setComponent(Key.EXPONENT, this.EXP);
return key;
}
//
// Dump content of certificate
//
CVC.prototype.dump = function() {
print(this.value);
if (this.certificateData) {
var profile = this.certificateData.byteAt(0);
var profileTemplate = this.Profiles[profile];
var offset = 0;
for (var i = 0; i < profileTemplate.length; i++) {
print(" " + profileTemplate[i].name + " : " + this.certificateData.bytes(offset, profileTemplate[i].length));
offset += profileTemplate[i].length;
}
print();
}
}<|fim▁end|>
|
offset += len;
this[name] = val;
}
this.certificateData = certdata;
|
<|file_name|>eclipse_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import pkgutil
from collections import defaultdict
from twitter.common.collections import OrderedSet
from pants.backend.jvm.tasks.ide_gen import IdeGen
from pants.base.build_environment import get_buildroot
from pants.base.generator import Generator, TemplateData
from pants.util.dirutil import safe_delete, safe_mkdir, safe_open
_TEMPLATE_BASEDIR = os.path.join('templates', 'eclipse')
_VERSIONS = {
'3.5': '3.7', # 3.5-3.7 are .project/.classpath compatible
'3.6': '3.7',
'3.7': '3.7',
}
_SETTINGS = (
'org.eclipse.core.resources.prefs',
'org.eclipse.jdt.ui.prefs',
)
class EclipseGen(IdeGen):
@classmethod
def register_options(cls, register):
super(EclipseGen, cls).register_options(register)
register('--version', choices=sorted(list(_VERSIONS.keys())), default='3.6',
help='The Eclipse version the project configuration should be generated for.')
def __init__(self, *args, **kwargs):
super(EclipseGen, self).__init__(*args, **kwargs)
version = _VERSIONS[self.get_options().version]
self.project_template = os.path.join(_TEMPLATE_BASEDIR, 'project-%s.mustache' % version)
self.classpath_template = os.path.join(_TEMPLATE_BASEDIR, 'classpath-%s.mustache' % version)
self.apt_template = os.path.join(_TEMPLATE_BASEDIR, 'factorypath-%s.mustache' % version)
self.pydev_template = os.path.join(_TEMPLATE_BASEDIR, 'pydevproject-%s.mustache' % version)
self.debug_template = os.path.join(_TEMPLATE_BASEDIR, 'debug-launcher-%s.mustache' % version)
self.coreprefs_template = os.path.join(_TEMPLATE_BASEDIR,
'org.eclipse.jdt.core.prefs-%s.mustache' % version)
self.project_filename = os.path.join(self.cwd, '.project')
self.classpath_filename = os.path.join(self.cwd, '.classpath')
self.apt_filename = os.path.join(self.cwd, '.factorypath')
self.pydev_filename = os.path.join(self.cwd, '.pydevproject')
self.coreprefs_filename = os.path.join(self.cwd, '.settings', 'org.eclipse.jdt.core.prefs')
def generate_project(self, project):
def linked_folder_id(source_set):
return source_set.source_base.replace(os.path.sep, '.')
def base_path(source_set):
return os.path.join(source_set.root_dir, source_set.source_base)
def create_source_base_template(source_set):
source_base = base_path(source_set)
return source_base, TemplateData(
id=linked_folder_id(source_set),
path=source_base
)
source_bases = dict(map(create_source_base_template, project.sources))
if project.has_python:
source_bases.update(map(create_source_base_template, project.py_sources))
source_bases.update(map(create_source_base_template, project.py_libs))
def create_source_template(base_id, includes=None, excludes=None):
return TemplateData(
base=base_id,
includes='|'.join(OrderedSet(includes)) if includes else None,
excludes='|'.join(OrderedSet(excludes)) if excludes else None,
)
def create_sourcepath(base_id, sources):
def normalize_path_pattern(path):
return '%s/' % path if not path.endswith('/') else path
includes = [normalize_path_pattern(src_set.path) for src_set in sources if src_set.path]
excludes = []
for source_set in sources:
excludes.extend(normalize_path_pattern(exclude) for exclude in source_set.excludes)
return create_source_template(base_id, includes, excludes)
pythonpaths = []
if project.has_python:
for source_set in project.py_sources:
pythonpaths.append(create_source_template(linked_folder_id(source_set)))
for source_set in project.py_libs:
lib_path = source_set.path if source_set.path.endswith('.egg') else '%s/' % source_set.path
pythonpaths.append(create_source_template(linked_folder_id(source_set),<|fim▁hole|> java=TemplateData(
jdk=self.java_jdk,
language_level=('1.%d' % self.java_language_level)
),
python=project.has_python,
scala=project.has_scala and not project.skip_scala,
source_bases=source_bases.values(),
pythonpaths=pythonpaths,
debug_port=project.debug_port,
)
outdir = os.path.abspath(os.path.join(self.gen_project_workdir, 'bin'))
safe_mkdir(outdir)
source_sets = defaultdict(OrderedSet) # base_id -> source_set
for source_set in project.sources:
source_sets[linked_folder_id(source_set)].add(source_set)
sourcepaths = [create_sourcepath(base_id, sources) for base_id, sources in source_sets.items()]
libs = list(project.internal_jars)
libs.extend(project.external_jars)
configured_classpath = TemplateData(
sourcepaths=sourcepaths,
has_tests=project.has_tests,
libs=libs,
scala=project.has_scala,
# Eclipse insists the outdir be a relative path unlike other paths
outdir=os.path.relpath(outdir, get_buildroot()),
)
def apply_template(output_path, template_relpath, **template_data):
with safe_open(output_path, 'w') as output:
Generator(pkgutil.get_data(__name__, template_relpath), **template_data).write(output)
apply_template(self.project_filename, self.project_template, project=configured_project)
apply_template(self.classpath_filename, self.classpath_template, classpath=configured_classpath)
apply_template(os.path.join(self.gen_project_workdir,
'Debug on port %d.launch' % project.debug_port),
self.debug_template, project=configured_project)
apply_template(self.coreprefs_filename, self.coreprefs_template, project=configured_project)
for resource in _SETTINGS:
with safe_open(os.path.join(self.cwd, '.settings', resource), 'w') as prefs:
prefs.write(pkgutil.get_data(__name__, os.path.join(_TEMPLATE_BASEDIR, resource)))
factorypath = TemplateData(
project_name=self.project_name,
# The easiest way to make sure eclipse sees all annotation processors is to put all libs on
# the apt factorypath - this does not seem to hurt eclipse performance in any noticeable way.
jarpaths=libs
)
apply_template(self.apt_filename, self.apt_template, factorypath=factorypath)
if project.has_python:
apply_template(self.pydev_filename, self.pydev_template, project=configured_project)
else:
safe_delete(self.pydev_filename)
print('\nGenerated project at %s%s' % (self.gen_project_workdir, os.sep))<|fim▁end|>
|
includes=[lib_path]))
configured_project = TemplateData(
name=self.project_name,
|
<|file_name|>legacy_file_diff_data.py<|end_file_name|><|fim▁begin|>"""LegacyFileDiffData model defitnition."""
<|fim▁hole|>from django.db import models
from django.utils.translation import ugettext_lazy as _
from djblets.db.fields import Base64Field, JSONField
class LegacyFileDiffData(models.Model):
"""Deprecated, legacy class for base64-encoded diff data.
This is no longer populated, and exists solely to store legacy data
that has not been migrated to :py:class:`RawFileDiffData`.
"""
binary_hash = models.CharField(_('hash'), max_length=40, primary_key=True)
binary = Base64Field(_('base64'))
extra_data = JSONField(null=True)
class Meta:
app_label = 'diffviewer'
db_table = 'diffviewer_filediffdata'
verbose_name = _('Legacy File Diff Data')
verbose_name_plural = _('Legacy File Diff Data Blobs')<|fim▁end|>
|
from __future__ import unicode_literals
|
<|file_name|>AndroidSDKVersioner.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
#
# Copyright 2014-2015 Facebook, 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.
"""See docstring for AndroidSDKVersioner class"""
# Disabling warnings for env members and imports that only affect recipe-
# specific processors.
# pylint: disable=e1101,f0401
import xml.etree.cElementTree as ET
import urllib2
from autopkglib import Processor, ProcessorError
__all__ = ["AndroidSDKVersioner"]
class AndroidSDKVersioner(Processor):
# pylint: disable=missing-docstring
description = ("Parse the XML file for the latest version of the SDK tools.")
input_variables = {
"xml_file": {
"required": True,
"description": "Path or URL to XML file."
},
}
output_variables = {
"version": {
"description": "Combined version of the SDK tools."
}
}
__doc__ = description
def main(self):
if 'http' in self.env['xml_file']:
try:
tree = ET.ElementTree(file=urllib2.urlopen(self.env['xml_file']))
except urllib2.URLError as err:
raise ProcessorError(err)
else:
try:
tree = ET.ElementTree(file=self.env['xml_file'])
except IOError as err:
raise ProcessorError(err)
root = tree.getroot()
schema = root.tag.split('}')[0] + '}'
match = root.findall('%s%s' % (schema, 'tool'))
revision = '%srevision' % schema
result = ''
try:
major = match[-1].find(revision).find('%smajor' % schema).text
minor = match[-1].find(revision).find('%sminor' % schema).text
micro = match[-1].find(revision).find('%smicro' % schema).text
except IndexError:
raise ProcessorError("Version not found!")
result = '%s.%s.%s' % (major, minor, micro)<|fim▁hole|>
if __name__ == "__main__":
PROCESSOR = AndroidSDKVersioner()
PROCESSOR.execute_shell()<|fim▁end|>
|
self.env['version'] = result
self.output("Version: %s" % self.env['version'])
|
<|file_name|>TestActor.ts<|end_file_name|><|fim▁begin|>import { Actor, StaticMeshComponent, CameraComponent, Game } from "../XEngine";
export class TestActor extends Actor {
public mesh: StaticMeshComponent;
public camera: CameraComponent;
constructor(game: Game) {
super(game);
this.canUpdate = true;
this.camera = new CameraComponent(game);
this.rootComponent = this.camera;
this.game.input.bindAxis("MoveForward", this, this.moveForward);
this.game.input.bindAxis("MoveRight", this, this.moveRight);
this.game.input.bindAxis("LookUp", this, this.lookUp);
this.game.input.bindAxis("LookLeft", this, this.lookLeft);
game.sceneManager.currentScene.mainCamera = this.camera;<|fim▁hole|> let fwVector = this.getActorForwardVector();
fwVector.scalar(50 * axisValue * this.game.time.deltaTime);
this.rootComponent.transform.position.add(fwVector);
}
private moveRight(axisValue: number) {
let fwVector = this.getActorRightVector();
fwVector.scalar(50 * axisValue * this.game.time.deltaTime);
this.Transform.position.add(fwVector);
}
private lookUp(axisValue: number) {
this.rootComponent.transform.rotation.x += axisValue * 3 * this.game.time.deltaTime;
}
private lookLeft(axisValue: number) {
this.rootComponent.transform.rotation.y -= axisValue * 3 * this.game.time.deltaTime;
}
}<|fim▁end|>
|
}
private moveForward(axisValue: number) {
|
<|file_name|>JobPlatform.py<|end_file_name|><|fim▁begin|>import platform
import socket
import sys
import os
from mule_local.JobGeneration import *
from mule.JobPlatformResources import *
from . import JobPlatformAutodetect
# Underscore defines symbols to be private
_job_id = None
def get_platform_autodetect():
"""
Returns
-------
bool
True if current platform matches, otherwise False
"""
return JobPlatformAutodetect.autodetect()
def get_platform_id():
"""
Return platform ID
Returns
-------<|fim▁hole|>
return "himmuc"
def get_platform_resources():
"""
Return information about hardware
"""
h = JobPlatformResources()
h.num_cores_per_node = 4
# Number of nodes per job are limited
h.num_nodes = 40
h.num_cores_per_socket = 4
h.max_wallclock_seconds = 8*60*60
return h
def jobscript_setup(jg : JobGeneration):
"""
Setup data to generate job script
"""
global _job_id
_job_id = jg.runtime.getUniqueID(jg.compile, jg.unique_id_filter)
return
def jobscript_get_header(jg : JobGeneration):
"""
These headers typically contain the information on e.g. Job exection, number of compute nodes, etc.
Returns
-------
string
multiline text for scripts
"""
global _job_id
p = jg.parallelization
time_str = p.get_max_wallclock_seconds_hh_mm_ss()
#
# See https://www.lrz.de/services/compute/linux-cluster/batch_parallel/example_jobs/
#
content = """#! /bin/bash
#SBATCH -o """+jg.p_job_stdout_filepath+"""
#SBATCH -e """+jg.p_job_stderr_filepath+"""
#SBATCH -D """+jg.p_job_dirpath+"""
#SBATCH -J """+_job_id+"""
#SBATCH --get-user-env
#SBATCH --nodes="""+str(p.num_nodes)+"""
#SBATCH --ntasks-per-node="""+str(p.num_ranks_per_node)+"""
# the above is a good match for the
# CooLMUC2 architecture.
#SBATCH --mail-type=end
#SBATCH [email protected]
#SBATCH --export=NONE
#SBATCH --time="""+time_str+"""
#SBATCH --partition=odr
"""
content += "\n"
content += "module load mpi\n"
if False:
if p.force_turbo_off:
content += """# Try to avoid slowing down CPUs
#SBATCH --cpu-freq=Performance
"""
content += """
source /etc/profile.d/modules.sh
"""
if jg.compile.threading != 'off':
content += """
export OMP_NUM_THREADS="""+str(p.num_threads_per_rank)+"""
"""
if p.core_oversubscription:
raise Exception("Not supported with this script!")
if p.core_affinity != None:
content += "\necho \"Affnity: "+str(p.core_affinity)+"\"\n"
if p.core_affinity == 'compact':
content += "\nexport OMP_PROC_BIND=close\n"
elif p.core_affinity == 'scatter':
content += "\nexport OMP_PROC_BIND=spread\n"
else:
raise Exception("Affinity '"+str(p.core_affinity)+"' not supported")
return content
def jobscript_get_exec_prefix(jg : JobGeneration):
"""
Prefix before executable
Returns
-------
string
multiline text for scripts
"""
content = ""
content += jg.runtime.get_jobscript_plan_exec_prefix(jg.compile, jg.runtime)
return content
def jobscript_get_exec_command(jg : JobGeneration):
"""
Prefix to executable command
Returns
-------
string
multiline text for scripts
"""
p = jg.parallelization
mpiexec = ''
#
# Only use MPI exec if we are allowed to do so
# We shouldn't use mpiexec for validation scripts
#
if not p.mpiexec_disabled:
mpiexec = "mpiexec -n "+str(p.num_ranks)
content = """
# mpiexec ... would be here without a line break
EXEC=\""""+jg.compile.getProgramPath()+"""\"
PARAMS=\""""+jg.runtime.getRuntimeOptions()+"""\"
echo \"${EXEC} ${PARAMS}\"
"""+mpiexec+""" $EXEC $PARAMS || exit 1
"""
return content
def jobscript_get_exec_suffix(jg : JobGeneration):
"""
Suffix before executable
Returns
-------
string
multiline text for scripts
"""
content = ""
content += jg.runtime.get_jobscript_plan_exec_suffix(jg.compile, jg.runtime)
return content
def jobscript_get_footer(jg : JobGeneration):
"""
Footer at very end of job script
Returns
-------
string
multiline text for scripts
"""
content = ""
return content
def jobscript_get_compile_command(jg : JobGeneration):
"""
Compile command(s)
This is separated here to put it either
* into the job script (handy for workstations)
or
* into a separate compile file (handy for clusters)
Returns
-------
string
multiline text with compile command to generate executable
"""
content = """
SCONS="scons """+jg.compile.getSConsParams()+' -j 4"'+"""
echo "$SCONS"
$SCONS || exit 1
"""
return content<|fim▁end|>
|
string
unique ID of platform
"""
|
<|file_name|>FavoriteLocationTest.java<|end_file_name|><|fim▁begin|>/*
* Transportr
*
* Copyright (c) 2013 - 2021 Torsten Grote
*
* This program is Free Software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.grobox.transportr.data.locations;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.List;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import de.grobox.transportr.data.DbTest;
import de.schildbach.pte.dto.Location;
import de.schildbach.pte.dto.Point;
import de.schildbach.pte.dto.Product;
import static de.schildbach.pte.NetworkId.BVG;
import static de.schildbach.pte.NetworkId.DB;
import static de.schildbach.pte.dto.LocationType.ADDRESS;
import static de.schildbach.pte.dto.LocationType.ANY;
import static de.schildbach.pte.dto.LocationType.POI;
import static de.schildbach.pte.dto.LocationType.STATION;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@RunWith(AndroidJUnit4.class)
public class FavoriteLocationTest extends DbTest {
private LocationDao dao;
@Before
@Override
public void createDb() throws Exception {
super.createDb();
dao = db.locationDao();
}
@Test
public void insertFavoriteLocation() throws Exception {
// no locations should exist
assertNotNull(getValue(dao.getFavoriteLocations(DB)));
// create a complete station location
Location loc1 = new Location(STATION, "stationId", Point.from1E6(23, 42), "place", "name", Product.ALL);
long uid1 = dao.addFavoriteLocation(new FavoriteLocation(DB, loc1));
// assert that location has been inserted and retrieved properly
List<FavoriteLocation> locations1 = getValue(dao.getFavoriteLocations(DB));
assertEquals(1, locations1.size());
FavoriteLocation f1 = locations1.get(0);
assertEquals(uid1, f1.getUid());
assertEquals(DB, f1.getNetworkId());
assertEquals(loc1.type, f1.type);
assertEquals(loc1.id, f1.id);
assertEquals(loc1.getLatAs1E6(), f1.lat);
assertEquals(loc1.getLonAs1E6(), f1.lon);
assertEquals(loc1.place, f1.place);<|fim▁hole|> // insert a second location in a different network
Location loc2 = new Location(ANY, null, Point.from1E6(1337, 0), null, null, Product.fromCodes("ISB".toCharArray()));
long uid2 = dao.addFavoriteLocation(new FavoriteLocation(BVG, loc2));
// assert that location has been inserted and retrieved properly
List<FavoriteLocation> locations2 = getValue(dao.getFavoriteLocations(BVG));
assertEquals(1, locations2.size());
FavoriteLocation f2 = locations2.get(0);
assertEquals(uid2, f2.getUid());
assertEquals(BVG, f2.getNetworkId());
assertEquals(loc2.type, f2.type);
assertEquals(loc2.id, f2.id);
assertEquals(loc2.getLatAs1E6(), f2.lat);
assertEquals(loc2.getLonAs1E6(), f2.lon);
assertEquals(loc2.place, f2.place);
assertEquals(loc2.name, f2.name);
assertEquals(loc2.products, f2.products);
}
@Test
public void replaceFavoriteLocation() throws Exception {
// create a complete station location
Location loc1 = new Location(STATION, "stationId", Point.from1E6(23, 42), "place", "name", Product.ALL);
long uid1 = dao.addFavoriteLocation(new FavoriteLocation(DB, loc1));
// retrieve favorite location
List<FavoriteLocation> locations1 = getValue(dao.getFavoriteLocations(DB));
assertEquals(1, locations1.size());
FavoriteLocation f1 = locations1.get(0);
assertEquals(uid1, f1.getUid());
// change the favorite location and replace it in the DB
f1.place = "new place";
f1.name = "new name";
f1.products = null;
uid1 = dao.addFavoriteLocation(f1);
assertEquals(uid1, f1.getUid());
// retrieve favorite location again
List<FavoriteLocation> locations2 = getValue(dao.getFavoriteLocations(DB));
assertEquals(1, locations2.size());
FavoriteLocation f2 = locations2.get(0);
// assert that same location was retrieved and data changed
assertEquals(f1.getUid(), f2.getUid());
assertEquals(f1.place, f2.place);
assertEquals(f1.name, f2.name);
assertEquals(f1.products, f2.products);
}
@Test
public void twoLocationsWithoutId() throws Exception {
Location loc1 = new Location(ADDRESS, null, Point.from1E6(23, 42), null, "name1", null);
Location loc2 = new Location(ADDRESS, null, Point.from1E6(0, 0), null, "name2", null);
dao.addFavoriteLocation(new FavoriteLocation(DB, loc1));
dao.addFavoriteLocation(new FavoriteLocation(DB, loc2));
assertEquals(2, getValue(dao.getFavoriteLocations(DB)).size());
}
@Test
public void twoLocationsWithSameId() throws Exception {
Location loc1 = new Location(ADDRESS, "test", Point.from1E6(23, 42), null, "name1", null);
Location loc2 = new Location(ADDRESS, "test", Point.from1E6(0, 0), null, "name2", null);
dao.addFavoriteLocation(new FavoriteLocation(DB, loc1));
dao.addFavoriteLocation(new FavoriteLocation(DB, loc2));
// second location should override first one and don't create a new one
List<FavoriteLocation> locations = getValue(dao.getFavoriteLocations(DB));
assertEquals(1, locations.size());
FavoriteLocation f = locations.get(0);
assertEquals(loc2.getLatAs1E6(), f.lat);
assertEquals(loc2.getLonAs1E6(), f.lon);
assertEquals(loc2.name, f.name);
}
@Test
public void twoLocationsWithSameIdDifferentNetworks() throws Exception {
Location loc1 = new Location(ADDRESS, "test", Point.from1E6(23, 42), null, "name1", null);
Location loc2 = new Location(ADDRESS, "test", Point.from1E6(0, 0), null, "name2", null);
dao.addFavoriteLocation(new FavoriteLocation(DB, loc1));
dao.addFavoriteLocation(new FavoriteLocation(BVG, loc2));
// second location should not override first one
assertEquals(1, getValue(dao.getFavoriteLocations(DB)).size());
assertEquals(1, getValue(dao.getFavoriteLocations(BVG)).size());
}
@Test
public void getFavoriteLocationByUid() throws Exception {
// insert a minimal location
Location l1 = new Location(STATION, "id", Point.from1E6(1, 1), "place", "name", null);
FavoriteLocation f1 = new FavoriteLocation(DB, l1);
long uid = dao.addFavoriteLocation(f1);
// retrieve by UID
FavoriteLocation f2 = dao.getFavoriteLocation(uid);
// assert that retrieval worked
assertNotNull(f2);
assertEquals(uid, f2.getUid());
assertEquals(DB, f2.getNetworkId());
assertEquals(l1.type, f2.type);
assertEquals(l1.id, f2.id);
assertEquals(l1.getLatAs1E6(), f2.lat);
assertEquals(l1.getLonAs1E6(), f2.lon);
assertEquals(l1.place, f2.place);
assertEquals(l1.name, f2.name);
assertEquals(l1.products, f2.products);
}
@Test
public void getFavoriteLocationByValues() {
// insert a minimal location
Location loc1 = new Location(ANY, null, Point.from1E6(0, 0), null, null, null);
dao.addFavoriteLocation(new FavoriteLocation(DB, loc1));
// assert the exists check works
assertNotNull(dao.getFavoriteLocation(DB, loc1.type, loc1.id, loc1.getLatAs1E6(), loc1.getLonAs1E6(), loc1.place, loc1.name));
assertNull(dao.getFavoriteLocation(DB, ADDRESS, loc1.id, loc1.getLatAs1E6(), loc1.getLonAs1E6(), loc1.place, loc1.name));
assertNull(dao.getFavoriteLocation(DB, loc1.type, "id", loc1.getLatAs1E6(), loc1.getLonAs1E6(), loc1.place, loc1.name));
assertNull(dao.getFavoriteLocation(DB, loc1.type, loc1.id, 1, loc1.getLonAs1E6(), loc1.place, loc1.name));
assertNull(dao.getFavoriteLocation(DB, loc1.type, loc1.id, loc1.getLatAs1E6(), 1, loc1.place, loc1.name));
assertNull(dao.getFavoriteLocation(DB, loc1.type, loc1.id, loc1.getLatAs1E6(), loc1.getLonAs1E6(), "place", loc1.name));
assertNull(dao.getFavoriteLocation(DB, loc1.type, loc1.id, loc1.getLatAs1E6(), loc1.getLonAs1E6(), loc1.place, "name"));
// insert a maximal location
Location loc2 = new Location(STATION, "id", Point.from1E6(1, 1), "place", "name", null);
dao.addFavoriteLocation(new FavoriteLocation(DB, loc2));
// assert the exists check works
assertNotNull(dao.getFavoriteLocation(DB, loc2.type, loc2.id, loc2.getLatAs1E6(), loc2.getLonAs1E6(), loc2.place, loc2.name));
assertNull(dao.getFavoriteLocation(DB, POI, loc2.id, loc2.getLatAs1E6(), loc2.getLonAs1E6(), loc2.place, loc2.name));
assertNull(dao.getFavoriteLocation(DB, loc2.type, "oid", loc2.getLatAs1E6(), loc2.getLonAs1E6(), loc2.place, loc2.name));
assertNull(dao.getFavoriteLocation(DB, loc2.type, loc2.id, 42, loc2.getLonAs1E6(), loc2.place, loc2.name));
assertNull(dao.getFavoriteLocation(DB, loc2.type, loc2.id, loc2.getLatAs1E6(), 42, loc2.place, loc2.name));
assertNull(dao.getFavoriteLocation(DB, loc2.type, loc2.id, loc2.getLatAs1E6(), loc2.getLonAs1E6(), "oplace", loc2.name));
assertNull(dao.getFavoriteLocation(DB, loc2.type, loc2.id, loc2.getLatAs1E6(), loc2.getLonAs1E6(), loc2.place, "oname"));
}
}<|fim▁end|>
|
assertEquals(loc1.name, f1.name);
assertEquals(loc1.products, f1.products);
|
<|file_name|>mainwindow.cpp<|end_file_name|><|fim▁begin|>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
** the names of its contributors may be used to endorse or promote
** products derived from this software without specific prior written
** permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/
#include "mainwindow.h"
#include <QtGui>
#include "svgview.h"
MainWindow::MainWindow()
: QMainWindow()
, m_view(new SvgView)
{
QMenu *fileMenu = new QMenu(tr("&File"), this);
QAction *openAction = fileMenu->addAction(tr("&Open..."));
openAction->setShortcut(QKeySequence(tr("Ctrl+O")));
QAction *quitAction = fileMenu->addAction(tr("E&xit"));
quitAction->setShortcuts(QKeySequence::Quit);
menuBar()->addMenu(fileMenu);
QMenu *viewMenu = new QMenu(tr("&View"), this);
m_backgroundAction = viewMenu->addAction(tr("&Background"));
m_backgroundAction->setEnabled(false);
m_backgroundAction->setCheckable(true);
m_backgroundAction->setChecked(false);
connect(m_backgroundAction, SIGNAL(toggled(bool)), m_view, SLOT(setViewBackground(bool)));
m_outlineAction = viewMenu->addAction(tr("&Outline"));
m_outlineAction->setEnabled(false);
m_outlineAction->setCheckable(true);
m_outlineAction->setChecked(true);
connect(m_outlineAction, SIGNAL(toggled(bool)), m_view, SLOT(setViewOutline(bool)));
menuBar()->addMenu(viewMenu);
QMenu *rendererMenu = new QMenu(tr("&Renderer"), this);
m_nativeAction = rendererMenu->addAction(tr("&Native"));
m_nativeAction->setCheckable(true);
m_nativeAction->setChecked(true);
#ifndef QT_NO_OPENGL
m_glAction = rendererMenu->addAction(tr("&OpenGL"));
m_glAction->setCheckable(true);
#endif
m_imageAction = rendererMenu->addAction(tr("&Image"));
m_imageAction->setCheckable(true);
#ifndef QT_NO_OPENGL
rendererMenu->addSeparator();
m_highQualityAntialiasingAction = rendererMenu->addAction(tr("&High Quality Antialiasing"));
m_highQualityAntialiasingAction->setEnabled(false);
m_highQualityAntialiasingAction->setCheckable(true);
m_highQualityAntialiasingAction->setChecked(false);
connect(m_highQualityAntialiasingAction, SIGNAL(toggled(bool)), m_view, SLOT(setHighQualityAntialiasing(bool)));
#endif
QActionGroup *rendererGroup = new QActionGroup(this);
rendererGroup->addAction(m_nativeAction);
#ifndef QT_NO_OPENGL
rendererGroup->addAction(m_glAction);
#endif
rendererGroup->addAction(m_imageAction);
menuBar()->addMenu(rendererMenu);
connect(openAction, SIGNAL(triggered()), this, SLOT(openFile()));
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(rendererGroup, SIGNAL(triggered(QAction*)),
this, SLOT(setRenderer(QAction*)));
setCentralWidget(m_view);
setWindowTitle(tr("SVG Viewer"));
}
void MainWindow::openFile(const QString &path)
{
QString fileName;
if (path.isNull())
fileName = QFileDialog::getOpenFileName(this, tr("Open SVG File"),
m_currentPath, "SVG files (*.svg *.svgz *.svg.gz)");
else
fileName = path;
if (!fileName.isEmpty()) {
QFile file(fileName);
if (!file.exists()) {
QMessageBox::critical(this, tr("Open SVG File"),
QString("Could not open file '%1'.").arg(fileName));
m_outlineAction->setEnabled(false);
m_backgroundAction->setEnabled(false);
return;
}
m_view->openFile(file);
if (!fileName.startsWith(":/")) {
m_currentPath = fileName;
setWindowTitle(tr("%1 - SVGViewer").arg(m_currentPath));
}
m_outlineAction->setEnabled(true);
m_backgroundAction->setEnabled(true);
resize(m_view->sizeHint() + QSize(80, 80 + menuBar()->height()));
}
}
void MainWindow::setRenderer(QAction *action)
{
#ifndef QT_NO_OPENGL
m_highQualityAntialiasingAction->setEnabled(false);
#endif
if (action == m_nativeAction)
m_view->setRenderer(SvgView::Native);<|fim▁hole|> m_view->setRenderer(SvgView::OpenGL);
}
#endif
else if (action == m_imageAction) {
m_view->setRenderer(SvgView::Image);
}
}<|fim▁end|>
|
#ifndef QT_NO_OPENGL
else if (action == m_glAction) {
m_highQualityAntialiasingAction->setEnabled(true);
|
<|file_name|>recipe-577484.py<|end_file_name|><|fim▁begin|># PRNG (Pseudo-Random Number Generator) Test
# PRNG info:
# http://en.wikipedia.org/wiki/Pseudorandom_number_generator
# FB - 201012046
# Compares output distribution of any given PRNG
# w/ an hypothetical True-Random Number Generator (TRNG)
import math
import time
global x
x = time.clock() # seed for the PRNG
# PRNG to test
def prng():<|fim▁hole|> return x
# combination by recursive method
def c(n, k):
if k == 0: return 1
if n == 0: return 0
return c(n - 1, k - 1) + c(n - 1, k)
### combination by multiplicative method
##def c_(n, k):
## mul = 1.0
## for i in range(k):
## mul = mul * (n - k + i + 1) / (i + 1)
## return mul
# MAIN
n = 20 # number of bits in each trial
print 'Test in progress...'
print
cnk = [] # array to hold bit counts
for k in range(n + 1):
cnk.append(0)
# generate 2**n n-bit pseudo-random numbers
for j in range(2 ** n):
# generate n-bit pseudo-random number and count the 0's in it
# num = ''
ctr = 0
for i in range(n):
b = int(round(prng())) # generate 1 pseudo-random bit
# num += str(b)
if b == 0: ctr += 1
# print num
# increase bit count in the array
cnk[ctr] += 1
print 'Number of bits in each pseudo-random number (n) =', n
print
print 'Comparison of "0" count distributions:'
print
print ' k', ' c(n,k)', ' actual', '%dif'
difSum = 0
for k in range(n + 1):
cnk_ = c(n, k)
dif = abs(cnk_ - cnk[k])
print '%2d %10d %10d %4d' % (k, cnk_, cnk[k], 100 * dif / cnk_)
difSum += dif
print
print 'Difference percentage between the distributions:'
print 100 * difSum / (2 ** n)<|fim▁end|>
|
global x
x = math.fmod((x + math.pi) ** 2.0, 1.0)
|
<|file_name|>index.ts<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
|
import MapGenerator from './mapGenerator';
export default MapGenerator;
|
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>extern crate netcdf;
extern crate ndarray;
use ndarray::ArrayD;
use netcdf::{test_file, test_file_new};
// Failure tests
#[test]
#[should_panic(expected = "No such file or directory")]
fn bad_filename() {
let f = test_file("blah_stuff.nc");
let _file = netcdf::open(&f).unwrap();
}
// Read tests
#[test]
fn root_dims() {
let f = test_file("simple_xy.nc");
let file = netcdf::open(&f).unwrap();
assert_eq!(f, file.name);
assert_eq!(file.root.dimensions.get("x").unwrap().len, 6);
assert_eq!(file.root.dimensions.get("y").unwrap().len, 12);
}
#[test]
fn global_attrs() {
let f = test_file("patmosx_v05r03-preliminary_NOAA-19_asc_d20130630_c20140325.nc");
let file = netcdf::open(&f).unwrap();
assert_eq!(f, file.name);
let ch1_attr = file.root.attributes.get("CH1_DARK_COUNT").unwrap();
let ch1 = ch1_attr.get_float(false).unwrap();
let eps = 1e-6;
assert!((ch1-40.65863).abs() < eps);
let ch1 = ch1_attr.get_int(true).unwrap();
assert_eq!(ch1, 40);
let sensor_attr = file.root.attributes.get("sensor").unwrap();
let sensor_data = sensor_attr.get_char(false).unwrap();
assert_eq!("AVHRR/3".to_string(), sensor_data);
}
#[test]
fn var_cast() {
let f = test_file("simple_xy.nc");
let file = netcdf::open(&f).unwrap();
assert_eq!(f, file.name);
let var = file.root.variables.get("data").unwrap();
let data : Vec<i32> = var.get_int(false).unwrap();
assert_eq!(data.len(), 6*12);
for x in 0..(6*12) {
assert_eq!(data[x], x as i32);
}
// do the same thing but cast to float
let data : Vec<f32> = var.get_float(true).unwrap();
assert_eq!(data.len(), 6*12);
for x in 0..(6*12) {
assert_eq!(data[x], x as f32);
}
}
#[test]
fn test_index_fetch() {
let f = test_file("simple_xy.nc");
let file = netcdf::open(&f).unwrap();
let var = file.root.variables.get("data").unwrap();
let first_val: i32 = var.value_at(&[0usize, 0usize]).unwrap();
let other_val: i32 = var.value_at(&[5, 3]).unwrap();
assert_eq!(first_val, 0 as i32);
assert_eq!(other_val, 63 as i32 );
}
#[test]
/// Tests implicit casts
fn implicit_cast() {
let f = test_file("simple_xy.nc");
let file = netcdf::open(&f).unwrap();
assert_eq!(f, file.name);
let var = file.root.variables.get("data").unwrap();
let data : Vec<i32> = var.values().unwrap();
assert_eq!(data.len(), 6*12);
for x in 0..(6*12) {
assert_eq!(data[x], x as i32);
}
// do the same thing but cast to float
let data : Vec<f32> = var.values().unwrap();
assert_eq!(data.len(), 6*12);
for x in 0..(6*12) {
assert_eq!(data[x], x as f32);
}
}
#[test]
#[should_panic(expected = "Types are not equivalent and cast==false")]
fn var_cast_fail() {
let f = test_file("simple_xy.nc");
let file = netcdf::open(&f).unwrap();
let var = file.root.variables.get("data").unwrap();
// getting int Variable as float with false argument should fail.
let _data : Vec<f32> = var.get_float(false).unwrap();
}
#[test]
fn last_dim_varies_fastest() {
let f = test_file("simple_xy.nc");
let file = netcdf::open(&f).unwrap();
assert_eq!(f, file.name);
let var = file.root.variables.get("data").unwrap();
let data : Vec<i32> = var.get_int(false).unwrap();
let nx = var.dimensions[0].len;
let ny = var.dimensions[1].len;
assert_eq!(nx, 6);
assert_eq!(ny, 12);
assert_eq!(nx*ny, var.len);
for x in 0..nx {
for y in 0..ny {
let ind = x*nx + y;
assert_eq!(data[ind as usize], ind as i32);
}
}
}
#[test]
fn open_pres_temp_4d() {
let f = test_file("pres_temp_4D.nc");
let file = netcdf::open(&f).unwrap();
assert_eq!(f, file.name);
let pres = file.root.variables.get("pressure").unwrap();
assert_eq!(pres.dimensions[0].name, "time");
assert_eq!(pres.dimensions[1].name, "level");
assert_eq!(pres.dimensions[2].name, "latitude");
assert_eq!(pres.dimensions[3].name, "longitude");
// test var attributes
assert_eq!(pres.attributes.get("units").unwrap().get_char(false).unwrap(),
"hPa".to_string());
}
#[test]
fn nc4_groups() {
let f = test_file("simple_nc4.nc");
let file = netcdf::open(&f).unwrap();
assert_eq!(f, file.name);
let grp1 = file.root.sub_groups.get("grp1").unwrap();
assert_eq!(grp1.name, "grp1".to_string());
let var = grp1.variables.get("data").unwrap();
let data : Vec<i32> = var.get_int(true).unwrap();
for x in 0..(6*12) {
assert_eq!(data[x], x as i32);
}
}
// Write tests
#[test]
fn create() {
let f = test_file_new("create.nc");
let file = netcdf::create(&f).unwrap();
assert_eq!(f, file.name);
}
#[test]
fn def_dims_vars_attrs() {
{
let f = test_file_new("def_dims_vars_attrs.nc");
let mut file = netcdf::create(&f).unwrap();
let dim1_name = "ljkdsjkldfs";
let dim2_name = "dsfkdfskl";
file.root.add_dimension(dim1_name, 10).unwrap();
file.root.add_dimension(dim2_name, 20).unwrap();
assert_eq!(file.root.dimensions.get(dim1_name).unwrap().len, 10);
assert_eq!(file.root.dimensions.get(dim2_name).unwrap().len, 20);
let var_name = "varstuff_int";
let data : Vec<i32> = vec![42; (10*20)];
file.root.add_variable(
var_name,
&vec![dim1_name.to_string(), dim2_name.to_string()],
&data
).unwrap();
assert_eq!(file.root.variables.get(var_name).unwrap().len, 20*10);
let var_name = "varstuff_float";
let data : Vec<f32> = vec![42.2; 10];
file.root.add_variable(
var_name,
&vec![dim1_name.to_string()],
&data
).unwrap();
assert_eq!(file.root.variables.get(var_name).unwrap().len, 10);
// test global attrs
file.root.add_attribute(
"testattr1",
3,
).unwrap();
file.root.add_attribute(
"testattr2",
"Global string attr".to_string(),
).unwrap();
// test var attrs
file.root.variables.get_mut(var_name).unwrap().add_attribute(
"varattr1",
5,
).unwrap();
file.root.variables.get_mut(var_name).unwrap().add_attribute(
"varattr2",
"Variable string attr".to_string(),
).unwrap();
}
// now, read in the file we created and verify everything
{
let f = test_file_new("def_dims_vars_attrs.nc");
let file = netcdf::open(&f).unwrap();
// verify dimensions
let dim1_name = "ljkdsjkldfs";
let dim2_name = "dsfkdfskl";
let dim1 = file.root.dimensions.get(dim1_name).unwrap();
let dim2 = file.root.dimensions.get(dim2_name).unwrap();
assert_eq!(dim1.len, 10);
assert_eq!(dim2.len, 20);
// verify variable data
let var_name = "varstuff_int";
let data_test : Vec<i32> = vec![42; (10*20)];
let data_file : Vec<i32> =
file.root.variables.get(var_name).unwrap().get_int(false).unwrap();
assert_eq!(data_test.len(), data_file.len());
for i in 0..data_test.len() {
assert_eq!(data_test[i], data_file[i]);
}
let var_name = "varstuff_float";
let data_test : Vec<f32> = vec![42.2; 10];
let data_file : Vec<f32> =
file.root.variables.get(var_name).unwrap().get_float(false).unwrap();
assert_eq!(data_test.len(), data_file.len());
for i in 0..data_test.len() {
assert_eq!(data_test[i], data_file[i]);
}
// verify global attrs
assert_eq!(3,
file.root.attributes.get("testattr1").unwrap().get_int(false).unwrap());
assert_eq!("Global string attr".to_string(),
file.root.attributes.get("testattr2").unwrap().get_char(false).unwrap());
// verify var attrs
assert_eq!(5,
file.root.variables.get(var_name).unwrap()
.attributes.get("varattr1").unwrap().get_int(false).unwrap());
assert_eq!("Variable string attr",
file.root.variables.get(var_name).unwrap()
.attributes.get("varattr2").unwrap().get_char(false).unwrap());
}
}
#[test]
fn all_var_types() {
// write
{
let f = test_file_new("all_var_types.nc");
let mut file = netcdf::create(&f).unwrap();
let dim_name = "dim1";
file.root.add_dimension(dim_name, 10).unwrap();
// byte
let data : Vec<i8> = vec![42 as i8; 10];
let var_name = "var_byte";
file.root.add_variable(
var_name,
&vec![dim_name.to_string()],
&data
).unwrap();
// short
let data : Vec<i16> = vec![42 as i16; 10];
let var_name = "var_short";
file.root.add_variable(
var_name,
&vec![dim_name.to_string()],
&data
).unwrap();
// ushort
let data : Vec<u16> = vec![42 as u16; 10];
let var_name = "var_ushort";
file.root.add_variable(
var_name,
&vec![dim_name.to_string()],
&data
).unwrap();
// int
let data : Vec<i32> = vec![42 as i32; 10];
let var_name = "var_int";
file.root.add_variable(
var_name,
&vec![dim_name.to_string()],
&data
).unwrap();
// uint
let data : Vec<u32> = vec![42 as u32; 10];
let var_name = "var_uint";
file.root.add_variable(
var_name,
&vec![dim_name.to_string()],
&data
).unwrap();
// int64
let data : Vec<i64> = vec![42 as i64; 10];
let var_name = "var_int64";
file.root.add_variable(
var_name,
&vec![dim_name.to_string()],
&data
).unwrap();
// uint64
let data : Vec<u64> = vec![42 as u64; 10];
let var_name = "var_uint64";
file.root.add_variable(
var_name,
&vec![dim_name.to_string()],
&data
).unwrap();
// float
let data : Vec<f32> = vec![42.2 as f32; 10];
let var_name = "var_float";
file.root.add_variable(
var_name,
&vec![dim_name.to_string()],
&data
).unwrap();
// double
let data : Vec<f64> = vec![42.2 as f64; 10];
let var_name = "var_double";
file.root.add_variable(
var_name,
&vec![dim_name.to_string()],
&data
).unwrap();
}
// read
{
let f = test_file_new("all_var_types.nc");
let file = netcdf::open(&f).unwrap();
// byte
let data : Vec<i8> =
file.root.variables.get("var_byte").unwrap().get_byte(false).unwrap();
for i in 0..10 {
assert_eq!(42 as i8, data[i]);
}
// short
let data : Vec<i16> =
file.root.variables.get("var_short").unwrap().get_short(false).unwrap();
for i in 0..10 {
assert_eq!(42 as i16, data[i]);
}
// ushort
let data : Vec<u16> =
file.root.variables.get("var_ushort").unwrap().get_ushort(false).unwrap();
for i in 0..10 {
assert_eq!(42 as u16, data[i]);
}
// int
let data : Vec<i32> =
file.root.variables.get("var_int").unwrap().get_int(false).unwrap();
for i in 0..10 {
assert_eq!(42 as i32, data[i]);
}
// uint
let data : Vec<u32> =
file.root.variables.get("var_uint").unwrap().get_uint(false).unwrap();
for i in 0..10 {
assert_eq!(42 as u32, data[i]);
}
// int64
let data : Vec<i64> =
file.root.variables.get("var_int64").unwrap().get_int64(false).unwrap();
for i in 0..10 {
assert_eq!(42 as i64, data[i]);
}
// uint64
let data : Vec<u64> =
file.root.variables.get("var_uint64").unwrap().get_uint64(false).unwrap();
for i in 0..10 {
assert_eq!(42 as u64, data[i]);
}
// float
let data : Vec<f32> =
file.root.variables.get("var_float").unwrap().get_float(false).unwrap();
for i in 0..10 {
assert_eq!(42.2 as f32, data[i]);
}
// double
let data : Vec<f64> =
file.root.variables.get("var_double").unwrap().get_double(false).unwrap();
for i in 0..10 {
assert_eq!(42.2 as f64, data[i]);
}
}
}
#[test]
fn all_attr_types() {
{
let f = test_file_new("all_attr_types.nc");
let mut file = netcdf::create(&f).unwrap();
// byte
file.root.add_attribute(
"attr_byte",
3 as i8,
).unwrap();
// short
file.root.add_attribute(
"attr_short",
3 as i16,
).unwrap();
// ushort
file.root.add_attribute(
"attr_ushort",
3 as u16,
).unwrap();
// int
file.root.add_attribute(
"attr_int",
3 as i32,
).unwrap();
// uint
file.root.add_attribute(
"attr_uint",
3 as u32,
).unwrap();
// int64
file.root.add_attribute(
"attr_int64",
3 as i64,
).unwrap();
// uint64
file.root.add_attribute(
"attr_uint64",
3 as u64,
).unwrap();
// float
file.root.add_attribute(
"attr_float",
3.2 as f32,
).unwrap();
// double
file.root.add_attribute(
"attr_double",
3.2 as f64,
).unwrap();
}
{
let f = test_file_new("all_attr_types.nc");
let file = netcdf::open(&f).unwrap();
// byte
assert_eq!(3 as i8,
file.root.attributes.get("attr_byte").unwrap().get_byte(false).unwrap());
// short
assert_eq!(3 as i16,
file.root.attributes.get("attr_short").unwrap().get_short(false).unwrap());
// ushort
assert_eq!(3 as u16,
file.root.attributes.get("attr_ushort").unwrap().get_ushort(false).unwrap());
// int
assert_eq!(3 as i32,
file.root.attributes.get("attr_int").unwrap().get_int(false).unwrap());
// uint
assert_eq!(3 as u32,
file.root.attributes.get("attr_uint").unwrap().get_uint(false).unwrap());
// int64
assert_eq!(3 as i64,
file.root.attributes.get("attr_int64").unwrap().get_int64(false).unwrap());
// uint64
assert_eq!(3 as u64,
file.root.attributes.get("attr_uint64").unwrap().get_uint64(false).unwrap());
// float
assert_eq!(3.2 as f32,
file.root.attributes.get("attr_float").unwrap().get_float(false).unwrap());
// double
assert_eq!(3.2 as f64,
file.root.attributes.get("attr_double").unwrap().get_double(false).unwrap());
}
}
#[test]
/// Tests the shape of a variable
/// when fetched using "Variable::as_array()"
fn fetch_ndarray() {
let f = test_file("pres_temp_4D.nc");
let file = netcdf::open(&f).unwrap();
assert_eq!(f, file.name);
let pres = file.root.variables.get("pressure").unwrap();
let values_array: ArrayD<f64> = pres.as_array().unwrap();
assert_eq!(values_array.shape(), &[2, 2, 6, 12]);
}
#[test]
// assert slice fetching
fn fetch_slice() {
let f = test_file("simple_xy.nc");
let file = netcdf::open(&f).unwrap();
assert_eq!(f, file.name);
let pres = file.root.variables.get("data").unwrap();
let values: Vec<i32> = pres.values_at(&[0, 0], &[6, 3]).unwrap();
let expected_values: [i32; 18] = [
0, 1, 2, 12, 13, 14, 24, 25, 26, 36, 37, 38, 48, 49, 50, 60, 61, 62];
for i in 0..values.len() {
assert_eq!(expected_values[i], values[i]);
}
}
#[test]
// assert slice fetching
fn fetch_slice_as_ndarray() {
let f = test_file("simple_xy.nc");
let file = netcdf::open(&f).unwrap();
assert_eq!(f, file.name);
let pres = file.root.variables.get("data").unwrap();
let values_array: ArrayD<i32> = pres.array_at(&[0, 0], &[6, 3]).unwrap();
assert_eq!(values_array.shape(), &[6, 3]);
}
#[test]
// test file modification
fn append() {
let f = test_file_new("append.nc");
let dim_name = "some_dimension";
{
// first creates a simple netCDF file
// and create a variable called "some_variable" in it
let mut file_w = netcdf::create(&f).unwrap();
file_w.root.add_dimension(dim_name, 3).unwrap();
file_w.root.add_variable(
"some_variable",
&vec![dim_name.into()],
&vec![1., 2., 3.]
).unwrap();
// close it (done when `file_w` goes out of scope)
}
{
// re-open it in append mode
// and create a variable called "some_other_variable"
let mut file_a = netcdf::append(&f).unwrap();
file_a.root.add_variable(
"some_other_variable",
&vec![dim_name.into()],
&vec![2., 4., 6.]
).unwrap();
// close it (done when `file_a` goes out of scope)
}
// finally open the file in read only mode
// and test the existence of both variable
let file = netcdf::append(&f).unwrap();
assert!(file.root.variables.contains_key("some_variable"));
assert!(file.root.variables.contains_key("some_other_variable"));
}
#[test]
// test file modification
fn put_single_value() {
let f = test_file_new("append_value.nc");
let dim_name = "some_dimension";
let var_name = "some_variable";
{
// first creates a simple netCDF file
// and create a variable called "some_variable" in it
let mut file_w = netcdf::create(&f).unwrap();
file_w.root.add_dimension(dim_name, 3).unwrap();
file_w.root.add_variable(
var_name,
&vec![dim_name.into()],
&vec![1., 2., 3.]
).unwrap();
// close it (done when `file_w` goes out of scope)
}
let indices: [usize; 1] = [0];
{
// re-open it in append mode
let mut file_a = netcdf::append(&f).unwrap();
let mut var = file_a.root.variables.get_mut(var_name).unwrap();
let res = var.put_value_at(100., &indices);
assert_eq!(res, Ok(()));
// close it (done when `file_a` goes out of scope)
}
// finally open the file in read only mode
// and test the values of 'some_variable'
let file = netcdf::open(&f).unwrap();
let var = file.root.variables.get(var_name).unwrap();
assert_eq!(var.value_at(&indices), Ok(100.));
}
<|fim▁hole|>// test file modification
fn put_values() {
let f = test_file_new("append_values.nc");
let dim_name = "some_dimension";
let var_name = "some_variable";
{
// first creates a simple netCDF file
// and create a variable called "some_variable" in it
let mut file_w = netcdf::create(&f).unwrap();
file_w.root.add_dimension(dim_name, 3).unwrap();
file_w.root.add_variable(
var_name,
&vec![dim_name.into()],
&vec![1., 2., 3.]
).unwrap();
// close it (done when `file_w` goes out of scope)
}
let indices: [usize; 1] = [1];
let values: [f32; 2] = [100., 200.];
{
// re-open it in append mode
let mut file_a = netcdf::append(&f).unwrap();
let mut var = file_a.root.variables.get_mut(var_name).unwrap();
let res = var.put_values_at(&values, &indices, &[values.len()]);
assert_eq!(res, Ok(()));
// close it (done when `file_a` goes out of scope)
}
// finally open the file in read only mode
// and test the values of 'some_variable'
let file = netcdf::open(&f).unwrap();
let var = file.root.variables.get(var_name).unwrap();
assert_eq!(
var.values_at::<f32>(&indices, &[values.len()]).unwrap().as_slice(),
values
);
}
#[test]
/// Test setting a fill value when creating a Variable
fn set_fill_value() {
let f = test_file_new("fill_value.nc");
let dim_name = "some_dimension";
let var_name = "some_variable";
let fill_value = -2. as f32;
let mut file_w = netcdf::create(&f).unwrap();
file_w.root.add_dimension(dim_name, 3).unwrap();
file_w.root.add_variable_with_fill_value(
var_name,
&vec![dim_name.into()],
&vec![1. as f32, 2. as f32, 3. as f32],
fill_value
).unwrap();
let var = file_w.root.variables.get(var_name).unwrap();
let attr = var.attributes.get("_FillValue").unwrap().get_float(false).unwrap();
// compare requested fill_value and attribute _FillValue
assert_eq!(fill_value, attr);
}
#[test]
/// Test reading variable into a buffer
fn read_values_into_buffer() {
let f = test_file("simple_xy.nc");
let file = netcdf::open(&f).unwrap();
let var = file.root.variables.get("data").unwrap();
// pre-allocate the Array
let mut data: Vec<i32> = Vec::with_capacity(var.len as usize);
var.read_values_into_buffer(&mut data);
assert_eq!(data.len(), 6*12);
for x in 0..(6*12) {
assert_eq!(data[x], x as i32);
}
}
#[test]
/// Test reading a slice of a variable into a buffer
fn read_slice_into_buffer() {
let f = test_file("simple_xy.nc");
let file = netcdf::open(&f).unwrap();
let pres = file.root.variables.get("data").unwrap();
// pre-allocate the Array
let mut values: Vec<i32> = Vec::with_capacity(6 * 3);
pres.read_slice_into_buffer(&[0, 0], &[6, 3], &mut values).unwrap();
let expected_values: [i32; 18] = [
0, 1, 2, 12, 13, 14, 24, 25, 26, 36, 37, 38, 48, 49, 50, 60, 61, 62];
for i in 0..values.len() {
assert_eq!(expected_values[i], values[i]);
}
}<|fim▁end|>
|
#[test]
|
<|file_name|>deleteNode.py<|end_file_name|><|fim▁begin|># Write a function to delete a node (except the tail) in a singly linked list,
# given only access to that node.
#
# Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node
# with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
#
# time: O(1)
# space: O(1)
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def deleteNode2(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
curt = node
prev = None
while curt.next is not None:
curt.val = curt.next.val
prev = curt
curt = curt.next
if prev is not None:
prev.next = None
return
def deleteNode1(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
curt = node
while curt.next is not None:
curt.val = curt.next.val
if curt.next.next is None:
curt.next = None
break
curt = curt.next
return
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next
return<|fim▁hole|> n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n4 = ListNode(4)
n1.next = n2
n2.next = n3
n3.next = n4
sol = Solution()
sol.deleteNode(n1)
print n1.val, n1.next.val, n1.next.next.val
try:
print n1.next.next.next.val
except:
print 'None Type!'
pass<|fim▁end|>
|
if __name__ == '__main__':
|
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import url, patterns
<|fim▁hole|>
urlpatterns = patterns(
"phileo.views",
url(r"^like/(?P<content_type_id>\d+):(?P<object_id>\d+)/$", "like_toggle", name="phileo_like_toggle")
)<|fim▁end|>
| |
<|file_name|>player.py<|end_file_name|><|fim▁begin|>#!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
# --------------------------------------------------------------------
# an image animation player
class UI(tkinter.Label):
def __init__(self, master, im):
if isinstance(im, list):
# list of images
self.im = im[1:]
im = self.im[0]
else:
# sequence
self.im = im
if im.mode == "1":
self.image = ImageTk.BitmapImage(im, foreground="white")
else:
self.image = ImageTk.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
self.update()
duration = im.info.get("duration", 100)
self.after(duration, self.next)
def next(self):
if isinstance(self.im, list):
try:
im = self.im[0]
del self.im[0]
self.image.paste(im)
except IndexError:
return # end of list
else:
try:
im = self.im
im.seek(im.tell() + 1)
self.image.paste(im)
except EOFError:
return # end of file
duration = im.info.get("duration", 100)
self.after(duration, self.next)
self.update_idletasks()
<|fim▁hole|># --------------------------------------------------------------------
# script interface
if __name__ == "__main__":
if not sys.argv[1:]:
print("Syntax: python player.py imagefile(s)")
sys.exit(1)
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
print("loading...")
im = []
for filename in sys.argv[1:]:
im.append(Image.open(filename))
else:
# sequence
im = Image.open(filename)
UI(root, im).pack()
root.mainloop()<|fim▁end|>
| |
<|file_name|>frost-detail-tabs-more-tabs.js<|end_file_name|><|fim▁begin|>/**<|fim▁hole|><|fim▁end|>
|
* Simple re-export of frost-detail-tabs-more-tabs in the app namespace
*/
export {default} from 'ember-frost-tabs/components/frost-detail-tabs-more-tabs'
|
<|file_name|>server.rs<|end_file_name|><|fim▁begin|>#![feature(core)]
extern crate eve;
extern crate getopts;
extern crate url;
extern crate core;
use std::thread;
use std::env;
use getopts::Options;
use std::net::SocketAddr;
use core::str::FromStr;
use eve::server;
use eve::login;
#[allow(dead_code)]
fn main() {
// handle command line arguments
let args: Vec<String> = env::args().collect();
// define the command line arguments
let mut opts = Options::new();
opts.optopt("f", "faddress", "specify a socket address for the static file server. Defaults to 0.0.0.0:8080","SOCKET ADDRESS");
opts.optopt("s", "saves", "specify the location of the saves directory","PATH");
opts.optflag("h", "help", "prints all options and usage");
// parse raw input arguments into options
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
// print the help menu
if matches.opt_present("h") {
print!("{}", opts.usage(""));
return;
}
// parse static file server address
let default_addr = SocketAddr::from_str("0.0.0.0:8080").unwrap();
let addr = match matches.opt_str("f") {
Some(ip) => {
match SocketAddr::from_str(&*ip) {
Ok(addr) => addr,
Err(_) => {
println!("WARNING: Could not parse static file server address.\nDefaulting to {:?}",default_addr);
default_addr
}
}
},
None => default_addr,
};
// parse the autosave file location
let default_autosave = "../saves/".to_owned();
let autosave = match matches.opt_str("s") {
Some(path) => path,
None => default_autosave,
};
thread::spawn(move || login::run(addr.clone()));<|fim▁hole|>}<|fim▁end|>
|
server::run(&*autosave);
|
<|file_name|>version.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
|
VERSION = '0.3.4'
|
<|file_name|>harjutus ülesanne 6.py<|end_file_name|><|fim▁begin|>a = "1"
b = 1<|fim▁hole|>print("Arvud on " + 5 * a + " ja " + str(5 * b))<|fim▁end|>
| |
<|file_name|>morestack4.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// error-pattern:explicit failure
// Just testing unwinding
<|fim▁hole|> let r = and_then_get_big_again(5);
if i != 0 {
getbig_and_fail(i - 1);
} else {
fail!();
}
}
struct and_then_get_big_again {
x:int,
}
impl Drop for and_then_get_big_again {
fn finalize(&self) {}
}
fn and_then_get_big_again(x:int) -> and_then_get_big_again {
and_then_get_big_again {
x: x
}
}
fn main() {
do task::spawn {
getbig_and_fail(1);
};
}<|fim▁end|>
|
extern mod std;
fn getbig_and_fail(i: int) {
|
<|file_name|>test_index.py<|end_file_name|><|fim▁begin|>import ujson
from unittest import mock
from unittest.mock import MagicMock
from flask import url_for
from flask_login import login_required, AnonymousUserMixin
from requests.exceptions import HTTPError
from werkzeug.exceptions import BadRequest, InternalServerError, NotFound
from pika.exceptions import ConnectionClosed, ChannelClosed
import listenbrainz.db.user as db_user
import listenbrainz.webserver.login
from listenbrainz.db.testing import DatabaseTestCase
from listenbrainz.webserver import create_app
from listenbrainz.webserver.testing import ServerTestCase
class IndexViewsTestCase(ServerTestCase, DatabaseTestCase):
def setUp(self):
ServerTestCase.setUp(self)
DatabaseTestCase.setUp(self)
def test_index(self):
resp = self.client.get(url_for('index.index'))
self.assert200(resp)
def test_downloads(self):
resp = self.client.get(url_for('index.downloads'))
self.assert_redirects(resp, url_for('index.data'))
def test_data(self):
resp = self.client.get(url_for('index.data'))
self.assert200(resp)
def test_contribute(self):
resp = self.client.get(url_for('index.contribute'))
self.assert200(resp)
def test_goals(self):
resp = self.client.get(url_for('index.goals'))
self.assert200(resp)
def test_faq(self):
resp = self.client.get(url_for('index.faq'))
self.assert200(resp)
def test_roadmap(self):
resp = self.client.get(url_for('index.roadmap'))
self.assert200(resp)
def test_add_data_info(self):
resp = self.client.get(url_for('index.add_data_info'))
self.assert200(resp)
def test_import_data_info(self):
resp = self.client.get(url_for('index.import_data_info'))
self.assert200(resp)
def test_404(self):
resp = self.client.get('/canyoufindthis')
self.assert404(resp)
self.assertIn('Not Found', resp.data.decode('utf-8'))
def test_lastfm_proxy(self):
resp = self.client.get(url_for('index.proxy'))
self.assert200(resp)
def test_flask_debugtoolbar(self):
""" Test if flask debugtoolbar is loaded correctly
Creating an app with default config so that debug is True
and SECRET_KEY is defined.
"""
app = create_app(debug=True)
client = app.test_client()
resp = client.get('/data')
self.assert200(resp)
self.assertIn('flDebug', str(resp.data))
def test_current_status(self):
resp = self.client.get(url_for('index.current_status'))
self.assert200(resp)
@mock.patch('listenbrainz.db.user.get')
def test_menu_not_logged_in(self, mock_user_get):
resp = self.client.get(url_for('index.index'))
data = resp.data.decode('utf-8')
self.assertIn('Sign in', data)
self.assertIn('Import', data)
# item in user menu doesn't exist
self.assertNotIn('My Listens', data)
mock_user_get.assert_not_called()
@mock.patch('listenbrainz.db.user.get_by_login_id')
def test_menu_logged_in(self, mock_user_get):
""" If the user is logged in, check that we perform a database query to get user data """
user = db_user.get_or_create(1, 'iliekcomputers')
db_user.agree_to_gdpr(user['musicbrainz_id'])
user = db_user.get_or_create(1, 'iliekcomputers')
mock_user_get.return_value = user
self.temporary_login(user['login_id'])
resp = self.client.get(url_for('index.index'))
data = resp.data.decode('utf-8')
# username (menu header)
self.assertIn('iliekcomputers', data)
self.assertIn('Import', data)
# item in user menu
self.assertIn('My Listens', data)
mock_user_get.assert_called_with(user['login_id'])
@mock.patch('listenbrainz.db.user.get_by_login_id')
def test_menu_logged_in_error_show(self, mock_user_get):
""" If the user is logged in, if we show a 400 or 404 error, show the user menu"""
@self.app.route('/page_that_returns_400')
def view400():
raise BadRequest('bad request')
@self.app.route('/page_that_returns_404')
def view404():
raise NotFound('not found')
user = db_user.get_or_create(1, 'iliekcomputers')
db_user.agree_to_gdpr(user['musicbrainz_id'])
user = db_user.get_or_create(1, 'iliekcomputers')
mock_user_get.return_value = user
self.temporary_login(user['login_id'])
resp = self.client.get('/page_that_returns_400')
data = resp.data.decode('utf-8')
self.assert400(resp)
# username (menu header)
self.assertIn('iliekcomputers', data)
self.assertIn('Import', data)
# item in user menu
self.assertIn('My Listens', data)
mock_user_get.assert_called_with(user['login_id'])
resp = self.client.get('/page_that_returns_404')
data = resp.data.decode('utf-8')
self.assert404(resp)
# username (menu header)
self.assertIn('iliekcomputers', data)
self.assertIn('Import', data)
# item in user menu
self.assertIn('My Listens', data)
mock_user_get.assert_called_with(user['login_id'])
@mock.patch('listenbrainz.db.user.get')
def test_menu_logged_in_error_dont_show_no_user(self, mock_user_get):
""" If the user is logged in, if we show a 500 error, do not show the user menu
Don't query the database to get a current_user for the template context"""
@self.app.route('/page_that_returns_500')
def view500():
raise InternalServerError('error')
user = db_user.get_or_create(1, 'iliekcomputers')
db_user.agree_to_gdpr(user['musicbrainz_id'])
user = db_user.get_or_create(1, 'iliekcomputers')
mock_user_get.return_value = user
self.temporary_login(user['login_id'])
resp = self.client.get('/page_that_returns_500')
data = resp.data.decode('utf-8')
# item not in user menu
self.assertNotIn('My Listens', data)
self.assertNotIn('Sign in', data)
self.assertIn('Import', data)
@mock.patch('listenbrainz.db.user.get_by_login_id')
def test_menu_logged_in_error_dont_show_user_loaded(self, mock_user_get):
""" If the user is logged in, if we show a 500 error, do not show the user menu
If the user has previously been loaded in the view, check that it's not
loaded while rendering the template"""
user = db_user.get_or_create(1, 'iliekcomputers')
db_user.agree_to_gdpr(user['musicbrainz_id'])
user = db_user.get_or_create(1, 'iliekcomputers')
mock_user_get.return_value = user
@self.app.route('/page_that_returns_500')
@login_required
def view500():
# flask-login user is loaded during @login_required, so check that the db has been queried
mock_user_get.assert_called_with(user['login_id'])
raise InternalServerError('error')
self.temporary_login(user['login_id'])
resp = self.client.get('/page_that_returns_500')
data = resp.data.decode('utf-8')
self.assertIn('Import', data)
# item not in user menu
self.assertNotIn('My Listens', data)
self.assertNotIn('Sign in', data)
# Even after rendering the template, the database has only been queried once (before the exception)
mock_user_get.assert_called_once()
self.assertIsInstance(self.get_context_variable('current_user'), listenbrainz.webserver.login.User)
@mock.patch('listenbrainz.webserver.views.index._authorize_mb_user_deleter')
@mock.patch('listenbrainz.webserver.views.index.delete_user')
def test_mb_user_deleter_valid_account(self, mock_delete_user, mock_authorize_mb_user_deleter):
user1 = db_user.create(1, 'iliekcomputers')
r = self.client.get(url_for('index.mb_user_deleter', musicbrainz_row_id=1, access_token='132'))<|fim▁hole|> mock_delete_user.assert_called_once_with('iliekcomputers')
@mock.patch('listenbrainz.webserver.views.index._authorize_mb_user_deleter')
@mock.patch('listenbrainz.webserver.views.index.delete_user')
def test_mb_user_deleter_not_found(self, mock_delete_user, mock_authorize_mb_user_deleter):
# no user in the db with musicbrainz_row_id = 2
r = self.client.get(url_for('index.mb_user_deleter', musicbrainz_row_id=2, access_token='312421'))
self.assert404(r)
mock_authorize_mb_user_deleter.assert_called_with('312421')
mock_delete_user.assert_not_called()
@mock.patch('listenbrainz.webserver.views.index.requests.get')
@mock.patch('listenbrainz.webserver.views.index.delete_user')
def test_mb_user_deleter_valid_access_token(self, mock_delete_user, mock_requests_get):
mock_requests_get.return_value = MagicMock()
mock_requests_get.return_value.json.return_value = {
'sub': 'UserDeleter',
'metabrainz_user_id': 2007538,
}
user1 = db_user.create(1, 'iliekcomputers')
r = self.client.get(url_for('index.mb_user_deleter', musicbrainz_row_id=1, access_token='132'))
self.assert200(r)
mock_requests_get.assert_called_with(
'https://musicbrainz.org/oauth2/userinfo',
headers={'Authorization': 'Bearer 132'},
)
mock_delete_user.assert_called_with('iliekcomputers')
@mock.patch('listenbrainz.webserver.views.index.requests.get')
@mock.patch('listenbrainz.webserver.views.index.delete_user')
def test_mb_user_deleter_invalid_access_tokens(self, mock_delete_user, mock_requests_get):
mock_requests_get.return_value = MagicMock()
mock_requests_get.return_value.json.return_value = {
'sub': 'UserDeleter',
'metabrainz_user_id': 2007531, # incorrect musicbrainz row id for UserDeleter
}
user1 = db_user.create(1, 'iliekcomputers')
r = self.client.get(url_for('index.mb_user_deleter', musicbrainz_row_id=1, access_token='132'))
self.assertStatus(r, 401)
mock_delete_user.assert_not_called()
# no sub value
mock_requests_get.return_value.json.return_value = {
'metabrainz_user_id': 2007538,
}
r = self.client.get(url_for('index.mb_user_deleter', musicbrainz_row_id=1, access_token='132'))
self.assertStatus(r, 401)
mock_delete_user.assert_not_called()
# no row id
mock_requests_get.return_value.json.return_value = {
'sub': 'UserDeleter',
}
r = self.client.get(url_for('index.mb_user_deleter', musicbrainz_row_id=1, access_token='132'))
self.assertStatus(r, 401)
mock_delete_user.assert_not_called()
# incorrect username
mock_requests_get.return_value.json.return_value = {
'sub': 'iliekcomputers',
'metabrainz_user_id': 2007538
}
r = self.client.get(url_for('index.mb_user_deleter', musicbrainz_row_id=1, access_token='132'))
self.assertStatus(r, 401)
mock_delete_user.assert_not_called()
# everything incorrect
mock_requests_get.return_value.json.return_value = {
'sub': 'iliekcomputers',
'metabrainz_user_id': 1,
}
r = self.client.get(url_for('index.mb_user_deleter', musicbrainz_row_id=1, access_token='132'))
self.assertStatus(r, 401)
mock_delete_user.assert_not_called()
# HTTPError while getting userinfo from MusicBrainz
mock_requests_get.return_value.raise_for_status.side_effect = HTTPError
r = self.client.get(url_for('index.mb_user_deleter', musicbrainz_row_id=1, access_token='132'))
self.assertStatus(r, 401)
mock_delete_user.assert_not_called()
def test_recent_listens_page(self):
response = self.client.get(url_for('index.recent_listens'))
self.assert200(response)
self.assertTemplateUsed('index/recent.html')
props = ujson.loads(self.get_context_variable('props'))
self.assertEqual(props['mode'], 'recent')
self.assertDictEqual(props['spotify'], {})
def test_feed_page(self):
user = db_user.get_or_create(1, 'iliekcomputers') # dev
db_user.agree_to_gdpr(user['musicbrainz_id'])
self.temporary_login(user['login_id'])
r = self.client.get('/feed')
self.assert200(r)
def test_similar_users(self):
resp = self.client.get(url_for('index.similar_users'))
self.assert200(resp)<|fim▁end|>
|
self.assert200(r)
mock_authorize_mb_user_deleter.assert_called_once_with('132')
|
<|file_name|>views.py<|end_file_name|><|fim▁begin|>import json
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from apps.exercises.models import Attempts
from apps.maps.models import Graphs<|fim▁hole|>
from apps.ki.utils import performInference
from apps.research.utils import getParticipantByUID, studyFilter
def knowledge_inference(request, gid=""):
if request.method == "GET":
g = get_object_or_404(Graphs, pk=gid)
if not request.user.is_authenticated(): return HttpResponse(status=403)
u, uc = User.objects.get_or_create(pk=request.user.pk)
p = getParticipantByUID(request.user.pk, gid)
if g.study_active and p is None: return HttpResponse(status=401)
ex = Attempts.objects.filter(graph=g).filter(submitted=True)
ex = studyFilter(g, p, u, ex)
inferences = []
if ex.count() > 1:
r = [e.get_correctness() for e in ex]
inferences = performInference(g.concept_dict, r)
return HttpResponse(json.dumps(inferences), mimetype='application/json')
else:
return HttpResponse(status=405)<|fim▁end|>
| |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>import React from 'react';
const isArray = x => Array.isArray(x);
const isString = x => typeof x === 'string' && x.length > 0;
const isSelector = x => isString(x) && (startsWith(x, '.') || startsWith(x, '#'));
const isChildren = x => /string|number|boolean/.test(typeof x) || isArray(x);
const startsWith = (string, start) => string.indexOf(start) === 0;
const split = (string, separator) => string.split(separator);
const subString = (string, start, end) => string.substring(start, end);
const parseSelector = selector => {
const classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/;
const parts = split(selector, classIdSplit);
return parts.reduce((acc, part) => {
if (startsWith(part, '#')) {
acc.id = subString(part, 1);
} else if (startsWith(part, '.')) {
acc.className = `${acc.className} ${subString(part, 1)}`.trim();
}
return acc;
}, { className: '' });
};
const createElement = (nameOrType, properties = {}, children = []) => {
if (properties.isRendered !== undefined && !properties.isRendered) {
return null;
}
const { isRendered, ...props } = properties;
const args = [nameOrType, props];
if (!isArray(children)) {
args.push(children);
} else {
args.push(...children);
}
return React.createElement.apply(React, args);
};
export const hh = nameOrType => (first, second, third) => {
if (isSelector(first)) {
const selector = parseSelector(first);
// selector, children<|fim▁hole|> return createElement(nameOrType, selector, second);
}
// selector, props, children
let { className = '' } = second || {};
className = `${selector.className} ${className} `.trim();
const props = { ...second, ...selector, className };
if (isChildren(third)) {
return createElement(nameOrType, props, third);
}
return createElement(nameOrType, props);
}
// children
if (isChildren(first)) {
return createElement(nameOrType, {}, first);
}
// props, children
if (isChildren(second)) {
return createElement(nameOrType, first, second);
}
return createElement(nameOrType, first);
};
const h = (nameOrType, ...rest) => hh(nameOrType)(...rest);
const TAG_NAMES = [
'a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo',
'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col',
'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt',
'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4',
'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins',
'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem',
'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param',
'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select',
'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td',
'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'video',
'wbr', 'circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask',
'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan'
];
module.exports = TAG_NAMES.reduce((exported, type) => {
exported[type] = hh(type);
return exported;
}, { h, hh });<|fim▁end|>
|
if (isChildren(second)) {
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>
pub use self::cpu::Cpu;
pub use self::instruction::Instruction;<|fim▁end|>
|
mod cpu;
mod instruction;
mod cp0;
mod opcode;
|
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>"""
Helper functions for handling DB accesses.
"""
import subprocess
import logging
import gzip
import io
from nominatim.db.connection import get_pg_env
from nominatim.errors import UsageError
LOG = logging.getLogger()
def _pipe_to_proc(proc, fdesc):
chunk = fdesc.read(2048)
while chunk and proc.poll() is None:
try:
proc.stdin.write(chunk)
except BrokenPipeError as exc:
raise UsageError("Failed to execute SQL file.") from exc
chunk = fdesc.read(2048)
return len(chunk)
def execute_file(dsn, fname, ignore_errors=False, pre_code=None, post_code=None):
""" Read an SQL file and run its contents against the given database
using psql. Use `pre_code` and `post_code` to run extra commands
before or after executing the file. The commands are run within the
same session, so they may be used to wrap the file execution in a
transaction.
"""
cmd = ['psql']
if not ignore_errors:
cmd.extend(('-v', 'ON_ERROR_STOP=1'))
if not LOG.isEnabledFor(logging.INFO):
cmd.append('--quiet')
proc = subprocess.Popen(cmd, env=get_pg_env(dsn), stdin=subprocess.PIPE)
try:
if not LOG.isEnabledFor(logging.INFO):
proc.stdin.write('set client_min_messages to WARNING;'.encode('utf-8'))
if pre_code:
proc.stdin.write((pre_code + ';').encode('utf-8'))
if fname.suffix == '.gz':
with gzip.open(str(fname), 'rb') as fdesc:
remain = _pipe_to_proc(proc, fdesc)
else:
with fname.open('rb') as fdesc:
remain = _pipe_to_proc(proc, fdesc)
if remain == 0 and post_code:
proc.stdin.write((';' + post_code).encode('utf-8'))
finally:
proc.stdin.close()
ret = proc.wait()
if ret != 0 or remain > 0:
raise UsageError("Failed to execute SQL file.")
# List of characters that need to be quoted for the copy command.
_SQL_TRANSLATION = {ord(u'\\'): u'\\\\',
ord(u'\t'): u'\\t',
ord(u'\n'): u'\\n'}
class CopyBuffer:
""" Data collector for the copy_from command.
"""
def __init__(self):
self.buffer = io.StringIO()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if self.buffer is not None:
self.buffer.close()
def add(self, *data):
""" Add another row of data to the copy buffer.
"""
first = True
for column in data:
if first:
first = False
else:
self.buffer.write('\t')<|fim▁hole|> self.buffer.write(str(column).translate(_SQL_TRANSLATION))
self.buffer.write('\n')
def copy_out(self, cur, table, columns=None):
""" Copy all collected data into the given table.
"""
if self.buffer.tell() > 0:
self.buffer.seek(0)
cur.copy_from(self.buffer, table, columns=columns)<|fim▁end|>
|
if column is None:
self.buffer.write('\\N')
else:
|
<|file_name|>glib-gtypes-generator.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Generate GLib GInterfaces from the Telepathy specification.
# The master copy of this program is in the telepathy-glib repository -
# please make any changes there.
#
# Copyright (C) 2006, 2007 Collabora Limited
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
import sys
import xml.dom.minidom
from libglibcodegen import escape_as_identifier, \
get_docstring, \
NS_TP, \
Signature, \
type_to_gtype, \
xml_escape
def types_to_gtypes(types):
return [type_to_gtype(t)[1] for t in types]
class GTypesGenerator(object):
def __init__(self, dom, output, mixed_case_prefix):
self.dom = dom
self.Prefix = mixed_case_prefix
self.PREFIX_ = self.Prefix.upper() + '_'
self.prefix_ = self.Prefix.lower() + '_'
self.header = open(output + '.h', 'w')
self.body = open(output + '-body.h', 'w')
self.docs = open(output + '-gtk-doc.h', 'w')
for f in (self.header, self.body, self.docs):
f.write('/* Auto-generated, do not edit.\n *\n'
' * This file may be distributed under the same terms\n'
' * as the specification from which it was generated.\n'
' */\n\n')
# keys are e.g. 'sv', values are the key escaped
self.need_mappings = {}
# keys are the contents of the struct (e.g. 'sssu'), values are the
# key escaped
self.need_structs = {}
# keys are the contents of the struct (e.g. 'sssu'), values are the
# key escaped
self.need_struct_arrays = {}
# keys are the contents of the array (unlike need_struct_arrays!),
# values are the key escaped
self.need_other_arrays = {}
def h(self, code):
self.header.write(code.encode("utf-8"))
def c(self, code):
self.body.write(code.encode("utf-8"))
def d(self, code):
self.docs.write(code.encode('utf-8'))
def do_mapping_header(self, mapping):
members = mapping.getElementsByTagNameNS(NS_TP, 'member')
assert len(members) == 2
impl_sig = ''.join([elt.getAttribute('type')
for elt in members])
esc_impl_sig = escape_as_identifier(impl_sig)
name = (self.PREFIX_ + 'HASH_TYPE_' +
mapping.getAttribute('name').upper())
impl = self.prefix_ + 'type_dbus_hash_' + esc_impl_sig
docstring = get_docstring(mapping) or '(Undocumented)'
self.d('/**\n * %s:\n *\n' % name)
self.d(' * %s\n' % xml_escape(docstring))
self.d(' *\n')
self.d(' * This macro expands to a call to a function\n')
self.d(' * that returns the #GType of a #GHashTable\n')
self.d(' * appropriate for representing a D-Bus\n')
self.d(' * dictionary of signature\n')
self.d(' * <literal>a{%s}</literal>.\n' % impl_sig)
self.d(' *\n')
key, value = members
self.d(' * Keys (D-Bus type <literal>%s</literal>,\n'
% key.getAttribute('type'))
tp_type = key.getAttributeNS(NS_TP, 'type')
if tp_type:
self.d(' * type <literal>%s</literal>,\n' % tp_type)
self.d(' * named <literal>%s</literal>):\n'
% key.getAttribute('name'))
docstring = get_docstring(key) or '(Undocumented)'
self.d(' * %s\n' % xml_escape(docstring))
self.d(' *\n')
self.d(' * Values (D-Bus type <literal>%s</literal>,\n'
% value.getAttribute('type'))
tp_type = value.getAttributeNS(NS_TP, 'type')
if tp_type:
self.d(' * type <literal>%s</literal>,\n' % tp_type)
self.d(' * named <literal>%s</literal>):\n'
% value.getAttribute('name'))
docstring = get_docstring(value) or '(Undocumented)'
self.d(' * %s\n' % xml_escape(docstring))
self.d(' *\n')
self.d(' */\n')
self.h('#define %s (%s ())\n\n' % (name, impl))
self.need_mappings[impl_sig] = esc_impl_sig
array_name = mapping.getAttribute('array-name')
if array_name:
gtype_name = self.PREFIX_ + 'ARRAY_TYPE_' + array_name.upper()
contents_sig = 'a{' + impl_sig + '}'
esc_contents_sig = escape_as_identifier(contents_sig)
impl = self.prefix_ + 'type_dbus_array_of_' + esc_contents_sig
self.d('/**\n * %s:\n\n' % gtype_name)
self.d(' * Expands to a call to a function\n')
self.d(' * that returns the #GType of a #GPtrArray\n')
self.d(' * of #%s.\n' % name)
self.d(' */\n\n')
self.h('#define %s (%s ())\n\n' % (gtype_name, impl))
self.need_other_arrays[contents_sig] = esc_contents_sig
def do_struct_header(self, struct):
members = struct.getElementsByTagNameNS(NS_TP, 'member')
impl_sig = ''.join([elt.getAttribute('type') for elt in members])
esc_impl_sig = escape_as_identifier(impl_sig)
name = (self.PREFIX_ + 'STRUCT_TYPE_' +
struct.getAttribute('name').upper())
impl = self.prefix_ + 'type_dbus_struct_' + esc_impl_sig
docstring = struct.getElementsByTagNameNS(NS_TP, 'docstring')
if docstring:
docstring = docstring[0].toprettyxml()
if docstring.startswith('<tp:docstring>'):
docstring = docstring[14:]
if docstring.endswith('</tp:docstring>\n'):
docstring = docstring[:-16]
if docstring.strip() in ('<tp:docstring/>', ''):
docstring = '(Undocumented)'
else:
docstring = '(Undocumented)'
self.d('/**\n * %s:\n\n' % name)
self.d(' * %s\n' % xml_escape(docstring))
self.d(' *\n')
self.d(' * This macro expands to a call to a function\n')
self.d(' * that returns the #GType of a #GValueArray\n')
self.d(' * appropriate for representing a D-Bus struct\n')
self.d(' * with signature <literal>(%s)</literal>.\n'
% impl_sig)
self.d(' *\n')
for i, member in enumerate(members):
self.d(' * Member %d (D-Bus type '
'<literal>%s</literal>,\n'
% (i, member.getAttribute('type')))
tp_type = member.getAttributeNS(NS_TP, 'type')
if tp_type:
self.d(' * type <literal>%s</literal>,\n' % tp_type)
self.d(' * named <literal>%s</literal>):\n'
% member.getAttribute('name'))
docstring = get_docstring(member) or '(Undocumented)'
self.d(' * %s\n' % xml_escape(docstring))
self.d(' *\n')
self.d(' */\n\n')
self.h('#define %s (%s ())\n\n' % (name, impl))
array_name = struct.getAttribute('array-name')
if array_name != '':
array_name = (self.PREFIX_ + 'ARRAY_TYPE_' + array_name.upper())
impl = self.prefix_ + 'type_dbus_array_' + esc_impl_sig
self.d('/**\n * %s:\n\n' % array_name)
self.d(' * Expands to a call to a function\n')
self.d(' * that returns the #GType of a #GPtrArray\n')
self.d(' * of #%s.\n' % name)
self.d(' */\n\n')
self.h('#define %s (%s ())\n\n' % (array_name, impl))
self.need_struct_arrays[impl_sig] = esc_impl_sig
self.need_structs[impl_sig] = esc_impl_sig
def __call__(self):
mappings = self.dom.getElementsByTagNameNS(NS_TP, 'mapping')
structs = self.dom.getElementsByTagNameNS(NS_TP, 'struct')
for mapping in mappings:
self.do_mapping_header(mapping)
for sig in self.need_mappings:
self.h('GType %stype_dbus_hash_%s (void);\n\n' %
(self.prefix_, self.need_mappings[sig]))
self.c('GType\n%stype_dbus_hash_%s (void)\n{\n' %
(self.prefix_, self.need_mappings[sig]))
self.c(' static GType t = 0;\n\n')
self.c(' if (G_UNLIKELY (t == 0))\n')
# FIXME: translate sig into two GTypes
items = tuple(Signature(sig))
gtypes = types_to_gtypes(items)
self.c(' t = dbus_g_type_get_map ("GHashTable", '
'%s, %s);\n' % (gtypes[0], gtypes[1]))
self.c(' return t;\n')
self.c('}\n\n')
for struct in structs:
self.do_struct_header(struct)
for sig in self.need_structs:
self.h('GType %stype_dbus_struct_%s (void);\n\n' %
(self.prefix_, self.need_structs[sig]))
self.c('GType\n%stype_dbus_struct_%s (void)\n{\n' %
(self.prefix_, self.need_structs[sig]))
self.c(' static GType t = 0;\n\n')
self.c(' if (G_UNLIKELY (t == 0))\n')
self.c(' t = dbus_g_type_get_struct ("GValueArray",\n')<|fim▁hole|> self.c(' %s,\n' % gtype)
self.c(' G_TYPE_INVALID);\n')
self.c(' return t;\n')
self.c('}\n\n')
for sig in self.need_struct_arrays:
self.h('GType %stype_dbus_array_%s (void);\n\n' %
(self.prefix_, self.need_struct_arrays[sig]))
self.c('GType\n%stype_dbus_array_%s (void)\n{\n' %
(self.prefix_, self.need_struct_arrays[sig]))
self.c(' static GType t = 0;\n\n')
self.c(' if (G_UNLIKELY (t == 0))\n')
self.c(' t = dbus_g_type_get_collection ("GPtrArray", '
'%stype_dbus_struct_%s ());\n' %
(self.prefix_, self.need_struct_arrays[sig]))
self.c(' return t;\n')
self.c('}\n\n')
for sig in self.need_other_arrays:
self.h('GType %stype_dbus_array_of_%s (void);\n\n' %
(self.prefix_, self.need_other_arrays[sig]))
self.c('GType\n%stype_dbus_array_of_%s (void)\n{\n' %
(self.prefix_, self.need_other_arrays[sig]))
self.c(' static GType t = 0;\n\n')
self.c(' if (G_UNLIKELY (t == 0))\n')
if sig[:2] == 'a{' and sig[-1:] == '}':
# array of mappings
self.c(' t = dbus_g_type_get_collection ('
'"GPtrArray", '
'%stype_dbus_hash_%s ());\n' %
(self.prefix_, escape_as_identifier(sig[2:-1])))
elif sig[:2] == 'a(' and sig[-1:] == ')':
# array of arrays of struct
self.c(' t = dbus_g_type_get_collection ('
'"GPtrArray", '
'%stype_dbus_array_%s ());\n' %
(self.prefix_, escape_as_identifier(sig[2:-1])))
elif sig[:1] == 'a':
# array of arrays of non-struct
self.c(' t = dbus_g_type_get_collection ('
'"GPtrArray", '
'%stype_dbus_array_of_%s ());\n' %
(self.prefix_, escape_as_identifier(sig[1:])))
else:
raise AssertionError("array of '%s' not supported" % sig)
self.c(' return t;\n')
self.c('}\n\n')
if __name__ == '__main__':
argv = sys.argv[1:]
dom = xml.dom.minidom.parse(argv[0])
GTypesGenerator(dom, argv[1], argv[2])()<|fim▁end|>
|
items = tuple(Signature(sig))
gtypes = types_to_gtypes(items)
for gtype in gtypes:
|
<|file_name|>screen.py<|end_file_name|><|fim▁begin|>import os
import sys
import datetime as dt
import json
from itertools import groupby
from kivy.properties import (StringProperty,
DictProperty,
ListProperty,
BooleanProperty)
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import Screen
from kivy.uix.gridlayout import GridLayout
from core.bglabel import BGLabel
from MythTV import MythBE
EPOCH = dt.datetime(1970, 1, 1)
class MythRecording(BoxLayout):
"""Widget class for displaying information about upcoming recordings."""
rec = DictProperty({})
bg = ListProperty([0.1, 0.15, 0.15, 1])
def __init__(self, **kwargs):
super(MythRecording, self).__init__(**kwargs)
self.rec = kwargs["rec"]
class MythRecordingHeader(BGLabel):
"""Widget class for grouping recordings by day."""
rec_date = StringProperty("")
def __init__(self, **kwargs):
super(MythRecordingHeader, self).__init__(**kwargs)
self.bgcolour = [0.1, 0.1, 0.4, 1]
self.rec_date = kwargs["rec_date"]
class MythTVScreen(Screen):
"""Main screen class for MythTV schedule.
Screen attempts to connect to MythTV backend and retrieve list of
upcoming recordings and display this.
Data is cached so that information can still be viewed even if backend
is offline (e.g. for power saving purposes).
"""
backendonline = BooleanProperty(False)
isrecording = BooleanProperty(False)
def __init__(self, **kwargs):
super(MythTVScreen, self).__init__(**kwargs)
# Get the path for the folder
scr = sys.modules[self.__class__.__module__].__file__
# Create variable to retain path to our cache fie
self.screendir = os.path.dirname(scr)
self.cacheFile = os.path.join(self.screendir, "cache", "cache.json")
# Some other useful variable
self.running = False
self.rec_timer = None
self.status_timer = None
self.be = None
self.recs = None
def on_enter(self):
# We only update when we enter the screen. No need for regular updates.
self.getRecordings()
self.drawScreen()
self.checkRecordingStatus()
def on_leave(self):
pass
def cacheRecs(self, recs):
"""Method to save local copy of recordings. Backend may not be online
all the time so a cache enables us to display recordings if if we
can't poll the server for an update.
"""
with open(self.cacheFile, 'w') as outfile:
json.dump(recs, outfile)
<|fim▁hole|> raw = open(self.cacheFile, 'r')
recs = json.load(raw)
except:
recs = []
return recs
def recs_to_dict(self, uprecs):
"""Converts the MythTV upcoming recording iterator into a list of
dict objects.
"""
raw_recs = []
recs = []
# Turn the response into a dict object and add to our list of recorings
for r in uprecs:
rec = {}
st = r.starttime
et = r.endtime
rec["title"] = r.title
rec["subtitle"] = r.subtitle if r.subtitle else ""
day = dt.datetime(st.year, st.month, st.day)
rec["day"] = (day - EPOCH).total_seconds()
rec["time"] = "{} - {}".format(st.strftime("%H:%M"),
et.strftime("%H:%M"))
rec["timestamp"] = (st - EPOCH).total_seconds()
rec["desc"] = r.description
raw_recs.append(rec)
# Group the recordings by day (so we can print a header)
for k, g in groupby(raw_recs, lambda x: x["day"]):
recs.append((k, list(g)))
return recs
def getRecordings(self):
"""Attempts to connect to MythTV backend and retrieve recordings."""
try:
# If we can connect then get recordings and save a local cache.
self.be = MythBE()
uprecs = self.be.getUpcomingRecordings()
self.recs = self.recs_to_dict(uprecs)
self.cacheRecs(self.recs)
self.backendonline = True
except:
# Can't connect so we need to set variables accordinly and try
# to load data from the cache.
self.be = None
self.recs = self.loadCache()
self.backendonline = False
def checkRecordingStatus(self):
"""Checks whether the backend is currently recording."""
try:
recbe = MythBE()
for recorder in recbe.getRecorderList():
if recbe.isRecording(recorder):
self.isrecording = True
break
except:
# If we can't connect to it then it can't be recording.
self.isrecording = False
def drawScreen(self):
"""Main method for rendering screen.
If there is recording data (live or cached) then is laid out in a
scroll view.
If not, the user is notified that the backend is unreachable.
"""
sv = self.ids.myth_scroll
sv.clear_widgets()
if self.recs:
# Create a child widget to hold the recordings.
self.sl = GridLayout(cols=1, size_hint=(1, None), spacing=2)
self.sl.bind(minimum_height=self.sl.setter('height'))
# Loop over the list of recordings.
for rec in self.recs:
# These are grouped by day so we need a header
day = dt.timedelta(0, rec[0]) + EPOCH
mrh = MythRecordingHeader(rec_date=day.strftime("%A %d %B"))
self.sl.add_widget(mrh)
# Then we loop over the recordings scheduled for that day
for r in rec[1]:
# and add them to the display.
mr = MythRecording(rec=r)
self.sl.add_widget(mr)
sv.add_widget(self.sl)
else:
lb = Label(text="Backend is unreachable and there is no cached"
" information")
sv.add_widget(lb)<|fim▁end|>
|
def loadCache(self):
"""Retrieves cached recorings and returns as a python list object."""
try:
|
<|file_name|>map.py<|end_file_name|><|fim▁begin|>#===========================================================================
# Copyright (c) 2011-2012, the PyFACT developers
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the PyFACT developers nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE PYFACT DEVELOPERS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#===========================================================================
# Imports
import sys, time, logging, os, datetime, math
import numpy as np
import scipy.optimize
import scipy.special
import scipy.ndimage
import pyfits
import pyfact as pf
#===========================================================================
# Functions & classes
#---------------------------------------------------------------------------
class SkyCoord:
"""Sky coordinate in RA and Dec. All units should be degree."""
def __init__(self, ra, dec) :
"""
Sky coordinate in RA and Dec. All units should be degree.
In the current implementation it should also work with arrays, though one has to be careful in dist.
Parameters
----------
ra : float/array
Right ascension of the coordinate.
dec : float/array
Declination of the coordinate.
"""
self.ra, self.dec = ra, dec
def dist(self, c) :
"""
Return the distance of the coordinates in degree following the haversine formula,
see e.g. http://en.wikipedia.org/wiki/Great-circle_distance.
Parameters
----------
c : SkyCoord
Returns
-------
distance : float
Return the distance of the coordinates in degree following the haversine formula.
Notes
-----
http://en.wikipedia.org/wiki/Great-circle_distance
"""
return 2. * np.arcsin(np.sqrt(np.sin((self.dec - c.dec) / 360. * np.pi) ** 2.
+ np.cos(self.dec / 180. * np.pi) * np.cos(c.dec / 180. * np.pi)\
* np.sin((self.ra - c.ra) / 360. * np.pi) ** 2.)) / np.pi * 180.
#---------------------------------------------------------------------------
class SkyCircle:
"""A circle on the sky."""
def __init__(self, c, r) :
"""
A circle on the sky.
Parameters
----------
coord : SkyCoord
Coordinates of the circle center (RA, Dec)
r : float
Radius of the circle (deg).
"""
self.c, self.r = c, r
def contains(self, c) :
"""
Checks if the coordinate lies inside the circle.
Parameters
----------
c : SkyCoord
Returns
-------
contains : bool
True if c lies in the SkyCircle.
"""
return self.c.dist(c) <= self.r
def intersects(self, sc) :
"""
Checks if two sky circles overlap.
Parameters
----------
sc : SkyCircle
"""
return self.c.dist(sc.c) <= self.r + sc.r
#---------------------------------------------------------------------------
def skycircle_from_str(cstr) :
"""Creates SkyCircle from circle region string."""
x, y, r = eval(cstr.upper().replace('CIRCLE', ''))
return SkyCircle(SkyCoord(x, y), r)
#---------------------------------------------------------------------------
def get_cam_acc(camdist, rmax=4., nbins=None, exreg=None, fit=False, fitfunc=None, p0=None) :
"""
Calculates the camera acceptance histogram from a given list with camera distances (event list).
Parameters
----------
camdist : array
Numpy array of camera distances (event list).
rmax : float, optional
Maximum radius for the acceptance histogram.
nbins : int, optional
Number of bins for the acceptance histogram (default = 0.1 deg).
exreg : array, optional
Array of exclusion regions. Exclusion regions are given by an aray of size 2
[r, d] with r = radius, d = distance to camera center
fit : bool, optional
Fit acceptance histogram (default=False).
"""
if not nbins :
nbins = int(rmax / .1)
# Create camera distance histogram
n, bins = np.histogram(camdist, bins=nbins, range=[0., rmax])
nerr = np.sqrt(n)
# Bin center array
r = (bins[1:] + bins[:-1]) / 2.
# Bin area (ring) array
r_a = (bins[1:] ** 2. - bins[:-1] ** 2.) * np.pi
# Deal with exclusion regions
ex_a = None
if exreg :
ex_a = np.zeros(len(r))
t = np.ones(len(r))
for reg in exreg :
ex_a += (pf.circle_circle_intersection_a(bins[1:], t * reg[0], t * reg[1])
- pf.circle_circle_intersection_a(bins[:-1], t * reg[0], t * reg[1]))
ex_a /= r_a
# Fit the data
fitter = None
if fit :
#fitfunc = lambda p, x: p[0] * x ** p[1] * (1. + (x / p[2]) ** p[3]) ** ((p[1] + p[4]) / p[3])
if not fitfunc :
fitfunc = lambda p, x: p[0] * x ** 0. * (1. + (x / p[1]) ** p[2]) ** ((0. + p[3]) / p[2])
#fitfunc = lambda p, x: p[0] * x ** 0. * (1. + (x / p[1]) ** p[2]) ** ((0. + p[3]) / p[2]) + p[4] / (np.exp(p[5] * (x - p[6])) + 1.)
if not p0 :
p0 = [n[0] / r_a[0], 1.5, 3., -5.] # Initial guess for the parameters
#p0 = [.5 * n[0] / r_a[0], 1.5, 3., -5., .5 * n[0] / r_a[0], 100., .5] # Initial guess for the parameters
fitter = pf.ChisquareFitter(fitfunc)
m = (n > 0.) * (nerr > 0.) * (r_a != 0.) * ((1. - ex_a) != 0.)
if np.sum(m) <= len(p0) :
logging.error('Could not fit camera acceptance (dof={0}, bins={1})'.format(len(p0), np.sum(m)))
else :
# ok, this _should_ be improved !!!
x, y, yerr = r[m], n[m] / r_a[m] / (1. - ex_a[m]) , nerr[m] / r_a[m] / (1. - ex_a[m])
m = np.isfinite(x) * np.isfinite(y) * np.isfinite(yerr) * (yerr != 0.)
if np.sum(m) <= len(p0) :
logging.error('Could not fit camera acceptance (dof={0}, bins={1})'.format(len(p0), np.sum(m)))
else :
fitter.fit_data(p0, x[m], y[m], yerr[m])
return (n, bins, nerr, r, r_a, ex_a, fitter)<|fim▁hole|>
#---------------------------------------------------------------------------
def get_sky_mask_circle(r, bin_size) :
"""
Returns a 2d numpy histogram with (2. * r / bin_size) bins per axis
where a circle of radius has bins filled 1.s, all other bins are 0.
Parameters
----------
r : float
Radius of the circle.
bin_size : float
Physical size of the bin, same units as rmin, rmax.
Returns
-------
sky_mask : 2d numpy array
Returns a 2d numpy histogram with (2. * r / bin_size) bins per axis
where a circle of radius has bins filled 1.s, all other bins are 0.
"""
nbins = int(np.ceil(2. * r / bin_size))
sky_x = np.ones((nbins, nbins)) * np.linspace(bin_size / 2., 2. * r - bin_size / 2., nbins)
sky_y = np.transpose(sky_x)
sky_mask = np.where(np.sqrt((sky_x - r) ** 2. + (sky_y - r) ** 2.) < r, 1., 0.)
return sky_mask
#---------------------------------------------------------------------------
def get_sky_mask_ring(rmin, rmax, bin_size) :
"""
Returns a 2d numpy histogram with (2. * rmax / bin_size) bins per axis
filled with a ring with inner radius rmin and outer radius rmax of 1.,
all other bins are 0..
Parameters
----------
rmin : float
Inner radius of the ring.
rmax : float
Outer radius of the ring.
bin_size : float
Physical size of the bin, same units as rmin, rmax.
Returns
-------
sky_mask : 2d numpy array
Returns a 2d numpy histogram with (2. * rmax / bin_size) bins per axis
filled with a ring with inner radius rmin and outer radius rmax of 1.,
all other bins are 0..
"""
nbins = int(np.ceil(2. * rmax / bin_size))
sky_x = np.ones((nbins, nbins)) * np.linspace(bin_size / 2., 2. * rmax - bin_size / 2., nbins)
sky_y = np.transpose(sky_x)
sky_mask = np.where((np.sqrt((sky_x - rmax) ** 2. + (sky_y - rmax) ** 2.) < rmax) * (np.sqrt((sky_x - rmax) ** 2. + (sky_y - rmax) ** 2.) > rmin), 1., 0.)
return sky_mask
#---------------------------------------------------------------------------
def get_exclusion_region_map(map, rarange, decrange, exreg) :
"""
Creates a map (2d numpy histogram) with all bins inside of exclusion regions set to 0. (others 1.).
Dec is on the 1st axis (x), RA is on the 2nd (y).
Parameters
----------
map : 2d array
rarange : array
decrange : array
exreg : array-type of SkyCircle
"""
xnbins, ynbins = map.shape
xstep, ystep = (decrange[1] - decrange[0]) / float(xnbins), (rarange[1] - rarange[0]) / float(ynbins)
sky_mask = np.ones((xnbins, ynbins))
for x, xval in enumerate(np.linspace(decrange[0] + xstep / 2., decrange[1] - xstep / 2., xnbins)) :
for y, yval in enumerate(np.linspace(rarange[0] + ystep / 2., rarange[1] - ystep / 2., ynbins)) :
for reg in exreg :
if reg.contains(SkyCoord(yval, xval)) :
sky_mask[x, y] = 0.
return sky_mask
#---------------------------------------------------------------------------
def oversample_sky_map(sky, mask, exmap=None) :
"""
Oversamples a 2d numpy histogram with a given mask.
Parameters
----------
sky : 2d array
mask : 2d array
exmap : 2d array
"""
sky = np.copy(sky)
sky_nx, sky_ny = sky.shape[0], sky.shape[1]
mask_nx, mask_ny = mask.shape[0], mask.shape[1]
mask_centerx, mask_centery = (mask_nx - 1) / 2, (mask_ny - 1) / 2
# new oversampled sky plot
sky_overs = np.zeros((sky_nx, sky_ny))
# 2d hist keeping the number of bins used (alpha)
sky_alpha = np.ones((sky_nx, sky_ny))
sky_base = np.ones((sky_nx, sky_ny))
if exmap != None :
sky *= exmap
sky_base *= exmap
scipy.ndimage.convolve(sky, mask, sky_overs, mode='constant')
scipy.ndimage.convolve(sky_base, mask, sky_alpha, mode='constant')
return (sky_overs, sky_alpha)
#===========================================================================<|fim▁end|>
| |
<|file_name|>faToggleOn.d.ts<|end_file_name|><|fim▁begin|>import { IconDefinition, IconPrefix, IconName } from "@fortawesome/fontawesome-common-types";
export const definition: IconDefinition;
export const faToggleOn: IconDefinition;
export const prefix: IconPrefix;
export const iconName: IconName;
export const width: number;
export const height: number;
export const ligatures: string[];<|fim▁hole|><|fim▁end|>
|
export const unicode: string;
export const svgPathData: string;
|
<|file_name|>session_mgmt.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python
#-*- coding: utf-8 -*-
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Shelter Database.
# Copyright (c) 2016 Luxembourg Institute of Science and Technology.
# All rights reserved.
#
#
#
# ***** END LICENSE BLOCK *****
__author__ = "Cedric Bonhomme"
__version__ = "$Revision: 0.2 $"
__date__ = "$Date: 2016/05/31$"
__revision__ = "$Date: 2016/06/11 $"
__copyright__ = "Copyright 2016 Luxembourg Institute of Science and Technology"
__license__ = ""
import logging
import datetime
from werkzeug import generate_password_hash
from flask import (render_template, flash, session, request,
url_for, redirect, current_app, g)
from flask_login import LoginManager, logout_user, \
login_required, current_user
from flask_principal import (Principal, AnonymousIdentity, UserNeed,
identity_changed, identity_loaded,
session_identity_loader)
import conf
from bootstrap import db
from web.views.common import admin_role, login_user_bundle
from web.models import User
from web.forms import LoginForm #, SignupForm
from web.lib.utils import HumanitarianId
#from notifications import notifications
Principal(current_app)
# Create a permission with a single Need, in this case a RoleNeed.
login_manager = LoginManager()
login_manager.init_app(current_app)
login_manager.login_message = u"Please log in to access this page."
login_manager.login_message_category = "warning"
login_manager.login_view = 'login'
logger = logging.getLogger(__name__)
@identity_loaded.connect_via(current_app._get_current_object())
def on_identity_loaded(sender, identity):
# Set the identity user object
identity.user = current_user
# Add the UserNeed to the identity
if current_user.is_authenticated:
identity.provides.add(UserNeed(current_user.id))
if current_user.is_admin:
identity.provides.add(admin_role)
@login_manager.user_loader
def load_user(user_id):
return User.query.filter(User.id==user_id, User.is_active==True).first()
@current_app.before_request
def before_request():
g.user = current_user
if g.user.is_authenticated:
g.user.last_seen = datetime.datetime.now()
db.session.commit()
@current_app.route('/login', methods=['GET'])
def join():
if current_user.is_authenticated or HumanitarianId().login():
return redirect(url_for('index'))
form = LoginForm()
#signup = SignupForm()
return render_template(
'login.html',
humanitarian_id_auth_uri=conf.HUMANITARIAN_ID_AUTH_URI,
client_id=conf.HUMANITARIAN_ID_CLIENT_ID,
redirect_uri=conf.HUMANITARIAN_ID_REDIRECT_URI,
loginForm=form #, signupForm=signup
)
@current_app.route('/login', methods=['POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
flash('You are logged in', 'info')
login_user_bundle(form.user)
return form.redirect('index')
#signup = SignupForm()
return render_template(
'login.html',
humanitarian_id_auth_uri=conf.HUMANITARIAN_ID_AUTH_URI,
client_id=conf.HUMANITARIAN_ID_CLIENT_ID,
redirect_uri=conf.HUMANITARIAN_ID_REDIRECT_URI,
loginForm=form #, signupForm=signup
)
@current_app.route('/callback/humanitarianid', methods=['GET'])
def login_humanitarianid():
if current_user.is_authenticated:
return redirect(url_for('index'))
access_token = request.values.get('access_token', None)
if access_token:
session['hid_access_token'] = access_token
return redirect(url_for('join'))
return render_template('humanitarianid_login.html')
@current_app.route('/logout')
@login_required
def logout():
# Remove the user information from the session
logout_user()
flash('You are logged out', 'warning')
# Remove session keys set by Flask-Principal
for key in ('identity.name', 'identity.auth_type', 'hid_access_token'):
session.pop(key, None)
# Tell Flask-Principal the user is anonymous
identity_changed.send(current_app, identity=AnonymousIdentity())
session_identity_loader()
if request.values.get('hid_logout'):
return redirect(conf.HUMANITARIAN_ID_AUTH_URI+'/logout')
return redirect(url_for('index'))
#@current_app.route('/signup', methods=['POST'])<|fim▁hole|># if current_user.is_authenticated:
# return redirect(url_for('index'))#
#
# form = SignupForm()
# if form.validate_on_submit():
# user = User(name=form.name.data,
# email=form.email.data,
# pwdhash=generate_password_hash(form.password.data),
# is_active=True)
# db.session.add(user)
# db.session.commit()
# flash('Your account has been created. ', 'success')
# login_user_bundle(user) # automatically log the user
#
# return form.redirect('index')
#
# loginForm = LoginForm()
# return render_template(
# 'join.html',
# loginForm=loginForm, signupForm=form
# )<|fim▁end|>
|
#def signup():
# """if not conf.SELF_REGISTRATION:
# flash("Self-registration is disabled.", 'warning')
# return redirect(url_for('index'))"""
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>pub use self::collision_objects_dispatcher::CollisionObjectsDispatcher;
pub use self::collision_world::{BroadPhaseObject, CollisionWorld};
use na::{Pnt3, Iso3, Pnt2, Iso2};
mod collision_object;
mod collision_groups;
mod collision_objects_dispatcher;
mod collision_world;
/// A 3D collision world associating collision objects to user-defined data of type `T`.
type CollisionWorld3<N, T> = CollisionWorld<Pnt3<N>, Iso3<N>, T>;
/// A 2D collision world associating collision objects to user-defined data of type `T`.
type CollisionWorld2<N, T> = CollisionWorld<Pnt2<N>, Iso2<N>, T>;<|fim▁end|>
|
//! High level API to detect collisions in large, complex scenes.
pub use self::collision_object::CollisionObject;
pub use self::collision_groups::CollisionGroups;
|
<|file_name|>google3.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Fix sys.path so it can find our libraries.
This file is named google3.py because gpylint specifically ignores it when
complaining about the order of import statements - google3 should always<|fim▁hole|>
import tr.google3 #pylint: disable-msg=C6204,W0611<|fim▁end|>
|
come before other non-python-standard imports.
"""
__author__ = '[email protected] (Avery Pennarun)'
|
<|file_name|>uidmap.rs<|end_file_name|><|fim▁begin|>use std::cmp::min;
use std::env;
use std::fs::{File};
use std::io::{BufReader, BufRead};
use std::str::FromStr;
use std::str::from_utf8;
use std::path::{Path, PathBuf};
use unshare::{Command, Stdio};
use libc::funcs::posix88::unistd::{geteuid, getegid};
use libc::{uid_t, gid_t};
use config::Range;
use config::Settings;
use self::Uidmap::*;
use process_util::{env_path_find, capture_stdout};
#[derive(Clone)]<|fim▁hole|>pub enum Uidmap {
Singleton(uid_t, gid_t),
Ranges(Vec<(uid_t, uid_t, uid_t)>, Vec<(gid_t, gid_t, gid_t)>),
}
fn read_uid_map(username: &str) -> Result<Vec<Range>,String> {
let file = try_msg!(File::open(&Path::new("/etc/subuid")),
"Can't open /etc/subuid: {err}");
let mut res = Vec::new();
let reader = BufReader::new(file);
for (num, line) in reader.lines().enumerate() {
let line = try_msg!(line, "Error reading /etc/subuid: {err}");
let parts: Vec<&str> = line[..].split(':').collect();
let start = FromStr::from_str(parts[1]);
let count: Result<uid_t, _> = FromStr::from_str(parts[2].trim_right());
if parts.len() != 3 || start.is_err() || count.is_err() {
return Err(format!("/etc/subuid:{}: Bad syntax", num+1));
}
if parts[0].eq(username) {
let start: uid_t = start.unwrap();
let end = start + count.unwrap() - 1;
res.push(Range::new(start, end));
}
}
return Ok(res);
}
fn read_gid_map(username: &str) -> Result<Vec<Range>,String> {
let file = try_msg!(File::open(&Path::new("/etc/subgid")),
"Can't open /etc/subgid: {err}");
let mut res = Vec::new();
let reader = BufReader::new(file);
for (num, line) in reader.lines().enumerate() {
let line = try_msg!(line, "Error reading /etc/subgid: {err}");
let parts: Vec<&str> = line[..].split(':').collect();
let start = FromStr::from_str(parts[1]);
let count: Result<uid_t, _> = FromStr::from_str(parts[2].trim_right());
if parts.len() != 3 || start.is_err() || count.is_err() {
return Err(format!("/etc/subgid:{}: Bad syntax", num+1));
}
if parts[0].eq(username) {
let start: gid_t = start.unwrap();
let end = start + count.unwrap() - 1;
res.push(Range::new(start, end));
}
}
return Ok(res);
}
pub fn match_ranges(req: &Vec<Range>, allowed: &Vec<Range>, own_id: uid_t)
-> Result<Vec<(uid_t, uid_t, uid_t)>, ()>
{
let mut res = vec!((0, own_id, 1));
let mut reqiter = req.iter();
let mut reqval = *reqiter.next().unwrap();
let mut allowiter = allowed.iter();
let mut allowval = *allowiter.next().unwrap();
loop {
if reqval.start() == 0 {
reqval = reqval.shift(1);
}
if allowval.start() == 0 {
allowval = allowval.shift(1);
}
let clen = min(reqval.len(), allowval.len());
if clen > 0 {
res.push((reqval.start(), allowval.start(), clen));
}
reqval = reqval.shift(clen);
allowval = allowval.shift(clen);
if reqval.len() == 0 {
reqval = match reqiter.next() {
Some(val) => *val,
None => break,
};
}
if allowval.len() == 0 {
allowval = match allowiter.next() {
Some(val) => *val,
None => return Err(()),
};
}
}
return Ok(res);
}
pub fn get_max_uidmap() -> Result<Uidmap, String>
{
let mut cmd = Command::new(env_path_find("id")
.unwrap_or(PathBuf::from("/usr/bin/id")));
cmd.arg("--user").arg("--name");
if let Ok(path) = env::var("HOST_PATH") {
cmd.env("PATH", path);
}
cmd.stdin(Stdio::null()).stderr(Stdio::inherit());
let username = try!(capture_stdout(cmd)
.map_err(|e| format!("Error running `id --user --name`: {}", e))
.and_then(|val| from_utf8(&val).map(|x| x.trim().to_string())
.map_err(|e| format!("Can't decode username: {}", e))));
let uid_map = read_uid_map(&username).ok();
let gid_map = read_gid_map(&username).ok();
let uid = unsafe { geteuid() };
let gid = unsafe { getegid() };
if let (Some(uid_map), Some(gid_map)) = (uid_map, gid_map) {
if uid_map.len() == 0 && gid_map.len() == 0 && uid == 0 {
let uid_rng = try!(read_uid_ranges("/proc/self/uid_map", true));
let gid_rng = try!(read_uid_ranges("/proc/self/gid_map", true));
return Ok(Ranges(
uid_rng.into_iter()
.map(|r| (r.start(), r.start(), r.len())).collect(),
gid_rng.into_iter()
.map(|r| (r.start(), r.start(), r.len())).collect()));
}
let mut uids = vec!((0, uid, 1));
for &rng in uid_map.iter() {
let mut rng = rng;
if uid >= rng.start() && uid <= rng.end() {
// TODO(tailhook) implement better heuristic
assert!(uid == rng.start());
rng = rng.shift(1);
if rng.len() == 0 { continue; }
}
uids.push((rng.start(), rng.start(), rng.len()));
}
let mut gids = vec!((0, gid, 1));
for &rng in gid_map.iter() {
let mut rng = rng;
if gid >= rng.start() && gid <= rng.end() {
// TODO(tailhook) implement better heuristic
assert!(gid == rng.start());
rng = rng.shift(1);
if rng.len() == 0 { continue; }
}
gids.push((rng.start(), rng.start(), rng.len()));
}
return Ok(Ranges(uids, gids));
} else {
warn!(concat!("Your system doesn't have /etc/subuid and /etc/subgid.",
" Presumably your system is too old. Some features may not work"));
return Ok(Singleton(uid, gid));
}
}
fn read_uid_ranges(path: &str, read_inside: bool) -> Result<Vec<Range>, String>
{
let file = BufReader::new(try!(File::open(&Path::new(path))
.map_err(|e| format!("Error reading uid/gid map: {}", e))));
let mut result = vec!();
for line in file.lines() {
let line = try!(line
.map_err(|_| format!("Error reading uid/gid map")));
let mut words = line[..].split_whitespace();
let inside: u32 = try!(words.next().and_then(|x| FromStr::from_str(x).ok())
.ok_or(format!("uid/gid map format error")));
let outside: u32 = try!(words.next().and_then(|x| FromStr::from_str(x).ok())
.ok_or(format!("uid/gid map format error")));
let count: u32 = try!(words.next().and_then(|x| FromStr::from_str(x).ok())
.ok_or(format!("uid/gid map format error")));
if read_inside {
result.push(Range::new(inside, inside+count-1));
} else {
result.push(Range::new(outside, outside+count-1));
}
}
return Ok(result);
}
pub fn map_users(settings: &Settings, uids: &Vec<Range>, gids: &Vec<Range>)
-> Result<Uidmap, String>
{
let default_uids = vec!(Range::new(0, 0));
let default_gids = vec!(Range::new(0, 0));
let uids = if uids.len() > 0 { uids } else { &default_uids };
let gids = if gids.len() > 0 { gids } else { &default_gids };
if settings.uid_map.is_none() {
let ranges = try!(read_uid_ranges("/proc/self/uid_map", true));
let uid_map = try!(match_ranges(uids, &ranges, 0)
.map_err(|()| {
return format!("Number of allowed subuids is too small. \
Required {:?}, allowed {:?}. You either need to increase \
allowed numbers in /etc/subuid (preferred) or decrease \
needed ranges in vagga.yaml by adding `uids` key \
to container config", uids, ranges);
}));
let ranges = try!(read_uid_ranges("/proc/self/gid_map", true));
let gid_map = try!(match_ranges(gids, &ranges, 0)
.map_err(|()| {
return format!("Number of allowed subgids is too small. \
Required {:?}, allowed {:?}. You either need to increase \
allowed numbers in /etc/subgid (preferred) or decrease \
needed ranges in vagga.yaml by adding `gids` key \
to container config", gids, ranges);
}));
return Ok(Ranges(uid_map, gid_map));
} else {
let &(ref uids, ref gids) = settings.uid_map.as_ref().unwrap();
return Ok(Ranges(uids.clone(), gids.clone()));
}
}<|fim▁end|>
| |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListType
from pyangbind.lib.yangtypes import YANGDynClass
from pyangbind.lib.yangtypes import ReferenceType
from pyangbind.lib.base import PybindBase
from collections import OrderedDict
from decimal import Decimal
from bitarray import bitarray
import six
# PY3 support of some PY2 keywords (needs improved)
if six.PY3:
import builtins as __builtin__
long = int
elif six.PY2:
import __builtin__
class state(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-network-instance - based on the path /network-instances/network-instance/protocols/protocol/bgp/global/afi-safis/afi-safi/graceful-restart/state. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: State information for BGP graceful-restart
"""
__slots__ = ("_path_helper", "_extmethods", "__enabled")
_yang_name = "state"
_pybind_generated_by = "container"
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__enabled = YANGDynClass(
base=YANGBool,
default=YANGBool("false"),
is_leaf=True,
yang_name="enabled",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="boolean",
is_config=False,
)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path() + [self._yang_name]
else:
return [
"network-instances",
"network-instance",
"protocols",
"protocol",
"bgp",
"global",
"afi-safis",
"afi-safi",
"graceful-restart",
"state",
]
def _get_enabled(self):
"""
Getter method for enabled, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/global/afi_safis/afi_safi/graceful_restart/state/enabled (boolean)
YANG Description: This leaf indicates whether graceful-restart is enabled for
this AFI-SAFI
"""
return self.__enabled
def _set_enabled(self, v, load=False):
"""
Setter method for enabled, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/global/afi_safis/afi_safi/graceful_restart/state/enabled (boolean)
If this variable is read-only (config: false) in the
source YANG file, then _set_enabled is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_enabled() directly.
YANG Description: This leaf indicates whether graceful-restart is enabled for
this AFI-SAFI
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=YANGBool,
default=YANGBool("false"),
is_leaf=True,
yang_name="enabled",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="boolean",
is_config=False,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """enabled must be of a type compatible with boolean""",
"defined-type": "boolean",
"generated-type": """YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enabled", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='boolean', is_config=False)""",
}
)
self.__enabled = t
if hasattr(self, "_set"):
self._set()
def _unset_enabled(self):
self.__enabled = YANGDynClass(
base=YANGBool,
default=YANGBool("false"),
is_leaf=True,
yang_name="enabled",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="boolean",
is_config=False,
)
enabled = __builtin__.property(_get_enabled)
_pyangbind_elements = OrderedDict([("enabled", enabled)])
class state(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-network-instance-l2 - based on the path /network-instances/network-instance/protocols/protocol/bgp/global/afi-safis/afi-safi/graceful-restart/state. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: State information for BGP graceful-restart
"""
__slots__ = ("_path_helper", "_extmethods", "__enabled")
_yang_name = "state"
_pybind_generated_by = "container"
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__enabled = YANGDynClass(
base=YANGBool,
default=YANGBool("false"),
is_leaf=True,
yang_name="enabled",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="boolean",
is_config=False,
)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path() + [self._yang_name]
else:
return [
"network-instances",
"network-instance",
"protocols",
"protocol",
"bgp",
"global",
"afi-safis",
"afi-safi",
"graceful-restart",
"state",
]
def _get_enabled(self):
"""
Getter method for enabled, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/global/afi_safis/afi_safi/graceful_restart/state/enabled (boolean)
YANG Description: This leaf indicates whether graceful-restart is enabled for
this AFI-SAFI
"""
return self.__enabled
def _set_enabled(self, v, load=False):
"""
Setter method for enabled, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/global/afi_safis/afi_safi/graceful_restart/state/enabled (boolean)
If this variable is read-only (config: false) in the
source YANG file, then _set_enabled is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_enabled() directly.
YANG Description: This leaf indicates whether graceful-restart is enabled for
this AFI-SAFI
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=YANGBool,
default=YANGBool("false"),
is_leaf=True,
yang_name="enabled",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="boolean",
is_config=False,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """enabled must be of a type compatible with boolean""",
"defined-type": "boolean",
"generated-type": """YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enabled", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='boolean', is_config=False)""",
}
)
self.__enabled = t
if hasattr(self, "_set"):
self._set()
def _unset_enabled(self):
self.__enabled = YANGDynClass(
base=YANGBool,
default=YANGBool("false"),
is_leaf=True,
yang_name="enabled",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",<|fim▁hole|> yang_type="boolean",
is_config=False,
)
enabled = __builtin__.property(_get_enabled)
_pyangbind_elements = OrderedDict([("enabled", enabled)])<|fim▁end|>
| |
<|file_name|>gfortran.py<|end_file_name|><|fim▁begin|>"""SCons.Tool.gfortran
Tool-specific initialization for gfortran, the GNU Fortran 95/Fortran
2003 compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2014 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY<|fim▁hole|># LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/gfortran.py 2014/09/27 12:51:43 garyo"
import SCons.Util
import fortran
def generate(env):
"""Add Builders and construction variables for gfortran to an
Environment."""
fortran.generate(env)
for dialect in ['F77', 'F90', 'FORTRAN', 'F95', 'F03']:
env['%s' % dialect] = 'gfortran'
env['SH%s' % dialect] = '$%s' % dialect
if env['PLATFORM'] in ['cygwin', 'win32']:
env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS' % dialect)
else:
env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS -fPIC' % dialect)
env['INC%sPREFIX' % dialect] = "-I"
env['INC%sSUFFIX' % dialect] = ""
def exists(env):
return env.Detect('gfortran')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:<|fim▁end|>
|
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
<|file_name|>comp-1531.component.spec.ts<|end_file_name|><|fim▁begin|>/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Comp1531Component } from './comp-1531.component';
describe('Comp1531Component', () => {
let component: Comp1531Component;
let fixture: ComponentFixture<Comp1531Component>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ Comp1531Component ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(Comp1531Component);
component = fixture.componentInstance;
fixture.detectChanges();<|fim▁hole|> });
it('should create', () => {
expect(component).toBeTruthy();
});
});<|fim▁end|>
| |
<|file_name|>virtualnetworktaps.go<|end_file_name|><|fim▁begin|>package network
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// VirtualNetworkTapsClient is the network Client
type VirtualNetworkTapsClient struct {
BaseClient
}
// NewVirtualNetworkTapsClient creates an instance of the VirtualNetworkTapsClient client.
func NewVirtualNetworkTapsClient(subscriptionID string) VirtualNetworkTapsClient {
return NewVirtualNetworkTapsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewVirtualNetworkTapsClientWithBaseURI creates an instance of the VirtualNetworkTapsClient client using a custom
// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure
// stack).
func NewVirtualNetworkTapsClientWithBaseURI(baseURI string, subscriptionID string) VirtualNetworkTapsClient {
return VirtualNetworkTapsClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// CreateOrUpdate creates or updates a Virtual Network Tap.
// Parameters:
// resourceGroupName - the name of the resource group.
// tapName - the name of the virtual network tap.
// parameters - parameters supplied to the create or update virtual network tap operation.
func (client VirtualNetworkTapsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, tapName string, parameters VirtualNetworkTap) (result VirtualNetworkTapsCreateOrUpdateFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.CreateOrUpdate")
defer func() {
sc := -1
if result.Response() != nil {
sc = result.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}}},
}},
}},
}},
}},
}},
{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}}},
}},
}},
}},
}},
}},
}}}}}); err != nil {
return result, validation.NewError("network.VirtualNetworkTapsClient", "CreateOrUpdate", err.Error())
}
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, tapName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "CreateOrUpdate", nil, "Failure preparing request")
return
}
result, err = client.CreateOrUpdateSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "CreateOrUpdate", result.Response(), "Failure sending request")
return
}
return
}
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client VirtualNetworkTapsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, tapName string, parameters VirtualNetworkTap) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"tapName": autorest.Encode("path", tapName),
}
const APIVersion = "2019-09-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
parameters.Etag = nil
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client VirtualNetworkTapsClient) CreateOrUpdateSender(req *http.Request) (future VirtualNetworkTapsCreateOrUpdateFuture, err error) {
var resp *http.Response
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
future.Future, err = azure.NewFutureFromResponse(resp)
return
}
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client VirtualNetworkTapsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetworkTap, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete deletes the specified virtual network tap.
// Parameters:
// resourceGroupName - the name of the resource group.
// tapName - the name of the virtual network tap.
func (client VirtualNetworkTapsClient) Delete(ctx context.Context, resourceGroupName string, tapName string) (result VirtualNetworkTapsDeleteFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.Delete")
defer func() {
sc := -1
if result.Response() != nil {
sc = result.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.DeletePreparer(ctx, resourceGroupName, tapName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "Delete", nil, "Failure preparing request")
return
}
result, err = client.DeleteSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "Delete", result.Response(), "Failure sending request")
return
}
return
}
// DeletePreparer prepares the Delete request.
func (client VirtualNetworkTapsClient) DeletePreparer(ctx context.Context, resourceGroupName string, tapName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"tapName": autorest.Encode("path", tapName),
}
const APIVersion = "2019-09-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client VirtualNetworkTapsClient) DeleteSender(req *http.Request) (future VirtualNetworkTapsDeleteFuture, err error) {
var resp *http.Response
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
future.Future, err = azure.NewFutureFromResponse(resp)
return
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client VirtualNetworkTapsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Get gets information about the specified virtual network tap.
// Parameters:
// resourceGroupName - the name of the resource group.<|fim▁hole|> defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.GetPreparer(ctx, resourceGroupName, tapName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client VirtualNetworkTapsClient) GetPreparer(ctx context.Context, resourceGroupName string, tapName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"tapName": autorest.Encode("path", tapName),
}
const APIVersion = "2019-09-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client VirtualNetworkTapsClient) GetSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client VirtualNetworkTapsClient) GetResponder(resp *http.Response) (result VirtualNetworkTap, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListAll gets all the VirtualNetworkTaps in a subscription.
func (client VirtualNetworkTapsClient) ListAll(ctx context.Context) (result VirtualNetworkTapListResultPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.ListAll")
defer func() {
sc := -1
if result.vntlr.Response.Response != nil {
sc = result.vntlr.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.fn = client.listAllNextResults
req, err := client.ListAllPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "ListAll", nil, "Failure preparing request")
return
}
resp, err := client.ListAllSender(req)
if err != nil {
result.vntlr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "ListAll", resp, "Failure sending request")
return
}
result.vntlr, err = client.ListAllResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "ListAll", resp, "Failure responding to request")
}
return
}
// ListAllPreparer prepares the ListAll request.
func (client VirtualNetworkTapsClient) ListAllPreparer(ctx context.Context) (*http.Request, error) {
pathParameters := map[string]interface{}{
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2019-09-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualNetworkTaps", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListAllSender sends the ListAll request. The method will close the
// http.Response Body if it receives an error.
func (client VirtualNetworkTapsClient) ListAllSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListAllResponder handles the response to the ListAll request. The method always
// closes the http.Response Body.
func (client VirtualNetworkTapsClient) ListAllResponder(resp *http.Response) (result VirtualNetworkTapListResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listAllNextResults retrieves the next set of results, if any.
func (client VirtualNetworkTapsClient) listAllNextResults(ctx context.Context, lastResults VirtualNetworkTapListResult) (result VirtualNetworkTapListResult, err error) {
req, err := lastResults.virtualNetworkTapListResultPreparer(ctx)
if err != nil {
return result, autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "listAllNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListAllSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "listAllNextResults", resp, "Failure sending next results request")
}
result, err = client.ListAllResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "listAllNextResults", resp, "Failure responding to next results request")
}
return
}
// ListAllComplete enumerates all values, automatically crossing page boundaries as required.
func (client VirtualNetworkTapsClient) ListAllComplete(ctx context.Context) (result VirtualNetworkTapListResultIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.ListAll")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.ListAll(ctx)
return
}
// ListByResourceGroup gets all the VirtualNetworkTaps in a subscription.
// Parameters:
// resourceGroupName - the name of the resource group.
func (client VirtualNetworkTapsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result VirtualNetworkTapListResultPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.ListByResourceGroup")
defer func() {
sc := -1
if result.vntlr.Response.Response != nil {
sc = result.vntlr.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.fn = client.listByResourceGroupNextResults
req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "ListByResourceGroup", nil, "Failure preparing request")
return
}
resp, err := client.ListByResourceGroupSender(req)
if err != nil {
result.vntlr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "ListByResourceGroup", resp, "Failure sending request")
return
}
result.vntlr, err = client.ListByResourceGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "ListByResourceGroup", resp, "Failure responding to request")
}
return
}
// ListByResourceGroupPreparer prepares the ListByResourceGroup request.
func (client VirtualNetworkTapsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2019-09-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the
// http.Response Body if it receives an error.
func (client VirtualNetworkTapsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always
// closes the http.Response Body.
func (client VirtualNetworkTapsClient) ListByResourceGroupResponder(resp *http.Response) (result VirtualNetworkTapListResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listByResourceGroupNextResults retrieves the next set of results, if any.
func (client VirtualNetworkTapsClient) listByResourceGroupNextResults(ctx context.Context, lastResults VirtualNetworkTapListResult) (result VirtualNetworkTapListResult, err error) {
req, err := lastResults.virtualNetworkTapListResultPreparer(ctx)
if err != nil {
return result, autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListByResourceGroupSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request")
}
result, err = client.ListByResourceGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request")
}
return
}
// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required.
func (client VirtualNetworkTapsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result VirtualNetworkTapListResultIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.ListByResourceGroup")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.ListByResourceGroup(ctx, resourceGroupName)
return
}
// UpdateTags updates an VirtualNetworkTap tags.
// Parameters:
// resourceGroupName - the name of the resource group.
// tapName - the name of the tap.
// tapParameters - parameters supplied to update VirtualNetworkTap tags.
func (client VirtualNetworkTapsClient) UpdateTags(ctx context.Context, resourceGroupName string, tapName string, tapParameters TagsObject) (result VirtualNetworkTap, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.UpdateTags")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, tapName, tapParameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "UpdateTags", nil, "Failure preparing request")
return
}
resp, err := client.UpdateTagsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "UpdateTags", resp, "Failure sending request")
return
}
result, err = client.UpdateTagsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "UpdateTags", resp, "Failure responding to request")
}
return
}
// UpdateTagsPreparer prepares the UpdateTags request.
func (client VirtualNetworkTapsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, tapName string, tapParameters TagsObject) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"tapName": autorest.Encode("path", tapName),
}
const APIVersion = "2019-09-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPatch(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}", pathParameters),
autorest.WithJSON(tapParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// UpdateTagsSender sends the UpdateTags request. The method will close the
// http.Response Body if it receives an error.
func (client VirtualNetworkTapsClient) UpdateTagsSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// UpdateTagsResponder handles the response to the UpdateTags request. The method always
// closes the http.Response Body.
func (client VirtualNetworkTapsClient) UpdateTagsResponder(resp *http.Response) (result VirtualNetworkTap, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}<|fim▁end|>
|
// tapName - the name of virtual network tap.
func (client VirtualNetworkTapsClient) Get(ctx context.Context, resourceGroupName string, tapName string) (result VirtualNetworkTap, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.Get")
|
<|file_name|>CallEventExecutionImpl.cpp<|end_file_name|><|fim▁begin|>#include "fUML/Semantics/CommonBehavior/impl/CallEventExecutionImpl.hpp"
#ifdef NDEBUG
#define DEBUG_MESSAGE(a) /**/
#else
#define DEBUG_MESSAGE(a) a
#endif
#ifdef ACTIVITY_DEBUG_ON
#define ACT_DEBUG(a) a
#else
#define ACT_DEBUG(a) /**/
#endif
//#include "util/ProfileCallCount.hpp"
#include <cassert>
#include <iostream>
#include <sstream>
#include "abstractDataTypes/Bag.hpp"
#include "abstractDataTypes/AnyEObject.hpp"
#include "abstractDataTypes/AnyEObjectBag.hpp"
#include "abstractDataTypes/SubsetUnion.hpp"
#include "ecore/EAnnotation.hpp"
#include "ecore/EClass.hpp"
#include "ecore/EAttribute.hpp"
#include "ecore/EStructuralFeature.hpp"
#include "ecore/ecorePackage.hpp"
//Includes from codegen annotation
#include "fUML/Semantics/CommonBehavior/CallEventOccurrence.hpp"
#include "fUML/Semantics/CommonBehavior/CallEventBehavior.hpp"
#include "fUML/fUMLFactory.hpp"
#include "fUML/Semantics/StructuredClassifiers/Reference.hpp"
#include "uml/ParameterDirectionKind.hpp"
#include "uml/Parameter.hpp"
#include "uml/Behavior.hpp"
//Forward declaration includes
#include "persistence/interfaces/XLoadHandler.hpp" // used for Persistence
#include "persistence/interfaces/XSaveHandler.hpp" // used for Persistence
#include <exception> // used in Persistence
#include "fUML/Semantics/CommonBehavior/CommonBehaviorFactory.hpp"
#include "fUML/Semantics/StructuredClassifiers/StructuredClassifiersFactory.hpp"
#include "fUML/Semantics/SimpleClassifiers/SimpleClassifiersFactory.hpp"
#include "fUML/Semantics/Loci/LociFactory.hpp"
#include "uml/umlFactory.hpp"
#include "uml/Behavior.hpp"
#include "uml/Classifier.hpp"
#include "fUML/Semantics/CommonBehavior/EventOccurrence.hpp"
#include "fUML/Semantics/CommonBehavior/Execution.hpp"
#include "fUML/Semantics/SimpleClassifiers/FeatureValue.hpp"
#include "fUML/Semantics/Loci/Locus.hpp"
#include "fUML/Semantics/StructuredClassifiers/Object.hpp"
#include "fUML/Semantics/CommonBehavior/ObjectActivation.hpp"
#include "uml/Operation.hpp"
#include "fUML/Semantics/CommonBehavior/ParameterValue.hpp"
#include "fUML/Semantics/Values/Value.hpp"
//Factories and Package includes
#include "fUML/Semantics/SemanticsPackage.hpp"
#include "fUML/fUMLPackage.hpp"
#include "fUML/Semantics/CommonBehavior/CommonBehaviorPackage.hpp"
#include "fUML/Semantics/Loci/LociPackage.hpp"
#include "fUML/Semantics/SimpleClassifiers/SimpleClassifiersPackage.hpp"
#include "fUML/Semantics/StructuredClassifiers/StructuredClassifiersPackage.hpp"
#include "fUML/Semantics/Values/ValuesPackage.hpp"
#include "uml/umlPackage.hpp"
using namespace fUML::Semantics::CommonBehavior;
//*********************************
// Constructor / Destructor
//*********************************
CallEventExecutionImpl::CallEventExecutionImpl()
{
/*
NOTE: Due to virtual inheritance, base class constrcutors may not be called correctly
*/
}
CallEventExecutionImpl::~CallEventExecutionImpl()
{
#ifdef SHOW_DELETION
std::cout << "-------------------------------------------------------------------------------------------------\r\ndelete CallEventExecution "<< this << "\r\n------------------------------------------------------------------------ " << std::endl;
#endif
}
CallEventExecutionImpl::CallEventExecutionImpl(const CallEventExecutionImpl & obj): CallEventExecutionImpl()
{
*this = obj;
}
CallEventExecutionImpl& CallEventExecutionImpl::operator=(const CallEventExecutionImpl & obj)
{
//call overloaded =Operator for each base class
ExecutionImpl::operator=(obj);
/* TODO: Find out if this call is necessary
* Currently, this causes an error because it calls an implicit assignment operator of CallEventExecution
* which is generated by the compiler (as CallEventExecution is an abstract class and does not have a user-defined assignment operator).
* Implicit compiler-generated assignment operators however only create shallow copies of members,
* which implies, that not a real deep copy is created when using the copy()-method.
*
* NOTE: Since all members are deep-copied by this assignment-operator anyway, why is it even necessary to call this implicit assignment-operator?
* This is only done for ecore-models, not for UML-models.
*/
//CallEventExecution::operator=(obj);
//create copy of all Attributes
#ifdef SHOW_COPIES
std::cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\ncopy CallEventExecution "<< this << "\r\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ " << std::endl;
#endif
//Clone Attributes with (deep copy)
m_callerSuspended = obj.getCallerSuspended();
//copy references with no containment (soft copy)
//Clone references with containment (deep copy)
return *this;
}
std::shared_ptr<ecore::EObject> CallEventExecutionImpl::copy() const
{
std::shared_ptr<CallEventExecutionImpl> element(new CallEventExecutionImpl());
*element =(*this);
element->setThisCallEventExecutionPtr(element);
return element;
}
//*********************************
// Operations
//*********************************
std::shared_ptr<fUML::Semantics::Values::Value> CallEventExecutionImpl::_copy()
{
//ADD_COUNT(__PRETTY_FUNCTION__)
//generated from body annotation
// Create a new call event execution that is a copy of this execution, with the
// caller initially not suspended.
std::shared_ptr<fUML::Semantics::CommonBehavior::CallEventExecution> newValue = std::dynamic_pointer_cast<fUML::Semantics::CommonBehavior::CallEventExecution>(fUML::Semantics::CommonBehavior::ExecutionImpl::_copy());
newValue->setCallerSuspended(false);
return newValue;
//end of body
}
std::shared_ptr<fUML::Semantics::CommonBehavior::EventOccurrence> CallEventExecutionImpl::createEventOccurrence()
{
//ADD_COUNT(__PRETTY_FUNCTION__)
//generated from body annotation
std::shared_ptr<fUML::Semantics::CommonBehavior::CallEventOccurrence> eventOccurrence = fUML::Semantics::CommonBehavior::CommonBehaviorFactory::eInstance()->createCallEventOccurrence();
eventOccurrence->setExecution(getThisCallEventExecutionPtr());
return eventOccurrence;
//end of body
}
void CallEventExecutionImpl::execute()
{
//ADD_COUNT(__PRETTY_FUNCTION__)
//generated from body annotation
// Make the call on the target object (which is the context of this execution)
// and suspend the caller until the call is completed.
// Note: The callerSuspended flag needs to be set before the call is made,
// in case the call is immediately handled and returned, even before the
// suspend loop is started.
this->setCallerSuspended(true);
this->makeCall();
this->suspendCaller();
//end of body
}
std::shared_ptr<Bag<fUML::Semantics::CommonBehavior::ParameterValue> > CallEventExecutionImpl::getInputParameterValues()
{
//ADD_COUNT(__PRETTY_FUNCTION__)
//generated from body annotation
// Return input parameter values for this execution.
std::shared_ptr<Bag<fUML::Semantics::CommonBehavior::ParameterValue>> parameterValues(new Bag<fUML::Semantics::CommonBehavior::ParameterValue>());
for(unsigned int i = 0; i < this->getParameterValues()->size(); i++)
{
std::shared_ptr<fUML::Semantics::CommonBehavior::ParameterValue> parameterValue = this->getParameterValues()->at(i);
if((parameterValue->getParameter()->getDirection() == uml::ParameterDirectionKind::IN) || (parameterValue->getParameter()->getDirection() == uml::ParameterDirectionKind::INOUT))
{
parameterValues->add(parameterValue);
}
}
return parameterValues;
//end of body
}
std::shared_ptr<uml::Operation> CallEventExecutionImpl::getOperation()
{
//ADD_COUNT(__PRETTY_FUNCTION__)
//generated from body annotation
// Return the operation being called by this call event execution.
return (std::dynamic_pointer_cast<fUML::Semantics::CommonBehavior::CallEventBehavior>(this->getBehavior()))->getOperation();
//end of body
}
bool CallEventExecutionImpl::isCallerSuspended()
{
//ADD_COUNT(__PRETTY_FUNCTION__)
//generated from body annotation
_beginIsolation();
bool isSuspended = m_callerSuspended;
_endIsolation();
return isSuspended;
//end of body
}
void CallEventExecutionImpl::makeCall()
{
//ADD_COUNT(__PRETTY_FUNCTION__)
//generated from body annotation
// Make the call on the target object (which is the context of this execution)
// by sending a call event occurrence. (Note that the call will never be
// completed if the target is not an active object, since then the object
// would then have no event pool in which the event occurrence could be placed.)
std::shared_ptr<fUML::Semantics::StructuredClassifiers::Reference> reference = fUML::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createReference();
reference->setReferent(this->getContext());
this->createEventOccurrence()->sendTo(reference);
//end of body
}
std::shared_ptr<fUML::Semantics::Values::Value> CallEventExecutionImpl::new_()
{
//ADD_COUNT(__PRETTY_FUNCTION__)
//generated from body annotation
// Create a new call event execution.
return fUML::Semantics::CommonBehavior::CommonBehaviorFactory::eInstance()->createCallEventExecution();
//end of body
}
void CallEventExecutionImpl::releaseCaller()
{
//ADD_COUNT(__PRETTY_FUNCTION__)
//generated from body annotation
setCallerSuspended(false);
//end of body
}
void CallEventExecutionImpl::setOutputParameterValues(std::shared_ptr<Bag<fUML::Semantics::CommonBehavior::ParameterValue>> parameterValues)
{
//ADD_COUNT(__PRETTY_FUNCTION__)
//generated from body annotation
// Set the output parameter values for this execution.
std::shared_ptr<Bag<uml::Parameter>> parameters = this->getBehavior()->getOwnedParameter();
unsigned int i = 1;
unsigned int j = 1;
while(i <= parameters->size())
{
std::shared_ptr<uml::Parameter> parameter = parameters->at(i-1);
if((parameter->getDirection() == uml::ParameterDirectionKind::INOUT) || (parameter->getDirection() == uml::ParameterDirectionKind::OUT) || (parameter->getDirection() == uml::ParameterDirectionKind::RETURN))
{
std::shared_ptr<fUML::Semantics::CommonBehavior::ParameterValue> parameterValue = getParameterValues()->at(j-1);
parameterValue->setParameter(parameter);
this->setParameterValue(parameterValue);
j += 1;
}
i += 1;
}
//end of body
}
void CallEventExecutionImpl::suspendCaller()
{
//ADD_COUNT(__PRETTY_FUNCTION__)
//generated from body annotation
while(isCallerSuspended())
{
wait_();
}
//end of body
}
void CallEventExecutionImpl::wait_()
{
//ADD_COUNT(__PRETTY_FUNCTION__)
//generated from body annotation
// Wait for an indeterminate amount of time to allow other concurrent
// executions to proceed
// [There is no further formal specification for this operation.].
//end of body
}
//*********************************
// Attribute Getters & Setters
//*********************************
/* Getter & Setter for attribute callerSuspended */
bool CallEventExecutionImpl::getCallerSuspended() const
{
return m_callerSuspended;
}
void CallEventExecutionImpl::setCallerSuspended(bool _callerSuspended)
{
m_callerSuspended = _callerSuspended;
}
//*********************************
// Reference Getters & Setters
//*********************************
//*********************************
// Union Getter
//*********************************
//*********************************
// Container Getter
//*********************************
std::shared_ptr<ecore::EObject> CallEventExecutionImpl::eContainer() const
{
return nullptr;
}
//*********************************
// Persistence Functions
//*********************************
void CallEventExecutionImpl::load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler)
{
std::map<std::string, std::string> attr_list = loadHandler->getAttributeList();
loadAttributes(loadHandler, attr_list);
//
// Create new objects (from references (containment == true))
//
// get fUMLFactory
int numNodes = loadHandler->getNumOfChildNodes();
for(int ii = 0; ii < numNodes; ii++)
{
loadNode(loadHandler->getNextNodeName(), loadHandler);
}
}
void CallEventExecutionImpl::loadAttributes(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler, std::map<std::string, std::string> attr_list)
{
try
{
std::map<std::string, std::string>::const_iterator iter;
iter = attr_list.find("callerSuspended");
if ( iter != attr_list.end() )
{
// this attribute is a 'bool'
bool value;
std::istringstream(iter->second) >> std::boolalpha >> value;
this->setCallerSuspended(value);
}
}
catch (std::exception& e)
{
std::cout << "| ERROR | " << e.what() << std::endl;
}
catch (...)
{
std::cout << "| ERROR | " << "Exception occurred" << std::endl;
}
ExecutionImpl::loadAttributes(loadHandler, attr_list);
}
void CallEventExecutionImpl::loadNode(std::string nodeName, std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler)
{
//load BasePackage Nodes
ExecutionImpl::loadNode(nodeName, loadHandler);
}
void CallEventExecutionImpl::resolveReferences(const int featureID, std::vector<std::shared_ptr<ecore::EObject> > references)
{
ExecutionImpl::resolveReferences(featureID, references);
}
void CallEventExecutionImpl::save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const
{
saveContent(saveHandler);
ExecutionImpl::saveContent(saveHandler);
fUML::Semantics::StructuredClassifiers::ObjectImpl::saveContent(saveHandler);
fUML::Semantics::StructuredClassifiers::ExtensionalValueImpl::saveContent(saveHandler);
fUML::Semantics::SimpleClassifiers::CompoundValueImpl::saveContent(saveHandler);
fUML::Semantics::SimpleClassifiers::StructuredValueImpl::saveContent(saveHandler);
fUML::Semantics::Values::ValueImpl::saveContent(saveHandler);
fUML::Semantics::Loci::SemanticVisitorImpl::saveContent(saveHandler);
ecore::EObjectImpl::saveContent(saveHandler);
}
void CallEventExecutionImpl::saveContent(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const
{
try
{
std::shared_ptr<fUML::Semantics::CommonBehavior::CommonBehaviorPackage> package = fUML::Semantics::CommonBehavior::CommonBehaviorPackage::eInstance();
// Add attributes
if ( this->eIsSet(package->getCallEventExecution_Attribute_callerSuspended()) )
{
saveHandler->addAttribute("callerSuspended", this->getCallerSuspended());
}
}
catch (std::exception& e)
{
std::cout << "| ERROR | " << e.what() << std::endl;
}
}
std::shared_ptr<ecore::EClass> CallEventExecutionImpl::eStaticClass() const
{
return fUML::Semantics::CommonBehavior::CommonBehaviorPackage::eInstance()->getCallEventExecution_Class();
}
//*********************************
// EStructuralFeature Get/Set/IsSet
//*********************************
Any CallEventExecutionImpl::eGet(int featureID, bool resolve, bool coreType) const
{
switch(featureID)
{
case fUML::Semantics::CommonBehavior::CommonBehaviorPackage::CALLEVENTEXECUTION_ATTRIBUTE_CALLERSUSPENDED:
return eAny(getCallerSuspended(),ecore::ecorePackage::EBOOLEAN_CLASS,false); //177
}
return ExecutionImpl::eGet(featureID, resolve, coreType);
}
bool CallEventExecutionImpl::internalEIsSet(int featureID) const
{
switch(featureID)
{
case fUML::Semantics::CommonBehavior::CommonBehaviorPackage::CALLEVENTEXECUTION_ATTRIBUTE_CALLERSUSPENDED:
return getCallerSuspended() != false; //177
}
return ExecutionImpl::internalEIsSet(featureID);
}
bool CallEventExecutionImpl::eSet(int featureID, Any newValue)
{
switch(featureID)
{
case fUML::Semantics::CommonBehavior::CommonBehaviorPackage::CALLEVENTEXECUTION_ATTRIBUTE_CALLERSUSPENDED:
{
// CAST Any to bool
bool _callerSuspended = newValue->get<bool>();
setCallerSuspended(_callerSuspended); //177
return true;
}
}
return ExecutionImpl::eSet(featureID, newValue);
}
//*********************************
// EOperation Invoke
//*********************************
Any CallEventExecutionImpl::eInvoke(int operationID, std::shared_ptr<std::list<Any>> arguments)
{<|fim▁hole|> // fUML::Semantics::CommonBehavior::CallEventExecution::_copy() : fUML::Semantics::Values::Value: 3198945315
case CommonBehaviorPackage::CALLEVENTEXECUTION_OPERATION__COPY:
{
result = eAnyObject(this->_copy(), fUML::Semantics::Values::ValuesPackage::VALUE_CLASS);
break;
}
// fUML::Semantics::CommonBehavior::CallEventExecution::createEventOccurrence() : fUML::Semantics::CommonBehavior::EventOccurrence: 1959549943
case CommonBehaviorPackage::CALLEVENTEXECUTION_OPERATION_CREATEEVENTOCCURRENCE:
{
result = eAnyObject(this->createEventOccurrence(), fUML::Semantics::CommonBehavior::CommonBehaviorPackage::EVENTOCCURRENCE_CLASS);
break;
}
// fUML::Semantics::CommonBehavior::CallEventExecution::execute(): 1935201218
case CommonBehaviorPackage::CALLEVENTEXECUTION_OPERATION_EXECUTE:
{
this->execute();
break;
}
// fUML::Semantics::CommonBehavior::CallEventExecution::getInputParameterValues() : fUML::Semantics::CommonBehavior::ParameterValue[*]: 4255424542
case CommonBehaviorPackage::CALLEVENTEXECUTION_OPERATION_GETINPUTPARAMETERVALUES:
{
std::shared_ptr<Bag<fUML::Semantics::CommonBehavior::ParameterValue> > resultList = this->getInputParameterValues();
return eAnyBag(resultList,fUML::Semantics::CommonBehavior::CommonBehaviorPackage::PARAMETERVALUE_CLASS);
break;
}
// fUML::Semantics::CommonBehavior::CallEventExecution::getOperation() : uml::Operation: 375307381
case CommonBehaviorPackage::CALLEVENTEXECUTION_OPERATION_GETOPERATION:
{
result = eAnyObject(this->getOperation(), uml::umlPackage::OPERATION_CLASS);
break;
}
// fUML::Semantics::CommonBehavior::CallEventExecution::isCallerSuspended() : bool: 2898441339
case CommonBehaviorPackage::CALLEVENTEXECUTION_OPERATION_ISCALLERSUSPENDED:
{
result = eAny(this->isCallerSuspended(),0,false);
break;
}
// fUML::Semantics::CommonBehavior::CallEventExecution::makeCall(): 2619341921
case CommonBehaviorPackage::CALLEVENTEXECUTION_OPERATION_MAKECALL:
{
this->makeCall();
break;
}
// fUML::Semantics::CommonBehavior::CallEventExecution::new_() : fUML::Semantics::Values::Value: 557164094
case CommonBehaviorPackage::CALLEVENTEXECUTION_OPERATION_NEW_:
{
result = eAnyObject(this->new_(), fUML::Semantics::Values::ValuesPackage::VALUE_CLASS);
break;
}
// fUML::Semantics::CommonBehavior::CallEventExecution::releaseCaller(): 1070213359
case CommonBehaviorPackage::CALLEVENTEXECUTION_OPERATION_RELEASECALLER:
{
this->releaseCaller();
break;
}
// fUML::Semantics::CommonBehavior::CallEventExecution::setOutputParameterValues(fUML::Semantics::CommonBehavior::ParameterValue[*]): 2257574777
case CommonBehaviorPackage::CALLEVENTEXECUTION_OPERATION_SETOUTPUTPARAMETERVALUES_PARAMETERVALUE:
{
//Retrieve input parameter 'parameterValues'
//parameter 0
std::shared_ptr<Bag<fUML::Semantics::CommonBehavior::ParameterValue>> incoming_param_parameterValues;
std::list<Any>::const_iterator incoming_param_parameterValues_arguments_citer = std::next(arguments->begin(), 0);
incoming_param_parameterValues = (*incoming_param_parameterValues_arguments_citer)->get<std::shared_ptr<Bag<fUML::Semantics::CommonBehavior::ParameterValue>> >();
this->setOutputParameterValues(incoming_param_parameterValues);
break;
}
// fUML::Semantics::CommonBehavior::CallEventExecution::suspendCaller(): 349016100
case CommonBehaviorPackage::CALLEVENTEXECUTION_OPERATION_SUSPENDCALLER:
{
this->suspendCaller();
break;
}
// fUML::Semantics::CommonBehavior::CallEventExecution::wait_(): 3761191063
case CommonBehaviorPackage::CALLEVENTEXECUTION_OPERATION_WAIT_:
{
this->wait_();
break;
}
default:
{
// call superTypes
result = ExecutionImpl::eInvoke(operationID, arguments);
if (result && !result->isEmpty())
break;
break;
}
}
return result;
}
std::shared_ptr<fUML::Semantics::CommonBehavior::CallEventExecution> CallEventExecutionImpl::getThisCallEventExecutionPtr() const
{
return m_thisCallEventExecutionPtr.lock();
}
void CallEventExecutionImpl::setThisCallEventExecutionPtr(std::weak_ptr<fUML::Semantics::CommonBehavior::CallEventExecution> thisCallEventExecutionPtr)
{
m_thisCallEventExecutionPtr = thisCallEventExecutionPtr;
setThisExecutionPtr(thisCallEventExecutionPtr);
}<|fim▁end|>
|
Any result;
switch(operationID)
{
|
<|file_name|>intersection_two.rs<|end_file_name|><|fim▁begin|>use docset::DocSet;
use query::Scorer;
use DocId;
use Score;
use SkipResult;
/// Creates a `DocSet` that iterator through the intersection of two `DocSet`s.
pub struct IntersectionTwoTerms<TDocSet> {
left: TDocSet,
right: TDocSet
}
impl<TDocSet: DocSet> IntersectionTwoTerms<TDocSet> {
pub fn new(left: TDocSet, right: TDocSet) -> IntersectionTwoTerms<TDocSet> {
IntersectionTwoTerms {
left,
right
}
}
}
impl<TDocSet: DocSet> DocSet for IntersectionTwoTerms<TDocSet> {
fn advance(&mut self) -> bool {
let (left, right) = (&mut self.left, &mut self.right);
if !left.advance() {
return false;
}
let mut candidate = left.doc();
loop {
match right.skip_next(candidate) {
SkipResult::Reached => {
return true;
}
SkipResult::End => {
return false;
}
SkipResult::OverStep => {
candidate = right.doc();
}
}
match left.skip_next(candidate) {
SkipResult::Reached => {
return true;
}
SkipResult::End => {
return false;
}
SkipResult::OverStep => {
candidate = left.doc();
}
}
}
}
fn doc(&self) -> DocId {<|fim▁hole|> self.left.doc()
}
fn size_hint(&self) -> u32 {
self.left.size_hint().min(self.right.size_hint())
}
}
impl<TScorer: Scorer> Scorer for IntersectionTwoTerms<TScorer> {
fn score(&mut self) -> Score {
self.left.score() + self.right.score()
}
}<|fim▁end|>
| |
<|file_name|>20.rs<|end_file_name|><|fim▁begin|>/* Problem 20: Factorial digit sum<|fim▁hole|> *
* For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
* and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
*
* Find the sum of the digits in the number 100! */
use num::bigint::{BigUint, ToBigUint};
use num::One;
fn main() {
let strnum = factorial(100).to_string();
let result = strnum.chars().fold(0, |digit, sum| digit + to_i(sum));
println!("{}", result);
}
fn factorial(n: u32) -> BigUint {
let mut result: BigUint = One::one();
let mut remaining: u32 = n;
while remaining > 0 {
result = result * remaining.to_biguint().unwrap();
remaining -= 1;
}
result
}
fn to_i(chr: char) -> u32 {
chr.to_digit(10).unwrap()
}<|fim▁end|>
|
*
* n! means n × (n − 1) × ... × 3 × 2 × 1
|
<|file_name|>ModelManager.java<|end_file_name|><|fim▁begin|>/*
* ModelManager.java
*
* DMXControl for Android
*
* Copyright (c) 2012 DMXControl-For-Android. All rights reserved.
*
* This software is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either
* version 3, june 2007 of the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License (gpl.txt) along with this software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
* For further information, please contact info [(at)] dmxcontrol.de
*
*
*/
package de.dmxcontrol.model;
import android.util.Log;
import java.util.HashMap;
import java.util.Map;
import de.dmxcontrol.device.EntitySelection;
import de.dmxcontrol.model.BaseModel.OnModelListener;
public class ModelManager {
private final static String TAG = "modelmanager";
public enum Type {
Color,
Gobo,
Position,
Dimmer,
Strobe,
Shutter,
Zoom,
Focus,
Iris,
Frost,
Effect
}
private Map<Type, BaseModel> mModels = new HashMap<Type, BaseModel>();
private static Map<Type, Class<? extends BaseModel>> mTypeLookup = new HashMap<Type, Class<? extends BaseModel>>();
private Map<OnModelListener, Boolean> mDefaultModelListeners = new HashMap<OnModelListener, Boolean>();
private EntitySelection mEntitySelection;
public ModelManager(EntitySelection es) {
addDefaultModelListener(es);
mEntitySelection = es;
}
public EntitySelection getEntitySelection() {
return mEntitySelection;
}
public void addDefaultModelListener(OnModelListener listener) {
mDefaultModelListeners.put(listener, true);
}
@SuppressWarnings("unchecked")
public <T extends BaseModel> T getModel(Type type) {
if(mModels.containsKey(type)) {
return (T) mModels.get(type);
}
else {
T model;
model = create(type);
mModels.put(type, (BaseModel) model);
return model;
}
}
@SuppressWarnings("unchecked")
private <T extends BaseModel> T create(Type type) {
Class<? extends BaseModel> clazz = mTypeLookup.get(type);
T model;<|fim▁hole|> model = (T) clazz.getDeclaredConstructors()[0].newInstance(this);
}
catch(Exception e) {
Log.e(TAG, "error creation of model with class " + clazz.getName());
Log.e(TAG, "exception: ", e);
return null;
}
model.addDefaultListener(mDefaultModelListeners);
return model;
}
static {
mTypeLookup.put(Type.Color, ColorModel.class);
mTypeLookup.put(Type.Gobo, GoboModel.class);
mTypeLookup.put(Type.Position, PositionModel.class);
mTypeLookup.put(Type.Dimmer, DimmerModel.class);
mTypeLookup.put(Type.Strobe, StrobeModel.class);
mTypeLookup.put(Type.Shutter, ShutterModel.class);
mTypeLookup.put(Type.Zoom, ZoomModel.class);
mTypeLookup.put(Type.Focus, FocusModel.class);
mTypeLookup.put(Type.Iris, IrisModel.class);
mTypeLookup.put(Type.Frost, FrostModel.class);
mTypeLookup.put(Type.Effect, EffectModel.class);
}
}<|fim▁end|>
|
try {
|
<|file_name|>simpleWorker.nls.zh-cn.js<|end_file_name|><|fim▁begin|>/*!-----------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Version: 0.5.3(793ede49d53dba79d39e52205f16321278f5183c)
* Released under the MIT license
* https://github.com/Microsoft/vscode/blob/master/LICENSE.txt
*-----------------------------------------------------------*/
define("vs/base/common/worker/simpleWorker.nls.zh-cn", {
"vs/base/common/errors": [
"{0}。错误代码: {1}",
"权限被拒绝 (HTTP {0})",
"权限被拒绝",
"{0} (HTTP {1}: {2})",
"{0} (HTTP {1})",
"未知连接错误 ({0})",
"出现未知连接错误。您的 Internet 连接已断开,或者您连接的服务器已脱机。",
"{0}: {1}",
"出现未知错误。有关详细信息,请参阅日志。",
"发生了系统错误({0})",
"出现未知错误。有关详细信息,请参阅日志。",
"{0} 个(共 {1} 个错误)",
"出现未知错误。有关详细信息,请参阅日志。",
"未实施",
"非法参数: {0}",
"非法参数",
"非法状态: {0}",
"非法状态",
"无法加载需要的文件。您的 Internet 连接已断开,或者您连接的服务器已脱机。请刷新浏览器并重试。",
"未能加载所需文件。请重启应用程序重试。详细信息: {0}",
],
"vs/base/common/keyCodes": [<|fim▁hole|> "Shift",
"Alt",
"命令",
"Windows",
"Ctrl",
"Shift",
"Alt",
"命令",
"Windows",
],
"vs/base/common/severity": [
"错误",
"警告",
"信息",
]
});<|fim▁end|>
|
"Windows",
"控件",
|
<|file_name|>accessorsEmit.ts<|end_file_name|><|fim▁begin|>class Result { }
class Test {
get Property(): Result {
var x = 1;
return null;
}
<|fim▁hole|>
class Test2 {
get Property() {
var x = 1;
return null;
}
}<|fim▁end|>
|
}
|
<|file_name|>search.py<|end_file_name|><|fim▁begin|>import json
import logging
import socket
from contextlib import closing
from django.core.exceptions import ValidationError
from django.db import connection
from zeroconf import get_all_addresses
from zeroconf import NonUniqueNameException
from zeroconf import ServiceInfo
from zeroconf import USE_IP_OF_OUTGOING_INTERFACE
from zeroconf import Zeroconf
from kolibri.core.discovery.models import DynamicNetworkLocation
from kolibri.core.public.utils import get_device_info
logger = logging.getLogger(__name__)
SERVICE_TYPE = "Kolibri._sub._http._tcp.local."
LOCAL_DOMAIN = "kolibri.local"
ZEROCONF_STATE = {"zeroconf": None, "listener": None, "service": None}
def _id_from_name(name):
assert name.endswith(SERVICE_TYPE), (
"Invalid service name; must end with '%s'" % SERVICE_TYPE
)
return name.replace(SERVICE_TYPE, "").strip(".")
def _is_port_open(host, port, timeout=1):
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
sock.settimeout(timeout)
return sock.connect_ex((host, port)) == 0
class KolibriZeroconfService(object):
info = None
def __init__(self, id, port=8080, data={}):
self.id = id
self.port = port
self.data = {key: json.dumps(val) for (key, val) in data.items()}
def register(self):
if not ZEROCONF_STATE["zeroconf"]:
initialize_zeroconf_listener()
if self.info is not None:
logger.error("Service is already registered!")
return
i = 1
id = self.id
while not self.info:
# attempt to create an mDNS service and register it on the network
try:
info = ServiceInfo(
SERVICE_TYPE,
name=".".join([id, SERVICE_TYPE]),
server=".".join([id, LOCAL_DOMAIN, ""]),
address=USE_IP_OF_OUTGOING_INTERFACE,
port=self.port,
properties=self.data,
)
ZEROCONF_STATE["zeroconf"].register_service(info, ttl=60)
self.info = info
except NonUniqueNameException:
# if there's a name conflict, append incrementing integer until no conflict
i += 1
id = "%s-%d" % (self.id, i)
if i > 100:
raise NonUniqueNameException()
self.id = id
return self
def unregister(self):
if self.info is None:
logging.error("Service is not registered!")
return
ZEROCONF_STATE["zeroconf"].unregister_service(self.info)
self.info = None
def cleanup(self, *args, **kwargs):
if self.info and ZEROCONF_STATE["zeroconf"]:
self.unregister()
class KolibriZeroconfListener(object):
instances = {}
def add_service(self, zeroconf, type, name):
timeout = 5000
info = zeroconf.get_service_info(type, name, timeout=timeout)
if info is None:
logger.warn(
"Zeroconf network service information could not be retrieved within {} seconds".format(
str(timeout / 1000.0)
)
)
return
id = _id_from_name(name)
ip = socket.inet_ntoa(info.address)
base_url = "http://{ip}:{port}/".format(ip=ip, port=info.port)
zeroconf_service = ZEROCONF_STATE.get("service")
is_self = zeroconf_service and zeroconf_service.id == id
instance = {<|fim▁hole|> "port": info.port,
"host": info.server.strip("."),
"base_url": base_url,
"self": is_self,
}
device_info = {
bytes.decode(key): json.loads(val) for (key, val) in info.properties.items()
}
instance.update(device_info)
self.instances[id] = instance
if not is_self:
try:
DynamicNetworkLocation.objects.update_or_create(
dict(base_url=base_url, **device_info), id=id
)
logger.info(
"Kolibri instance '%s' joined zeroconf network; service info: %s"
% (id, self.instances[id])
)
except ValidationError:
import traceback
logger.warn(
"""
A new Kolibri instance '%s' was seen on the zeroconf network,
but we had trouble getting the information we needed about it.
Service info:
%s
The following exception was raised:
%s
"""
% (id, self.instances[id], traceback.format_exc(limit=1))
)
finally:
connection.close()
def remove_service(self, zeroconf, type, name):
id = _id_from_name(name)
logger.info("Kolibri instance '%s' has left the zeroconf network." % (id,))
try:
if id in self.instances:
del self.instances[id]
except KeyError:
pass
DynamicNetworkLocation.objects.filter(pk=id).delete()
connection.close()
def register_zeroconf_service(port):
device_info = get_device_info()
DynamicNetworkLocation.objects.all().delete()
connection.close()
id = device_info.get("instance_id")
if ZEROCONF_STATE["service"] is not None:
unregister_zeroconf_service()
logger.info("Registering ourselves to zeroconf network with id '%s'..." % id)
data = device_info
ZEROCONF_STATE["service"] = KolibriZeroconfService(id=id, port=port, data=data)
ZEROCONF_STATE["service"].register()
def unregister_zeroconf_service():
if ZEROCONF_STATE["service"] is not None:
ZEROCONF_STATE["service"].cleanup()
ZEROCONF_STATE["service"] = None
if ZEROCONF_STATE["zeroconf"] is not None:
ZEROCONF_STATE["zeroconf"].close()
def initialize_zeroconf_listener():
ZEROCONF_STATE["zeroconf"] = Zeroconf()
ZEROCONF_STATE["listener"] = KolibriZeroconfListener()
ZEROCONF_STATE["zeroconf"].add_service_listener(
SERVICE_TYPE, ZEROCONF_STATE["listener"]
)
def get_peer_instances():
try:
return ZEROCONF_STATE["listener"].instances.values()
except AttributeError:
return []<|fim▁end|>
|
"id": id,
"ip": ip,
"local": ip in get_all_addresses(),
|
<|file_name|>slots.rs<|end_file_name|><|fim▁begin|>// Copyright (c) 2016 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
use libc::{c_char, c_int};
use std::ffi::CString;
use std::{isize, mem, ptr};
use crate::conversion::ToPyObject;
use crate::err::{PyErr, PyResult};
use crate::exc;
use crate::ffi;
use crate::function::CallbackConverter;
use crate::objects::PyObject;
use crate::py_class::CompareOp;
use crate::python::{Python, PythonObject};
use crate::Py_hash_t;
#[macro_export]
#[doc(hidden)]
macro_rules! py_class_type_object_static_init {
($class_name:ident,
$gc:tt,
/* slots: */ {
/* type_slots */ [ $( $slot_name:ident : $slot_value:expr, )* ]
$as_number:tt
$as_sequence:tt
$as_mapping:tt
$setdelitem:tt
}) => (
$crate::_detail::ffi::PyTypeObject {
$( $slot_name : $slot_value, )*
tp_dealloc: Some($crate::py_class::slots::tp_dealloc_callback::<$class_name>),
tp_flags: $crate::py_class_type_object_flags!($gc),
tp_traverse: $crate::py_class_tp_traverse!($class_name, $gc),
..
$crate::_detail::ffi::PyTypeObject_INIT
}
);
}
#[macro_export]
#[doc(hidden)]
macro_rules! py_class_type_object_flags {
(/* gc: */ {
/* traverse_proc: */ None,
/* traverse_data: */ [ /*name*/ ]
}) => {
$crate::py_class::slots::TPFLAGS_DEFAULT
};
(/* gc: */ {
$traverse_proc: expr,
$traverse_data: tt
}) => {
$crate::py_class::slots::TPFLAGS_DEFAULT | $crate::_detail::ffi::Py_TPFLAGS_HAVE_GC
};
}
#[cfg(feature = "python27-sys")]
pub const TPFLAGS_DEFAULT: ::libc::c_long = ffi::Py_TPFLAGS_DEFAULT | ffi::Py_TPFLAGS_CHECKTYPES;
#[cfg(feature = "python3-sys")]
pub const TPFLAGS_DEFAULT: ::libc::c_ulong = ffi::Py_TPFLAGS_DEFAULT;
#[macro_export]
#[doc(hidden)]
macro_rules! py_class_type_object_dynamic_init {
// initialize those fields of PyTypeObject that we couldn't initialize statically
($class: ident, $py:ident, $type_object:ident, $module_name: ident,
/* slots: */ {
$type_slots:tt
$as_number:tt
$as_sequence:tt
$as_mapping:tt
$setdelitem:tt
}
$props:tt
) => {
unsafe {
$type_object.init_ob_type(&mut $crate::_detail::ffi::PyType_Type);
$type_object.tp_name =
$crate::py_class::slots::build_tp_name($module_name, stringify!($class));
$type_object.tp_basicsize = <$class as $crate::py_class::BaseObject>::size()
as $crate::_detail::ffi::Py_ssize_t;
}
// call slot macros outside of unsafe block
*(unsafe { &mut $type_object.tp_as_sequence }) =
$crate::py_class_as_sequence!($as_sequence);
*(unsafe { &mut $type_object.tp_as_number }) = $crate::py_class_as_number!($as_number);
$crate::py_class_as_mapping!($type_object, $as_mapping, $setdelitem);
*(unsafe { &mut $type_object.tp_getset }) = $crate::py_class_tp_getset!($class, $props);
};
}
pub fn build_tp_name(module_name: Option<&str>, type_name: &str) -> *mut c_char {
let name = match module_name {
Some(module_name) => CString::new(format!("{}.{}", module_name, type_name)),
None => CString::new(type_name),
};
name.expect("Module name/type name must not contain NUL byte")
.into_raw()
}
pub unsafe extern "C" fn tp_dealloc_callback<T>(obj: *mut ffi::PyObject)
where
T: super::BaseObject,
{
let guard = crate::function::AbortOnDrop("Cannot unwind out of tp_dealloc");
let py = Python::assume_gil_acquired();
let r = T::dealloc(py, obj);
mem::forget(guard);
r
}
#[macro_export]
#[doc(hidden)]
macro_rules! py_class_wrap_newfunc {
($class:ident :: $f:ident [ $( { $pname:ident : $ptype:ty = $detail:tt } )* ]) => {{
unsafe extern "C" fn wrap_newfunc(
cls: *mut $crate::_detail::ffi::PyTypeObject,
args: *mut $crate::_detail::ffi::PyObject,
kwargs: *mut $crate::_detail::ffi::PyObject)
-> *mut $crate::_detail::ffi::PyObject
{
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::_detail::handle_callback(
LOCATION, $crate::_detail::PyObjectCallbackConverter,
|py| {
$crate::py_argparse_raw!(py, Some(LOCATION), args, kwargs,
[ $( { $pname : $ptype = $detail } )* ]
{
let cls = $crate::PyType::from_type_ptr(py, cls);
let ret = $class::$f(&cls, py $(, $pname )* );
$crate::PyDrop::release_ref(cls, py);
ret
})
})
}
Some(wrap_newfunc)
}}
}
#[macro_export]
#[doc(hidden)]
macro_rules! py_class_as_sequence {
([]) => (0 as *mut $crate::_detail::ffi::PySequenceMethods);
([$( $slot_name:ident : $slot_value:expr ,)+]) => {{
static mut SEQUENCE_METHODS : $crate::_detail::ffi::PySequenceMethods
= $crate::_detail::ffi::PySequenceMethods {
$( $slot_name : $slot_value, )*
..
$crate::_detail::ffi::PySequenceMethods_INIT
};
unsafe { &mut SEQUENCE_METHODS }
}}
}
#[macro_export]
#[doc(hidden)]
macro_rules! py_class_as_number {
([]) => (0 as *mut $crate::_detail::ffi::PyNumberMethods);
([$( $slot_name:ident : $slot_value:expr ,)+]) => {{
static mut NUMBER_METHODS : $crate::_detail::ffi::PyNumberMethods
= $crate::_detail::ffi::PyNumberMethods {
$( $slot_name : $slot_value, )*
..
$crate::_detail::ffi::PyNumberMethods_INIT
};
unsafe { &mut NUMBER_METHODS }
}}
}
#[macro_export]
#[doc(hidden)]
macro_rules! py_class_as_mapping {
( $type_object:ident, [], [
sdi_setitem: {},
sdi_delitem: {},
]) => {};
( $type_object:ident, [ $( $slot_name:ident : $slot_value:expr ,)+ ], [
sdi_setitem: {},
sdi_delitem: {},
]) => {
static mut MAPPING_METHODS : $crate::_detail::ffi::PyMappingMethods
= $crate::_detail::ffi::PyMappingMethods {
$( $slot_name : $slot_value, )*
..
$crate::_detail::ffi::PyMappingMethods_INIT
};
unsafe { $type_object.tp_as_mapping = &mut MAPPING_METHODS; }
};
( $type_object:ident, [ $( $slot_name:ident : $slot_value:expr ,)* ], [
sdi_setitem: $setitem:tt,
sdi_delitem: $delitem:tt,
]) => {{
unsafe extern "C" fn mp_ass_subscript(
slf: *mut $crate::_detail::ffi::PyObject,
key: *mut $crate::_detail::ffi::PyObject,
val: *mut $crate::_detail::ffi::PyObject
) -> $crate::_detail::libc::c_int {
if val.is_null() {
$crate::py_class_mp_ass_subscript!($delitem, slf,
b"Subscript assignment not supported by %.200s\0",
key)
} else {
$crate::py_class_mp_ass_subscript!($setitem, slf,
b"Subscript deletion not supported by %.200s\0",
key, val)
}
}
static mut MAPPING_METHODS : $crate::_detail::ffi::PyMappingMethods
= $crate::_detail::ffi::PyMappingMethods {
$( $slot_name : $slot_value, )*
mp_ass_subscript: Some(mp_ass_subscript),
..
$crate::_detail::ffi::PyMappingMethods_INIT
};
unsafe { $type_object.tp_as_mapping = &mut MAPPING_METHODS; }
}};
}
#[macro_export]
#[doc(hidden)]
macro_rules! py_class_mp_ass_subscript {
({}, $slf:ident, $error:expr, $( $arg:expr ),+) => {
$crate::py_class::slots::mp_ass_subscript_error($slf, $error)
};
({$slot:expr}, $slf:ident, $error:expr, $( $arg:expr ),+) => {
$slot.unwrap()($slf, $( $arg ),+)
}
}
pub unsafe fn mp_ass_subscript_error(o: *mut ffi::PyObject, err: &[u8]) -> c_int {
ffi::PyErr_Format(
ffi::PyExc_NotImplementedError,
err.as_ptr() as *const c_char,
(*ffi::Py_TYPE(o)).tp_name,
);
-1
}
#[macro_export]
#[doc(hidden)]
macro_rules! py_class_call_slot_impl_with_ref {
(
$py:ident,
$slf:ident,
$f:ident,
$arg:ident: [ Option<&$arg_type:ty> ],
$arg_normal:expr,
$arg_if_none:expr,
$arg_if_some:expr
$(, $extra_arg:ident)*
) => {{
if $arg.is_none($py) {
Ok($slf.$f($py, $arg_if_none $(, $extra_arg)*))
} else {
<$arg_type as $crate::RefFromPyObject>::with_extracted(
$py,
&$arg,
|$arg: &$arg_type| $slf.$f($py, $arg_if_some $(, $extra_arg)*)
)
}
}};
(
$py:ident,
$slf:ident,
$f:ident,
$arg:ident: [ &$arg_type:ty ],
$arg_normal:expr,
$arg_if_none:expr,
$arg_if_some:expr
$(, $extra_arg:ident)*
) => {{
<$arg_type as $crate::RefFromPyObject>::with_extracted(
$py,
&$arg,
|$arg: &$arg_type| $slf.$f($py, $arg_normal $(, $extra_arg)*)
)
}};
(
$py:ident,
$slf:ident,
$f:ident,
$arg:ident: [ $arg_type:ty ],
$arg_normal:expr,
$arg_if_none:expr,
$arg_if_some:expr
$(, $extra_arg:ident)*
) => {{
<$arg_type as $crate::FromPyObject>::extract($py, &$arg)
.map(|$arg| $slf.$f($py, $arg_normal $(, $extra_arg)*))
}};
}
#[macro_export]
#[doc(hidden)]
macro_rules! py_class_unary_slot {
($class:ident :: $f:ident, $res_type:ty, $conv:expr) => {{
unsafe extern "C" fn wrap_unary(slf: *mut $crate::_detail::ffi::PyObject) -> $res_type {
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::_detail::handle_callback(LOCATION, $conv, |py| {
let slf =
$crate::PyObject::from_borrowed_ptr(py, slf).unchecked_cast_into::<$class>();
let ret = slf.$f(py);
$crate::PyDrop::release_ref(slf, py);
ret
})
}
Some(wrap_unary)
}};
}
#[macro_export]
#[doc(hidden)]
macro_rules! py_class_binary_slot {
($class:ident :: $f:ident, $arg_type:tt, $res_type:ty, $conv:expr) => {{
unsafe extern "C" fn wrap_binary(
slf: *mut $crate::_detail::ffi::PyObject,
arg: *mut $crate::_detail::ffi::PyObject,
) -> $res_type {
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::_detail::handle_callback(LOCATION, $conv, |py| {
let slf =
$crate::PyObject::from_borrowed_ptr(py, slf).unchecked_cast_into::<$class>();
let arg = $crate::PyObject::from_borrowed_ptr(py, arg);
let ret = match $crate::py_class_call_slot_impl_with_ref!(
py,
slf,
$f,
arg: $arg_type,
arg,
None,
Some(arg)
) {
Ok(r) => r,
Err(e) => Err(e),
};
$crate::PyDrop::release_ref(arg, py);
$crate::PyDrop::release_ref(slf, py);
ret
})
}
Some(wrap_binary)
}};
}
#[macro_export]
#[doc(hidden)]
macro_rules! py_class_ternary_slot {
($class:ident :: $f:ident, $arg1_type:tt, $arg2_type:ty, $res_type:ty, $conv:expr) => {{
unsafe extern "C" fn wrap_binary(
slf: *mut $crate::_detail::ffi::PyObject,
arg1: *mut $crate::_detail::ffi::PyObject,
arg2: *mut $crate::_detail::ffi::PyObject,
) -> $res_type {
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::_detail::handle_callback(LOCATION, $conv, |py| {
let slf =
$crate::PyObject::from_borrowed_ptr(py, slf).unchecked_cast_into::<$class>();
let arg1 = $crate::PyObject::from_borrowed_ptr(py, arg1);
let arg2 = $crate::PyObject::from_borrowed_ptr(py, arg2);
let ret = match <$arg2_type as $crate::FromPyObject>::extract(py, &arg2) {
Ok(arg2) => {
match $crate::py_class_call_slot_impl_with_ref!(
py,
slf,
$f,
arg1: $arg1_type,
arg1,
None,
Some(arg1),
arg2
) {
Ok(r) => r,
Err(e) => Err(e),
}
}
Err(e) => Err(e),
};
$crate::PyDrop::release_ref(arg1, py);
$crate::PyDrop::release_ref(arg2, py);
$crate::PyDrop::release_ref(slf, py);
ret
})
}
Some(wrap_binary)
}};
}
pub fn extract_op(py: Python, op: c_int) -> PyResult<CompareOp> {
match op {
ffi::Py_LT => Ok(CompareOp::Lt),
ffi::Py_LE => Ok(CompareOp::Le),
ffi::Py_EQ => Ok(CompareOp::Eq),
ffi::Py_NE => Ok(CompareOp::Ne),
ffi::Py_GT => Ok(CompareOp::Gt),
ffi::Py_GE => Ok(CompareOp::Ge),
_ => Err(PyErr::new_lazy_init(
py.get_type::<exc::ValueError>(),
Some(
"tp_richcompare called with invalid comparison operator"
.to_py_object(py)
.into_object(),
),
)),
}
}
// sq_richcompare is special-cased slot
#[macro_export]
#[doc(hidden)]
macro_rules! py_class_richcompare_slot {
($class:ident :: $f:ident, $arg_type:tt, $res_type:ty, $conv:expr) => {{
unsafe extern "C" fn tp_richcompare(
slf: *mut $crate::_detail::ffi::PyObject,
arg: *mut $crate::_detail::ffi::PyObject,
op: $crate::_detail::libc::c_int,
) -> $res_type {
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::_detail::handle_callback(LOCATION, $conv, |py| {
let slf =
$crate::PyObject::from_borrowed_ptr(py, slf).unchecked_cast_into::<$class>();
let arg = $crate::PyObject::from_borrowed_ptr(py, arg);
let ret = match $crate::py_class::slots::extract_op(py, op) {
Ok(op) => {
match $crate::py_class_call_slot_impl_with_ref!(
py,
slf,
$f,
arg: $arg_type,
arg,
None,
Some(arg),
op
) {
Ok(r) => r.map(|r| r.into_py_object(py).into_object()),
Err(e) => Ok(py.NotImplemented()),
}
}
Err(_) => Ok(py.NotImplemented()),
};
$crate::PyDrop::release_ref(arg, py);
$crate::PyDrop::release_ref(slf, py);
ret
})
}
Some(tp_richcompare)
}};
}
// sq_contains is special-cased slot because it converts type errors to Ok(false)
#[macro_export]
#[doc(hidden)]
macro_rules! py_class_contains_slot {
($class:ident :: $f:ident, $arg_type:tt) => {{
unsafe extern "C" fn sq_contains(
slf: *mut $crate::_detail::ffi::PyObject,
arg: *mut $crate::_detail::ffi::PyObject,
) -> $crate::_detail::libc::c_int {
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::_detail::handle_callback(
LOCATION,
$crate::py_class::slots::BoolConverter,
|py| {
let slf = $crate::PyObject::from_borrowed_ptr(py, slf)
.unchecked_cast_into::<$class>();
let arg = $crate::PyObject::from_borrowed_ptr(py, arg);
let ret = match $crate::py_class_call_slot_impl_with_ref!(
py,
slf,
$f,
arg: $arg_type,
arg,
None,
Some(arg)
) {
Ok(r) => r,
Err(e) => $crate::py_class::slots::type_error_to_false(py, e),
};
$crate::PyDrop::release_ref(arg, py);
$crate::PyDrop::release_ref(slf, py);
ret
},
)
}
Some(sq_contains)
}};
}
pub fn type_error_to_false(py: Python, e: PyErr) -> PyResult<bool> {
if e.matches(py, py.get_type::<exc::TypeError>()) {
Ok(false)
} else {
Err(e)
}
}
#[macro_export]
#[doc(hidden)]
macro_rules! py_class_numeric_slot {
(binary $class:ident :: $f:ident) => {{
unsafe extern "C" fn binary_numeric(
lhs: *mut $crate::_detail::ffi::PyObject,
rhs: *mut $crate::_detail::ffi::PyObject,
) -> *mut $crate::_detail::ffi::PyObject {
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::_detail::handle_callback(
LOCATION,
$crate::_detail::PyObjectCallbackConverter,
|py| {
let lhs = $crate::PyObject::from_borrowed_ptr(py, lhs);
let rhs = $crate::PyObject::from_borrowed_ptr(py, rhs);
let ret = $class::$f(py, &lhs, &rhs);
$crate::PyDrop::release_ref(rhs, py);
$crate::PyDrop::release_ref(lhs, py);
ret
},
)
}
Some(binary_numeric)
}};
(ternary $class:ident :: $f:ident) => {{
unsafe extern "C" fn ternary_numeric(
lhs: *mut $crate::_detail::ffi::PyObject,
rhs: *mut $crate::_detail::ffi::PyObject,
ex: *mut $crate::_detail::ffi::PyObject,
) -> *mut $crate::_detail::ffi::PyObject {
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::_detail::handle_callback(
LOCATION,
$crate::_detail::PyObjectCallbackConverter,
|py| {
let lhs = $crate::PyObject::from_borrowed_ptr(py, lhs);
let rhs = $crate::PyObject::from_borrowed_ptr(py, rhs);
let ex = $crate::PyObject::from_borrowed_ptr(py, ex);
let ret = $class::$f(py, &lhs, &rhs, &ex);
$crate::PyDrop::release_ref(ex, py);
$crate::PyDrop::release_ref(rhs, py);
$crate::PyDrop::release_ref(lhs, py);
ret
},
)
}
Some(ternary_numeric)
}};
}
pub struct UnitCallbackConverter;
impl CallbackConverter<()> for UnitCallbackConverter {
type R = c_int;
#[inline]
fn convert(_: (), _: Python) -> c_int {
0
}
#[inline]
fn error_value() -> c_int {
-1
}
}
pub struct LenResultConverter;
impl CallbackConverter<usize> for LenResultConverter {
type R = isize;
fn convert(val: usize, py: Python) -> isize {
if val <= (isize::MAX as usize) {
val as isize
} else {
PyErr::new_lazy_init(py.get_type::<exc::OverflowError>(), None).restore(py);
-1
}
}
#[inline]
fn error_value() -> isize {
-1
}
}
pub struct IterNextResultConverter;
impl<T> CallbackConverter<Option<T>> for IterNextResultConverter
where
T: ToPyObject,
{
type R = *mut ffi::PyObject;
fn convert(val: Option<T>, py: Python) -> *mut ffi::PyObject {
match val {
Some(val) => val.into_py_object(py).into_object().steal_ptr(),
None => unsafe {
ffi::PyErr_SetNone(ffi::PyExc_StopIteration);
ptr::null_mut()
},
}
}
#[inline]
fn error_value() -> *mut ffi::PyObject {
ptr::null_mut()
}
}
pub trait WrappingCastTo<T> {
fn wrapping_cast(self) -> T;
}
macro_rules! wrapping_cast {
($from:ty, $to:ty) => {
impl WrappingCastTo<$to> for $from {
#[inline]
fn wrapping_cast(self) -> $to {
self as $to
}
}
};
}
wrapping_cast!(u8, Py_hash_t);
wrapping_cast!(u16, Py_hash_t);
wrapping_cast!(u32, Py_hash_t);
wrapping_cast!(usize, Py_hash_t);
wrapping_cast!(u64, Py_hash_t);
wrapping_cast!(i8, Py_hash_t);
wrapping_cast!(i16, Py_hash_t);
wrapping_cast!(i32, Py_hash_t);
wrapping_cast!(isize, Py_hash_t);
wrapping_cast!(i64, Py_hash_t);
pub struct HashConverter;
impl<T> CallbackConverter<T> for HashConverter
where
T: WrappingCastTo<Py_hash_t>,
{
type R = Py_hash_t;
#[inline]
fn convert(val: T, _py: Python) -> Py_hash_t {
let hash = val.wrapping_cast();
if hash == -1 {
-2
} else {
hash
}
}
#[inline]
fn error_value() -> Py_hash_t {
-1
}
}
pub struct BoolConverter;
impl CallbackConverter<bool> for BoolConverter {
type R = c_int;
#[inline]
fn convert(val: bool, _py: Python) -> c_int {
val as c_int<|fim▁hole|> #[inline]
fn error_value() -> c_int {
-1
}
}
#[macro_export]
#[doc(hidden)]
macro_rules! py_class_call_slot {
($class:ident :: $f:ident [ $( { $pname:ident : $ptype:ty = $detail:tt } )* ]) => {{
unsafe extern "C" fn wrap_call(
slf: *mut $crate::_detail::ffi::PyObject,
args: *mut $crate::_detail::ffi::PyObject,
kwargs: *mut $crate::_detail::ffi::PyObject)
-> *mut $crate::_detail::ffi::PyObject
{
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::_detail::handle_callback(
LOCATION, $crate::_detail::PyObjectCallbackConverter,
|py| {
$crate::py_argparse_raw!(py, Some(LOCATION), args, kwargs,
[ $( { $pname : $ptype = $detail } )* ]
{
let slf = $crate::PyObject::from_borrowed_ptr(py, slf).unchecked_cast_into::<$class>();
let ret = slf.$f(py $(, $pname )* );
$crate::PyDrop::release_ref(slf, py);
ret
})
})
}
Some(wrap_call)
}}
}
/// Used as implementation in the `sq_item` slot to forward calls to the `mp_subscript` slot.
pub unsafe extern "C" fn sq_item(
obj: *mut ffi::PyObject,
index: ffi::Py_ssize_t,
) -> *mut ffi::PyObject {
let arg = ffi::PyLong_FromSsize_t(index);
if arg.is_null() {
return arg;
}
let ret = ffi::PyObject_GetItem(obj, arg);
ffi::Py_DECREF(arg);
ret
}
#[macro_export]
#[doc(hidden)]
macro_rules! py_class_prop_getter {
($class:ident :: $f:ident) => {{
unsafe extern "C" fn wrap_getter(
slf: *mut $crate::_detail::ffi::PyObject,
_closure: *mut $crate::_detail::libc::c_void,
) -> *mut $crate::_detail::ffi::PyObject {
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "{}");
$crate::_detail::handle_callback(
LOCATION,
$crate::_detail::PyObjectCallbackConverter,
|py| {
let slf = $crate::PyObject::from_borrowed_ptr(py, slf)
.unchecked_cast_into::<$class>();
let ret = slf.$f(py);
$crate::PyDrop::release_ref(slf, py);
ret
},
)
}
Some(wrap_getter)
}};
}
#[macro_export]
#[doc(hidden)]
macro_rules! py_class_prop_setter {
($class:ident :: $f:ident, $value_type:tt) => {{
unsafe extern "C" fn wrap_setter(
slf: *mut $crate::_detail::ffi::PyObject,
obj: *mut $crate::_detail::ffi::PyObject,
_closure: *mut $crate::_detail::libc::c_void,
) -> $crate::_detail::libc::c_int {
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "{}");
$crate::_detail::handle_callback(
LOCATION,
$crate::py_class::slots::UnitCallbackConverter,
|py| {
let slf = $crate::PyObject::from_borrowed_ptr(py, slf)
.unchecked_cast_into::<$class>();
let ret = if obj.is_null() {
slf.$f(py, None)
} else {
let obj = $crate::PyObject::from_borrowed_ptr(py, obj);
let ret = match $crate::py_class_call_slot_impl_with_ref!(
py,
slf,
$f,
obj: $value_type,
Some(obj),
Some(None),
Some(Some(obj))
) {
Ok(r) => r,
Err(e) => Err(e),
};
$crate::PyDrop::release_ref(obj, py);
ret
};
$crate::PyDrop::release_ref(slf, py);
ret
},
)
}
Some(wrap_setter)
}};
}
#[macro_export]
#[doc(hidden)]
macro_rules! py_class_tp_getset {
( $class:ident, { [] [] } ) => { 0 as *mut $crate::_detail::ffi::PyGetSetDef };
(
$class:ident,
{
[ $( { $doc:expr } $getter_name:ident: $prop_type:ty, )* ]
[ $( $setter_name:ident: $value_type:tt => $setter_setter:ident, )* ]
}
) => {{
let mut index = 0usize;
$( let $getter_name = index; index += 1; )*
unsafe {
static mut GETSET: &mut [$crate::_detail::ffi::PyGetSetDef] = &mut [
$($crate::_detail::ffi::PyGetSetDef {
name: 0 as *mut _,
get: $crate::py_class_prop_getter!($class::$getter_name),
set: None,
doc: 0 as *mut _,
closure: 0 as *mut _,
},)*
$crate::_detail::ffi::PyGetSetDef {
name: 0 as *mut _,
get: None,
set: None,
doc: 0 as *mut _,
closure: 0 as *mut _,
}
];
$(
GETSET[$getter_name].name = $crate::strip_raw!(
concat!(stringify!($getter_name), "\0")
).as_ptr() as *mut _;
if !$doc.is_empty() {
GETSET[$getter_name].doc = concat!($doc, "\0").as_ptr() as *mut _;
}
)*
$(
GETSET[$setter_name].set = $crate::py_class_prop_setter!($class::$setter_setter, $value_type);
)*
GETSET.as_ptr() as *mut _
}
}};
}<|fim▁end|>
|
}
|
<|file_name|>notFound.js<|end_file_name|><|fim▁begin|>/**
* 404 (Not Found) Handler
*
* Usage:
* return res.notFound();
* return res.notFound(err);
* return res.notFound(err, 'some/specific/notfound/view');
*
* e.g.:
* ```
* return res.notFound();
* ```
*
* NOTE:
* If a request doesn't match any explicit routes (i.e. `config/routes.js`)
* or route blueprints (i.e. "shadow routes", Sails will call `res.notFound()`
* automatically.
*/
module.exports = function notFound (data, options) {
// Get access to `req`, `res`, & `sails`
var req = this.req;
var res = this.res;
var sails = req._sails;
// Set status code
res.status(404);
// Log error to console
if (data !== undefined) {
sails.log.verbose('Sending 404 ("Not Found") response: \n',data);
}
else sails.log.verbose('Sending 404 ("Not Found") response');<|fim▁hole|> // send back any identifying information about errors.
if (sails.config.environment === 'production' && sails.config.keepResponseErrors !== true) {
data = undefined;
}
// If the user-agent wants JSON, always respond with JSON
if (req.wantsJSON) {
return res.jsonx(data);
}
// If second argument is a string, we take that to mean it refers to a view.
// If it was omitted, use an empty object (`{}`)
options = (typeof options === 'string') ? { view: options } : options || {};
// If a view was provided in options, serve it.
// Otherwise try to guess an appropriate view, or if that doesn't
// work, just send JSON.
if (options.view) {
return res.view(options.view, { data: data });
}
// If no second argument provided, try to serve the default view,
// but fall back to sending JSON(P) if any errors occur.
else return res.view('404', { data: data }, function (err, html) {
// If a view error occured, fall back to JSON(P).
if (err) {
//
// Additionally:
// • If the view was missing, ignore the error but provide a verbose log.
if (err.code === 'E_VIEW_FAILED') {
sails.log.verbose('res.notFound() :: Could not locate view for error page (sending JSON instead). Details: ',err);
}
// Otherwise, if this was a more serious error, log to the console with the details.
else {
sails.log.warn('res.notFound() :: When attempting to render error page view, an error occured (sending JSON instead). Details: ', err);
}
return res.jsonx(data);
}
return res.send(html);
});
};<|fim▁end|>
|
// Only include errors in response if application environment
// is not set to 'production'. In production, we shouldn't
|
<|file_name|>builtin.py<|end_file_name|><|fim▁begin|>#!/bin/false
# -*- coding: utf-8 -*-
from objects.orobject import OrObject
from objects.function import Function
from objects.number import Number
from objects.file import File
from objects.inheritdict import InheritDict
from objects.ordict import OrDict
from objects.orddict import ODict
import objects.console as console
import objects.exception as exception
import objects.orstring as orstring
import types<|fim▁hole|>import libbuiltin
def expose(r, n=""):
v = OrObject.from_py(r)
if n:
v.name = n
return v
builtin = InheritDict()
builtin.update({
"int": expose(libbuiltin.toint),
"num": expose(Number),
"dict": expose(OrDict),
"odict": expose(ODict),
"set": expose(set),
"io": expose(console.io),
"file": expose(File),
"input": expose(console.input),
"output": expose(console.output),
"error": expose(console.error),
"endl": expose("\n"),
"repr": expose(repr),
"join": expose(libbuiltin.join),
"range": expose(range),
"type": expose(libbuiltin.typeof, "type"),
"dir": expose(libbuiltin.dirof, "dir"),
"attrs": expose(libbuiltin.attrsof, "attrs"),
"reverse": expose(reversed),
"sort": expose(sorted),
"chr": expose(unichr),
"Exception": expose(Exception),
"hasattr": expose(OrObject.has, "hasattr"),
"getattr": expose(OrObject.get, "getattr"),
"setattr": expose(OrObject.set, "setattr"),
})
stolen_builtins = [
'abs', 'all', 'any', 'bool', 'callable', #buffer
'cmp', #chr (not as unichr)
'dict', 'divmod', 'enumerate', #delattr
'exit', 'filter', # frozenset
'hash', 'id', #get/hasattr
'iter', 'len', 'list',
'map', 'max', 'min', 'ord', # object
'range', 'repr', #property
'round', 'set', 'slice', #setattr
'str', 'sum', 'unicode', #super
'zip'
]
for i in stolen_builtins:
builtin[i] = expose(__builtins__[i])<|fim▁end|>
| |
<|file_name|>domrectreadonly.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::{DOMRectReadOnlyMethods, Wrap};
use dom::bindings::error::Fallible;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use std::cell::Cell;
#[dom_struct]
pub struct DOMRectReadOnly {
reflector_: Reflector,
x: Cell<f64>,
y: Cell<f64>,
width: Cell<f64>,
height: Cell<f64>,
}
impl DOMRectReadOnly {
pub fn new_inherited(x: f64, y: f64, width: f64, height: f64) -> DOMRectReadOnly {
DOMRectReadOnly {
x: Cell::new(x),
y: Cell::new(y),
width: Cell::new(width),
height: Cell::new(height),
reflector_: Reflector::new(),
}
}
pub fn new(global: &GlobalScope,
x: f64,
y: f64,
width: f64,
height: f64)
-> DomRoot<DOMRectReadOnly> {
reflect_dom_object(Box::new(DOMRectReadOnly::new_inherited(x, y, width, height)),
global,
Wrap)
}
pub fn Constructor(global: &GlobalScope,
x: f64,
y: f64,
width: f64,
height: f64)
-> Fallible<DomRoot<DOMRectReadOnly>> {
Ok(DOMRectReadOnly::new(global, x, y, width, height))
}
pub fn set_x(&self, value: f64) {
self.x.set(value);
}
pub fn set_y(&self, value: f64) {
self.y.set(value);
}
pub fn set_width(&self, value: f64) {
self.width.set(value);
}
pub fn set_height(&self, value: f64) {
self.height.set(value);
}
}
impl DOMRectReadOnlyMethods for DOMRectReadOnly {
// https://drafts.fxtf.org/geometry/#dom-domrectreadonly-x
fn X(&self) -> f64 {
self.x.get()
}
// https://drafts.fxtf.org/geometry/#dom-domrectreadonly-y
fn Y(&self) -> f64 {
self.y.get()
}
// https://drafts.fxtf.org/geometry/#dom-domrectreadonly-width
fn Width(&self) -> f64 {
self.width.get()
}
// https://drafts.fxtf.org/geometry/#dom-domrectreadonly-height
fn Height(&self) -> f64 {
self.height.get()
}
// https://drafts.fxtf.org/geometry/#dom-domrectreadonly-top
fn Top(&self) -> f64 {
let height = self.height.get();
if height >= 0f64 {
self.y.get()
} else {
self.y.get() + height
}
}
// https://drafts.fxtf.org/geometry/#dom-domrectreadonly-right
fn Right(&self) -> f64 {
let width = self.width.get();
if width < 0f64 {
self.x.get()
} else {
self.x.get() + width
}
}
// https://drafts.fxtf.org/geometry/#dom-domrectreadonly-bottom
fn Bottom(&self) -> f64 {
let height = self.height.get();
if height < 0f64 {
self.y.get()
} else {
self.y.get() + height<|fim▁hole|>
// https://drafts.fxtf.org/geometry/#dom-domrectreadonly-left
fn Left(&self) -> f64 {
let width = self.width.get();
if width >= 0f64 {
self.x.get()
} else {
self.x.get() + width
}
}
}<|fim▁end|>
|
}
}
|
<|file_name|>app.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
from flask import Flask, session, render_template, url_for, redirect, request, flash, g
from flask.ext import assets
import pyxb
import json
import json
import os
import paypalrestsdk
app = Flask(__name__)
paypal_client_id = "AacMHTvbcCGRzaeuHY6i6zwqGvveuhN4X_2sZ2mZJi76ZGtSZATh7XggfVuVixzyrRuG-bJTLOJIXltg"
paypal_client_secret = "EOLqrOVlYbzBeQIXIu_lQiB2Idh7fpK71hemdmlrfV1UwkW9EfDIuHOYS9lZYcxDKj4BzKO08b-CdDt9"
#Assets
env = assets.Environment(app)
env.load_path = [
os.path.join(os.path.dirname(__file__), 'assets')
]
env.register (
'js_all',
assets.Bundle(
'js/jquery.js',
'js/bootstrap.min.js',
'js/moment-with-locales.min.js',
'js/bootstrap-datetimepicker.min.js',
'js/slider.js',
'js/amounts.js',
'js/landing.js',
output='js_all.js'
)
)
env.register(
'css_all',
assets.Bundle(
'css/bootstrap.min.css',
'css/bootstrap-datetimepicker.min.css',
'css/slider.css',
'css/landing-page.css',
output='css_all.css'
)
)
# Paypal lib
paypalrestsdk.configure(
mode="sandbox", # sandbox or live
client_id=paypal_client_id,
client_secret= paypal_client_secret
)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/payment/donation/create', methods=["POST"])
def paypal_process():
amount = 0
categories = {
'amount-homeless': 'homeless people',
'amount-refugees': 'refugees people',
'amount-orphans': 'orphans people',
'amount-poverished': 'perverished people'<|fim▁hole|>
items = []
for key, value in categories.iteritems():
amount += float(request.form[key])
if request.form[key] != 0:
items.append({
"name": "Donation to " + value,
"price": "%.2f" % float(request.form[key]),
"currency": "GBP",
"quantity": 1
})
if amount == 0:
raise Exception("Invalid amount")
# Payment
# A Payment Resource; create one using
# the above types and intent as 'sale'
payment = paypalrestsdk.Payment({
"intent": "sale",
# Payer
# A resource representing a Payer that funds a payment
# Payment Method as 'paypal'
"payer": {
"payment_method": "paypal"},
# Redirect URLs
"redirect_urls": {
"return_url": "http://localhost:5000/payment/donation/done",
"cancel_url": "http://localhost:5000/"},
# Transaction
# A transaction defines the contract of a
# payment - what is the payment for and who
# is fulfilling it.
"transactions": [{
# ItemList
"item_list": {
"items": items
},
# Amount
# Let's you specify a payment amount.
"amount": {
"total": "%.2f" % amount,
"currency": "GBP"
},
"description": "Donation to Railaid"
}]
})
print(payment)
# Create Payment and return status
if payment.create():
print("Payment[%s] created successfully" % (payment.id))
# Redirect the user to given approval url
for link in payment.links:
if link.method == "REDIRECT":
# Convert to str to avoid google appengine unicode issue
# https://github.com/paypal/rest-api-sdk-python/pull/58
redirect_url = str(link.href)
return redirect(redirect_url)
else:
print(payment.error)
@app.route('/payment/donation/done')
def paypal_success():
# Don't know what to do with it for now
payment_id = request.args.get('paymentId')
payment = paypalrestsdk.Payment.find(payment_id)
print(payment.transactions[0].amount.total);
return "Thank you for your donation of " + payment.transactions[0].amount.total + "!"
# @app.route('/search/tickets')
# def search_tickets():
# p1 = Passenger(age=30)
#
# tp1 = TravelPoint(
# origin="GBQQU",
# destination="GBQQM",
# departure=datetime(2015, 11, 23, 8))
#
# fq = FareSearch(
# travel_points = [tp1],
# fare_filter = FARE_FILTER.CHEAPEST,
# passengers = [p1])
#
# fares_result = sc.search_fare(fq)
# fr = fares_result.results
# print(fr)
# return render_template('search-result.html', data=fr)
if __name__ == '__main__':
app.run(debug=True)<|fim▁end|>
|
}
|
<|file_name|>config.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright 2012 Red Hat, Inc.
# Copyright 2013 NTT corp.
#
# 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.
"""Command-line flag library.
Emulates gflags by wrapping cfg.ConfigOpts.
The idea is to move fully to cfg eventually, and this wrapper is a
stepping stone.
"""
import socket
from oslo_config import cfg<|fim▁hole|>from cinder.i18n import _
CONF = cfg.CONF
logging.register_options(CONF)
core_opts = [
cfg.StrOpt('api_paste_config',
default="api-paste.ini",
help='File name for the paste.deploy config for cinder-api'),
cfg.StrOpt('state_path',
default='/var/lib/cinder',
deprecated_name='pybasedir',
help="Top-level directory for maintaining cinder's state"), ]
debug_opts = [
]
CONF.register_cli_opts(core_opts)
CONF.register_cli_opts(debug_opts)
global_opts = [
cfg.StrOpt('my_ip',
default=netutils.get_my_ipv4(),
help='IP address of this host'),
cfg.StrOpt('glance_host',
default='$my_ip',
help='Default glance host name or IP'),
cfg.IntOpt('glance_port',
default=9292,
help='Default glance port'),
cfg.ListOpt('glance_api_servers',
default=['$glance_host:$glance_port'],
help='A list of the glance API servers available to cinder '
'([hostname|ip]:port)'),
cfg.IntOpt('glance_api_version',
default=1,
help='Version of the glance API to use'),
cfg.IntOpt('glance_num_retries',
default=0,
help='Number retries when downloading an image from glance'),
cfg.BoolOpt('glance_api_insecure',
default=False,
help='Allow to perform insecure SSL (https) requests to '
'glance'),
cfg.BoolOpt('glance_api_ssl_compression',
default=False,
help='Enables or disables negotiation of SSL layer '
'compression. In some cases disabling compression '
'can improve data throughput, such as when high '
'network bandwidth is available and you use '
'compressed image formats like qcow2.'),
cfg.StrOpt('glance_ca_certificates_file',
help='Location of ca certificates file to use for glance '
'client requests.'),
cfg.IntOpt('glance_request_timeout',
default=None,
help='http/https timeout value for glance operations. If no '
'value (None) is supplied here, the glanceclient default '
'value is used.'),
cfg.StrOpt('scheduler_topic',
default='cinder-scheduler',
help='The topic that scheduler nodes listen on'),
cfg.StrOpt('volume_topic',
default='cinder-volume',
help='The topic that volume nodes listen on'),
cfg.StrOpt('backup_topic',
default='cinder-backup',
help='The topic that volume backup nodes listen on'),
cfg.BoolOpt('enable_v1_api',
default=True,
help=_("DEPRECATED: Deploy v1 of the Cinder API.")),
cfg.BoolOpt('enable_v2_api',
default=True,
help=_("Deploy v2 of the Cinder API.")),
cfg.BoolOpt('api_rate_limit',
default=True,
help='Enables or disables rate limit of the API.'),
cfg.ListOpt('osapi_volume_ext_list',
default=[],
help='Specify list of extensions to load when using osapi_'
'volume_extension option with cinder.api.contrib.'
'select_extensions'),
cfg.MultiStrOpt('osapi_volume_extension',
default=['cinder.api.contrib.standard_extensions'],
help='osapi volume extension to load'),
cfg.StrOpt('volume_manager',
default='cinder.volume.manager.VolumeManager',
help='Full class name for the Manager for volume'),
cfg.StrOpt('backup_manager',
default='cinder.backup.manager.BackupManager',
help='Full class name for the Manager for volume backup'),
cfg.StrOpt('scheduler_manager',
default='cinder.scheduler.manager.SchedulerManager',
help='Full class name for the Manager for scheduler'),
cfg.StrOpt('host',
default=socket.gethostname(),
help='Name of this node. This can be an opaque identifier. '
'It is not necessarily a host name, FQDN, or IP address.'),
# NOTE(vish): default to nova for compatibility with nova installs
cfg.StrOpt('storage_availability_zone',
default='nova',
help='Availability zone of this node'),
cfg.StrOpt('default_availability_zone',
default=None,
help='Default availability zone for new volumes. If not set, '
'the storage_availability_zone option value is used as '
'the default for new volumes.'),
cfg.StrOpt('default_volume_type',
default=None,
help='Default volume type to use'),
cfg.StrOpt('volume_usage_audit_period',
default='month',
help='Time period for which to generate volume usages. '
'The options are hour, day, month, or year.'),
cfg.StrOpt('rootwrap_config',
default='/etc/cinder/rootwrap.conf',
help='Path to the rootwrap configuration file to use for '
'running commands as root'),
cfg.BoolOpt('monkey_patch',
default=False,
help='Enable monkey patching'),
cfg.ListOpt('monkey_patch_modules',
default=[],
help='List of modules/decorators to monkey patch'),
cfg.IntOpt('service_down_time',
default=60,
help='Maximum time since last check-in for a service to be '
'considered up'),
cfg.StrOpt('volume_api_class',
default='cinder.volume.api.API',
help='The full class name of the volume API class to use'),
cfg.StrOpt('backup_api_class',
default='cinder.backup.api.API',
help='The full class name of the volume backup API class'),
cfg.StrOpt('auth_strategy',
default='keystone',
choices=['noauth', 'keystone', 'deprecated'],
help='The strategy to use for auth. Supports noauth, keystone, '
'and deprecated.'),
cfg.ListOpt('enabled_backends',
default=None,
help='A list of backend names to use. These backend names '
'should be backed by a unique [CONFIG] group '
'with its options'),
cfg.BoolOpt('no_snapshot_gb_quota',
default=False,
help='Whether snapshots count against gigabyte quota'),
cfg.StrOpt('transfer_api_class',
default='cinder.transfer.api.API',
help='The full class name of the volume transfer API class'),
cfg.StrOpt('replication_api_class',
default='cinder.replication.api.API',
help='The full class name of the volume replication API class'),
cfg.StrOpt('consistencygroup_api_class',
default='cinder.consistencygroup.api.API',
help='The full class name of the consistencygroup API class'),
cfg.StrOpt('os_privileged_user_name',
default=None,
help='OpenStack privileged account username. Used for requests '
'to other services (such as Nova) that require an account '
'with special rights.'),
cfg.StrOpt('os_privileged_user_password',
default=None,
help='Password associated with the OpenStack privileged '
'account.',
secret=True),
cfg.StrOpt('os_privileged_user_tenant',
default=None,
help='Tenant name associated with the OpenStack privileged '
'account.'),
]
CONF.register_opts(global_opts)<|fim▁end|>
|
from oslo_log import log as logging
from oslo_utils import netutils
|
<|file_name|>debounce.js<|end_file_name|><|fim▁begin|>var asyncplify = require('../dist/asyncplify');
var tests = require('asyncplify-tests');
describe('debounce', function () {
asyncplify
.interval(15)
.debounce(10)
.take(1)
.pipe(tests.itShouldClose())
.pipe(tests.itShouldEndAsync())
.pipe(tests.itShouldEmitValues([0]));<|fim▁hole|><|fim▁end|>
|
});
|
<|file_name|>box.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The `Box` type, which represents the leaves of the layout tree.
use extra::url::Url;
use extra::arc::{MutexArc, Arc};
use geom::{Point2D, Rect, Size2D, SideOffsets2D};
use gfx::color::rgb;
use gfx::display_list::{BaseDisplayItem, BorderDisplayItem, BorderDisplayItemClass};
use gfx::display_list::{DisplayList, ImageDisplayItem, ImageDisplayItemClass};
use gfx::display_list::{SolidColorDisplayItem, SolidColorDisplayItemClass, TextDisplayItem};
use gfx::display_list::{TextDisplayItemClass, TextDisplayItemFlags, ClipDisplayItem};
use gfx::display_list::{ClipDisplayItemClass};
use gfx::font::{FontStyle, FontWeight300};
use gfx::text::text_run::TextRun;
use servo_msg::constellation_msg::{FrameRectMsg, PipelineId, SubpageId};
use servo_net::image::holder::ImageHolder;
use servo_net::local_image_cache::LocalImageCache;
use servo_util::geometry::Au;
use servo_util::geometry;
use servo_util::range::*;
use servo_util::slot::Slot;
use std::cast;
use std::cell::Cell;
use std::cmp::ApproxEq;
use std::num::Zero;
use style::{ComputedValues, TElement, TNode};
use style::computed_values::{LengthOrPercentage, overflow};
use style::computed_values::{border_style, clear, font_family, font_style, line_height};
use style::computed_values::{text_align, text_decoration, vertical_align, visibility};
use css::node_style::StyledNode;
use layout::context::LayoutContext;
use layout::display_list_builder::{DisplayListBuilder, ExtraDisplayListData, ToGfxColor};
use layout::float_context::{ClearType, ClearLeft, ClearRight, ClearBoth};
use layout::flow::Flow;
use layout::flow;
use layout::model::{MaybeAuto, specified};
use layout::util::OpaqueNode;
use layout::wrapper::LayoutNode;
/// Boxes (`struct Box`) are the leaves of the layout tree. They cannot position themselves. In
/// general, boxes do not have a simple correspondence with CSS boxes in the specification:
///
/// * Several boxes may correspond to the same CSS box or DOM node. For example, a CSS text box
/// broken across two lines is represented by two boxes.
///
/// * Some CSS boxes are not created at all, such as some anonymous block boxes induced by inline
/// boxes with block-level sibling boxes. In that case, Servo uses an `InlineFlow` with
/// `BlockFlow` siblings; the `InlineFlow` is block-level, but not a block container. It is
/// positioned as if it were a block box, but its children are positioned according to inline
/// flow.
///
/// A `GenericBox` is an empty box that contributes only borders, margins, padding, and
/// backgrounds. It is analogous to a CSS nonreplaced content box.
///
/// A box's type influences how its styles are interpreted during layout. For example, replaced
/// content such as images are resized differently from tables, text, or other content. Different
/// types of boxes may also contain custom data; for example, text boxes contain text.
///
/// FIXME(pcwalton): This can be slimmed down quite a bit.
#[deriving(Clone)]
pub struct Box {
/// An opaque reference to the DOM node that this `Box` originates from.
node: OpaqueNode,
/// The CSS style of this box.
style: Arc<ComputedValues>,
/// The position of this box relative to its owning flow.
position: Slot<Rect<Au>>,
/// The border of the content box.
///
/// FIXME(pcwalton): This need not be stored in the box.
border: Slot<SideOffsets2D<Au>>,
/// The padding of the content box.
padding: Slot<SideOffsets2D<Au>>,
/// The margin of the content box.
margin: Slot<SideOffsets2D<Au>>,
/// Info specific to the kind of box. Keep this enum small.
specific: SpecificBoxInfo,
/// positioned box offsets
position_offsets: Slot<SideOffsets2D<Au>>,
}
/// Info specific to the kind of box. Keep this enum small.
#[deriving(Clone)]
pub enum SpecificBoxInfo {
GenericBox,
ImageBox(ImageBoxInfo),
IframeBox(IframeBoxInfo),
ScannedTextBox(ScannedTextBoxInfo),
UnscannedTextBox(UnscannedTextBoxInfo),
}
/// A box that represents a replaced content image and its accompanying borders, shadows, etc.
#[deriving(Clone)]
pub struct ImageBoxInfo {
/// The image held within this box.
image: Slot<ImageHolder>,
/// The width attribute supplied by the DOM, if any.
dom_width: Option<Au>,
/// The height attribute supplied by the DOM, if any.
dom_height: Option<Au>,
}
impl ImageBoxInfo {
/// Creates a new image box from the given URL and local image cache.
///
/// FIXME(pcwalton): The fact that image boxes store the cache in the box makes little sense to
/// me.
pub fn new(node: &LayoutNode, image_url: Url, local_image_cache: MutexArc<LocalImageCache>)
-> ImageBoxInfo {
fn convert_length(node: &LayoutNode, name: &str) -> Option<Au> {
node.with_element(|element| {
element.get_attr(None, name).and_then(|string| {
let n: Option<int> = FromStr::from_str(string);
n
}).and_then(|pixels| Some(Au::from_px(pixels)))
})
}
ImageBoxInfo {
image: Slot::init(ImageHolder::new(image_url, local_image_cache)),
dom_width: convert_length(node, "width"),
dom_height: convert_length(node, "height"),
}
}
// Calculates the width of an image, accounting for the width attribute.
fn image_width(&self) -> Au {
// TODO(brson): Consult margins and borders?
self.dom_width.unwrap_or_else(|| {
Au::from_px(self.image.mutate().ptr.get_size().unwrap_or(Size2D(0, 0)).width)
})
}
// Calculate the height of an image, accounting for the height attribute.
pub fn image_height(&self) -> Au {
// TODO(brson): Consult margins and borders?
self.dom_height.unwrap_or_else(|| {
Au::from_px(self.image.mutate().ptr.get_size().unwrap_or(Size2D(0, 0)).height)
})
}
}
/// A box that represents an inline frame (iframe). This stores the pipeline ID so that the size
/// of this iframe can be communicated via the constellation to the iframe's own layout task.
#[deriving(Clone)]
pub struct IframeBoxInfo {
/// The pipeline ID of this iframe.
pipeline_id: PipelineId,
/// The subpage ID of this iframe.
subpage_id: SubpageId,
}
impl IframeBoxInfo {
/// Creates the information specific to an iframe box.
pub fn new(node: &LayoutNode) -> IframeBoxInfo {
let (pipeline_id, subpage_id) = node.iframe_pipeline_and_subpage_ids();
IframeBoxInfo {
pipeline_id: pipeline_id,
subpage_id: subpage_id,
}
}
}
/// A scanned text box represents a single run of text with a distinct style. A `TextBox` may be
/// split into two or more boxes across line breaks. Several `TextBox`es may correspond to a single
/// DOM text node. Split text boxes are implemented by referring to subsets of a single `TextRun`
/// object.
#[deriving(Clone)]
pub struct ScannedTextBoxInfo {
/// The text run that this represents.
run: Arc<~TextRun>,
/// The range within the above text run that this represents.
range: Range,
}
impl ScannedTextBoxInfo {
/// Creates the information specific to a scanned text box from a range and a text run.
pub fn new(run: Arc<~TextRun>, range: Range) -> ScannedTextBoxInfo {
ScannedTextBoxInfo {
run: run,
range: range,
}
}
}
/// Data for an unscanned text box. Unscanned text boxes are the results of flow construction that
/// have not yet had their width determined.
#[deriving(Clone)]
pub struct UnscannedTextBoxInfo {
/// The text inside the box.
text: ~str,
}
impl UnscannedTextBoxInfo {
/// Creates a new instance of `UnscannedTextBoxInfo` from the given DOM node.
pub fn new(node: &LayoutNode) -> UnscannedTextBoxInfo {
// FIXME(pcwalton): Don't copy text; atomically reference count it instead.
UnscannedTextBoxInfo {
text: node.text(),
}
}
}
/// Represents the outcome of attempting to split a box.
pub enum SplitBoxResult {
CannotSplit,
// in general, when splitting the left or right side can
// be zero length, due to leading/trailing trimmable whitespace
SplitDidFit(Option<Box>, Option<Box>),
SplitDidNotFit(Option<Box>, Option<Box>)
}
impl Box {
/// Constructs a new `Box` instance.
pub fn new(node: LayoutNode, specific: SpecificBoxInfo) -> Box {
// Find the nearest ancestor element and take its style. (It should be either that node or
// its immediate parent.)
//
// FIXME(pcwalton): This is incorrect for non-inherited properties on anonymous boxes. For
// example:
//
// <div style="border: solid">
// <p>Foo</p>
// Bar
// <p>Baz</p>
// </div>
//
// An anonymous block box is generated around `Bar`, but it shouldn't inherit the border.
let mut nearest_ancestor_element = node;
while !nearest_ancestor_element.is_element() {
nearest_ancestor_element = node.parent_node().expect("no nearest element?!");
}
Box {
node: OpaqueNode::from_layout_node(&node),
style: (*nearest_ancestor_element.style()).clone(),
position: Slot::init(Au::zero_rect()),
border: Slot::init(Zero::zero()),
padding: Slot::init(Zero::zero()),
margin: Slot::init(Zero::zero()),
specific: specific,
position_offsets: Slot::init(Zero::zero()),
}
}
/// Returns a debug ID of this box. This ID should not be considered stable across multiple
/// layouts or box manipulations.
pub fn debug_id(&self) -> uint {
unsafe {
cast::transmute(self)
}
}
/// Transforms this box into another box of the given type, with the given size, preserving all
/// the other data.
pub fn transform(&self, size: Size2D<Au>, specific: SpecificBoxInfo) -> Box {
Box {
node: self.node,
style: self.style.clone(),
position: Slot::init(Rect(self.position.get().origin, size)),
border: Slot::init(self.border.get()),
padding: Slot::init(self.padding.get()),
margin: Slot::init(self.margin.get()),
specific: specific,
position_offsets: Slot::init(Zero::zero())
}
}
/// Returns the shared part of the width for computation of minimum and preferred width per
/// CSS 2.1.
fn guess_width(&self) -> Au {
match self.specific {
GenericBox | IframeBox(_) | ImageBox(_) => {}
ScannedTextBox(_) | UnscannedTextBox(_) => return Au(0),
}
let style = self.style();
let width = MaybeAuto::from_style(style.Box.width, Au::new(0)).specified_or_zero();
let margin_left = MaybeAuto::from_style(style.Margin.margin_left,
Au::new(0)).specified_or_zero();
let margin_right = MaybeAuto::from_style(style.Margin.margin_right,
Au::new(0)).specified_or_zero();
let padding_left = self.compute_padding_length(style.Padding.padding_left, Au::new(0));
let padding_right = self.compute_padding_length(style.Padding.padding_right, Au::new(0));
width + margin_left + margin_right + padding_left + padding_right +
self.border.get().left + self.border.get().right
}
/// Sets the size of this box.
fn set_size(&self, new_size: Size2D<Au>) {
self.position.set(Rect(self.position.get().origin, new_size))
}
pub fn calculate_line_height(&self, font_size: Au) -> Au {
match self.line_height() {
line_height::Normal => font_size.scale_by(1.14),
line_height::Number(l) => font_size.scale_by(l),
line_height::Length(l) => l
}
}
/// Populates the box model border parameters from the given computed style.
///
/// FIXME(pcwalton): This should not be necessary. Just go to the style.
pub fn compute_borders(&self, style: &ComputedValues) {
#[inline]
fn width(width: Au, style: border_style::T) -> Au {
if style == border_style::none {
Au(0)
} else {
width
}
}
self.border.set(SideOffsets2D::new(width(style.Border.border_top_width,
style.Border.border_top_style),
width(style.Border.border_right_width,
style.Border.border_right_style),
width(style.Border.border_bottom_width,
style.Border.border_bottom_style),
width(style.Border.border_left_width,
style.Border.border_left_style)))
}
pub fn compute_positioned_offset(&self, style: &ComputedValues) {
self.position_offsets.set(SideOffsets2D::new(
MaybeAuto::from_style(style.PositionOffsets.top, Au::new(0)).specified_or_zero(),
MaybeAuto::from_style(style.PositionOffsets.right, Au::new(0)).specified_or_zero(),
MaybeAuto::from_style(style.PositionOffsets.bottom, Au::new(0)).specified_or_zero(),
MaybeAuto::from_style(style.PositionOffsets.left, Au::new(0)).specified_or_zero()));
}
/// Populates the box model padding parameters from the given computed style.
pub fn compute_padding(&self, style: &ComputedValues, containing_block_width: Au) {
let padding = SideOffsets2D::new(self.compute_padding_length(style.Padding.padding_top,
containing_block_width),
self.compute_padding_length(style.Padding.padding_right,
containing_block_width),
self.compute_padding_length(style.Padding.padding_bottom,
containing_block_width),
self.compute_padding_length(style.Padding.padding_left,
containing_block_width));
self.padding.set(padding)
}
fn compute_padding_length(&self, padding: LengthOrPercentage, content_box_width: Au) -> Au {
specified(padding, content_box_width)
}
pub fn noncontent_width(&self) -> Au {
let left = self.margin.get().left + self.border.get().left + self.padding.get().left;
let right = self.margin.get().right + self.border.get().right + self.padding.get().right;
left + right
}
pub fn noncontent_height(&self) -> Au {
let top = self.margin.get().top + self.border.get().top + self.padding.get().top;
let bottom = self.margin.get().bottom + self.border.get().bottom +
self.padding.get().bottom;
top + bottom
}
/// Always inline for SCCP.
///
/// FIXME(pcwalton): Just replace with the clear type from the style module for speed?
#[inline(always)]
pub fn clear(&self) -> Option<ClearType> {
let style = self.style();
match style.Box.clear {
clear::none => None,
clear::left => Some(ClearLeft),
clear::right => Some(ClearRight),
clear::both => Some(ClearBoth),
}
}
/// Converts this node's computed style to a font style used for rendering.
///
/// FIXME(pcwalton): This should not be necessary; just make the font part of style sharable
/// with the display list somehow. (Perhaps we should use an ARC.)
pub fn font_style(&self) -> FontStyle {
let my_style = self.style();
debug!("(font style) start");
// FIXME: Too much allocation here.
let font_families = do my_style.Font.font_family.map |family| {
match *family {
font_family::FamilyName(ref name) => (*name).clone(),
}
};
let font_families = font_families.connect(", ");
debug!("(font style) font families: `{:s}`", font_families);
let font_size = my_style.Font.font_size.to_f64().unwrap() / 60.0;
debug!("(font style) font size: `{:f}px`", font_size);
let (italic, oblique) = match my_style.Font.font_style {
font_style::normal => (false, false),
font_style::italic => (true, false),
font_style::oblique => (false, true),
};
FontStyle {
pt_size: font_size,
weight: FontWeight300,
italic: italic,
oblique: oblique,
families: font_families,
}
}
#[inline(always)]
pub fn style<'a>(&'a self) -> &'a ComputedValues {
self.style.get()
}
/// Returns the text alignment of the computed style of the nearest ancestor-or-self `Element`
/// node.
pub fn text_align(&self) -> text_align::T {
self.style().Text.text_align
}
pub fn line_height(&self) -> line_height::T {
self.style().Box.line_height
}
pub fn vertical_align(&self) -> vertical_align::T {
self.style().Box.vertical_align
}
/// Returns the text decoration of this box, according to the style of the nearest ancestor
/// element.
///
/// NB: This may not be the actual text decoration, because of the override rules specified in
/// CSS 2.1 § 16.3.1. Unfortunately, computing this properly doesn't really fit into Servo's
/// model. Therefore, this is a best lower bound approximation, but the end result may actually
/// have the various decoration flags turned on afterward.
pub fn text_decoration(&self) -> text_decoration::T {
self.style().Text.text_decoration
}
/// Returns the sum of margin, border, and padding on the left.
pub fn offset(&self) -> Au {
self.margin.get().left + self.border.get().left + self.padding.get().left
}
/// Returns true if this element is replaced content. This is true for images, form elements,
/// and so on.
pub fn is_replaced(&self) -> bool {
match self.specific {
ImageBox(*) => true,
_ => false,
}
}
/// Returns true if this element can be split. This is true for text boxes.
pub fn can_split(&self) -> bool {
match self.specific {
ScannedTextBox(*) => true,
_ => false,
}
}
/// Returns the amount of left and right "fringe" used by this box. This is based on margins,
/// borders, padding, and width.
pub fn get_used_width(&self) -> (Au, Au) {
// TODO: This should actually do some computation! See CSS 2.1, Sections 10.3 and 10.4.
(Au::new(0), Au::new(0))
}
/// Returns the amount of left and right "fringe" used by this box. This should be based on
/// margins, borders, padding, and width.
pub fn get_used_height(&self) -> (Au, Au) {
// TODO: This should actually do some computation! See CSS 2.1, Sections 10.5 and 10.6.
(Au::new(0), Au::new(0))
}
/// Adds the display items necessary to paint the background of this box to the display list if
/// necessary.
pub fn paint_background_if_applicable<E:ExtraDisplayListData>(
&self,
list: &Cell<DisplayList<E>>,
absolute_bounds: &Rect<Au>) {
// FIXME: This causes a lot of background colors to be displayed when they are clearly not
// needed. We could use display list optimization to clean this up, but it still seems
// inefficient. What we really want is something like "nearest ancestor element that
// doesn't have a box".
let style = self.style();
let background_color = style.resolve_color(style.Background.background_color);
if !background_color.alpha.approx_eq(&0.0) {
list.with_mut_ref(|list| {
let solid_color_display_item = ~SolidColorDisplayItem {
base: BaseDisplayItem {
bounds: *absolute_bounds,
extra: ExtraDisplayListData::new(self),
},
color: background_color.to_gfx_color(),
};
list.append_item(SolidColorDisplayItemClass(solid_color_display_item))
})
}
}
/// Adds the display items necessary to paint the borders of this box to a display list if
/// necessary.
pub fn paint_borders_if_applicable<E:ExtraDisplayListData>(
&self,
list: &Cell<DisplayList<E>>,
abs_bounds: &Rect<Au>) {
// Fast path.
let border = self.border.get();
if border.is_zero() {
return
}
let style = self.style();
let top_color = style.resolve_color(style.Border.border_top_color);
let right_color = style.resolve_color(style.Border.border_right_color);
let bottom_color = style.resolve_color(style.Border.border_bottom_color);
let left_color = style.resolve_color(style.Border.border_left_color);
let top_style = style.Border.border_top_style;
let right_style = style.Border.border_right_style;
let bottom_style = style.Border.border_bottom_style;
let left_style = style.Border.border_left_style;
// Append the border to the display list.
do list.with_mut_ref |list| {
let border_display_item = ~BorderDisplayItem {
base: BaseDisplayItem {
bounds: *abs_bounds,
extra: ExtraDisplayListData::new(self),
},
border: border,
color: SideOffsets2D::new(top_color.to_gfx_color(),
right_color.to_gfx_color(),
bottom_color.to_gfx_color(),
left_color.to_gfx_color()),
style: SideOffsets2D::new(top_style,
right_style,
bottom_style,
left_style)
};
list.append_item(BorderDisplayItemClass(border_display_item))
}
}
/// Adds the display items for this box to the given display list.
///
/// Arguments:
/// * `builder`: The display list builder, which manages the coordinate system and options.
/// * `dirty`: The dirty rectangle in the coordinate system of the owning flow.
/// * `origin`: The total offset from the display list root flow to the owning flow of this
/// box.
/// * `list`: The display list to which items should be appended.
///
/// TODO: To implement stacking contexts correctly, we need to create a set of display lists,
/// one per layer of the stacking context (CSS 2.1 § 9.9.1). Each box is passed the list set
/// representing the box's stacking context. When asked to construct its constituent display
/// items, each box puts its display items into the correct stack layer according to CSS 2.1
/// Appendix E. Finally, the builder flattens the list.
pub fn build_display_list<E:ExtraDisplayListData>(
&self,
builder: &DisplayListBuilder,
dirty: &Rect<Au>,
offset: Point2D<Au>,
flow: &Flow,
list: &Cell<DisplayList<E>>) {
let box_bounds = self.position.get();
let absolute_box_bounds = box_bounds.translate(&offset);
debug!("Box::build_display_list at rel={}, abs={}: {:s}",
box_bounds, absolute_box_bounds, self.debug_str());
debug!("Box::build_display_list: dirty={}, offset={}", *dirty, offset);
if self.style().Box.visibility != visibility::visible {
return;
}
if absolute_box_bounds.intersects(dirty) {
debug!("Box::build_display_list: intersected. Adding display item...");
} else {
debug!("Box::build_display_list: Did not intersect...");
return;
}
// Add the background to the list, if applicable.
self.paint_background_if_applicable(list, &absolute_box_bounds);
match self.specific {
UnscannedTextBox(_) => fail!("Shouldn't see unscanned boxes here."),
ScannedTextBox(ref text_box) => {
do list.with_mut_ref |list| {
let item = ~ClipDisplayItem {
base: BaseDisplayItem {
bounds: absolute_box_bounds,
extra: ExtraDisplayListData::new(self),
},
child_list: ~[],
need_clip: false
};
list.append_item(ClipDisplayItemClass(item));
}
let color = self.style().Color.color.to_gfx_color();
// Set the various text display item flags.
let flow_flags = flow::base(flow).flags;
let mut text_flags = TextDisplayItemFlags::new();
text_flags.set_override_underline(flow_flags.override_underline());
text_flags.set_override_overline(flow_flags.override_overline());
text_flags.set_override_line_through(flow_flags.override_line_through());
// Create the text box.
do list.with_mut_ref |list| {
let text_display_item = ~TextDisplayItem {
base: BaseDisplayItem {
bounds: absolute_box_bounds,
extra: ExtraDisplayListData::new(self),
},
text_run: text_box.run.clone(),
range: text_box.range,
color: color,
flags: text_flags,
};
list.append_item(TextDisplayItemClass(text_display_item))
}
// Draw debug frames for text bounds.
//
// FIXME(pcwalton): This is a bit of an abuse of the logging infrastructure. We
// should have a real `SERVO_DEBUG` system.
debug!("{:?}", {
// Compute the text box bounds and draw a border surrounding them.
let debug_border = SideOffsets2D::new_all_same(Au::from_px(1));
do list.with_mut_ref |list| {
let border_display_item = ~BorderDisplayItem {
base: BaseDisplayItem {
bounds: absolute_box_bounds,
extra: ExtraDisplayListData::new(self),
},
border: debug_border,
color: SideOffsets2D::new_all_same(rgb(0, 0, 200)),
style: SideOffsets2D::new_all_same(border_style::solid)
};
list.append_item(BorderDisplayItemClass(border_display_item))
}
// Draw a rectangle representing the baselines.
//
// TODO(Issue #221): Create and use a Line display item for the baseline.
let ascent = text_box.run.get().metrics_for_range(
&text_box.range).ascent;
let baseline = Rect(absolute_box_bounds.origin + Point2D(Au(0), ascent),
Size2D(absolute_box_bounds.size.width, Au(0)));
do list.with_mut_ref |list| {
let border_display_item = ~BorderDisplayItem {
base: BaseDisplayItem {
bounds: baseline,
extra: ExtraDisplayListData::new(self),
},
border: debug_border,
color: SideOffsets2D::new_all_same(rgb(0, 200, 0)),
style: SideOffsets2D::new_all_same(border_style::dashed)
};
list.append_item(BorderDisplayItemClass(border_display_item))
}
()
});
},
GenericBox | IframeBox(_) => {
do list.with_mut_ref |list| {
let item = ~ClipDisplayItem {
base: BaseDisplayItem {
bounds: absolute_box_bounds,
extra: ExtraDisplayListData::new(self),
},
child_list: ~[],<|fim▁hole|>
// FIXME(pcwalton): This is a bit of an abuse of the logging infrastructure. We
// should have a real `SERVO_DEBUG` system.
debug!("{:?}", {
let debug_border = SideOffsets2D::new_all_same(Au::from_px(1));
do list.with_mut_ref |list| {
let border_display_item = ~BorderDisplayItem {
base: BaseDisplayItem {
bounds: absolute_box_bounds,
extra: ExtraDisplayListData::new(self),
},
border: debug_border,
color: SideOffsets2D::new_all_same(rgb(0, 0, 200)),
style: SideOffsets2D::new_all_same(border_style::solid)
};
list.append_item(BorderDisplayItemClass(border_display_item))
}
()
});
},
ImageBox(ref image_box) => {
do list.with_mut_ref |list| {
let item = ~ClipDisplayItem {
base: BaseDisplayItem {
bounds: absolute_box_bounds,
extra: ExtraDisplayListData::new(self),
},
child_list: ~[],
need_clip: false
};
list.append_item(ClipDisplayItemClass(item));
}
match image_box.image.mutate().ptr.get_image() {
Some(image) => {
debug!("(building display list) building image box");
// Place the image into the display list.
do list.with_mut_ref |list| {
let image_display_item = ~ImageDisplayItem {
base: BaseDisplayItem {
bounds: absolute_box_bounds,
extra: ExtraDisplayListData::new(self),
},
image: image.clone(),
};
list.append_item(ImageDisplayItemClass(image_display_item))
}
}
None => {
// No image data at all? Do nothing.
//
// TODO: Add some kind of placeholder image.
debug!("(building display list) no image :(");
}
}
}
}
// If this is an iframe, then send its position and size up to the constellation.
//
// FIXME(pcwalton): Doing this during display list construction seems potentially
// problematic if iframes are outside the area we're computing the display list for, since
// they won't be able to reflow at all until the user scrolls to them. Perhaps we should
// separate this into two parts: first we should send the size only to the constellation
// once that's computed during assign-heights, and second we should should send the origin
// to the constellation here during display list construction. This should work because
// layout for the iframe only needs to know size, and origin is only relevant if the
// iframe is actually going to be displayed.
match self.specific {
IframeBox(ref iframe_box) => {
self.finalize_position_and_size_of_iframe(iframe_box, offset, builder.ctx)
}
GenericBox | ImageBox(_) | ScannedTextBox(_) | UnscannedTextBox(_) => {}
}
// Add a border, if applicable.
//
// TODO: Outlines.
self.paint_borders_if_applicable(list, &absolute_box_bounds);
}
/// Returns the *minimum width* and *preferred width* of this box as defined by CSS 2.1.
pub fn minimum_and_preferred_widths(&self) -> (Au, Au) {
let guessed_width = self.guess_width();
let (additional_minimum, additional_preferred) = match self.specific {
GenericBox | IframeBox(_) => (Au(0), Au(0)),
ImageBox(ref image_box_info) => {
let image_width = image_box_info.image_width();
(image_width, image_width)
}
ScannedTextBox(ref text_box_info) => {
let range = &text_box_info.range;
let min_line_width = text_box_info.run.get().min_width_for_range(range);
let mut max_line_width = Au::new(0);
for line_range in text_box_info.run.get().iter_natural_lines_for_range(range) {
let line_metrics = text_box_info.run.get().metrics_for_range(&line_range);
max_line_width = Au::max(max_line_width, line_metrics.advance_width);
}
(min_line_width, max_line_width)
}
UnscannedTextBox(*) => fail!("Unscanned text boxes should have been scanned by now!"),
};
(guessed_width + additional_minimum, guessed_width + additional_preferred)
}
/// Returns, and computes, the height of this box.
///
/// FIXME(pcwalton): Rename to just `height`?
/// FIXME(pcwalton): This function *mutates* the height? Gross! Refactor please.
pub fn box_height(&self) -> Au {
match self.specific {
GenericBox | IframeBox(_) => Au(0),
ImageBox(ref image_box_info) => {
let size = image_box_info.image.mutate().ptr.get_size();
let height = Au::from_px(size.unwrap_or(Size2D(0, 0)).height);
// Eww. Refactor this.
self.position.mutate().ptr.size.height = height;
debug!("box_height: found image height: {}", height);
height
}
ScannedTextBox(ref text_box_info) => {
// Compute the height based on the line-height and font size.
let (range, run) = (&text_box_info.range, &text_box_info.run);
let text_bounds = run.get().metrics_for_range(range).bounding_box;
let em_size = text_bounds.size.height;
self.calculate_line_height(em_size)
}
UnscannedTextBox(_) => fail!("Unscanned text boxes should have been scanned by now!"),
}
}
/// Attempts to split this box so that its width is no more than `max_width`.
pub fn split_to_width(&self, max_width: Au, starts_line: bool) -> SplitBoxResult {
match self.specific {
GenericBox | IframeBox(_) | ImageBox(_) => CannotSplit,
UnscannedTextBox(_) => fail!("Unscanned text boxes should have been scanned by now!"),
ScannedTextBox(ref text_box_info) => {
let mut pieces_processed_count: uint = 0;
let mut remaining_width: Au = max_width;
let mut left_range = Range::new(text_box_info.range.begin(), 0);
let mut right_range: Option<Range> = None;
debug!("split_to_width: splitting text box (strlen={:u}, range={}, \
avail_width={})",
text_box_info.run.get().text.get().len(),
text_box_info.range,
max_width);
for (glyphs, offset, slice_range) in text_box_info.run.get().iter_slices_for_range(
&text_box_info.range) {
debug!("split_to_width: considering slice (offset={}, range={}, \
remain_width={})",
offset,
slice_range,
remaining_width);
let metrics = text_box_info.run.get().metrics_for_slice(glyphs, &slice_range);
let advance = metrics.advance_width;
let should_continue;
if advance <= remaining_width {
should_continue = true;
if starts_line && pieces_processed_count == 0 && glyphs.is_whitespace() {
debug!("split_to_width: case=skipping leading trimmable whitespace");
left_range.shift_by(slice_range.length() as int);
} else {
debug!("split_to_width: case=enlarging span");
remaining_width = remaining_width - advance;
left_range.extend_by(slice_range.length() as int);
}
} else {
// The advance is more than the remaining width.
should_continue = false;
let slice_begin = offset + slice_range.begin();
let slice_end = offset + slice_range.end();
if glyphs.is_whitespace() {
// If there are still things after the trimmable whitespace, create the
// right chunk.
if slice_end < text_box_info.range.end() {
debug!("split_to_width: case=skipping trimmable trailing \
whitespace, then split remainder");
let right_range_end = text_box_info.range.end() - slice_end;
right_range = Some(Range::new(slice_end, right_range_end));
} else {
debug!("split_to_width: case=skipping trimmable trailing \
whitespace");
}
} else if slice_begin < text_box_info.range.end() {
// There are still some things left over at the end of the line. Create
// the right chunk.
let right_range_end = text_box_info.range.end() - slice_begin;
right_range = Some(Range::new(slice_begin, right_range_end));
debug!("split_to_width: case=splitting remainder with right range={:?}",
right_range);
}
}
pieces_processed_count += 1;
if !should_continue {
break
}
}
let left_box = if left_range.length() > 0 {
let new_text_box_info = ScannedTextBoxInfo::new(text_box_info.run.clone(), left_range);
let new_metrics = new_text_box_info.run.get().metrics_for_range(&left_range);
Some(self.transform(new_metrics.bounding_box.size,
ScannedTextBox(new_text_box_info)))
} else {
None
};
let right_box = right_range.map_default(None, |range: Range| {
let new_text_box_info = ScannedTextBoxInfo::new(text_box_info.run.clone(), range);
let new_metrics = new_text_box_info.run.get().metrics_for_range(&range);
Some(self.transform(new_metrics.bounding_box.size,
ScannedTextBox(new_text_box_info)))
});
if pieces_processed_count == 1 || left_box.is_none() {
SplitDidNotFit(left_box, right_box)
} else {
SplitDidFit(left_box, right_box)
}
}
}
}
/// Returns true if this box is an unscanned text box that consists entirely of whitespace.
pub fn is_whitespace_only(&self) -> bool {
match self.specific {
UnscannedTextBox(ref text_box_info) => text_box_info.text.is_whitespace(),
_ => false,
}
}
/// Assigns the appropriate width to this box.
pub fn assign_width(&self) {
match self.specific {
GenericBox | IframeBox(_) => {
// FIXME(pcwalton): This seems clownshoes; can we remove?
self.position.mutate().ptr.size.width = Au::from_px(45)
}
ImageBox(ref image_box_info) => {
let image_width = image_box_info.image_width();
self.position.mutate().ptr.size.width = image_width
}
ScannedTextBox(_) => {
// Scanned text boxes will have already had their widths assigned by this point.
}
UnscannedTextBox(_) => fail!("Unscanned text boxes should have been scanned by now!"),
}
}
/// Returns true if this box can merge with another adjacent box or false otherwise.
pub fn can_merge_with_box(&self, other: &Box) -> bool {
match (&self.specific, &other.specific) {
(&UnscannedTextBox(_), &UnscannedTextBox(_)) => {
self.font_style() == other.font_style() &&
self.text_decoration() == other.text_decoration()
}
_ => false,
}
}
/// Cleans up all the memory associated with this box.
pub fn teardown(&self) {
match self.specific {
ScannedTextBox(ref text_box_info) => text_box_info.run.get().teardown(),
_ => {}
}
}
/// Returns true if the contents should be clipped (i.e. if `overflow` is `hidden`).
pub fn needs_clip(&self) -> bool {
self.style().Box.overflow == overflow::hidden
}
/// Returns a debugging string describing this box.
pub fn debug_str(&self) -> ~str {
let class_name = match self.specific {
GenericBox => "GenericBox",
IframeBox(_) => "IframeBox",
ImageBox(_) => "ImageBox",
ScannedTextBox(_) => "ScannedTextBox",
UnscannedTextBox(_) => "UnscannedTextBox",
};
format!("({}{}{}{})",
class_name,
self.side_offsets_debug_string("b", self.border.get()),
self.side_offsets_debug_string("p", self.padding.get()),
self.side_offsets_debug_string("m", self.margin.get()))
}
/// A helper function to return a debug string describing the side offsets for one of the rect
/// box model properties (border, padding, or margin).
fn side_offsets_debug_string(&self, name: &str, value: SideOffsets2D<Au>) -> ~str {
let zero: SideOffsets2D<Au> = Zero::zero();
if value == zero {
return "".to_str()
}
format!(" {}{},{},{},{}",
name,
*value.top,
*value.right,
*value.bottom,
*value.left)
}
/// Sends the size and position of this iframe box to the constellation. This is out of line to
/// guide inlining.
#[inline(never)]
fn finalize_position_and_size_of_iframe(&self,
iframe_box: &IframeBoxInfo,
offset: Point2D<Au>,
layout_context: &LayoutContext) {
let left = offset.x + self.margin.get().left + self.border.get().left +
self.padding.get().left;
let top = offset.y + self.margin.get().top + self.border.get().top +
self.padding.get().top;
let width = self.position.get().size.width - self.noncontent_width();
let height = self.position.get().size.height - self.noncontent_height();
let origin = Point2D(geometry::to_frac_px(left) as f32, geometry::to_frac_px(top) as f32);
let size = Size2D(geometry::to_frac_px(width) as f32, geometry::to_frac_px(height) as f32);
let rect = Rect(origin, size);
debug!("finalizing position and size of iframe for {:?},{:?}",
iframe_box.pipeline_id,
iframe_box.subpage_id);
let msg = FrameRectMsg(iframe_box.pipeline_id, iframe_box.subpage_id, rect);
layout_context.constellation_chan.send(msg)
}
}<|fim▁end|>
|
need_clip: self.needs_clip()
};
list.append_item(ClipDisplayItemClass(item));
}
|
<|file_name|>jqwidgets.d.ts<|end_file_name|><|fim▁begin|>/*
jQWidgets TypeScript definitions
Copyright (c) 2011-2021 jQWidgets.
License: https://jqwidgets.com/license/
*/
interface JQueryStatic {
jqx: any;
}
declare var generatedata: any;
declare var jqx: any;
declare module jqwidgets {
export function createInstance(selector: string, widgetName: string, params?: any): any;
export class widget
{
constructor(selector: string, options?: Object);
refresh(): void;
destroy(): void;
getInstance(): any;
addEventHandler(event: string, funcEventHandler: (any: any) => void): void;
removeEventHandler(event: string): void;
setOptions(params?: any): any;
}
export interface BarGaugeLabelsFont {
// BarGaugeLabelsFont properties
color?: string;
size?: number | string;
family?: string;
}// BarGaugeLabelsFont
export interface BarGaugeLabels {
// BarGaugeLabels properties
connectorColor?: string;
connectorWidth?: number;
font?: BarGaugeLabelsFont;
formatFunction?: (value: number, index?: number) => string;
indent?: number;
precision?: number;
visible?: boolean;
}// BarGaugeLabels
export interface BarGaugeTextFont {
// BarGaugeTextFont properties
color?: string;
family?: string;
opacity?: number;
size?: number | string;
weight?: number;
}// BarGaugeTextFont
export interface BarGaugeTitleMargin {
// BarGaugeTitleMargin properties
bottom?: number;
left?: number;
right?: number;
top?: number;
}// BarGaugeTitleMargin
export interface BarGaugeTitleSubtitle {
// BarGaugeTitleSubtitle properties
text?: string;
font?: BarGaugeTextFont;
}// BarGaugeTitleSubtitle
export interface BarGaugeTitle {
// BarGaugeTitle properties
text?: string;
font?: BarGaugeTextFont;
horizontalAlignment?: string;
margin?: BarGaugeTitleMargin;
subtitle?: BarGaugeTitleSubtitle;
verticalAlignment?: string;
}// BarGaugeTitle
export interface BarGaugeTooltip {
// BarGaugeTooltip properties
classname?: string;
formatFunction?: (value: string, index?: number, color?: string) => string;
visible?: boolean;
precision?: number;
}// BarGaugeTooltip
export interface BarGaugeCustomColorScheme {
// BarGaugeCustomColorScheme properties
name: string;
colors: Array<string>;
}// BarGaugeCustomColorScheme
export interface BarGaugeOptions {
// BarGaugeOptions properties
animationDuration?: number;
backgroundColor?: string;
barSpacing?: number;
baseValue?: number;
colorScheme?: string;
customColorScheme?: BarGaugeCustomColorScheme;
disabled?: boolean;
endAngle?: number;
formatFunction?: (value: number, index?: number, color?: string) => string;
height?: string | number;
labels?: BarGaugeLabels;
max?: number | string;
min?: number;
relativeInnerRadius?: number | string;
rendered?: () => void;
startAngle?: number;
title?: BarGaugeTitle;
tooltip?: BarGaugeTooltip;
useGradient?: boolean;
values?: Array<number>;
width?: string | number;
}// BarGaugeOptions
export interface jqxBarGauge extends widget, BarGaugeOptions {
// jqxBarGauge functions
refresh(): void;
render(): void;
val(value: Array<number>): Array<number>;
}// jqxBarGauge
export interface BulletChartLabelsFormatFunction {
// BulletChartLabelsFormatFunction properties
value?: string;
position?: string;
}// BulletChartLabelsFormatFunction
export interface BulletChartTooltipFormatFunction {
// BulletChartTooltipFormatFunction properties
pointerValue?: number;
targetValue?: number;
}// BulletChartTooltipFormatFunction
export interface BulletChartPointer {
// BulletChartPointer properties
value?: number;
label?: string;
size?: number | string;
color?: string;
}// BulletChartPointer
export interface BulletChartRanges {
// BulletChartRanges properties
startValue: number;
endValue: number;
opacity?: number;
color?: string;
}// BulletChartRanges
export interface BulletChartTicks {
// BulletChartTicks properties
position?: string;
interval?: number;
size?: number | string;
}// BulletChartTicks
export interface BulletChartOptions {
// BulletChartOptions properties
animationDuration?: number;
barSize?: number | string;
description?: string;
disabled?: boolean;
height?: string | number;
labelsFormat?: string;
labelsFormatFunction?: (value?: BulletChartLabelsFormatFunction['value'], position?: BulletChartLabelsFormatFunction['position']) => any;
orientation?: string;
pointer?: BulletChartPointer;
rtl?: boolean;
ranges?: Array<BulletChartRanges>;
showTooltip?: boolean;
target?: BulletChartPointer;
ticks?: BulletChartTicks;
title?: string;
tooltipFormatFunction?: (pointerValue?: BulletChartTooltipFormatFunction['pointerValue'], targetValue?: BulletChartTooltipFormatFunction['targetValue']) => string;
width?: string | number;
}// BulletChartOptions
export interface jqxBulletChart extends widget, BulletChartOptions {
// jqxBulletChart functions
destroy(): void;
render(): void;
refresh(): void;
val(value: number): number;
}// jqxBulletChart
export interface ButtonGroupOptions {
// ButtonGroupOptions properties
disabled?: boolean;
enableHover?: boolean;
mode?: string;
rtl?: boolean;
template?: string;
theme?: string;
}// ButtonGroupOptions
export interface jqxButtonGroup extends widget, ButtonGroupOptions {
// jqxButtonGroup functions
disableAt(index: number): void;
disable(): void;
destroy(): void;
enable(): void;
enableAt(index: number): void;
getSelection(): any;
render(): void;
setSelection(index: number): void;
}// jqxButtonGroup
export interface ButtonOptions {
// ButtonOptions properties
disabled?: boolean;
height?: number | string;
imgSrc?: string;
imgWidth?: number | string;
imgHeight?: number | string;
imgPosition?: string;
roundedCorners?: string;
rtl?: boolean;
enableDefault?: boolean;
cursor?: boolean;
textPosition?: string;
textImageRelation?: string;
theme?: string;
template?: string;
width?: number | string;
value?: string;
}// ButtonOptions
export interface jqxButton extends widget, ButtonOptions {
// jqxButton functions
destroy(): void;
focus(): void;
render(): void;
val(value: string): string;
}// jqxButton
export interface CalendarOptions {
// CalendarOptions properties
backText?: string;
columnHeaderHeight?: number;
clearString?: string;
culture?: string;
dayNameFormat?: string;
disabled?: boolean;
enableWeekend?: boolean;
enableViews?: boolean;
enableOtherMonthDays?: boolean;
enableFastNavigation?: boolean;
enableHover?: boolean;
enableAutoNavigation?: boolean;
enableTooltips?: boolean;
forwardText?: string;
firstDayOfWeek?: number;
height?: string | number;
min?: any;
max?: any;
navigationDelay?: number;
rowHeaderWidth?: number | string;
readOnly?: boolean;
restrictedDates?: Array<Date>;
rtl?: boolean;
stepMonths?: number;
showWeekNumbers?: boolean;
showDayNames?: boolean;
showOtherMonthDays?: boolean;
showFooter?: boolean;
selectionMode?: string;
specialDates?: Array<any>;
theme?: string;
titleHeight?: number;
titleFormat?: string;
todayString?: string;
value?: Date;
width?: string | number;
}// CalendarOptions
export interface jqxCalendar extends widget, CalendarOptions {
// jqxCalendar functions
clear(): void;
destroy(): void;
focus(): void;
addSpecialDate(date: any, specialDateClass: any, text: any): void;
getMinDate(): any;
getMaxDate(): any;
getDate(): any;
getRange(): any;
navigateForward(months: number): void;
navigateBackward(months: number): void;
render(): void;
refresh(): void;
setMinDate(date: any): void;
setMaxDate(date: any): void;
setDate(date: any): void;
setRange(date: any, date2: any): void;
today(): void;
val(value: Date | string, value2: Date | string): Date | string;
}// jqxCalendar
export interface ChartDraw {
// ChartDraw properties
renderer?: any;
rect?: any;
}// ChartDraw
export interface ChartDrawBefore {
// ChartDrawBefore properties
renderer?: any;
rect?: any;
}// ChartDrawBefore
export interface ChartOffset {
// ChartOffset properties
x: number;
y: number;
}// ChartOffset
export interface ChartRect {
// ChartRect properties
x: number;
y: number;
width: number | string;
height: number | string;
}// ChartRect
export interface ChartPadding {
// ChartPadding properties
left: number;
right: number;
top: number;
bottom: number;
}// ChartPadding
export interface ChartTickMarks {
// ChartTickMarks properties
visible?: any;
color?: string;
step?: number;
dashStyle?: string;
lineWidth?: number;
size?: number | string;
interval?: any;
custom?: Array<ChartCustomOffset>;
}// ChartTickMarks
export interface ChartGridLines {
// ChartGridLines properties
visible?: any;
color?: string;
step?: number;
dashStyle?: string;
lineWidth?: number;
interval?: any;
custom?: Array<ChartCustomOffset>;
}// ChartGridLines
export interface ChartAxisLine {
// ChartAxisLine properties
visible?: any;
color?: string;
dashStyle?: string;
lineWidth?: number;
}// ChartAxisLine
export interface ChartCustomOffset {
// ChartCustomOffset properties
value?: any;
offset?: number;
}// ChartCustomOffset
export interface ChartAxisLabels {
// ChartAxisLabels properties
visible?: any;
class?: string;
step?: number;
angle?: number;
rotationPoint?: string;
horizontalAlignment?: string;
verticalAlignment?: string;
offset?: ChartOffset;
custom?: Array<ChartCustomOffset>;
formatSettings?: ChartFormatSettings;
formatFunction?: (value: any, itemIndex?: number, serieIndex?: number, groupIndex?: number, xAxisValue?: any, xAxis?: ChartXAxis) => string;
autoRotate?: boolean;
}// ChartAxisLabels
export interface ChartFormatSettings {
// ChartFormatSettings properties
prefix?: string;
sufix?: string;
decimalSeparator?: string;
thousandsSeparator?: string;
decimalPlaces?: number;
negativeWithBrackets?: boolean;
dateFormat?: string;
}// ChartFormatSettings
export interface ChartSeriesLabels {
// ChartSeriesLabels properties
visible?: boolean;
class?: string;
angle?: number;
horizontalAlignment?: string;
verticalAlignment?: string;
offset?: ChartOffset;
backgroundColor?: string;
backgroundOpacity?: number;
borderColor?: string;
borderOpacity?: number;
padding?: ChartPadding;
linesEnabled?: boolean;
linesAngles?: boolean;
autoRotate?: boolean;
radius?: any;
}// ChartSeriesLabels
export interface ChartAxisTitle {
// ChartAxisTitle properties
visible?: boolean;
text?: string;
class?: string;
horizontalAlignment?: string;
verticalAlignment?: string;
angle?: number;
rotationPoint?: string;
offset?: ChartOffset;
}// ChartAxisTitle
export interface ChartColorBand {
// ChartColorBand properties
minValue?: number;
maxValue?: number;
fillColor?: string;
opacity?: number;
lineColor?: string;
lineWidth?: number;
dashStyle?: string;
}// ChartColorBand
export interface ChartXAxis {
// ChartXAxis properties
visible?: boolean;
unitInterval?: number;
dataField?: string;
displayText?: string;
type?: string;
baseUnit?: string;
valuesOnTicks?: boolean;
dateFormat?: string;
axisSize?: number | string;
customDraw?: boolean;
flip?: boolean;
position?: string;
padding?: ChartPadding;
title?: ChartAxisTitle;
tickMarks?: ChartTickMarks;
gridLines?: ChartGridLines;
line?: ChartAxisLine;
labels?: ChartAxisLabels;
logarithmicScale?: boolean;
logarithmicScaleBase?: number;
minValue?: any;
maxValue?: any;
bands?: Array<ChartColorBand>;
alternatingBackgroundColor?: string;
alternatingBackgroundColor2?: string;
alternatingBackgroundOpacity?: number;
formatSettings?: any;
formatFunction?: any;
toolTipFormatSettings?: ChartFormatSettings;
toolTipFormatFunction?: any;
rangeSelector?: any;
textRotationAngle?: number;
}// ChartXAxis
export interface ChartSerie {
// ChartSerie properties
dataField?: string;
displayText?: string;
dataFieldFrom?: string;
displayTextFrom?: string;
dataFieldTo?: string;
displayTextTo?: string;
dataFieldOpen?: string;
displayTextOpen?: string;
dataFieldLow?: string;
displayTextLow?: string;
dataFieldHigh?: string;
displayTextHigh?: string;
dataFieldClose?: string;
displayTextClose?: string;
lineWidth?: number;
dashStyle?: string;
symbolType?: string;
symbolSize?: number;
symbolSizeSelected?: number;
emptyPointsDisplay?: string;
linesUnselectMode?: string;
opacity?: number;
useGradientColors?: boolean;
greyScale?: boolean;
lineColor?: string;
lineColorSelected?: string;
fillColor?: string;
fillColorSelected?: string;
lineColorSymbol?: string;
lineColorSymbolSelected?: string;
fillColorSymbol?: string;
fillColorSymbolSelected?: string;
fillColorAlt?: string;
fillColorAltSelected?: string;
colorFunction?: (dataValue: any, itemIndex?: number, serie?: any, group?: any) => any;
labels?: ChartSeriesLabels;
formatSettings?: ChartFormatSettings;
formatFunction?: (value: any, itemIndex?: number, serieIndex?: number, groupIndex?: number, xAxisValue?: any, xAxis?: ChartXAxis) => string;
legendFormatSettings?: ChartFormatSettings;
legendFormatFunction?: (value: any, itemIndex?: number, serieIndex?: number, groupIndex?: number, xAxisValue?: any, xAxis?: ChartXAxis) => string;
legendLineColor?: string;
legnedFillColor?: string;
toolTipFormatSettings?: ChartFormatSettings;
toolTipFormatFunction?: (value: any, itemIndex?: number, serieIndex?: number, groupIndex?: number, xAxisValue?: any, xAxis?: ChartXAxis) => string;
toolTipLineColor?: string;
toolTipBackground?: string;
toolTipClass?: string;
radius?: any;
innerRadius?: any;
startAngle?: number;
endAngle?: number;
offsetX?: number;
offsetY?: number;
hiddenPointsDisplay?: boolean;
enableSeriesToggle?: boolean;
enableSelection?: boolean;
radiusDataField?: string;
minRadius?: any;
maxRadius?: any;
summary?: string;
labelRadius?: any;
initialAngle?: number;
centerOffset?: number;
}// ChartSerie
export interface ChartValueAxis {
// ChartValueAxis properties
visible?: boolean;
flip?: boolean;
position?: string;
axisSize?: any;
minValue?: number;
maxValue?: number;
baselineValue?: number;
logarithmicScale?: boolean;
logarithmicScaleBase?: number;
valuesOnTicks?: boolean;
unitInterval?: number;
title?: ChartAxisTitle;
labels?: ChartAxisLabels;
gridLines?: ChartGridLines;
tickMarks?: ChartTickMarks;
padding?: ChartPadding;
bands?: Array<ChartColorBand>;
alternatingBackgroundColor?: string;
alternatingBackgroundColor2?: string;
alternatingBackgroundOpacity?: number;
toolTipFormatSettings?: ChartFormatSettings;
formatFunction?: any;
}// ChartValueAxis
export interface ChartSeriesGroup {
// ChartSeriesGroup properties
type: string;
orientation?: string;
valueAxis?: ChartValueAxis;
series: Array<ChartSerie>;
formatSettings?: ChartFormatSettings;
toolTipFormatFunction?: any;
columnsGapPercent?: number;
seriesGapPercent?: number;
columnsMinWidth?: number;
columnsMaxWidth?: number;
columnsTopWidthPercent?: number;
columnsBottomWidthPercent?: number;
skipOverlappingPoints?: boolean;
polar?: boolean;
spider?: boolean;
radius?: any;
startAngle?: number;
endAngle?: number;
offsetX?: number;
offsetY?: number;
source?: any;
xAxis?: ChartXAxis;
colorScheme?: string;
showLabels?: boolean;
alignEndPointsWithIntervals?: boolean;
annotations?: any;
}// ChartSeriesGroup
export interface ChartLegendLayout {
// ChartLegendLayout properties
left: number;
top: number;
width: number | string;
height: number | string;
flow: string;
}// ChartLegendLayout
export interface ChartOptions {
// ChartOptions properties
title?: string;
description?: string;
source?: any;
showBorderLine?: boolean;
borderLineColor?: string;
borderLineWidth?: number;
backgroundColor?: string;
backgroundImage?: string;
showLegend?: boolean;
legendLayout?: ChartLegendLayout;
padding?: ChartPadding;
titlePadding?: ChartPadding;
colorScheme?: string;
greyScale?: boolean;
showToolTips?: boolean;
toolTipShowDelay?: number;
toolTipHideDelay?: number;
toolTipMoveDuration?: number;
drawBefore?: (renderer?: ChartDrawBefore['renderer'], rect?: ChartDrawBefore['rect']) => void;
draw?: (renderer?: ChartDraw['renderer'], rect?: ChartDraw['rect']) => void;
rtl?: boolean;
enableCrosshairs?: boolean;
crosshairsColor?: string;
crosshairsDashStyle?: string;
crosshairsLineWidth?: number;
columnSeriesOverlap?: boolean;
enabled?: boolean;
enableAnimations?: boolean;
animationDuration?: number;
enableAxisTextAnimation?: boolean;
renderEngine?: string;
xAxis?: ChartXAxis;
valueAxis?: ChartValueAxis;
categoryAxis?: any;
seriesGroups: Array<ChartSeriesGroup>;
}// ChartOptions
export interface jqxChart extends widget, ChartOptions {
// jqxChart functions
getInstance(): any;
refresh(): void;
update(): void;
destroy(): void;
addColorScheme(schemeName: string, colors: Array<string>): void;
removeColorScheme(schemeName: string): void;
getItemsCount(groupIndex: number, serieIndex: number): number;
getItemCoord(groupIndex: number, serieIndex: number, itemIndex: number): any;
getXAxisRect(groupIndex: number): ChartRect;
getXAxisLabels(groupIndex: number): Array<any>;
getValueAxisRect(groupIndex: number): ChartRect;
getValueAxisLabels(groupIndex: number): Array<any>;
getColorScheme(colorScheme: string): Array<string>;
hideSerie(groupIndex: number, serieIndex: number, itemIndex?: number): void;
showSerie(groupIndex: number, serieIndex: number, itemIndex?: number): void;
hideToolTip(hideDelay: number): void;
showToolTip(groupIndex: number, serieIndex: number, itemIndex: number, showDelay?: number, hideDelay?: number): void;
saveAsJPEG(fileName: string, exportServerUrl?: string): void;
saveAsPNG(fileName: string, exportServerUrl?: string): void;
saveAsPDF(fileName: string, exportServerUrl?: string): void;
getXAxisValue(offset: number, groupIndex: number): any;
getValueAxisValue(offset: number, groupIndex: number): any;
}// jqxChart
export interface CheckBoxOptions {
// CheckBoxOptions properties
animationShowDelay?: number;
animationHideDelay?: number;
boxSize?: number | string;
checked?: boolean | null;
disabled?: boolean;
enableContainerClick?: boolean;
groupName?: string;
height?: number | string;
hasThreeStates?: boolean;
locked?: boolean;
rtl?: boolean;
theme?: string;
width?: number | string;
}// CheckBoxOptions
export interface jqxCheckBox extends widget, CheckBoxOptions {
// jqxCheckBox functions
check(): void;
disable(): void;
destroy(): void;
enable(): void;
focus(): void;
indeterminate(): void;
render(): void;
toggle(): void;
uncheck(): void;
val(value: boolean): boolean;
}// jqxCheckBox
export interface ColorPickerOptions {
// ColorPickerOptions properties
color?: string;
colorMode?: string;
disabled?: boolean;
height?: string | number;
showTransparent?: boolean;
width?: string | number;
}// ColorPickerOptions
export interface jqxColorPicker extends widget, ColorPickerOptions {
// jqxColorPicker functions
getColor(): any;
setColor(color: any): void;
}// jqxColorPicker
export interface ComboBoxRenderer {
// ComboBoxRenderer properties
index?: number;
label?: number | string;
value?: number | string;
}// ComboBoxRenderer
export interface ComboBoxRenderSelectedItem {
// ComboBoxRenderSelectedItem properties
index?: number;
item?: any;
}// ComboBoxRenderSelectedItem
export interface ComboBoxSearch {
// ComboBoxSearch properties
searchString?: string;
}// ComboBoxSearch
export interface ComboBoxValidateSelection {
// ComboBoxValidateSelection properties
itemValue?: string;
}// ComboBoxValidateSelection
export interface ComboBoxOptions {
// ComboBoxOptions properties
animationType?: string;
autoComplete?: boolean;
autoOpen?: boolean;
autoItemsHeight?: boolean;
autoDropDownHeight?: boolean;
closeDelay?: number;
checkboxes?: boolean;
disabled?: boolean;
displayMember?: string;
dropDownHorizontalAlignment?: string;
dropDownVerticalAlignment?: string;
dropDownHeight?: number | string;
dropDownWidth?: number | string;
enableHover?: boolean;
enableSelection?: boolean;
enableBrowserBoundsDetection?: boolean;
height?: string | number;
itemHeight?: number;
multiSelect?: boolean;
minLength?: number;
openDelay?: number;
popupZIndex?: number;
placeHolder?: string;
remoteAutoComplete?: boolean;
remoteAutoCompleteDelay?: number;
renderer?: (index?: ComboBoxRenderer['index'], label?: ComboBoxRenderer['label'], value?: ComboBoxRenderer['value']) => string;
renderSelectedItem?: (index?: ComboBoxRenderSelectedItem['index'], item?: ComboBoxRenderSelectedItem['item']) => string;
rtl?: boolean;
selectedIndex?: number;
showArrow?: boolean;
showCloseButtons?: boolean;
searchMode?: string;
search?: (searchString?: ComboBoxSearch['searchString']) => void;
source?: any;
scrollBarSize?: number | string;
template?: string;
theme?: string;
validateSelection?: (itemValue?: ComboBoxValidateSelection['itemValue']) => boolean;
valueMember?: string;
width?: string | number;
}// ComboBoxOptions
export interface jqxComboBox extends widget, ComboBoxOptions {
// jqxComboBox functions
addItem(item: any): boolean;
clearSelection(): void;
clear(): void;
close(): void;
checkIndex(index: number): void;
checkItem(item: any): void;
checkAll(): void;
destroy(): void;
disableItem(item: any): void;
disableAt(index: number): void;
enableItem(item: any): void;
enableAt(index: number): void;
ensureVisible(index: number): void;
focus(): void;
getItem(index: number): any;
getItemByValue(value: string): any;
getVisibleItems(): Array<any>;
getItems(): Array<any>;
getCheckedItems(): Array<any>;
getSelectedItem(): any;
getSelectedItems(): Array<any>;
getSelectedIndex(): number;
insertAt(item: any, index: number): boolean;
isOpened(): boolean;
indeterminateIndex(index: number): void;
indeterminateItem(item: any): void;
loadFromSelect(selectTagId: string): void;
open(): void;
removeItem(item: any): boolean;
removeAt(index: number): boolean;
selectIndex(index: number): void;
selectItem(item: any): void;
searchString(): string;
updateItem(item: any, itemValue: string): void;
updateAt(item: any, index: any): void;
unselectIndex(index: number): void;
unselectItem(item: any): void;
uncheckIndex(index: number): void;
uncheckItem(item: any): void;
uncheckAll(): void;
val(value: string): string;
}// jqxComboBox
export interface ComplexInputOptions {
// ComplexInputOptions properties
decimalNotation?: string;
disabled?: boolean;
height?: string | number;
placeHolder?: string;
roundedCorners?: boolean;
rtl?: boolean;
spinButtons?: boolean;
spinButtonsStep?: number;
template?: string;
theme?: string;
value?: string;
width?: string | number;
}// ComplexInputOptions
export interface jqxComplexInput extends widget, ComplexInputOptions {
// jqxComplexInput functions
destroy(): void;
getDecimalNotation(part: string, decimalNotation: string): string;
getReal(complexnumber: number): number;
getImaginary(complexnumber: number): number;
render(): void;
refresh(): void;
val(value: any): string;
}// jqxComplexInput
export interface DataTableColumns {
// DataTableColumns properties
text: string;
dataField: string;
displayField?: string;
sortable?: boolean;
filterable?: boolean;
hidden?: boolean;
columnGroup ?: string;
autoCellHeight?: boolean;
renderer?: (text:string, align?:string, height?: string | number) => string;
rendered?: (element:any, align?:string, height?: string | number) => boolean;
cellsRenderer?: (row:number, column?:any, value?: any, rowData?:any) => string;
columnType?: string;
validation?: (cell:number, value?:any) => any;
initEditor?: (row:number, cellValue?:any, editor?:any, cellText?:string, width?:string | number, height?:string | number) => void;
createEditor?: (row:number, cellValue?:any, editor?:any, cellText?:string, width?:string | number, height?:string | number) => void;
getEditorValue?: (row:number, cellValue?:any, editor?:any) => void;
cellsFormat?: string;
aggregates?: Array<any>;
aggregatesRenderer?: (aggregates?: any, column?: any, element?: any) => string;
align?: string;
cellsAlign?: string;
width?: number | string;
minWidth?: number | string;
maxWidth?: number | string;
resizable?: boolean;
draggable?: boolean;
editable?: boolean;
className?: string;
cellClassName?: any;
pinned?: boolean;
}// DataTableColumns
export interface DataTableColumnGroups {
// DataTableColumnGroups properties
text?: string;
parentGroup?: string;
align?: string;
name?: string;
}// DataTableColumnGroups
export interface DataTableGroupsRenderer {
// DataTableGroupsRenderer properties
value?: string;
rowdata?: any;
level?: number;
}// DataTableGroupsRenderer
export interface DataTableInitRowDetails {
// DataTableInitRowDetails properties
id?: number;
row?: number;
element?: any;
rowinfo?: any;
}// DataTableInitRowDetails
export interface DataTableRenderToolbar {
// DataTableRenderToolbar properties
toolbar?: any;
}// DataTableRenderToolbar
export interface DataTableRenderStatusBar {
// DataTableRenderStatusBar properties
statusbar?: any;
}// DataTableRenderStatusBar
export interface DataTableEditSettings {
// DataTableEditSettings properties
saveOnPageChange?: boolean;
saveOnBlur?: boolean;
saveOnSelectionChange?: boolean;
cancelOnEsc?: boolean;
saveOnEnter?: boolean;
editSingleCell?: boolean;
editOnDoubleClick?: boolean;
editOnF2?: boolean;
}// DataTableEditSettings
export interface DataTableExportSettings {
// DataTableExportSettings properties
columnsHeader?: boolean;
hiddenColumns?: boolean;
serverURL?: any;
characterSet?: any;
recordsInView?: boolean;
fileName?: string;
}// DataTableExportSettings
export interface DataTableOptions {
// DataTableOptions properties
altRows?: boolean;
autoRowHeight?: boolean;
aggregatesHeight?: number;
autoShowLoadElement?: boolean;
columnsHeight?: number;
columns?: Array<DataTableColumns>;
columnGroups?: Array<DataTableColumnGroups>;
columnsResize?: boolean;
columnsReorder?: boolean;
disabled?: boolean;
editable?: boolean;
editSettings?: DataTableEditSettings;
exportSettings?: DataTableExportSettings;
enableHover?: boolean;
enableBrowserSelection?: boolean;
filterable?: boolean;
filterHeight?: number;
filterMode?: string;
groups?: Array<any>;
groupsRenderer?: (value?:DataTableGroupsRenderer['value'], rowData?:DataTableGroupsRenderer['rowdata'], level?:DataTableGroupsRenderer['level']) => string;
height?: number | string;
initRowDetails?: (id?:DataTableInitRowDetails['id'], row?:DataTableInitRowDetails['row'], element?:DataTableInitRowDetails['element'], rowInfo?:DataTableInitRowDetails['rowinfo']) => void;
incrementalSearch?: boolean;
localization?: any;
pagerHeight?: number;
pageSize?: number;
pageSizeOptions?: Array<string | number>;
pageable?: boolean;
pagerPosition?: string;
pagerMode?: string;
pagerButtonsCount?: number;
pagerRenderer?: () => any;
ready?: () => void;
rowDetails?: boolean;
renderToolbar?: (toolbar?:DataTableRenderToolbar['toolbar']) => void;
renderStatusBar?: (statusbar?:DataTableRenderStatusBar['statusbar']) => void;
rendering?: () => void;
rendered?: () => void;
rtl?: boolean;
source?: any;
sortable?: boolean;
showAggregates?: boolean;
showToolbar?: boolean;
showStatusbar?: boolean;
statusBarHeight?: number;
scrollBarSize?: number | string;
selectionMode?: string;
serverProcessing?: boolean;
showHeader?: boolean;
theme?: string;
toolbarHeight?: number;
width?: string | number;
}// DataTableOptions
export interface jqxDataTable extends widget, DataTableOptions {
// jqxDataTable functions
addRow(rowIndex: number, rowData: any, rowPosition: any): void;
addFilter(dataField: string, filerGroup: any): void;
applyFilters(): void;
beginUpdate(): void;
beginRowEdit(rowIndex: number): void;
beginCellEdit(rowIndex: number, dataField: string): void;
clearSelection(): void;
clearFilters(): void;
clear(): void;
destroy(): void;
deleteRow(rowIndex: number): void;
endUpdate(): void;
ensureRowVisible(rowIndex: number): void;
endRowEdit(rowIndex: number, cancelChanges: boolean): void;
endCellEdit(rowIndex: number, dataField: string): void;
exportData(exportDataType: any): any;
focus(): void;
getColumnProperty(dataField: string, propertyName: string): any;
goToPage(pageIndex: number): void;
goToPrevPage(): void;
goToNextPage(): void;
getSelection(): Array<any>;
getRows(): Array<any>;
getView(): Array<any>;
getCellValue(rowIndex: number, dataField: string): any;
hideColumn(dataField: string): void;
hideDetails(rowIndex: boolean): void;
isBindingCompleted(): boolean;
lockRow(rowIndex: number): void;
refresh(): void;
render(): void;
removeFilter(dataField: string): void;
scrollOffset(top: number, left: number): void;
setColumnProperty(dataField: string, propertyName: string, propertyValue: any): void;
showColumn(dataField: string): void;
selectRow(rowIndex: number): void;
showDetails(rowIndex: number): void;
setCellValue(rowIndex: number, dataField: string, value: any): void;
sortBy(dataField: string, sortOrder: any): void;
updating(): boolean;
updateBoundData(): void;
unselectRow(rowIndex: number): void;
updateRow(rowIndex: number, rowData: any): void;
unlockRow(rowIndex: number): void;
}// jqxDataTable
export interface DateTimeInputOptions {
// DateTimeInputOptions properties
animationType?: string;
allowNullDate?: boolean;
allowKeyboardDelete?: boolean;
clearString?: string;
culture?: string;
closeDelay?: number;
closeCalendarAfterSelection?: boolean;
dropDownHorizontalAlignment?: string;
dropDownVerticalAlignment?: string;
disabled?: boolean;
enableBrowserBoundsDetection?: boolean;
enableAbsoluteSelection?: boolean;
editMode?: string;
firstDayOfWeek?: number;
formatString?: string;
height?: string | number;
min?: Date;
max?: Date;
openDelay?: number;
placeHolder?: string;
popupZIndex?: number;
rtl?: boolean;
readonly?: boolean;
showFooter?: boolean;
selectionMode?: string;
showWeekNumbers?: boolean;
showTimeButton?: boolean;
showCalendarButton?: boolean;
theme?: string;
template?: string;
textAlign?: string;
todayString?: string;
value?: Date | null;
width?: string | number;
yearCutoff?: number;
}// DateTimeInputOptions
export interface jqxDateTimeInput extends widget, DateTimeInputOptions {
// jqxDateTimeInput functions
close(): void;
destroy(): void;
focus(): void;
getRange(): any;
getText(): string;
getDate(): any;
getMaxDate(): any;
getMinDate(): any;
open(): void;
setRange(date: any, date2: any): void;
setMinDate(date: any): void;
setMaxDate(date: any): void;
setDate(date: any): void;
val(value: any, value2: any): any;
}// jqxDateTimeInput
export interface DockingCookieOptions {
// DockingCookieOptions properties
domain?: string;
expires?: number;
}// DockingCookieOptions
export interface DockingOptions {
// DockingOptions properties
cookies?: boolean;
cookieOptions?: DockingCookieOptions;
disabled?: boolean;
floatingWindowOpacity?: number;
height?: number | string;
keyboardNavigation?: boolean;
mode?: string;
orientation?: string;
rtl?: boolean;
theme?: string;
width?: number | string;
windowsMode?: object;
windowsOffset?: number;
}// DockingOptions
export interface jqxDocking extends widget, DockingOptions {
// jqxDocking functions
addWindow(windowId: string, mode: any, panel: number, position: any): void;
closeWindow(windowId: string): void;
collapseWindow(windowId: string): void;
destroy(): void;
disableWindowResize(windowId: string): void;
disable(): void;
exportLayout(): string;
enable(): void;
expandWindow(windowId: string): void;
enableWindowResize(windowId: string): void;
focus(): void;
hideAllCloseButtons(): void;
hideAllCollapseButtons(): void;
hideCollapseButton(windowId: string): void;
hideCloseButton(windowId: string): void;
importLayout(Json: string): void;
move(windowId: string, panel: number, position: number): void;
pinWindow(windowId: string): void;
setWindowMode(windowId: string, mode: any): void;
showCloseButton(windowId: string): void;
showCollapseButton(windowId: string): void;
setWindowPosition(windowId: string, top: any, left: number): void;
showAllCloseButtons(): void;
showAllCollapseButtons(): void;
unpinWindow(windowId: string): void;
}// jqxDocking
export interface DockingLayoutLayout {
// DockingLayoutLayout properties
type: string;
alignment?: string;
allowClose?: boolean;
allowPin?: boolean;
allowUnpin?: boolean;
contentContainer?: string;
height?: number | string;
initContent?: () => void;
minHeight?: number | string;
minWidth?: number | string;
orientation?: string;
pinnedHeight?: number | string;
pinnedWidth?: number | string;
position?: DockingLayoutLayoutPosition;
selected?: boolean;
title?: string;
unpinnedHeight?: number | string;
unpinnedWidth?: number | string;
width?: number | string;
items?: Array<DockingLayoutLayout>;
}// DockingLayoutLayout
export interface DockingLayoutLayoutPosition {
// DockingLayoutLayoutPosition properties
x: number;
y: number;
}// DockingLayoutLayoutPosition
export interface DockingLayoutOptions {
// DockingLayoutOptions properties
contextMenu?: boolean;
height?: string | number;
layout?: Array<DockingLayoutLayout>;
minGroupHeight?: number | string;
minGroupWidth?: number | string;
resizable?: boolean;
rtl?: boolean;
theme?: string;
width?: string | number;
}// DockingLayoutOptions
export interface jqxDockingLayout extends widget, DockingLayoutOptions {
// jqxDockingLayout functions
addFloatGroup(width: number | string, height: number | string, position: DockingLayoutLayoutPosition, panelType: string, title: string, content: string, initContent: any): void;
destroy(): void;
loadLayout(layout: any): void;
refresh(): void;
render(): void;
saveLayout(): any;
}// jqxDockingLayout
export interface DockPanelOptions {
// DockPanelOptions properties
disabled?: boolean;
height?: string | number;
lastchildfill?: boolean;
width?: string | number;
}// DockPanelOptions
export interface jqxDockPanel extends widget, DockPanelOptions {
// jqxDockPanel functions
refresh(): void;
}// jqxDockPanel
export interface DragDropOnDrag {
// DragDropOnDrag properties
data?: any;
position?: object;
}// DragDropOnDrag
export interface DragDropOnDragStart {
// DragDropOnDragStart properties
position?: object;
}// DragDropOnDragStart
export interface DragDropOnTargetDrop {
// DragDropOnTargetDrop properties
data?: any;
}// DragDropOnTargetDrop
export interface DragDropOnDropTargetLeave {
// DragDropOnDropTargetLeave properties
data?: any;
}// DragDropOnDropTargetLeave
export interface DragDropOptions {
// DragDropOptions properties
appendTo?: string;
disabled?: boolean;
distance?: number;
data?: any;
dropAction?: string;
dropTarget?: any;
dragZIndex?: number;
feedback?: string;
initFeedback?: (feedback?:any) => void;
opacity?: number;
onDragEnd?: () => void;
onDrag?: (data?: DragDropOnDrag['data'], position?: DragDropOnDrag['position']) => void;
onDragStart?: (position?: DragDropOnDragStart['position']) => void;
onTargetDrop?: (data?: DragDropOnTargetDrop['data']) => void;
onDropTargetEnter?: () => void;
onDropTargetLeave?: (data?: DragDropOnDropTargetLeave['data']) => void;
restricter?: string | object;
revert?: boolean;
revertDuration?: number;
tolerance?: string;
}// DragDropOptions
export interface jqxDragDrop extends widget, DragDropOptions {
// jqxDragDrop functions
}// jqxDragDrop
export interface DrawOptions {
// DrawOptions properties
renderEngine?: string;
}// DrawOptions
export interface jqxDraw extends widget, DrawOptions {
// jqxDraw functions
attr(element: any, attributes: any): void;
circle(cx: number, cy: number, r: number, attributes: any): any;
clear(): void;
getAttr(element: any, attributes: any): string;
getSize(): any;
line(x1: number, y1: number, x2: number, y2: number, attributes: any): any;
measureText(text: string, angle: number, attributes: any): any;
on(element: any, event: string, func: any): void;
off(element: any, event: string, func: any): void;
path(path: string, attributes: any): any;
pieslice(cx: number, xy: number, innerRadius: any, outerRadius: any, fromAngle: number, endAngle: number, centerOffset: number, attributes: any): any;
refresh(): void;
rect(x: number, y: number, width: number | string, height: number | string, attributes: any): any;
saveAsJPEG(image: string, url: string): void;
saveAsPNG(image: string, url: string): void;
text(text: string, x: number, y: number, width: number | string, height: number | string, angle: number, attributes: any, clip: boolean, halign: string, valign: string, rotateAround: string): any;
}// jqxDraw
export interface DropDownButtonOptions {
// DropDownButtonOptions properties
animationType?: string;
arrowSize?: number;
autoOpen?: boolean;
closeDelay?: number;
disabled?: boolean;
dropDownHorizontalAlignment?: string;
dropDownVerticalAlignment?: string;
dropDownWidth?: number | string;
enableBrowserBoundsDetection?: boolean;
height?: string | number;
initContent?: () => void;
openDelay?: number;
popupZIndex?: number;
rtl?: boolean;
template?: string;
theme?: string;
width?: string | number;
}// DropDownButtonOptions
export interface jqxDropDownButton extends widget, DropDownButtonOptions {
// jqxDropDownButton functions
close(): void;
destroy(): void;
focus(): void;
getContent(): any;
isOpened(): boolean;
open(): void;
setContent(content: string): void;
}// jqxDropDownButton
export interface DropDownListItem {
// DropDownListItem properties
label?: string;
value?: any;
disabled?: boolean;
checked?: any;
hasThreeStates?: boolean;
html?: string;
group?: string;
}// DropDownListItem
export interface DropDownListRenderer {
// DropDownListRenderer properties
index?: number;
label?: string;
value?: string;
}// DropDownListRenderer
export interface DropDownListSelectionRenderer {
// DropDownListSelectionRenderer properties
element?: any;
index?: number;
label?: string;
value?: any;
}// DropDownListSelectionRenderer
export interface DropDownListOptions {
// DropDownListOptions properties
autoOpen?: boolean;
autoDropDownHeight?: boolean;
animationType?: string;
checkboxes?: boolean;
closeDelay?: number;
disabled?: boolean;
displayMember?: string;
dropDownHorizontalAlignment?: string;
dropDownVerticalAlignment?: string;
dropDownHeight?: number | string;
dropDownWidth?: number | string;
enableSelection?: boolean;
enableBrowserBoundsDetection?: boolean;
enableHover?: boolean;
filterable?: boolean;
filterHeight?: number;
filterDelay?: number;
filterPlaceHolder?: string;
height?: number | string;
incrementalSearch?: boolean;
incrementalSearchDelay?: number;
itemHeight?: number;
openDelay?: number;
placeHolder?: string;
popupZIndex?: number;
rtl?: boolean;
renderer?: (index?: DropDownListRenderer['index'], label?: DropDownListRenderer['label'], value?: DropDownListRenderer['value']) => string;
selectionRenderer?: (element?: DropDownListSelectionRenderer['element'], index?: DropDownListSelectionRenderer['index'], label?: DropDownListSelectionRenderer['label'], value?: DropDownListSelectionRenderer['value']) => string;
searchMode?: string;
source?: Array<any>;
selectedIndex?: number;
theme?: string;
template?: string;
valueMember?: string;
width?: number | string;
}// DropDownListOptions
export interface jqxDropDownList extends widget, DropDownListOptions {
// jqxDropDownList functions
addItem(item: DropDownListItem): boolean;
clearSelection(): void;
clear(): void;
close(): void;
checkIndex(index: number): void;
checkItem(item: any): void;
checkAll(): void;
clearFilter(): void;
destroy(): void;
disableItem(item: any): void;
disableAt(index: number): void;
enableItem(item: any): void;
enableAt(index: number): void;
ensureVisible(index: number): void;
focus(): void;
getItem(index: number): DropDownListItem;
getItemByValue(itemValue: string): DropDownListItem;
getItems(): Array<DropDownListItem>;
getCheckedItems(): Array<DropDownListItem>;
getSelectedItem(): DropDownListItem;
getSelectedIndex(): number;
insertAt(item: DropDownListItem, index: number): void;
isOpened(): boolean;
indeterminateIndex(index: number): void;
indeterminateItem(item: any): void;
loadFromSelect(arg: string): void;
open(): void;
removeItem(item: any): void;
removeAt(index: number): void;
selectIndex(index: number): void;
selectItem(item: DropDownListItem): void;
setContent(content: string): void;
updateItem(newItem: DropDownListItem, item: any): void;
updateAt(item: DropDownListItem, index: number): void;
unselectIndex(index: number): void;
unselectItem(item: any): void;
uncheckIndex(index: number): void;
uncheckItem(item: any): void;
uncheckAll(): void;
val(value: string): string;
}// jqxDropDownList
export interface EditorLocalization {
// EditorLocalization properties
bold?: string;
italic?: string;
underline?: string;
format?: string;
size?: number | string;
font?: string;
html?: string;
color?: string;
background?: string;
left?: string;
center?: string;
right?: string;
outdent?: string;
indent?: string;
ul?: string;
ol?: string;
image?: string;
link?: string;
clean?: string;
}// EditorLocalization
export interface EditorCreateCommand {
// EditorCreateCommand properties
name?: string;
}// EditorCreateCommand
export interface EditorOptions {
// EditorOptions properties
createCommand?: (name:EditorCreateCommand['name']) => void;
disabled?: boolean;
editable?: boolean;
height?: string | number;
lineBreak?: string;
localization?: EditorLocalization;
pasteMode?: string;
rtl?: boolean;
stylesheets?: Array<any>;
theme?: string;
toolbarPosition?: string;
tools?: string;
width?: string | number;
}// EditorOptions
export interface jqxEditor extends widget, EditorOptions {
// jqxEditor functions
destroy(): void;
focus(): void;
print(): void;
setMode(mode: boolean): void;
val(value: string): string;
}// jqxEditor
export interface ExpanderOptions {
// ExpanderOptions properties
animationType?: string;
arrowPosition?: string;
collapseAnimationDuration?: number;
disabled?: boolean;
expanded?: boolean;
expandAnimationDuration?: number;
height?: number | string;
headerPosition?: string;
initContent?: () => void;
rtl?: boolean;
showArrow?: boolean;
theme?: string;
toggleMode?: string;
width?: number | string;
}// ExpanderOptions
export interface jqxExpander extends widget, ExpanderOptions {
// jqxExpander functions
collapse(): void;
disable(): void;
destroy(): void;
enable(): void;
expand(): void;
focus(): void;
getContent(): string;
getHeaderContent(): string;
invalidate(): void;
refresh(): void;
render(): void;
setHeaderContent(headerContent: string): void;
setContent(content: string): void;
}// jqxExpander
export interface FileUploadLocalization {
// FileUploadLocalization properties
browseButton?: string;
uploadButton?: string;
cancelButton?: string;
uploadFileTooltip?: string;
cancelFileTooltip?: string;
}// FileUploadLocalization
export interface FileUploadRenderFiles {
// FileUploadRenderFiles properties
fileName?: string;
}// FileUploadRenderFiles
export interface FileUploadOptions {
// FileUploadOptions properties
autoUpload?: boolean;
accept?: string;
browseTemplate?: string;
cancelTemplate?: string;
disabled?: boolean;
fileInputName?: string;
height?: number | string;
localization?: FileUploadLocalization;
multipleFilesUpload?: boolean;
renderFiles?: (filename:FileUploadRenderFiles['fileName']) => void;
rtl?: boolean;
theme?: string;
uploadUrl?: string;
uploadTemplate?: string;
width?: string | number;
}// FileUploadOptions
export interface jqxFileUpload extends widget, FileUploadOptions {
// jqxFileUpload functions
browse(): void;
cancelFile(fileIndex: number): void;
cancelAll(): void;
destroy(): void;
render(): void;
refresh(): void;
uploadFile(fileIndex: number): void;
uploadAll(): void;
}// jqxFileUpload
export interface FormPadding {
// FormPadding properties
left: number | string;
right: number | string;
top: number | string;
bottom: number | string;
}// FormPadding
export interface FormTemplateItem {
// FormTemplateItem properties
name?: string;
text?: string;
type?: string;
bind?: string;
submit?: boolean;
required?: boolean;
requiredPosition?: string;
info?: string;
infoPosition?: string;
component?: string;
init?: (value: any) => void;
label?: string;
labelPosition?: string;
labelAlign?: string;
align?: string;
valign?: string;
labelValign?: string;
height?: number | string;
rowHeight?: number | string;
width?: number | string;
columnWidth?: number | string;
labelWidth?: number | string;
labelHeight?: number | string;
padding?: FormPadding;
labelPadding?: FormPadding;
columns?: Array<FormTemplateItem>;
optionsLayout?: string;
options?: Array<any>;
}// FormTemplateItem
export interface FormOptions {
// FormOptions properties
padding?: FormPadding;
backgroundColor?: string;
borderColor?: string;
value?: any;
template: Array<FormTemplateItem>;
}// FormOptions
export interface jqxForm extends widget, FormOptions {
// jqxForm functions
getInstance(): any;
refresh(): void;
destroy(): void;
hideComponent(name: string): void;
showComponent(name: string): void;
val(value?: any): any;
submit(action?: string, target?: string, method?: string): void;
getComponentByName(name?: string): any;
}// jqxForm
export interface FormattedInputOptions {
// FormattedInputOptions properties
disabled?: boolean;
decimalNotation?: string;
dropDown?: boolean;
dropDownWidth?: number | string;
height?: number | string;
min?: number | string;
max?: number | string;
placeHolder?: string;
popupZIndex?: number;
roundedCorners?: boolean;
rtl?: boolean;
radix?: number | string;
spinButtons?: boolean;
spinButtonsStep?: number;
template?: string;
theme?: string;
upperCase?: boolean;
value?: any;
width?: number | string;
}// FormattedInputOptions
export interface jqxFormattedInput extends widget, FormattedInputOptions {
// jqxFormattedInput functions
close(): void;
destroy(): void;
focus(): void;
open(): void;
render(): void;
refresh(): void;
selectAll(): void;
selectFirst(): void;
selectLast(): void;
val(value: number | string): any;
}// jqxFormattedInput
export interface GaugeStyle {
// GaugeStyle properties
fill?: string;
stroke?: string;
}// GaugeStyle
export interface GaugeBorder {
// GaugeBorder properties
size?: number | string;
visible?: boolean;
style?: GaugeStyle;
showGradient?: boolean;
}// GaugeBorder
export interface GaugeCaption {
// GaugeCaption properties
value?: string;
position?: string;
offset?: Array<number>;
visible?: boolean;
}// GaugeCaption
export interface GaugeCap {
// GaugeCap properties
size?: number | string;
visible?: boolean;
style?: GaugeStyle;
}// GaugeCap
export interface GaugeLabels {
// GaugeLabels properties
distance?: string;
position?: string;
interval?: number | string;
offset?: Array<number>;
visible?: boolean;
formatValue?: (value?: number) => string;
}// GaugeLabels
export interface GaugePointer {
// GaugePointer properties
pointerType?: string;
style?: GaugeStyle;
width?: number | string;
length?: number | string;
visible?: boolean;
}// GaugePointer
export interface GaugeRanges {
// GaugeRanges properties
startValue: number | string;
endValue: number | string;
startWidth: number | string;
endWidth: number | string;
startDistance?: number | string;
endDistance?: number | string;
style: GaugeStyle;
}// GaugeRanges
export interface GaugeTicks {
// GaugeTicks properties
size: number | string;
interval: number | string;
visible?: boolean;
style?: GaugeStyle;
}// GaugeTicks
export interface GaugeOptions {
// GaugeOptions properties
animationDuration?: string | number;
border?: GaugeBorder;
caption?: GaugeCaption;
cap?: GaugeCap;
colorScheme?: string;
disabled?: boolean;
easing?: string;
endAngle?: number | string;
height?: number | string;
int64?: boolean;
labels?: GaugeLabels;
min?: number;
max?: number | string;
pointer?: GaugePointer;
radius?: number | string;
ranges?: Array<GaugeRanges>;
startAngle?: number | string;
showRanges?: boolean;
styles?: GaugeStyle;
ticksMajor?: GaugeTicks;
ticksMinor?: GaugeTicks;
ticksDistance?: string;
value?: number;
width?: number | string;
}// GaugeOptions
export interface jqxGauge extends widget, GaugeOptions {
// jqxGauge functions
disable(): void;
enable(): void;
val(value: number): number;
}// jqxGauge
export interface ValidationResult {
// ValidationResult properties
result: boolean;
message?: string;
}// ValidationResult
export interface GridCharting {
// GridCharting properties
appendTo?: string;
colorScheme?: string;
dialog?: (width: number, height: number, header: string, position: any, enabled: boolean) => void;
formatSettings?: any;
ready?: any;
}// GridCharting
export interface GridColumn {
// GridColumn properties
text?: string;
datafield?: string;
displayfield?: string;
threestatecheckbox?: boolean;
sortable?: boolean;
filterable?: boolean;
filter?: (cellValue?: any, rowData?: any, dataField?: string, filterGroup?: any, defaultFilterResult?: any) => any;
buttonclick?: (row: number) => void;
hideable?: boolean;
hidden?: boolean;
groupable?: boolean;
menu?: boolean;
exportable?: boolean;
columngroup?: string;
enabletooltips?: boolean;
columntype?: string;
renderer?: (defaultText?: string, alignment?: string, height?: number) => string;
rendered?: (columnHeaderElement?: any) => void;
cellsrenderer?: (row?: number, columnfield?: string, value?: any, defaulthtml?: string, columnproperties?: any, rowdata?: any) => string;
aggregatesrenderer?: (aggregates?: any, column?: any, element?: any, summaryData?: any) => string;
validation?: (cell?: any, value?: number) => any;
createwidget?: (row: any, column: any, value: string, cellElement: any) => void;
initwidget?: (row: number, column: string, value: string, cellElement: any) => void;
createfilterwidget?: (column: any, htmlElement: HTMLElement, editor: any) => void;
createfilterpanel?: (datafield: string, filterPanel: any) => void;
initeditor?: (row: number, cellvalue: any, editor: any, celltext: any, pressedChar: string, callback: any) => void;
createeditor?: (row: number, cellvalue: any, editor: any, celltext: any, cellwidth: any, cellheight: any) => void;
destroyeditor?: (row: number, callback: any) => void;
geteditorvalue?: (row: number, cellvalue:any, editor:any) => any;
cellbeginedit?: (row: number, datafield: string, columntype: string, value: any) => boolean;
cellendedit?: (row: number, datafield: string, columntype: string, oldvalue: any, newvalue: any) => boolean;
cellvaluechanging?: (row: number, datafield: string, columntype: string, oldvalue: any, newvalue: any) => string | void;
createeverpresentrowwidget?: (datafield: string, htmlElement: HTMLElement, popup: any, addRowCallback: any) => any;
initeverpresentrowwidget?: (datafield: string, htmlElement: HTMLElement, popup: any) => void;
reseteverpresentrowwidgetvalue?: (datafield: string, htmlElement: HTMLElement) => void;
geteverpresentrowwidgetvalue?: (datafield: string, htmlElement: HTMLElement) => any;
destroyeverpresentrowwidget?: (htmlElement: HTMLElement) => void;
validateeverpresentrowwidgetvalue?: (datafield: string, value: any, rowValues: any) => boolean | object;
cellsformat?: string;
cellclassname?: any;
aggregates?: any;
align?: string;
cellsalign?: string;
width?: number | string;
minwidth?: any;
maxwidth?: any;
resizable?: boolean;
draggable?: boolean;
editable?: boolean;
classname?: string;
pinned?: boolean;
nullable?: boolean;
filteritems?: any;
filterdelay?: number;
filtertype?: string;
filtercondition?: string;
}// GridColumn
export interface GridSourceDataFields {
// GridSourceDataFields properties
name: string;
type?: string;
format?: string;
map?: string;
id?: string;
text?: string;
source?: Array<any>;
}// GridSourceDataFields
export interface GridSource {
// GridSource properties
url?: string;
data?: any;
localdata?: any;
datatype?: string;
type?: string;
id?: string;
root?: string;
record?: string;
datafields?: Array<GridSourceDataFields>;
pagenum?: number;
pagesize?: number;
pager?: (pagenum?: number, pagesize?: number, oldpagenum?: number) => any;
sortcolumn?: string;
sortdirection?: string;
sort?: (column?: any, direction?: any) => void;
filter?: (filters?: any, recordsArray?: any) => void;
addrow?: (rowid?: any, rowdata?: any, position?: any, commit?: boolean) => void;
deleterow?: (rowid?: any, commit?: boolean) => void;
updaterow?: (rowid?: any, newdata?: any, commit? : any) => void;
processdata?: (data: any) => void;
formatdata?: (data: any) => any;
async?: boolean;
totalrecords?: number;
unboundmode?: boolean;
}// GridSource
export interface GridGetColumn {
// GridGetColumn properties
datafield?: string;
displayfield?: string;
text?: string;
sortable?: boolean;
filterable?: boolean;
exportable?: boolean;
editable?: boolean;
groupable?: boolean;
resizable?: boolean;
draggable?: boolean;
classname?: string;
cellclassname?: any;
width?: number | string;
menu?: boolean;
}// GridGetColumn
export interface GridGetDataInformation {
// GridGetDataInformation properties
rowscount?: string;
sortinformation?: any;
sortcolumn?: any;
sortdirection?: any;
paginginformation?: any;
pagenum?: any;
pagesize?: any;
pagescount?: any;
}// GridGetDataInformation
export interface GridGetSortInformation {
// GridGetSortInformation properties
sortcolumn?: string;
sortdirection?: any;
}// GridGetSortInformation
export interface GridGetPagingInformation {
// GridGetPagingInformation properties
pagenum?: string;
pagesize?: any;
pagescount?: any;
}// GridGetPagingInformation
export interface GridDateNaming {
// GridDateNaming properties
names?: Array<string>;
namesAbbr?: Array<string>;
namesShort?: Array<string>;
}// GridDateNaming
export interface GridLocalizationobject {
// GridLocalizationobject properties
filterstringcomparisonoperators?: any;
filternumericcomparisonoperators?: any;
filterdatecomparisonoperators?: any;
filterbooleancomparisonoperators?: any;
pagergotopagestring?: string;
pagershowrowsstring?: string;
pagerrangestring?: string;
pagernextbuttonstring?: string;
pagerpreviousbuttonstring?: string;
sortascendingstring?: string;
sortdescendingstring?: string;
sortremovestring?: string;
firstDay?: number;
percentsymbol?: string;
currencysymbol?: string;
currencysymbolposition?: string;
decimalseparator?: string;
thousandsseparator?: string;
days?: GridDateNaming;
months?: GridDateNaming;
addrowstring?: string;
updaterowstring?: string;
deleterowstring?: string;
resetrowstring?: string;
everpresentrowplaceholder?: string;
emptydatastring?: string;
}// GridLocalizationobject
export interface GridScrollPosition {
// GridScrollPosition properties
top?: number;
left?: number;
}// GridScrollPosition
export interface GridGetGroup {
// GridGetGroup properties
group?: number;
level?: number;
expanded?: number;
subgroups?: number;
subrows?: number;
}// GridGetGroup
export interface GridGetCell {
// GridGetCell properties
value?: number;
row?: number;
column?: number;
}// GridGetCell
export interface GridGetSelectedCell {
// GridGetSelectedCell properties
rowindex?: number;
datafield?: string;
}// GridGetSelectedCell
export interface GridGetStateColumns {
// GridGetStateColumns properties
width?: number | string;
hidden?: boolean;
index?: number;
pinned?: boolean;
groupable?: boolean;
resizable?: boolean;
draggable?: boolean;
text?: string;
align?: string;
cellsalign?: string;
}// GridGetStateColumns
export interface GridGetState {
// GridGetState properties
width?: number | string;
height?: number | string;
pagenum?: number;
pagesize?: number;
pagesizeoptions?: Array<string>;
sortcolumn?: any;
sortdirection?: any;
filters?: any;
groups?: any;
columns?: GridGetStateColumns;
}// GridGetState
export interface GridColumnmenuopening {
// GridColumnmenuopening properties
menu?: any;
datafield?: any;
height?: any;
}// GridColumnmenuopening
export interface GridColumnmenuclosing {
// GridColumnmenuclosing properties
menu?: any;
datafield?: any;
height?: any;
}// GridColumnmenuclosing
export interface GridCellhover {
// GridCellhover properties
cellhtmlElement?: any;
x?: any;
y?: any;
}// GridCellhover
export interface GridGroupsrenderer {
// GridGroupsrenderer properties
text?: string;
group?: number;
expanded?: boolean;
data?: object;
}// GridGroupsrenderer
export interface GridGroupcolumnrenderer {
// GridGroupcolumnrenderer properties
text?: any;
}// GridGroupcolumnrenderer
export interface GridHandlekeyboardnavigation {
// GridHandlekeyboardnavigation properties
event?: any;
}// GridHandlekeyboardnavigation
export interface GridScrollfeedback {
// GridScrollfeedback properties
row?: any;
}// GridScrollfeedback
export interface GridFilter {
// GridFilter properties
cellValue?: any;
rowData?: any;
dataField?: string;
filterGroup?: any;
defaultFilterResult?: boolean;
}// GridFilter
export interface GridRendertoolbar {
// GridRendertoolbar properties
toolbar?: any;
}// GridRendertoolbar
export interface GridRenderstatusbar {
// GridRenderstatusbar properties
statusbar?: any;
}// GridRenderstatusbar
export interface GridOptions {
// GridOptions properties
altrows?: boolean;
altstart?: number;
altstep?: number;
autoshowloadelement?: boolean;
autoshowfiltericon?: boolean;
autoshowcolumnsmenubutton?: boolean;
showcolumnlines?: boolean;
showrowlines?: boolean;
showcolumnheaderlines?: boolean;
adaptive?: boolean;
adaptivewidth?: number;
clipboard?: boolean;
closeablegroups?: boolean;
columnsmenuwidth?: number;
columnmenuopening?: (menu?: GridColumnmenuopening['menu'], datafield?: GridColumnmenuopening['datafield'], height?: GridColumnmenuopening['height']) => boolean | void;
columnmenuclosing?: (menu?: GridColumnmenuclosing['menu'], datafield?: GridColumnmenuclosing['datafield'], height?: GridColumnmenuclosing['height']) => boolean;
cellhover?: (cellhtmlElement?: GridCellhover['cellhtmlElement'], x?: GridCellhover['x'], y?: GridCellhover['y']) => void;
enablekeyboarddelete?: boolean;
enableellipsis?: boolean;
enablemousewheel?: boolean;
enableanimations?: boolean;
enabletooltips?: boolean;
enablehover?: boolean;
enablebrowserselection?: boolean;
everpresentrowposition?: string;
everpresentrowheight?: number;
everpresentrowactions?: string;
everpresentrowactionsmode?: string;
filterrowheight?: number;
filtermode?: string;
groupsrenderer?: (text?: GridGroupsrenderer['text'], group?: GridGroupsrenderer['group'], expanded?: GridGroupsrenderer['expanded'], data?: GridGroupsrenderer['data']) => string;
groupcolumnrenderer?: (text?: GridGroupcolumnrenderer['text']) => string;
groupsexpandedbydefault?: boolean;
handlekeyboardnavigation?: (event: GridHandlekeyboardnavigation['event']) => boolean;
pagerrenderer?: () => any[];
rtl?: boolean;
showdefaultloadelement?: boolean;
showfiltercolumnbackground?: boolean;
showfiltermenuitems?: boolean;
showpinnedcolumnbackground?: boolean;
showsortcolumnbackground?: boolean;
showsortmenuitems?: boolean;
showgroupmenuitems?: boolean;
showrowdetailscolumn?: boolean;
showheader?: boolean;
showgroupsheader?: boolean;
showaggregates?: boolean;
showgroupaggregates?: boolean;
showeverpresentrow?: boolean;
showfilterrow?: boolean;
showemptyrow?: boolean;
showstatusbar?: boolean;
statusbarheight?: number;
showtoolbar?: boolean;
showfilterbar?: boolean;
filterbarmode?: string;
selectionmode?: string;
updatefilterconditions?: (type?: string, defaultconditions?: any) => any;
updatefilterpanel?: (filtertypedropdown1?: any, filtertypedropdown2?: any, filteroperatordropdown?: any, filterinputfield1?: any, filterinputfield2?: any, filterbutton?: any, clearbutton?: any, columnfilter?: any, filtertype?: any, filterconditions?: any) => any;
theme?: string;
toolbarheight?: number;
autoheight?: boolean;
autorowheight?: boolean;
columnsheight?: number;
deferreddatafields?: Array<string>;
groupsheaderheight?: number;
groupindentwidth?: number;
height?: number | string;
pagerheight?: number | string;
rowsheight?: number;
scrollbarsize?: number | string;
scrollmode?: string;
scrollfeedback?: (row: GridScrollfeedback['row']) => string;
width?: string | number;
autosavestate?: boolean;
autoloadstate?: boolean;
columns?: GridColumn[];
cardview?: boolean;
cardviewcolumns?: any;
cardheight?: number;
cardsize?: number;
columngroups?: Array<any>;
columnsmenu?: boolean;
columnsresize?: boolean;
columnsautoresize?: boolean;
columnsreorder?: boolean;
charting?: GridCharting;
disabled?: boolean;
editable?: boolean;
editmode?: string;
filter?: (cellValue?: GridFilter['cellValue'], rowData?: GridFilter['rowData'], dataField?: GridFilter['dataField'], filterGroup?: GridFilter['filterGroup'], defaultFilterResult?: GridFilter['defaultFilterResult']) => any;
filterable?: boolean;
groupable?: boolean;
groups?: Array<string>;
horizontalscrollbarstep?: number;
horizontalscrollbarlargestep?: number;
initrowdetails?: (index?: number, parentElement?: any, gridElement?: any, datarecord?: any) => void;
keyboardnavigation?: boolean;
localization?: GridLocalizationobject;
pagesize?: number;
pagesizeoptions?: Array<number | string>;
pagermode?: 'simple' | 'default' | 'material';
pagerbuttonscount?: number;
pageable?: boolean;
autofill?: boolean;
rowdetails?: boolean;
rowdetailstemplate?: any;
ready?: () => void;
rendered?: (type: any) => void;
renderstatusbar?: (statusbar?: GridRenderstatusbar['statusbar']) => void;
rendertoolbar?: (toolbar?: GridRendertoolbar['toolbar']) => void;
rendergridrows?: (params?: any) => any;
sortable?: boolean;
sortmode?: string;
selectedrowindex?: number;
selectedrowindexes?: Array<number>;
source?: GridSource;
sorttogglestates?: string;
updatedelay?: number;
virtualmode?: boolean;
verticalscrollbarstep?: number;
verticalscrollbarlargestep?: number;
}// GridOptions
export interface jqxGrid extends widget, GridOptions {
// jqxGrid functions
autoresizecolumns(type: string): void;
autoresizecolumn(dataField: string, type: string): void;
beginupdate(): void;
clear(): void;
createChart(type: string, dataSource: any): void;
destroy(): void;
endupdate(): void;
ensurerowvisible(rowBoundIndex: number): void;
focus(): void;
getcolumnindex(dataField: string): number;
getcolumn(dataField: string): GridGetColumn;
getcolumnproperty(dataField: string, propertyName: string): any;
getrowid(rowBoundIndex: number): string;
getrowdata(rowBoundIndex: number): any;
getrowdatabyid(rowID: string): any;
getrowboundindexbyid(rowID: string): number;
getrowboundindex(rowDisplayIndex: number): number;
getrows(): Array<any>;
getboundrows(): Array<any>;
getdisplayrows(): Array<any>;
getdatainformation(): GridGetDataInformation;
getsortinformation(): GridGetSortInformation;
getpaginginformation(): GridGetPagingInformation;
hidecolumn(dataField: string): void;
hideloadelement(): void;
hiderowdetails(rowBoundIndex: number): void;
iscolumnvisible(dataField: string): boolean;
iscolumnpinned(dataField: string): boolean;
localizestrings(localizationobject: GridLocalizationobject): void;
pincolumn(dataField: string): void;
refreshdata(): void;
refresh(): void;
render(): void;
scrolloffset(top: number, left: number): void;
scrollposition(): GridScrollPosition;
showloadelement(): void;
showrowdetails(rowBoundIndex: number): void;
setcolumnindex(dataField: string, index: number): void;
setcolumnproperty(dataField: string, propertyName: any, propertyValue: any): void;
showcolumn(dataField: string): void;
unpincolumn(dataField: string): void;
updatebounddata(type: any): void;
updating(): boolean;
getsortcolumn(): string;
removesort(): void;
sortby(dataField: string, sortOrder: string): void;
addgroup(dataField: string): void;
cleargroups(): void;
collapsegroup(group: number | string): void;
collapseallgroups(): void;
expandallgroups(): void;
expandgroup(group: number | string): void;
getrootgroupscount(): number;
getgroup(groupIndex: number): GridGetGroup;
insertgroup(groupIndex: number, dataField: string): void;
iscolumngroupable(): boolean;
removegroupat(groupIndex: number): void;
removegroup(dataField: string): void;
addfilter(dataField: string, filterGroup: any, refreshGrid: boolean): void;
applyfilters(): void;
clearfilters(): void;
getfilterinformation(): any;
getcolumnat(index: number): any;
removefilter(dataField: string, refreshGrid: boolean): void;
refreshfilterrow(): void;
gotopage(pagenumber: number): void;
gotoprevpage(): void;
gotonextpage(): void;
addrow(rowIds: any, data: any, rowPosition: any): void;
begincelledit(rowBoundIndex: number, dataField: string): void;
beginrowedit(rowBoundIndex: number): void;
closemenu(): void;
deleterow(rowIds: string | number | Array<number | string>): void;
endcelledit(rowBoundIndex: number, dataField: string, confirmChanges: boolean): void;
endrowedit(rowBoundIndex: number, confirmChanges: boolean): void;
getcell(rowBoundIndex: number, datafield: string): GridGetCell;
getcellatposition(left: number, top: number): GridGetCell;
getcelltext(rowBoundIndex: number, dataField: string): string;
getcelltextbyid(rowID: string, dataField: string): string;
getcellvaluebyid(rowID: string, dataField: string): any;
getcellvalue(rowBoundIndex: number, dataField: string): any;
isBindingCompleted(): boolean;
openmenu(dataField: string): void;
setcellvalue(rowBoundIndex: number, dataField: string, value: any): void;
setcellvaluebyid(rowID: string, dataField: string, value: any): void;
showvalidationpopup(rowBoundIndex: number, dataField: string, validationMessage: string): void;
updaterow(rowIds: string | number | Array<number | string>, data: any): void;
clearselection(): void;
getselectedrowindex(): number;
getselectedrowindexes(): Array<number>;
getselectedcell(): GridGetSelectedCell;
getselectedcells(): Array<GridGetSelectedCell>;
selectcell(rowBoundIndex: number, dataField: string): void;
selectallrows(): void;
selectrow(rowBoundIndex: number): void;
unselectrow(rowBoundIndex: number): void;
unselectcell(rowBoundIndex: number, dataField: string): void;
getcolumnaggregateddata(dataField: string, aggregates: Array<any>): string;
refreshaggregates(): void;
renderaggregates(): void;
exportdata(dataType: string, fileName: string, exportHeader: boolean, rows: Array<number>, exportHiddenColumns: boolean, serverURL: string, charSet: string): any;
exportview(dataType: string, fileName: string): any;
openColumnChooser(columns: any, header: string): void;
getstate(): GridGetState;
loadstate(stateobject: any): void;
savestate(): GridGetState;
}// jqxGrid
export interface InputOptions {
// InputOptions properties
disabled?: boolean;
dropDownWidth?: number | string;
displayMember?: string;
height?: string | number;
items?: number;
minLength?: number;
maxLength?: number;
opened?: boolean;
placeHolder?: string;
popupZIndex?: number;
query?: string;
renderer?: (itemValue?: string, inputValue?: string) => string;
rtl?: boolean;
searchMode?: string;
source?: any;
theme?: string;
valueMember?: string;
width?: string | number;
value?: number | string;
}// InputOptions
export interface jqxInput extends widget, InputOptions {
// jqxInput functions
destroy(): void;
focus(): void;
selectAll(): void;
val(value: number | string): string;
}// jqxInput
export interface KanbanColumns {
// KanbanColumns properties
text?: string;
dataField?: string;
maxItems?: number;
collapsible?: boolean;
collapseDirection?: string;
headerElement?: any;
collapsedHeaderElement?: any;
iconClassName?: string;
}// KanbanColumns
export interface KanbanColumnRenderer {
// KanbanColumnRenderer properties
element?: any;
collapsedElement?: any;
column?: any;
}// KanbanColumnRenderer
export interface KanbanItemRenderer {
// KanbanItemRenderer properties
element?: any;
item?: any;
resource?: any;
}// KanbanItemRenderer
export interface KanbanSource {
// KanbanSource properties
id?: number;
status?: string;
text?: string;
content?: any;
tags?: string;
color?: string;
resourceId?: any;
className?: string;
}// KanbanSource
export interface KanbanUpdateItem {
// KanbanUpdateItem properties
status?: string;
text?: string;
content?: any;
tags?: string;
color?: string;
resourceId?: any;
className?: string;
}// KanbanUpdateItem
export interface KanbanOptions {
// KanbanOptions properties
columnRenderer?: (element?: KanbanColumnRenderer['element'], collapsedElement?: KanbanColumnRenderer['collapsedElement'], column?: KanbanColumnRenderer['column']) => void;
columns?: Array<KanbanColumns>;
connectWith?: string;
headerHeight?: number | string;
headerWidth?: number;
height?: string | number;
itemRenderer?: (element?: KanbanItemRenderer['element'], item?: KanbanItemRenderer['item'], resource?: KanbanItemRenderer['resource']) => void;
ready?: () => void;
rtl?: boolean;
source?: any;
resources?: any;
template?: string;
templateContent?: any;
theme?: string;
width?: string | number;
}// KanbanOptions
export interface jqxKanban extends widget, KanbanOptions {
// jqxKanban functions
addItem(newItem: any): void;
destroy(): void;
getColumn(dataField: string): KanbanColumns;
getColumnItems(dataField: string): Array<KanbanSource>;
getItems(): KanbanSource;
removeItem(itemId: string): void;
updateItem(itemId: string, newContent: KanbanUpdateItem): void;
}// jqxKanban
export interface KnobChanging {
// KnobChanging properties
oldValue?: number;
newValue?: number;
}// KnobChanging
export interface KnobLabelsFormatFunction {
// KnobLabelsFormatFunction properties
formatFunction?: (label: string | number) => string | number;
}// KnobLabelsFormatFunction
export interface KnobMarks {
// KnobMarks properties
colorProgress?: any;
colorRemaining?: any;
drawAboveProgressBar?: boolean;
minorInterval?: number;
majorInterval?: number;
majorSize?: number | string;
offset?: string;
rotate?: boolean;
size?: number | string;
type?: string;
thickness?: number;
visible?: boolean;
}// KnobMarks
export interface KnobDial {
// KnobDial properties
innerRadius?: any;
outerRadius?: any;
style?: any;
startAngle?: number;
endAngle?: number;
}// KnobDial
export interface KnobLabels {
// KnobLabels properties
rotate?: any;
offset?: number | string;
visible?: boolean;
step?: number;
style?: any;
formatFunction?: KnobLabelsFormatFunction['formatFunction'];
}// KnobLabels
export interface KnobProgressBar {
// KnobProgressBar properties
offset?: number | string;
style?: any;
size?: number | string;
background?: any;
ranges?: Array<any>;
}// KnobProgressBar
export interface KnobPointer {
// KnobPointer properties
offset?: number | string;
type?: string;
style?: any;
size?: number | string;
thickness?: number;
visible?: boolean;
}// KnobPointer
export interface KnobSpinner {
// KnobSpinner properties
innerRadius?: any;
outerRadius?: any;
style?: any;
marks?: KnobMarks;
}// KnobSpinner
export interface KnobStyle {
// KnobStyle properties
fill?: any;
stroke?: string;
strokeWidth?: number;
}// KnobStyle
export interface KnobOptions {
// KnobOptions properties
allowValueChangeOnClick?: boolean;
allowValueChangeOnDrag?: boolean;
allowValueChangeOnMouseWheel?: boolean;
changing?: (oldValue: KnobChanging['oldValue'] | KnobChanging['oldValue'][], newValue: KnobChanging['newValue'] | KnobChanging['newValue'][]) => boolean;
dragEndAngle?: number;
dragStartAngle?: number;
disabled?: boolean;
dial?: KnobDial;
endAngle?: number;
height?: number | string;
labels?: KnobLabels;
marks?: KnobMarks;
min?: number;
max?: number;
progressBar?: KnobProgressBar;
pointer?: KnobPointer | KnobPointer[];
pointerGrabAction?: string;
rotation?: string;
startAngle?: number;
spinner?: KnobSpinner;
styles?: KnobStyle;
step?: number | string;
snapToStep?: boolean;
value?: any;
width?: number | string;
}// KnobOptions
export interface jqxKnob extends widget, KnobOptions {
// jqxKnob functions
destroy(): void;
val(value: number | string): number;
}// jqxKnob
export interface Layout {
// Layout properties
type: string;
alignment?: string;
allowClose?: boolean;
allowPin?: boolean;
allowUnpin?: boolean;
contentContainer?: string;
height?: number | string;
initContent?: () => void;
minHeight?: number | string;
minWidth?: number | string;
orientation?: string;
pinnedHeight?: number | string;
pinnedWidth?: number | string;
selected?: boolean;
title?: number | string;
unpinnedHeight?: number | string;
unpinnedWidth?: number | string;
width?: number | string;
items?: Array<Layout>;
}// Layout
export interface LayoutOptions {
// LayoutOptions properties
contextMenu?: boolean;
height?: string | number;
layout?: Array<Layout>;
minGroupHeight?: number | string;
minGroupWidth?: number | string;
resizable?: boolean;
rtl?: boolean;
theme?: string;
width?: string | number;
}// LayoutOptions
export interface jqxLayout extends widget, LayoutOptions {
// jqxLayout functions
destroy(): void;
loadLayout(Layout: any): void;
refresh(): void;
render(): void;
saveLayout(): any;
}// jqxLayout
export interface LinearGaugeRanges {
// LinearGaugeRanges properties
startValue?: number;
endValue?: number;
style?: any;
}// LinearGaugeRanges
export interface LinearGaugeBackground {
// LinearGaugeBackground properties
borderType?: string;
borderRadius?: any;
visible?: boolean;
style?: any;
showGradient?: boolean;
}// LinearGaugeBackground
export interface LinearGaugeLabels {
// LinearGaugeLabels properties
position?: string;
style?: any;
interval?: number;
offset?: number;
formatValue?: (value:any, position:string) => any;
visible?: boolean;
}// LinearGaugeLabels
export interface LinearGaugePointer {
// LinearGaugePointer properties
pointerType?: string;
style?: any;
size?: number | string;
offset?: number;
visible?: boolean;
}// LinearGaugePointer
export interface LinearGaugeTicks {
// LinearGaugeTicks properties
size?: number | string;
interval?: number;
visible?: boolean;
style?: any;
}// LinearGaugeTicks
export interface LinearGaugeOptions {
// LinearGaugeOptions properties
animationDuration?: number;
background?: LinearGaugeBackground;
colorScheme?: string;
disabled?: boolean;
easing?: string;
height?: number | string;
int64?: boolean;
labels?: LinearGaugeLabels | LinearGaugeLabels[];
min?: number;
max?: number;
orientation?: string;
pointer?: LinearGaugePointer;
rangesOffset?: number;
rangeSize?: number | string;
ranges?: Array<LinearGaugeRanges>;
showRanges?: boolean;
scaleStyle?: any;
scaleLength?: number | string;
ticksOffset?: Array<number | string>;
ticksPosition?: string;
ticksMinor?: LinearGaugeTicks;
ticksMajor?: LinearGaugeTicks;
value?: number;
width?: number | string;
}// LinearGaugeOptions
export interface jqxLinearGauge extends widget, LinearGaugeOptions {
// jqxLinearGauge functions
disable(): void;
enable(): void;
val(value: number | string): number;
}// jqxLinearGauge
export interface LinkButtonOptions {
// LinkButtonOptions properties
disabled?: boolean;
height?: string | number;
rtl?: boolean;
theme?: string;
width?: string | number;
}// LinkButtonOptions
export interface jqxLinkButton extends widget, LinkButtonOptions {
}// jqxLinkButton
export interface ListBoxDragStart {
// ListBoxDragStart properties
item?: object;
}// ListBoxDragStart
export interface ListBoxDragEnd {
// ListBoxDragEnd properties
dragItem?: object;
dropItem?: object;
}// ListBoxDragEnd
export interface ListBoxRenderer {
// ListBoxRenderer properties
index?: number;
label?: string | number;
value?: string | number;
}// ListBoxRenderer
export interface ListBoxOptions {
// ListBoxOptions properties
autoHeight?: boolean;
allowDrag?: boolean;
allowDrop?: boolean;
checkboxes?: boolean;
disabled?: boolean;
displayMember?: number | string;
dropAction?: string;
dragStart?: (item:ListBoxDragStart['item']) => boolean;
dragEnd?: (dragItem: ListBoxDragEnd['dragItem'], dropItem: ListBoxDragEnd['dropItem']) => boolean;
enableHover?: boolean;
enableSelection?: boolean;
equalItemsWidth?: boolean;
filterable?: boolean;
filterHeight?: number;
filterDelay?: number | string;
filterPlaceHolder?: number | string;
height?: string | number;
hasThreeStates?: boolean;
itemHeight?: number;
incrementalSearch?: boolean;
incrementalSearchDelay?: number | string;
multiple?: boolean;
multipleextended?: boolean;
renderer?: (index: ListBoxRenderer['index'], label: ListBoxRenderer['label'], value: ListBoxRenderer['value']) => string;
rendered?: () => any;
rtl?: boolean;
selectedIndex?: number | string;
selectedIndexes?: any;
source?: Array<any>;
scrollBarSize?: number;
searchMode?: string;
theme?: string;
valueMember?: number | string;
width?: string | number;
}// ListBoxOptions
export interface jqxListBox extends widget, ListBoxOptions {
// jqxListBox functions
addItem(Item: any): boolean;
beginUpdate(): void;
clear(): void;
clearSelection(): void;
checkIndex(Index: number): void;
checkItem(Item: any): void;
checkAll(): void;
clearFilter(): void;
destroy(): void;
disableItem(Item: any): void;
disableAt(Index: number): void;
enableItem(Item: any): void;
enableAt(Index: number | string): void;
ensureVisible(item: any): void;
endUpdate(): void;
focus(): void;
getItems(): Array<any>;
getSelectedItems(): Array<any>;
getCheckedItems(): Array<any>;
getItem(Index: number): any;
getItemByValue(Item: any): any;
getSelectedItem(): any;
getSelectedIndex(): number;
insertAt(Item: any, Index: number | string): void;
invalidate(): void;
indeterminateItem(Item: any): void;
indeterminateIndex(Index: number): void;
loadFromSelect(selector: string): void;
removeItem(Item: any): void;
removeAt(Index: number | string): void;
render(): void;
refresh(): void;
selectItem(Item: any): void;
selectIndex(Index: number | string): void;
updateItem(Item: any, Value: number | string): void;
updateAt(item: any, index: number | string): void;
unselectIndex(index: number | string): void;
unselectItem(item: any): void;
uncheckIndex(index: number | string): void;
uncheckItem(item: any): void;
uncheckAll(): void;
val(value: number | string): string;
}// jqxListBox
export interface ListMenuFilterCallback {
// ListMenuFilterCallback properties
text?: string;
searchValue?: string | number;
}// ListMenuFilterCallback
export interface ListMenuOptions {
// ListMenuOptions properties
alwaysShowNavigationArrows?: boolean;
animationType?: string;
animationDuration?: number | string;
autoSeparators?: boolean;
backLabel?: number | string;
disabled?: boolean;
enableScrolling?: boolean;
filterCallback?: (text:ListMenuFilterCallback['text'], searchValue:ListMenuFilterCallback['searchValue']) => boolean;
height?: number | string;
headerAnimationDuration?: number | string;
placeHolder?: number | string;
readOnly?: boolean;
rtl?: boolean;
roundedCorners?: boolean;
showNavigationArrows?: boolean;
showFilter?: boolean;
showHeader?: boolean;
showBackButton?: boolean;
theme?: string;
width?: string | number;
}// ListMenuOptions
export interface jqxListMenu extends widget, ListMenuOptions {
// jqxListMenu functions
back(): void;
changePage(Item: any): void;
destroy(): void;
}// jqxListMenu
export interface LoaderOptions {
// LoaderOptions properties
autoOpen?: boolean;
height?: string | number;
html?: string;
isModal?: boolean;
imagePosition?: string;
rtl?: boolean;
text?: number | string;
textPosition?: string;
theme?: string;
width?: string | number;
}// LoaderOptions
export interface jqxLoader extends widget, LoaderOptions {
// jqxLoader functions
close(): void;
open(left: number | string, top: number | string): void;
}// jqxLoader
export interface MaskedInputOptions {
// MaskedInputOptions properties
disabled?: boolean;
height?: string | number;
mask?: string;
promptChar?: number | string;
readOnly?: boolean;
rtl?: boolean;
theme?: string;
textAlign?: string;
value?: number | string;
width?: string | number;
}// MaskedInputOptions
export interface jqxMaskedInput extends widget, MaskedInputOptions {
// jqxMaskedInput functions
clear(): void;
destroy(): void;
focus(): void;
val(value: number | string): string;
}// jqxMaskedInput
export interface MenuOptions {
// MenuOptions properties
animationShowDuration?: number;
animationHideDuration?: number;
animationHideDelay?: number;
animationShowDelay?: number;
autoCloseInterval?: number;
autoSizeMainItems?: boolean;
autoCloseOnClick?: boolean;
autoOpenPopup?: boolean;
autoOpen?: boolean;
autoCloseOnMouseLeave?: boolean;
clickToOpen?: boolean;
disabled?: boolean;
enableHover?: boolean;
easing?: string;
height?: string | number;
keyboardNavigation?: boolean;
minimizeWidth?: number | string;
mode?: string;
popupZIndex?: number | string;
rtl?: boolean;
showTopLevelArrows?: boolean;
source?: any;
theme?: string;
width?: string | number;
}// MenuOptions
export interface jqxMenu extends widget, MenuOptions {
// jqxMenu functions
closeItem(itemID: number | string): void;
close(): void;
disable(itemID: number | string, value: boolean): void;
destroy(): void;
focus(): void;
minimize(): void;
open(left: number, top: number): void;
openItem(itemID: number | string): void;
restore(): void;
setItemOpenDirection(item: number | string, horizontaldirection: string, verticaldirection: string): void;
}// jqxMenu
export interface NavBarOptions {
// NavBarOptions properties
columns?: Array<string>;
disabled?: boolean;
height?: string | number;
minimized?: boolean;
minimizeButtonPosition?: string;
minimizedHeight?: number | string;
minimizedTitle?: number | string;
orientation?: string;
popupAnimationDelay?: number;
rtl?: boolean;
selection?: boolean;
selectedItem?: number | string;
theme?: string;
width?: string | number;
}// NavBarOptions
export interface jqxNavBar extends widget, NavBarOptions {
// jqxNavBar functions
close(): void;
destroy(): void;
getSelectedIndex(): number;
open(): void;
selectAt(index: number | string): void;
}// jqxNavBar
export interface NavigationBarOptions {
// NavigationBarOptions properties
animationType?: string;
arrowPosition?: string;
collapseAnimationDuration?: number;
disabled?: boolean;
expandAnimationDuration?: number;
expandMode?: string;
expandedIndexes?: Array<number>;
height?: string | number;
initContent?: (index:number) => void;
rtl?: boolean;
showArrow?: boolean;
theme?: string;
toggleMode?: string;
width?: string | number;
}// NavigationBarOptions
export interface jqxNavigationBar extends widget, NavigationBarOptions {
// jqxNavigationBar functions
add(header: number | string, content: number | string): void;
collapseAt(index: number | string): void;
disableAt(index: number | string): void;
disable(): void;
destroy(): void;
expandAt(index: number | string): void;
enableAt(index: number | string): void;
enable(): void;
focus(): void;
getHeaderContentAt(index: number | string): string;
getContentAt(index: number | string): string;
hideArrowAt(index: number | string): void;
invalidate(): void;
insert(Index: number, header: number | string, content: number | string): void;
refresh(): void;
render(): void;
remove(index: number | string): void;
setContentAt(index: number, item: number | string): void;
setHeaderContentAt(index: number, item: number | string): void;
showArrowAt(index: number | string): void;
update(index: number, header: number | string, content: number | string): void;
val(value: number | string): string | number;
}// jqxNavigationBar
export interface NotificationIcon {
// NotificationIcon properties
width?: number | string;
height?: number | string;
url?: string;
padding?: number | string;
}// NotificationIcon
export interface NotificationOptions {
// NotificationOptions properties
appendContainer?: string;
autoOpen?: boolean;
animationOpenDelay?: number;
animationCloseDelay?: number;
autoClose?: boolean;
autoCloseDelay?: number | string;
blink?: boolean;
browserBoundsOffset?: number;
closeOnClick?: boolean;
disabled?: boolean;
height?: number | string;
hoverOpacity?: number;
icon?: NotificationIcon;
notificationOffset?: number;
opacity?: number;
position?: string;
rtl?: boolean;
showCloseButton?: boolean;
template?: string;
theme?: string;
width?: string | number;
}// NotificationOptions
export interface jqxNotification extends widget, NotificationOptions {
// jqxNotification functions
closeAll(): void;
closeLast(): void;
destroy(): void;
open(): void;
refresh(): void;
render(): void;
}// jqxNotification
export interface NumberInputOptions {
// NumberInputOptions properties
allowNull?: boolean;
decimal?: number | string;
disabled?: boolean;
decimalDigits?: number | string;
decimalSeparator?: number | string;
digits?: number | string;
groupSeparator?: string;
groupSize?: number | string;
height?: string | number;
inputMode?: string;
min?: number | string;
max?: number | string;
negativeSymbol?: string;
placeHolder?: number | string;
promptChar?: string;
rtl?: boolean;
readOnly?: boolean;
spinMode?: string;
spinButtons?: boolean;
spinButtonsWidth?: number;
spinButtonsStep?: number | string;
symbol?: string;
symbolPosition?: string;
textAlign?: string;
template?: string;
theme?: string;
value?: number | string;
width?: string | number;
}// NumberInputOptions
export interface jqxNumberInput extends widget, NumberInputOptions {
// jqxNumberInput functions
clear(): void;
destroy(): void;
focus(): void;
getDecimal(): number;
setDecimal(index: number | string): void;
val(value: number | string): number;
}// jqxNumberInput
export interface PanelOptions {
// PanelOptions properties
autoUpdate?: boolean;
disabled?: boolean;
height?: string | number;
rtl?: boolean;
sizeMode?: string;
scrollBarSize?: number | string;
theme?: string;
width?: string | number;
}// PanelOptions
export interface jqxPanel extends widget, PanelOptions {
// jqxPanel functions
append(HTMLElement: any): void;
clearcontent(): void;
destroy(): void;
focus(): void;
getScrollHeight(): number;
getVScrollPosition(): number;
getScrollWidth(): number;
getHScrollPosition(): number;
prepend(HTMLElement: any): void;
remove(HTMLElement: any): void;
scrollTo(left: number | string, top: number | string): void;
}// jqxPanel
export interface PasswordInputLocalization {
// PasswordInputLocalization properties
passwordStrengthString?: string;
tooShort?: string;
weak?: string;
fair?: string;
good?: string;
strong?: string;
}// PasswordInputLocalization
export interface PasswordInputStrengthColors {
// PasswordInputStrengthColors properties
tooShort?: string;
weak?: string;
fair?: string;
good?: string;
strong?: string;
}// PasswordInputStrengthColors
export interface PasswordInputPasswordStrength {
// PasswordInputPasswordStrength properties
password?: any;
characters?: any;
defaultStrength?: string;
}// PasswordInputPasswordStrength
export interface PasswordInputStrengthTypeRenderer {
// PasswordInputStrengthTypeRenderer properties
password?: any;
characters?: any;
defaultStrength?: string;
}// PasswordInputStrengthTypeRenderer
export interface PasswordInputOptions {
// PasswordInputOptions properties
disabled?: boolean;
height?: string | number;
localization?: PasswordInputLocalization;
maxLength?: number | string;
placeHolder?: number | string;
passwordStrength?: (password:PasswordInputPasswordStrength['password'], characters:PasswordInputPasswordStrength['characters'], defaultStrength:PasswordInputPasswordStrength['defaultStrength']) => string;
rtl?: boolean;
strengthColors?: PasswordInputStrengthColors;
showStrength?: boolean;
showStrengthPosition?: string;
strengthTypeRenderer?: (password:PasswordInputStrengthTypeRenderer['password'], characters:PasswordInputStrengthTypeRenderer['characters'], defaultStrength:PasswordInputStrengthTypeRenderer['defaultStrength']) => string;
showPasswordIcon?: boolean;
theme?: string;
width?: string | number;
}// PasswordInputOptions
export interface jqxPasswordInput extends widget, PasswordInputOptions {
// jqxPasswordInput functions
render(): void;
refresh(): void;
val(value: string): string;
}// jqxPasswordInput
export interface PivotDesignerOptions {
// PivotDesignerOptions properties
type?: string;
target: any;
}// PivotDesignerOptions
export interface jqxPivotDesigner extends widget, PivotDesignerOptions {
// jqxPivotDesigner functions
refresh(): void;
}// jqxPivotDesigner
export interface PivotGridItemsRenderer {
// PivotGridItemsRenderer properties
pivotItem?: any;
}// PivotGridItemsRenderer
export interface PivotGridCellsRenderer {
// PivotGridCellsRenderer properties
pivotCell?: any;
}// PivotGridCellsRenderer
export class PivotGridDesigner {
// PivotGridDesigner properties
type: string;
target: any;
// PivotGridDesigner functions
refresh(): void;
}// PivotGridDesigner
export interface PivotGridCell {
// PivotGridCell properties
pivotRow: PivotGridItem;
pivotColumn: PivotGridItem;
}// PivotGridCell
export interface PivotGridCellFormatting {
// PivotGridCellFormatting properties
prefix?: string;
sufix?: string;
decimalSeparator?: string;
thousandsSeparator?: string;
decimalPlaces?: number;
negativeWithBrackets?: boolean;
}// PivotGridCellFormatting
export interface PivotGridCells {
// PivotGridCells properties
// PivotGridCells functions
hitTest(point: PivotGridPoint): any;
clear(): void;
setCellValue(pivotRow: PivotGridItem, pivotColumn: PivotGridItem, value: any): void;
getCellValue(pivotRow: PivotGridItem, pivotColumn: PivotGridItem): any;
drillThroughCell(pivotRow: PivotGridItem, pivotColumn: PivotGridItem): Array<any>;
selectCell(pivotRow: PivotGridItem, pivotColumn: PivotGridItem): void;
unselectCell(pivotRow: PivotGridItem, pivotColumn: PivotGridItem): void;
clearSelection(): void;
isCellSelected(pivotRow: PivotGridItem, pivotColumn: PivotGridItem): boolean;
getSelectedCellsCount(): number;
getSelectedCells(): Array<PivotGridCell>;
getNextCell(pivotCell: PivotGridCell, position: string): any;
}// PivotGridCells
export interface PivotGridColumns {
// PivotGridColumns properties
resizable: boolean;
sortable: boolean;
showExpandCollapseButtons: boolean;
parentPivotGrid: object;
items: Array<PivotGridItem>;
valueItems: Array<PivotGridItem>;
isHidden: boolean;
// PivotGridColumns functions
show(): void;
hide(): void;
refresh(): void;
getHierarchyDepth(): number;
autoResize(autoResizeMode: string): void;
getSortItem(): any;
getSortOrder(): any;
sortBy(pivotItem: PivotGridItem, order: string): void;
removeSort(): void;
selectItem(pivotItem: PivotGridItem): void;
unselectItem(pivotItem: PivotGridItem): void;
clearSelection(): void;
getSelectedItems(): Array<any>;
}// PivotGridColumns
export interface PivotGridField {
// PivotGridField properties
dataField: string;
text?: string;
align?: string;
className?: string;
classNameSelected?: string;
}// PivotGridField
export interface PivotGridFilterField {
// PivotGridFilterField properties
dataField: string;
text?: string;
filterFunction: (value: any) => boolean;
}// PivotGridFilterField
export interface PivotGridItem {
// PivotGridItem properties
isExpanded: boolean;
isHidden: boolean;
isSelected: boolean;
parentItem: PivotGridItem;
hierarchy: any;
parentPivotGrid: object;
items: Array<PivotGridItem>;
valueItems: Array<PivotGridItem>;
// PivotGridItem functions
getWidth(): number;
getDisplayWidth(): number;
autoResize(): void;
getHeight(): number;
getDisplayHeight(): number;
setHeight(height: number): void;
expand(): void;
collapse(): void;
}// PivotGridItem
export interface PivotGridRows {
// PivotGridRows properties
resizable: boolean;
sortable: boolean;
showExpandCollapseButtons: boolean;
parentPivotGrid: object;
items: Array<PivotGridItem>;
valueItems: Array<PivotGridItem>;
isHidden?: boolean;
// PivotGridRows functions
show(): void;
hide(): void;
refresh(): void;
getHierarchyDepth(): number;
autoResize(autoResizeMode: string): void;
getSortItem(): any;
getSortOrder(): any;
sortBy(pivotItem: PivotGridItem, sortOrder: string): void;
removeSort(): void;
selectItem(pivotItem: PivotGridItem): void;
unselectItem(pivotItem: PivotGridItem): void;
clearSelection(): void;
getSelectedItems(): Array<any>;
}// PivotGridRows
export interface PivotGridSettings {
// PivotGridSettings properties
pivotValuesOnRows?: boolean;
rows: Array<PivotGridField>;
columns: Array<PivotGridField>;
values: Array<PivotGridValueField>;
filters?: Array<PivotGridFilterField>;
theme?: string;
}// PivotGridSettings
export interface PivotGridValueField {
// PivotGridValueField properties
dataField: string;
function: any;
text?: string;
align?: string;
className?: string;
classNameSelected?: string;
cellsClassName?: string;
cellsClassNameSelected?: string;
formatSettings?: PivotGridCellFormatting;
}// PivotGridValueField
export interface PivotGridPoint {
// PivotGridPoint properties
x: number;
y: number;
}// PivotGridPoint
export interface PivotGridOptions {
// PivotGridOptions properties
source: any;
localization?: any;
scrollBarsEnabled?: boolean;
selectionEnabled?: boolean;
multipleSelectionEnabled?: boolean;
treeStyleRows?: boolean;
autoResize?: boolean;
itemsRenderer?: (pivotItem: PivotGridItemsRenderer['pivotItem']) => string;
cellsRenderer?: (pivotCell: PivotGridCellsRenderer['pivotCell']) => string;
}// PivotGridOptions
export interface jqxPivotGrid extends widget, PivotGridOptions {
// jqxPivotGrid functions
getInstance(): any;
refresh(): void;
getPivotRows(): PivotGridRows;
getPivotColumns(): PivotGridColumns;
getPivotCells(): PivotGridCells;
}// jqxPivotGrid
export interface PopoverOptions {
// PopoverOptions properties
arrowOffsetValue?: number;
animationOpenDelay?: number | string;
animationCloseDelay?: number | string;
autoClose?: boolean;
animationType?: string;
height?: number | string;
initContent?: () => void;
isModal?: boolean;
offset?: any;
position?: string;
rtl?: boolean;
selector?: string;
showArrow?: boolean;
showCloseButton?: boolean;
width?: number | string;
title?: string | number;
theme?: string;
}// PopoverOptions
export interface jqxPopover extends widget, PopoverOptions {
// jqxPopover functions
close(): void;
destroy(): void;
open(): void;
}// jqxPopover
export interface ProgressBarColorRanges {
// ProgressBarColorRanges properties
stop: number | string;
color: string;
}// ProgressBarColorRanges
export interface ProgressBarRenderText {
// ProgressBarRenderText properties
text?: string;
value?: number;
}// ProgressBarRenderText
export interface ProgressBarOptions {
// ProgressBarOptions properties
animationDuration?: number;
colorRanges?: Array<ProgressBarColorRanges>;
disabled?: boolean;
height?: string | number;
layout?: string;
max?: string | number;
min?: number | string;
orientation?: string;
rtl?: boolean;
renderText?: (text?: ProgressBarRenderText['text'], value?: ProgressBarRenderText['value']) => string;
showText?: boolean;
template?: string;
theme?: string;
value?: string | number;
width?: string | number;
}// ProgressBarOptions
export interface jqxProgressBar extends widget, ProgressBarOptions {
// jqxProgressBar functions
actualValue(value: number | string): void;
destroy(): void;
val(value: number | string): number;
}// jqxProgressBar
export interface RadioButtonOptions {
// RadioButtonOptions properties
animationShowDelay?: number;
animationHideDelay?: number;
boxSize?: number | string;
checked?: boolean;
disabled?: boolean;
enableContainerClick?: boolean;
groupName?: string;
hasThreeStates?: boolean;
height?: string | number;
rtl?: boolean;
theme?: string;
width?: string | number;
}// RadioButtonOptions
export interface jqxRadioButton extends widget, RadioButtonOptions {
// jqxRadioButton functions
check(): void;
disable(): void;
destroy(): void;
enable(): void;
focus(): void;
render(): void;
uncheck(): void;
val(value: boolean): boolean;
}// jqxRadioButton
export interface RangeSelectorRange {
// RangeSelectorRange properties
from?: number | string | Date;
to?: number | string | Date;
min?: number | string | object;
max?: number | string | object;
}// RangeSelectorRange
export interface RangeSelectorGetRange {
// RangeSelectorGetRange properties
from?: number | string;
to?: number | string;
}// RangeSelectorGetRange
export interface RangeSelectorLabelsFormatFunction {
// RangeSelectorLabelsFormatFunction properties
value?: number | string;
}// RangeSelectorLabelsFormatFunction
export interface RangeSelectorMarkersFormatFunction {
// RangeSelectorMarkersFormatFunction properties
value?: number | string;
position?: string;
}// RangeSelectorMarkersFormatFunction
export interface RangeSelectorGroupLabelsFormatFunction {
// RangeSelectorGroupLabelsFormatFunction properties
value?: string;
date?: any;
}// RangeSelectorGroupLabelsFormatFunction
export interface RangeSelectorOptions {
// RangeSelectorOptions properties
disabled?: boolean;
groupLabelsFormatFunction?: (value: RangeSelectorGroupLabelsFormatFunction['value'], date: RangeSelectorGroupLabelsFormatFunction['date']) => string;
height?: string | number;
labelsFormat?: string;
labelsFormatFunction?: (value: RangeSelectorLabelsFormatFunction['value']) => string;
labelsOnTicks?: boolean;
markersFormat?: string;
markersFormatFunction?: (value: RangeSelectorMarkersFormatFunction['value'], position: RangeSelectorMarkersFormatFunction['position']) => string;
majorTicksInterval?: any;
minorTicksInterval?: any;
max?: any;
min?: any;
moveOnClick?: boolean;
padding?: number | string;
range?: RangeSelectorRange;
resizable?: boolean;
rtl?: boolean;
showGroupLabels?: boolean;
showMinorTicks?: boolean;
snapToTicks?: boolean;
showMajorLabels?: boolean;
showMarkers?: boolean;
theme?: string;
width?: string | number;
}// RangeSelectorOptions
export interface jqxRangeSelector extends widget, RangeSelectorOptions {
// jqxRangeSelector functions
destroy(): void;
getRange(): RangeSelectorGetRange;
render(): void;
refresh(): void;
setRange(from: any, to: any): void;
}// jqxRangeSelector
export interface RatingOptions {
// RatingOptions properties
count?: number;
disabled?: boolean;
height?: string | number;
itemHeight?: number;
itemWidth?: number;
precision?: number;
singleVote?: boolean;
value?: number;
width?: string | number;
}// RatingOptions
export interface jqxRating extends widget, RatingOptions {
// jqxRating functions
disable(): void;
enable(): void;
getValue(): number;
setValue(value: number): void;
val(value: number): number;
}// jqxRating
export interface RepeatButtonOptions {
// RepeatButtonOptions properties
delay?: number;
disabled?: boolean;
height?: number | string;
imgSrc?: string;
imgWidth?: number | string;
imgHeight?: number | string;
imgPosition?: string;
roundedCorners?: string;
rtl?: boolean;
textPosition?: string;
textImageRelation?: string;
theme?: string;
template?: string;
toggled?: boolean;
width?: string | number;
value?: string;
}// RepeatButtonOptions
export interface jqxRepeatButton extends widget, RepeatButtonOptions {
// jqxRepeatButton functions
destroy(): void;
focus(): void;
render(): void;
val(value: string): string;
}// jqxRepeatButton
export interface ResponsivePanelOptions {
// ResponsivePanelOptions properties
animationDirection?: string;
animationHideDelay?: number | string;
animationShowDelay?: number | string;
animationType?: string;
autoClose?: boolean;
collapseBreakpoint?: number;
collapseWidth?: number;
height?: string | number;
initContent?: () => void;
theme?: string;
toggleButton?: string | any;
toggleButtonSize?: number | string;
width?: string | number;
}// ResponsivePanelOptions
export interface jqxResponsivePanel extends widget, ResponsivePanelOptions {
// jqxResponsivePanel functions
close(): void;
destroy(): void;
isCollapsed(): boolean;
isOpened(): boolean;
open(): void;
refresh(): void;
render(): void;
}// jqxResponsivePanel
export interface RibbonItem {
}// RibbonItem
export interface RibbonOptions {
// RibbonOptions properties
animationType?: string;
animationDelay?: number | string;
disabled?: boolean;
height?: number | string;
initContent?: (index: any) => void;
mode?: string;
popupCloseMode?: string;
position?: string;
reorder?: boolean;
rtl?: boolean;
selectedIndex?: number;
selectionMode?: string;
scrollPosition?: string;
scrollStep?: number;
scrollDelay?: number;
theme?: string;
width?: string | number;
}// RibbonOptions
export interface jqxRibbon extends widget, RibbonOptions {
// jqxRibbon functions
addAt(index: number, item: RibbonItem): void;
clearSelection(): void;
disableAt(index: number): void;
destroy(): void;
enableAt(index: number): void;
hideAt(index: number): void;
removeAt(index: number): void;
render(): void;
refresh(): void;
selectAt(index: number): void;
showAt(index: number): void;
setPopupLayout(index: number, layout: any, width: number | string, height: number | string): void;
updateAt(index: number, item: RibbonItem): void;
val(value: string): string;
}// jqxRibbon
export interface SchedulerAppointmentDataFields {
// SchedulerAppointmentDataFields properties
allDay?: boolean | string;
background?: string;
borderColor?: string;
color?: string;
description?: string;
draggable?: boolean | string;
from?: string;
hidden?: boolean | string;
id?: number | string;
location?: string;
recurrencePattern?: SchedulerRecurrencePattern | string;
recurrenceException?: string;
resizable?: boolean | string;
resourceId?: number | string;
readOnly?: boolean | string;
subject?: string;
style?: string;
status?: string;
to?: string;
tooltip?: string;
timeZone?: string;
}// SchedulerAppointmentDataFields
export interface SchedulerRecurrencePattern {
// SchedulerRecurrencePattern properties
FREQ?: string;
COUNT?: number;
UNTIL?: string;
BYDAY?: string;
BYMONTHDAY?: string;
BYMONTH?: number;
INTERVAL?: number;
}// SchedulerRecurrencePattern
export interface SchedulerChangedAppointments {
// SchedulerChangedAppointments properties
type?: string;
appointment?: SchedulerAppointmentDataFields;
}// SchedulerChangedAppointments
export interface SchedulerContextMenuOpen {
// SchedulerContextMenuOpen properties
menu?: any;
appointment?: any;
event?: any;
}// SchedulerContextMenuOpen
export interface SchedulerContextMenuClose {
// SchedulerContextMenuClose properties
menu?: any;
appointment?: any;
event?: any;
}// SchedulerContextMenuClose
export interface SchedulerContextMenuItemClick {
// SchedulerContextMenuItemClick properties
menu?: any;
appointment?: any;
event?: any;
}// SchedulerContextMenuItemClick
export interface SchedulerContextMenuCreate {
// SchedulerContextMenuCreate properties
menu?: any;
settings?: any;
}// SchedulerContextMenuCreate
export interface SchedulerEditDialogCreate {
// SchedulerEditDialogCreate properties
dialog?: any;
fields?: any;
editAppointment?: any;
}// SchedulerEditDialogCreate
export interface SchedulerEditDialogOpen {
// SchedulerEditDialogOpen properties
dialog?: any;
fields?: any;
editAppointment?: any;
}// SchedulerEditDialogOpen
export interface SchedulerEditDialogClose {
// SchedulerEditDialogClose properties
dialog?: any;
fields?: any;
editAppointment?: any;
}// SchedulerEditDialogClose
export interface SchedulerEditDialogKeyDown {
// SchedulerEditDialogKeyDown properties
dialog?: any;
fields?: any;
editAppointment?: any;
event?: any;
}// SchedulerEditDialogKeyDown
export interface SchedulerExportSettings {
// SchedulerExportSettings properties
serverURL?: string;
characterSet?: string;
fileName?: string | null;
dateTimeFormatString?: string;
resourcesInMultipleICSFiles?: boolean;
}// SchedulerExportSettings
export interface SchedulerRenderAppointment {
// SchedulerRenderAppointment properties
data?: any;
}// SchedulerRenderAppointment
export interface SchedulerResources {
// SchedulerResources properties
source?: string;
colorScheme?: string;
orientation?: string;
dataField?: string;
resourceColumnWidth?: number | string;
resourceRowHeight?: number;
}// SchedulerResources
export interface SchedulerStatuses {
// SchedulerStatuses properties
free?: string;
tentative?: string;
busy?: string;
doNotDisturb?: string;
outOfOffice?: string;
}// SchedulerStatuses
export interface SchedulerGetSelection {
// SchedulerGetSelection properties
from?: any;
to?: any;
ResourceId?: any;
}// SchedulerGetSelection
export interface SchedulerOptions {
// SchedulerOptions properties
appointmentOpacity?: number;
appointmentsMinHeight?: number;
appointmentDataFields?: SchedulerAppointmentDataFields;
appointmentTooltips?: boolean;
columnsHeight?: number;
contextMenu?: boolean;
contextMenuOpen?: (menu: SchedulerContextMenuOpen['menu'], appointment: SchedulerContextMenuOpen['appointment'], event: SchedulerContextMenuOpen['event']) => void;
contextMenuClose?: (menu: SchedulerContextMenuClose['menu'], appointment: SchedulerContextMenuClose['appointment'], event: SchedulerContextMenuClose['event']) => void;
contextMenuItemClick?: (menu: SchedulerContextMenuItemClick['menu'], appointment: SchedulerContextMenuItemClick['appointment'], event: SchedulerContextMenuItemClick['event']) => boolean;
contextMenuCreate?: (menu: SchedulerContextMenuCreate['menu'], settings: SchedulerContextMenuCreate['settings']) => void;
changedAppointments?: Array<SchedulerChangedAppointments>;
disabled?: boolean;
date?: any;
dayNameFormat?: string;
enableHover?: boolean;
editDialog?: boolean;
editDialogDateTimeFormatString?: string;
editDialogDateFormatString?: string;
editDialogOpen?: (dialog?: SchedulerEditDialogOpen['dialog'], fields?: SchedulerEditDialogOpen['fields'], editAppointment?: SchedulerEditDialogOpen['editAppointment']) => void;
editDialogCreate?: (dialog?: SchedulerEditDialogCreate['dialog'], fields?: SchedulerEditDialogCreate['fields'], editAppointment?: SchedulerEditDialogCreate['editAppointment']) => void;
editDialogKeyDown?: (dialog?: SchedulerEditDialogKeyDown['dialog'], fields?: SchedulerEditDialogKeyDown['fields'], editAppointment?: SchedulerEditDialogKeyDown['editAppointment'], event?: SchedulerEditDialogKeyDown['event']) => boolean;
editDialogClose?: (dialog?: SchedulerEditDialogClose['dialog'], fields?: SchedulerEditDialogClose['fields'], editAppointment?: SchedulerEditDialogClose['editAppointment']) => void;
exportSettings?: SchedulerExportSettings;
height?: number | string;
legendPosition?: string;
legendHeight?: number;
localization?: any;
min?: any;
max?: any;
ready?: () => void;
renderAppointment?: (data: SchedulerRenderAppointment['data']) => any;
rendering?: () => void;
rendered?: () => void;
rtl?: boolean;
resources?: SchedulerResources;
rowsHeight?: number;
showToolbar?: boolean;
showLegend?: boolean;
scrollBarSize?: number;
source?: any;
statuses?: SchedulerStatuses;
touchRowsHeight?: number;
theme?: string;
touchAppointmentsMinHeight?: number;
touchScrollBarSize?: number;
timeZone?: string;
touchDayNameFormat?: string;
toolBarRangeFormat?: string;
toolBarRangeFormatAbbr?: string;
toolbarHeight?: number;
views?: Array<any>;
view?: string;
width?: number | string;
}// SchedulerOptions
export interface jqxScheduler extends widget, SchedulerOptions {
// jqxScheduler functions
addAppointment(item: SchedulerAppointmentDataFields): void;
beginAppointmentsUpdate(): void;
clearAppointmentsSelection(): void;
clearSelection(): void;
closeMenu(): void;
closeDialog(): void;
deleteAppointment(appointmenId: string): void;
destroy(): void;
endAppointmentsUpdate(): void;
ensureAppointmentVisible(id: string): void;
ensureVisible(item: any, resourceId: string): void;
exportData(format: string): any;
focus(): void;
getAppointmentProperty(appointmentId: string, name: string): any;
getSelection(): SchedulerGetSelection;
getAppointments(): Array<SchedulerAppointmentDataFields>;
getDataAppointments(): Array<any>;
hideAppointmentsByResource(resourcesId: string): void;
openMenu(left: number, top: number): void;
openDialog(left: number, top: number): void;
selectAppointment(appointmentId: string): void;
setAppointmentProperty(appointmentId: string, name: string, value: any): void;
selectCell(date: any, allday: boolean, resourceId: string): void;
showAppointmentsByResource(resourceId: string): void;
scrollWidth(): number;
scrollHeight(): number;
scrollLeft(left: number): void;
scrollTop(top: number): void;
}// jqxScheduler
export interface ScrollBarOptions {
// ScrollBarOptions properties
disabled?: boolean;
height?: string | number;
largestep?: number;
min?: number;
max?: number;
rtl?: boolean;
step?: number;
showButtons?: boolean;
thumbMinSize?: number;
theme?: string;
vertical?: boolean;
value?: number;
width?: string | number;
}// ScrollBarOptions
export interface jqxScrollBar extends widget, ScrollBarOptions {
// jqxScrollBar functions
destroy(): void;
isScrolling(): boolean;
setPosition(index: number): void;
}// jqxScrollBar
export interface ScrollViewOptions {
// ScrollViewOptions properties
animationDuration?: number;
bounceEnabled?: boolean;
buttonsOffset?: Array<number>;
currentPage?: number;
disabled?: boolean;
height?: string | number;
moveThreshold?: number;
showButtons?: boolean;
slideShow?: boolean;
slideDuration?: number;
theme?: string;
width?: string | number;
}// ScrollViewOptions
export interface jqxScrollView extends widget, ScrollViewOptions {
// jqxScrollView functions
back(): void;
changePage(index: number): void;
forward(): void;
refresh(): void;
}// jqxScrollView
export interface SliderTickLabelFormatFunction {
// SliderTickLabelFormatFunction properties
value?: number;
}// SliderTickLabelFormatFunction
export interface SliderTooltipFormatFunction {
// SliderTooltipFormatFunction properties
value?: number;
}// SliderTooltipFormatFunction
export interface SliderOptions {
// SliderOptions properties
buttonsPosition?: string;
disabled?: boolean;
height?: string | number;
layout?: string;
mode?: string;
minorTicksFrequency?: number;
minorTickSize?: number;
max?: number;
min?: number;
orientation?: string;
rangeSlider?: boolean;
rtl?: boolean;
step?: number;
showTicks?: boolean;
showMinorTicks?: boolean;
showTickLabels?: boolean;
showButtons?: boolean;
showRange?: boolean;
template?: string;
theme?: string;
ticksPosition?: string;
ticksFrequency?: number;
tickSize?: number;
tickLabelFormatFunction?: (value: SliderTickLabelFormatFunction['value']) => string;
tooltip?: boolean;
tooltipHideDelay?: number;
tooltipPosition?: string;
tooltipFormatFunction?: (value: SliderTooltipFormatFunction['value']) => any;
value?: any;
values?: Array<number>;
width?: number | string;
}// SliderOptions
export interface jqxSlider extends widget, SliderOptions {
// jqxSlider functions
destroy(): void;
decrementValue(): void;
disable(): void;
enable(): void;
focus(): void;
getValue(): number;
incrementValue(): void;
setValue(index: number | number[]): void;
val(value: string): string;
}// jqxSlider
export interface SortableCursorAt {
// SortableCursorAt properties
left?: number;
top?: number;
right?: number;
bottom?: number;
}// SortableCursorAt
export interface SortableOptions {
// SortableOptions properties
appendTo?: string;
axis?: number | string;
cancel?: string;
connectWith?: string | boolean;
containment?: string | boolean;
cursor?: string;
cursorAt?: SortableCursorAt;
delay?: number;
disabled?: boolean;
distance?: number;
dropOnEmpty?: boolean;
forceHelperSize?: boolean;
forcePlaceholderSize?: boolean;
grid?: Array<number>;
handle?: string | boolean;
helper?: (originalEvent?: any, content?: any) => void | 'original' | 'clone';
items?: string;
opacity?: number | boolean;
placeholderShow?: string | boolean;
revert?: number | boolean;
scroll?: boolean;
scrollSensitivity?: number;
scrollSpeed?: number;
tolerance?: string;
zIndex?: number;
}// SortableOptions
export interface jqxSortable extends widget, SortableOptions {
// jqxSortable functions
cancelMethod(): void;
destroy(): void;
disable(): void;
enable(): void;
refresh(): void;
refreshPositions(): void;
serialize(object: any): string;
toArray(): Array<any>;
}// jqxSortable
export interface SplitterPanel {
// SplitterPanel properties
size?: number | string;
min?: number | string;
collapsible?: boolean;
collapsed?: boolean;
}// SplitterPanel
export interface SplitterOptions {
// SplitterOptions properties
disabled?: boolean;
height?: string | number;
orientation?: string;
panels?: Array<SplitterPanel>;
resizable?: boolean;
splitBarSize?: number;
showSplitBar?: boolean;
theme?: string;
width?: string | number;
}// SplitterOptions
export interface jqxSplitter extends widget, SplitterOptions {
// jqxSplitter functions
collapse(): void;
destroy(): void;
disable(): void;
enable(): void;
expand(): void;
render(): void;
refresh(): void;
}// jqxSplitter
export interface SwitchButtonOptions {
// SwitchButtonOptions properties
checked?: boolean;
disabled?: boolean;
height?: string | number;
orientation?: string;
onLabel?: string;
offLabel?: string;
thumbSize?: string;
rtl?: boolean;
width?: string | number;
}// SwitchButtonOptions
export interface jqxSwitchButton extends widget, SwitchButtonOptions {
// jqxSwitchButton functions
check(): void;
disable(): void;
enable(): void;
toggle(): void;
uncheck(): void;
val(value: boolean): boolean;
}// jqxSwitchButton
export interface TabsOptions {
// TabsOptions properties
animationType?: string;
autoHeight?: boolean;
closeButtonSize?: number;
collapsible?: boolean;
contentTransitionDuration?: number;
disabled?: boolean;
enabledHover?: boolean;
enableScrollAnimation?: boolean;
enableDropAnimation?: boolean;
height?: string | number;
initTabContent?: (tab?: number) => void;
keyboardNavigation?: boolean;
next?: any;
previous?: any;
position?: string;
reorder?: boolean;
rtl?: boolean;
scrollAnimationDuration?: number;
selectedItem?: number;
selectionTracker?: boolean;
scrollable?: boolean;
scrollPosition?: string;
scrollStep?: number;
showCloseButtons?: boolean;
toggleMode?: string;
theme?: string;
width?: string | number;
}// TabsOptions
export interface jqxTabs extends widget, TabsOptions {
// jqxTabs functions
addAt(index: number, title: string, content: string): void;
addFirst(htmlElement1: any, htmlElement2: any): void;
addLast(htmlElement1: any, htmlElement2: any): void;
collapse(): void;
disable(): void;
disableAt(index: number): void;
destroy(): void;
ensureVisible(index: number): void;
enableAt(index: number): void;
expand(): void;
enable(): void;
focus(): void;
getTitleAt(index: number): string;
getContentAt(index: number): any;
getDisabledTabsCount(): any;
hideCloseButtonAt(index: number): void;
hideAllCloseButtons(): void;
length(): number;
removeAt(index: number): void;
removeFirst(): void;
removeLast(): void;
select(index: number): void;
setContentAt(index: number, htmlElement: string): void;
setTitleAt(index: number, htmlElement: string): void;
showCloseButtonAt(index: number): void;
showAllCloseButtons(): void;
val(value: string): string;
}// jqxTabs
export interface TagCloudTagRenderer {
// TagCloudTagRenderer properties
itemData?: any;
minValue?: number;
valueRange?: number;
}// TagCloudTagRenderer
export interface TagCloudSource {
// TagCloudSource properties
url?: string;
data?: any;
localdata?: string;
datatype?: string;
type?: string;
id?: string;
root?: string;
record?: string;
}// TagCloudSource
export interface TagCloudOptions {
// TagCloudOptions properties
alterTextCase?: string;
disabled?: boolean;
displayLimit?: number;
displayMember?: string;
displayValue?: boolean;
fontSizeUnit?: string;
height?: number | string;
maxColor?: string;
maxFontSize?: number;
maxValueToDisplay?: number;
minColor?: string;
minFontSize?: number;
minValueToDisplay?: number;
rtl?: boolean;
sortBy?: string;
sortOrder?: string;
source?: TagCloudSource;
tagRenderer?: (itemData: TagCloudTagRenderer['itemData'], minValue: TagCloudTagRenderer['minValue'], valueRange: TagCloudTagRenderer['valueRange']) => any;
takeTopWeightedItems?: boolean;
textColor?: string;
urlBase?: string;
urlMember?: string;
valueMember?: string;
width?: string | number;
}// TagCloudOptions
export interface jqxTagCloud extends widget, TagCloudOptions {
// jqxTagCloud functions
destroy(): void;
findTagIndex(tag: string): number;
getHiddenTagsList(): Array<any>;
getRenderedTags(): Array<any>;
getTagsList(): Array<any>;
hideItem(index: number): void;
insertAt(index: number, item: any): void;
removeAt(index: number): void;
updateAt(index: number, item: any): void;
showItem(index: number): void;
}// jqxTagCloud
export interface ToggleButtonOptions {
// ToggleButtonOptions properties
disabled?: boolean;
height?: number | string;
imgSrc?: string;
imgWidth?: number | string;
imgHeight?: number | string;
imgPosition?: string;
roundedCorners?: string;
rtl?: boolean;
textPosition?: string;
textImageRelation?: string;
theme?: string;
template?: string;
toggled?: boolean;
width?: string | number;
value?: string;
}// ToggleButtonOptions
export interface jqxToggleButton extends widget, ToggleButtonOptions {
// jqxToggleButton functions
check(): void;
destroy(): void;
focus(): void;
render(): void;
toggle(): void;
unCheck(): void;
val(value: string): string;
}// jqxToggleButton
export interface TextAreaOptions {
// TextAreaOptions properties
disabled?: boolean;
displayMember?: string;
dropDownWidth?: number | string;
height?: string | number;
items?: number;
maxLength?: number;
minLength?: number;
opened?: boolean;
placeHolder?: string;
popupZIndex?: number;
query?: string;
renderer?: (itemValue: any, inputValue: any) => any;
roundedCorners?: boolean;
rtl?: boolean;
scrollBarSize?: number;
searchMode?: string;
source?: any;
theme?: string;
valueMember?: string;
width?: string | number;
}// TextAreaOptions
export interface jqxTextArea extends widget, TextAreaOptions {
// jqxTextArea functions
destroy(): void;
focus(): void;
refresh(): void;
render(): void;
selectAll(): void;
val(value: string): string;
}// jqxTextArea
export interface ToolBarToolItem {
// ToolBarToolItem properties
type?: string;
tool?: any;
separatorAfterWidget?: boolean;
minimizable?: boolean;
minimized?: boolean;
menuTool?: any;
menuSeparator?: any;
}// ToolBarToolItem
export interface ToolBarOptions {
// ToolBarOptions properties
disabled?: boolean;
height?: string | number;
initTools?: (type?: string, index?: number, tool?: any, menuToolIninitialization?: boolean) => void;
minimizeWidth?: number;
minWidth?: number | string;
maxWidth?: number | string;
rtl?: boolean;
tools?: string;
theme?: string;
width?: string | number;
}// ToolBarOptions
export interface jqxToolBar extends widget, ToolBarOptions {
// jqxToolBar functions
addTool(type: string, position: string, separator: boolean, menuToolIninitialization: (type?: string, tool?: any, menuToolIninitialization?: boolean) => void): void;
disableTool(index: number, disable: boolean): void;
destroy(): void;
destroyTool(index: number): void;
getTools(): Array<ToolBarToolItem>;
render(): void;
refresh(): void;
}// jqxToolBar
export interface TooltipOptions {
// TooltipOptions properties
absolutePositionX?: number;
absolutePositionY?: number;
autoHide?: boolean;
autoHideDelay?: number;
animationShowDelay?: number | string;
animationHideDelay?: number | string;
content?: string;
closeOnClick?: boolean;
disabled?: boolean;
enableBrowserBoundsDetection?: boolean;
height?: number | string;
left?: number;
name?: string;
opacity?: number;
position?: string;
rtl?: boolean;
showDelay?: number;
showArrow?: boolean;
top?: number | string;
trigger?: string;
theme?: string;
width?: number | string;
}// TooltipOptions
export interface jqxTooltip extends widget, TooltipOptions {
// jqxTooltip functions
close(index: number): void;
destroy(): void;
open(left: number, top: number): void;
refresh(): void;
}// jqxTooltip
export interface TreeDragStart {
// TreeDragStart properties
item?: any;
}// TreeDragStart
export interface TreeDragEnd {
// TreeDragEnd properties
dragItem?: any;
dropItem?: any;
args?: any;
dropPosition?: any;
tree?: any;
}// TreeDragEnd
export interface TreeItem {
// TreeItem properties
label?: string;
value?: string;
disabled?: boolean;
checked?: boolean;
element?: any;
parentElement?: any;
isExpanded?: boolean;
selected?: boolean;
}// TreeItem
export interface TreeOffset {
// TreeOffset properties
top?: number;
left?: number;
}// TreeOffset
export interface TreeOptions {
// TreeOptions properties
animationShowDuration?: number;
animationHideDuration?: number;
allowDrag?: boolean;
allowDrop?: boolean;
checkboxes?: boolean;
dragStart?: (item: TreeDragStart['item']) => boolean;
dragEnd?: (dragItem?: TreeDragEnd['dragItem'], dropItem?: TreeDragEnd['dropItem'], args?: TreeDragEnd['args'], dropPosition?: TreeDragEnd['dropPosition'], tree?: TreeDragEnd['tree']) => boolean;
disabled?: boolean;
easing?: string;
enableHover?: boolean;
height?: number | string;
hasThreeStates?: boolean;
incrementalSearch?: boolean;
keyboardNavigation?: boolean;
rtl?: boolean;
source?: any;
toggleIndicatorSize?: number;
toggleMode?: string;
theme?: string;
width?: string | number;
}// TreeOptions
export interface jqxTree extends widget, TreeOptions {
// jqxTree functions
addBefore(item: any, id: string): void;
addAfter(item: any, id: string): void;
addTo(item: any, id: string | null): void;
clear(): void;
checkAll(): void;
checkItem(item: any, checked: boolean): void;
collapseAll(): void;
collapseItem(item: any): void;
destroy(): void;
disableItem(item: any): void;
ensureVisible(item: any): void;
enableItem(item: any): void;
enableAll(): void;
expandAll(): void;
expandItem(item: any): void;
focus(): void;
getCheckedItems(): Array<TreeItem>;
getUncheckedItems(): Array<TreeItem>;
getItems(): Array<TreeItem>;
getItem(element: any): TreeItem;
getSelectedItem(): TreeItem;
getPrevItem(item: any): TreeItem;
getNextItem(item: any): TreeItem;
hitTest(left: number, top: number): any;
removeItem(item: any): void;
render(): void;
refresh(): void;
selectItem(item: any): void;
uncheckAll(): void;
uncheckItem(item: any): void;
updateItem(item: any, newItem: any): void;
val(value: string): string;
}// jqxTree
export interface TreeGridEditSettings {
// TreeGridEditSettings properties
saveOnEnter?: boolean;
saveOnPageChange?: boolean;
saveOnBlur?: boolean;
saveOnSelectionChange?: boolean;
cancelOnEsc?: boolean;
editSingleCell?: boolean;
editOnDoubleClick?: boolean;
editOnF2?: boolean;
}// TreeGridEditSettings
export interface TreeGridExportSettings {
// TreeGridExportSettings properties
columnsHeader?: boolean;
hiddenColumns?: boolean;
serverURL?: string | any;
characterSet?: string;
collapsedRecords?: boolean;
recordsInView?: boolean;
fileName?: string | null;
}// TreeGridExportSettings
export interface TreeGridGetRow {
// TreeGridGetRow properties
type?: string;
checked?: boolean;
expanded?: boolean;
icon?: string;
leaf?: boolean;
level?: number;
parent?: any;
records?: Array<any>;
selected?: boolean;
uid?: number | string;
}// TreeGridGetRow
export interface TreeGridRowDetailsRenderer {
// TreeGridRowDetailsRenderer properties
key?: number;
dataRow?: number;
}// TreeGridRowDetailsRenderer
export interface TreeGridRenderStatusBar {
// TreeGridRenderStatusBar properties
statusbar?: any;
}// TreeGridRenderStatusBar
export interface TreeGridRenderToolbar {
// TreeGridRenderToolbar properties
toolbar?: any;
}// TreeGridRenderToolbar
export interface TreeGridScrollOffset {
// TreeGridScrollOffset properties
top?: number;
left?: number;
}// TreeGridScrollOffset
export interface TreeGridOptions {
// TreeGridOptions properties
altRows?: boolean;
autoRowHeight?: boolean;
aggregatesHeight?: number;
autoShowLoadElement?: boolean;
checkboxes?: boolean;
columnsHeight?: number;
columns?: Array<any>;
columnGroups?: Array<any>;
columnsResize?: boolean;
columnsReorder?: boolean;
disabled?: boolean;
editable?: boolean;
editSettings?: TreeGridEditSettings;
exportSettings?: TreeGridExportSettings;
enableHover?: boolean;
enableBrowserSelection?: boolean;
filterable?: boolean;
filterHeight?: number;
filterMode?: string;
height?: number | string;
hierarchicalCheckboxes?: boolean;
icons?: any;
incrementalSearch?: boolean;
localization?: any;
pagerHeight?: number;
pageSize?: number;
pageSizeOptions?: Array<number | string>;
pageable?: boolean;
pagerPosition?: string;
pagerMode?: string;
pageSizeMode?: string;
pagerButtonsCount?: number;
pagerRenderer?: () => any;
ready?: () => void;
rowDetails?: boolean;
rowDetailsRenderer?: (key: TreeGridRowDetailsRenderer['key'], dataRow: TreeGridRowDetailsRenderer['dataRow']) => any;
renderToolbar?: (toolBar?: TreeGridRenderToolbar['toolbar']) => void;
renderStatusBar?: (statusBar?: TreeGridRenderStatusBar['statusbar']) => void;
rendering?: () => void;
rendered?: () => void;
rtl?: boolean;
source?: any;
sortable?: boolean;
showAggregates?: boolean;
showSubAggregates?: boolean;
showToolbar?: boolean;
showStatusbar?: boolean;
statusBarHeight?: number;
scrollBarSize?: number;
selectionMode?: string;
showHeader?: boolean;
theme?: string;
toolbarHeight?: number;
width?: string | number;
virtualModeCreateRecords?: (expandedRecord?: any, done?: any) => void;
virtualModeRecordCreating?: (record?: any) => any;
}// TreeGridOptions
export interface jqxTreeGrid extends widget, TreeGridOptions {
// jqxTreeGrid functions
addRow(rowKey: number | string | null, rowData: any, rowPosition: string, parent: string): void;
addFilter(dataField: string, filerGroup: any): void;
applyFilters(): void;
beginUpdate(): void;
beginRowEdit(rowKey: number | string): void;
beginCellEdit(rowKey: number | string, dataField: string): void;
clearSelection(): void;
clearFilters(): void;
clear(): void;
checkRow(rowKey: number | string): void;
collapseRow(rowKey: number | string): void;
collapseAll(): void;
destroy(): void;
deleteRow(rowKey: string[] | string): void;
expandRow(rowKey: Array<number | string> | string | number): void;
expandAll(): void;
endUpdate(): void;
ensureRowVisible(rowKey: number | string): void;
endRowEdit(rowKey: number | string, cancelChanges: boolean): void;
endCellEdit(rowKey: number | string, dataField: string, cancelChanges: boolean): void;
exportData(exportDataType: any): any;
focus(): void;
getColumnProperty(dataField: string, propertyName: string): any;
goToPage(pageIndex: number): void;
goToPrevPage(): void;
goToNextPage(): void;
getSelection(): Array<any>;
getKey(row: any): string;
getRow(rowKey: number | string): TreeGridGetRow;
getRows(): Array<TreeGridGetRow>;
getCheckedRows(): Array<TreeGridGetRow>;
getView(): Array<TreeGridGetRow>;
getCellValue(rowKey: number | string, dataField: string): any;
hideColumn(dataField: string): void;
isBindingCompleted(): boolean;
lockRow(rowKey: string | number | Array<number | string>): void;
refresh(): void;
render(): void;
removeFilter(dataField: string): void;
scrollOffset(top: number, left: number): TreeGridScrollOffset;
setColumnProperty(dataField: string, propertyName: string, propertyValue: any): void;
showColumn(dataField: string): void;
selectRow(rowId: string | number | Array<number | string>): void;
setCellValue(rowId: string, dataField: string, cellValue: any): void;
sortBy(dataField: number | string, sortOrder: 'asc' | 'desc' | null): void;
updating(): boolean;
updateBoundData(): void;
unselectRow(rowId: string | number | Array<number | string>): void;
uncheckRow(rowId: string): void;
updateRow(rowId: number | string, data: any): void;
unlockRow(rowId: string | number | Array<number | string>): void;
}// jqxTreeGrid
export interface TreeMapColorRanges {
// TreeMapColorRanges properties
color?: string;
min?: number;
max?: number;
}// TreeMapColorRanges
export interface TreeMapLegendPosition {
// TreeMapLegendPosition properties
x?: number | string;
y?: number | string;
}// TreeMapLegendPosition
export interface TreeMapLegendScaleCallback {
// TreeMapLegendScaleCallback properties
v?: number;
}// TreeMapLegendScaleCallback
export interface TreeMapOptions {
// TreeMapOptions properties
baseColor?: string;
colorRanges?: Array<TreeMapColorRanges>;
colorRange?: number;
colorMode?: string;
displayMember?: string;
height?: string | number;
hoverEnabled?: boolean;
headerHeight?: number;
legendLabel?: string;
legendPosition?: TreeMapLegendPosition;
legendScaleCallback?: (v: TreeMapLegendScaleCallback['v']) => string | number;
renderCallbacks?: any;
selectionEnabled?: boolean;
showLegend?: boolean;
source?: any;
theme?: string;
valueMember?: string;
width?: string | number;
}// TreeMapOptions
export interface jqxTreeMap extends widget, TreeMapOptions {
// jqxTreeMap functions
destroy(): void;
render(): void;
}// jqxTreeMap
export interface ValidatorRule {
// ValidatorRule properties
input?: string;
message?: string;
action?: string;
rule?: string | any;
position?: string;
hintRender?: any;
}// ValidatorRule
export interface ValidatorOptions {
// ValidatorOptions properties
arrow?: boolean;
animation?: string;
animationDuration?: number;
closeOnClick?: boolean;
focus?: boolean;
hintType?: string;
onError?: () => void;
onSuccess?: () => void;
position?: string;
rules?: Array<ValidatorRule>;
rtl?: boolean;
}// ValidatorOptions
export interface jqxValidator extends widget, ValidatorOptions {
// jqxValidator functions
hideHint(id: string): void;
hide(): void;
updatePosition(): void;
validate(htmlElement: any): void;
validateInput(id: string): void;
}// jqxValidator
export interface WindowDragArea {
// WindowDragArea properties
left: number;
top: number;
width: number | string;
height: number | string;
}// WindowDragArea
export interface WindowOptions {
// WindowOptions properties
autoOpen?: boolean;
animationType?: string;
collapsed?: boolean;
collapseAnimationDuration?: number;
content?: string;
closeAnimationDuration?: number;
closeButtonSize?: number;
closeButtonAction?: string;
cancelButton?: any;
dragArea?: WindowDragArea;
draggable?: boolean;
disabled?: boolean;
height?: string | number;
initContent?: () => void;
isModal?: boolean;
keyboardCloseKey?: number | string;
keyboardNavigation?: boolean;
minHeight?: string | number;
maxHeight?: string | number;
minWidth?: number | string;
maxWidth?: number | string;
modalOpacity?: any;
modalZIndex?: number;
modalBackgroundZIndex?: number;
okButton?: any;
position?: string | any;
rtl?: boolean;
resizable?: boolean;
showAnimationDuration?: number;
showCloseButton?: boolean;
showCollapseButton?: boolean;
theme?: string;
title?: string;
width?: string | number;
zIndex?: number;
}// WindowOptions
export interface jqxWindow extends widget, WindowOptions {
// jqxWindow functions
bringToFront(): void;
close(): void;
collapse(): void;
closeAll(): void;
disable(): void;
destroy(): void;
enable(): void;
expand(): void;
focus(): void;
isOpen(): boolean;
move(top: number, left: number): void;
open(): void;
hide(): void;
resize(top: number, left: number): void;
setTitle(title: string): void;
setContent(content: string): void;
}// jqxWindow
export interface HeatMapXAxis {
// HeatMapXAxis properties
labels?: any[];
opposedPosition?: boolean;
isInversed?: boolean;
minimum?: any;
maximum?: any;
labelFormat?: string;
}// HeatMapXAxis
export interface HeatMapYAxis {
// HeatMapYAxis properties
labels?: any[];
opposedPosition?: boolean;
isInversed?: boolean;
}// HeatMapYAxis
export interface HeatMapPaletteSettings {
// HeatMapPaletteSettings properties<|fim▁hole|> emptyPointColor?: string;
}// HeatMapPaletteSettings
export interface HeatMapPalette {
// HeatMapPalette properties
value: number;
color: string;
label?: string;
}// HeatMapPalette
export interface HeatMapLegendSettings {
// HeatMapLegendSettings properties
position?: string;
}// HeatMapLegendSettings
export interface HeatMapTooltipRender {
// HeatMapTooltipRender properties
xLabel?: any[];
yLabel?: any[];
value?: string;
content?: string;
date?: Date;
}// HeatMapTooltipRender
export interface HeatMapOptions {
// HeatMapOptions properties
xAxis?: HeatMapXAxis;
yAxis?: HeatMapYAxis;
paletteSettings?: HeatMapPaletteSettings;
legendSettings?: HeatMapLegendSettings;
source?: any[];
title?: string;
width?: number | string;
tooltipRender?: (args: HeatMapTooltipRender) => void;
}// HeatMapOptions
export interface jqxHeatMap extends widget, HeatMapOptions {
// jqxHeatMap functions
destroy(): void;
setLegendPosition(position: string): void;
setOpposedXAxisPosition(opposedPosition: boolean): void;
setOpposedYAxisPosition(opposedPosition: boolean): void;
reverseXAxisPosition(isInversed: boolean): void;
reverseYAxisPosition(isInversed: boolean): void;
setPaletteType(type: string): void;
}// jqxHeatMap
export interface TimePickerOptions {
// TimePickerOptions properties
autoSwitchToMinutes?: boolean;
disabled?: boolean;
footer?: boolean;
footerTemplate?: string;
format?: string;
height?: number | string;
minuteInterval?: number;
name?: string;
readonly?: boolean;
selection?: string;
theme?: string;
unfocusable?: boolean;
value?: any;
view?: string;
width?: number | string;
}// TimePickerOptions
export interface jqxTimePicker extends widget, TimePickerOptions {
// jqxTimePicker functions
setHours(hours: number): void;
setMinutes(minutes: number): void;
}// jqxTimePicker
} // module jqwidgets<|fim▁end|>
|
palette?: any[];
type?: string;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.