text:
package org.mifos.customers.office.persistence;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.mifos.accounts.savings.persistence.GenericDao;
import org.mifos.application.NamedQueryConstants;
import org.mifos.application.master.MessageLookup;
import org.mifos.application.master.business.LookUpValueEntity;
import org.mifos.application.servicefacade.ApplicationContextProvider;
import org.mifos.config.util.helpers.ConfigurationConstants;
import org.mifos.core.MifosRuntimeException;
import org.mifos.customers.exceptions.CustomerException;
import org.mifos.customers.group.util.helpers.GroupConstants;
import org.mifos.customers.office.business.OfficeBO;
import org.mifos.customers.office.business.OfficeLevelEntity;
import org.mifos.customers.office.exceptions.OfficeException;
import org.mifos.customers.office.util.helpers.OfficeConstants;
import org.mifos.customers.office.util.helpers.OfficeLevel;
import org.mifos.customers.office.util.helpers.OfficeStatus;
import org.mifos.customers.personnel.util.helpers.PersonnelConstants;
import org.mifos.dto.domain.OfficeDetailsDto;
import org.mifos.dto.domain.OfficeDto;
import org.mifos.dto.domain.OfficeHierarchyDto;
import org.mifos.dto.domain.OfficeLevelDto;
import org.mifos.security.authorization.HierarchyManager;
import org.mifos.security.util.UserContext;
import org.mifos.service.BusinessRuleException;
import org.springframework.beans.factory.annotation.Autowired;

public class OfficeDaoHibernate implements OfficeDao {

    private final GenericDao genericDao;

    @Autowired
    public OfficeDaoHibernate(GenericDao genericDao) {
        this.genericDao = genericDao;
    }

    @Override
    public void save(OfficeLevelEntity entity) {
        this.genericDao.createOrUpdate(entity);
    }

    @Override
    public void save(OfficeBO office) {
        this.genericDao.createOrUpdate(office);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<OfficeBO> findBranchsOnlyWithParentsMatching(String searchId) {

        HashMap<String, Object> queryParameters = new HashMap<String, Object>();
        queryParameters.put("LEVEL_ID", OfficeLevel.BRANCHOFFICE.getValue());
        queryParameters.put("SEARCH_ID", searchId + "%");
        queryParameters.put("STATUS_ID", OfficeStatus.ACTIVE.getValue());
        List<OfficeBO> queryResult = (List<OfficeBO>) genericDao.executeNamedQuery(
                "office.getBranchParents", queryParameters);

        if (queryResult == null) {
            queryResult = new ArrayList<OfficeBO>();
        }

        return queryResult;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<OfficeDto> findNonBranchesOnlyWithParentsMatching(String searchId) {

        HashMap<String, Object> queryParameters = new HashMap<String, Object>();
        queryParameters.put("LEVEL_ID", OfficeLevel.BRANCHOFFICE.getValue());
        queryParameters.put("SEARCH_ID", searchId + "%");
        queryParameters.put("STATUS_ID", OfficeStatus.ACTIVE.getValue());
        List<OfficeDto> queryResult = (List<OfficeDto>) genericDao.executeNamedQuery("office.retrieveAllActiveOfficesNotAtAGivenLevelMatchingSearchIdPattern", queryParameters);

        if (queryResult == null) {
            queryResult = new ArrayList<OfficeDto>();
        }

        return queryResult;
    }

    @Override
    public OfficeBO findOfficeById(Short officeId) {

        HashMap<String, Object> queryParameters = new HashMap<String, Object>();
        queryParameters.put("OFFICE_ID", officeId);

        return (OfficeBO) genericDao.executeUniqueResultNamedQuery("findOfficeById", queryParameters);
    }

    @Override
    public OfficeDto findOfficeDtoById(Short officeId) {

        HashMap<String, Object> queryParameters = new HashMap<String, Object>();
        queryParameters.put("OFFICE_ID", officeId);

        return (OfficeDto) genericDao.executeUniqueResultNamedQuery("findOfficeDtoById", queryParameters);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<OfficeDto> findAllOffices() {

        List<OfficeDto> headOffices = (List<OfficeDto>) genericDao.executeNamedQuery("findAllHeadOffices", null);

        List<OfficeDto> allNonHeadOffices = (List<OfficeDto>) genericDao.executeNamedQuery("findAllNonHeadOfficesApplicableToOfficeHierarchy", null);

        List<OfficeDto> allOffices = new ArrayList<OfficeDto>(allNonHeadOffices);
        allOffices.addAll(headOffices);

        return allOffices;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<OfficeDetailsDto> findActiveOfficeLevels() {

        HashMap<String, Object> queryParameters = new HashMap<String, Object>();
        List<OfficeDetailsDto> queryResult = (List<OfficeDetailsDto>) genericDao.executeNamedQuery(
                "masterdata.activeLevels", queryParameters);
        if (queryResult == null) {
            queryResult = new ArrayList<OfficeDetailsDto>();
        }

        return queryResult;
    }

    @SuppressWarnings("unchecked")
    @Override
    public OfficeLevelDto findOfficeLevelsWithConfiguration() {

        HashMap<String, Object> queryParameters = new HashMap<String, Object>();
        List<OfficeLevelEntity> officeLevelEntities = (List<OfficeLevelEntity>) genericDao.executeNamedQuery("officeLevel.getOfficeLevelsWithConfiguration", queryParameters);
        if (officeLevelEntities == null) {
            officeLevelEntities = new ArrayList<OfficeLevelEntity>();
        }

        OfficeLevelDto officeLevels = new OfficeLevelDto();
        for (OfficeLevelEntity officeLevelEntity : officeLevelEntities) {

            LookUpValueEntity lookupValue = officeLevelEntity.getLookUpValue();
            String messageText = lookupValue.getMessageText();
            if (StringUtils.isBlank(messageText)) {
                messageText = ApplicationContextProvider.getBean(MessageLookup.class).lookup(lookupValue.getPropertiesKey());
            }

            OfficeLevel level = OfficeLevel.getOfficeLevel(officeLevelEntity.getId());
            switch (level) {
            case HEADOFFICE:
                officeLevels.setHeadOfficeEnabled(officeLevelEntity.isConfigured());
                officeLevels.setHeadOfficeNameKey(messageText);
                break;
            case REGIONALOFFICE:
                officeLevels.setRegionalOfficeEnabled(officeLevelEntity.isConfigured());
                officeLevels.setRegionalOfficeNameKey(messageText);
                break;
            case SUBREGIONALOFFICE:
                officeLevels.setSubRegionalOfficeEnabled(officeLevelEntity.isConfigured());
                officeLevels.setSubRegionalOfficeNameKey(messageText);
                break;
            case AREAOFFICE:
                officeLevels.setAreaOfficeEnabled(officeLevelEntity.isConfigured());
                officeLevels.setAreaOfficeNameKey(messageText);
                break;
            case BRANCHOFFICE:
                officeLevels.setBranchOfficeEnabled(officeLevelEntity.isConfigured());
                officeLevels.setBranchOfficeNameKey(messageText);
                break;
            default:
                break;
            }
        }

        return officeLevels;
    }

    @Override
    public OfficeHierarchyDto headOfficeHierarchy() {
        OfficeBO headOffice = getHeadOffice();
        return officeHierarchy(headOffice);
    }

    @SuppressWarnings("unchecked")
    private OfficeBO getHeadOffice() {
        HashMap<String, Object> queryParameters = new HashMap<String, Object>();
        queryParameters.put("LEVEL_ID", OfficeConstants.HEADOFFICE);

        List<OfficeBO> queryResult = (List<OfficeBO>) this.genericDao.executeNamedQuery("office.getHeadOffice", queryParameters);

        if (queryResult != null && queryResult.size() != 0) {
            return queryResult.get(0);
        }
        throw new MifosRuntimeException("No head office found: ");
    }

    private OfficeHierarchyDto officeHierarchy(OfficeBO office) {
        List<OfficeHierarchyDto> childOfficeList = new LinkedList<OfficeHierarchyDto>();
        Set<OfficeBO> children = office.getChildren();
        for (OfficeBO child : children) {
            childOfficeList.add(officeHierarchy(child));
        }
        Collections.sort(childOfficeList);
        OfficeHierarchyDto hierarchy = new OfficeHierarchyDto(office.getOfficeId(), office.getOfficeName().trim(), office.getSearchId(), office.isActive(), childOfficeList);
        return hierarchy;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<String> topLevelOfficeNames(Collection<Short> officeIds) {
        HashMap<String, Object> queryParameters = new HashMap<String, Object>();
        queryParameters.put("OFFICE_IDS", officeIds);

        return (List<String>) this.genericDao.executeNamedQuery("holiday.topLevelOfficeNames", queryParameters);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void validateNoActiveChildrenExist(Short officeId) throws OfficeException {

        HashMap<String, Object> queryParameters = new HashMap<String, Object>();
        queryParameters.put("OFFICE_ID", officeId);
        List queryResult = this.genericDao.executeNamedQuery("getCountOfActiveChildren", queryParameters);
        int activeChildren = ((Number) queryResult.get(0)).intValue();

        if (activeChildren > 0) {
            throw new OfficeException(OfficeConstants.KEYHASACTIVECHILDREN);
        }
    }

    @Override
    public void validateBranchIsActiveWithNoActivePersonnel(Short officeId, UserContext userContext) throws CustomerException {

        OfficeBO office = findOfficeById(officeId);

        if (!office.isActive()) {
            throw new CustomerException(GroupConstants.BRANCH_INACTIVE, new Object[] { ApplicationContextProvider.getBean(MessageLookup.class)
                    .lookupLabel(ConfigurationConstants.GROUP) });
        }

        if (hasActivePeronnel(office.getOfficeId())) {
            throw new CustomerException(GroupConstants.LOANOFFICER_INACTIVE, new Object[] { ApplicationContextProvider.getBean(MessageLookup.class)
                    .lookup(ConfigurationConstants.BRANCHOFFICE) });
        }
    }

    @SuppressWarnings("unchecked")
    private boolean hasActivePeronnel(Short officeId) {

        HashMap<String, Object> queryParameters = new HashMap<String, Object>();
        queryParameters.put("OFFICE_ID", officeId);
        queryParameters.put("STATUS_ID", PersonnelConstants.ACTIVE);
        List queryResult = this.genericDao.executeNamedQuery("getCountActivePersonnel", queryParameters);

        return ((Number) queryResult.get(0)).longValue() > 0;
    }

    @Override
    public void validateNoActivePeronnelExist(Short officeId) throws OfficeException {

        if (hasActivePeronnel(officeId)) {
            throw new OfficeException(OfficeConstants.KEYHASACTIVEPERSONNEL);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public void validateOfficeNameIsNotTaken(String officeName) throws OfficeException {
        HashMap<String, Object> queryParameters = new HashMap<String, Object>();
        queryParameters.put("OFFICE_NAME", officeName);
        List queryResult = this.genericDao.executeNamedQuery("office.getOfficeWithName", queryParameters);

        int officeCount = ((Number) queryResult.get(0)).intValue();

        if (officeCount > 0) {
            throw new OfficeException(OfficeConstants.OFFICENAMEEXIST);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public void validateOfficeShortNameIsNotTaken(String shortName) throws OfficeException {
        HashMap<String, Object> queryParameters = new HashMap<String, Object>();
        queryParameters.put("SHORT_NAME", shortName);
        List queryResult = this.genericDao.executeNamedQuery("office.getOfficeWithShortName", queryParameters);
        int officeCount = ((Number) queryResult.get(0)).intValue();

        if (officeCount > 0) {
            throw new OfficeException(OfficeConstants.OFFICESHORTNAMEEXIST);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<OfficeDto> findActiveParents(OfficeLevel officeLevel) {
        HashMap<String, Object> queryParameters = new HashMap<String, Object>();
        queryParameters.put("LEVEL_ID", officeLevel.getValue());
        queryParameters.put("STATUS_ID", OfficeStatus.ACTIVE.getValue());

        return (List<OfficeDto>) this.genericDao.executeNamedQuery("office.findActiveParents", queryParameters);
    }

    @Override
    public OfficeLevelEntity retrieveOfficeLevel(OfficeLevel officeLevel) {
        HashMap<String, Object> queryParameters = new HashMap<String, Object>();
        queryParameters.put("OFFICE_LEVEL_ID", officeLevel.getValue());

        return (OfficeLevelEntity) this.genericDao.executeUniqueResultNamedQuery("officeLevel.findById", queryParameters);
    }

    @Override
    public void validateNoOfficesExistGivenOfficeLevel(OfficeLevel officeLevel) {
        HashMap<String, Object> queryParameters = new HashMap<String, Object>();
        queryParameters.put("LEVEL_ID", officeLevel.getValue());
        Number count = (Number) this.genericDao.executeUniqueResultNamedQuery("office.getOfficeCountForLevel", queryParameters);
        if (count != null && count.longValue() > 0) {
            throw new BusinessRuleException(OfficeConstants.KEYHASACTIVEOFFICEWITHLEVEL);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<OfficeDetailsDto> findActiveBranches(Short officeId) {

        List<OfficeDetailsDto> matchingActiveBranches = new ArrayList<OfficeDetailsDto>();

        String searchId = HierarchyManager.getInstance().getSearchId(officeId);
        HashMap<String, Object> queryParameters = new HashMap<String, Object>();
        queryParameters.put("levelId", OfficeConstants.BRANCHOFFICE);
        queryParameters.put("OFFICESEARCHID", searchId);
        queryParameters.put("OFFICE_LIKE_SEARCHID", searchId + "%.");
        queryParameters.put("statusId", OfficeConstants.ACTIVE);
        List<OfficeDetailsDto> queryResult = (List<OfficeDetailsDto>) this.genericDao.executeNamedQuery(NamedQueryConstants.MASTERDATA_ACTIVE_BRANCHES,queryParameters);
        if (queryResult != null) {
            matchingActiveBranches = new ArrayList<OfficeDetailsDto>(queryResult);
        }
        return matchingActiveBranches;
    }
}


text:
#import "MMGridViewCell.h"
#import "AppDefine.h"
@interface IMMemberGridViewCell : MMGridViewCell
{
    UILabel *textLabel;
    UIImageView *backgroundView;
}

@property (nonatomic, retain) UILabel *textLabel;
@property (nonatomic, retain) UIImageView *backgroundView;
@end

redpajama_set_name: RedPajamaGithub


text:
namespace blink {
namespace scheduler {

// A list of features which influence scheduling behaviour (throttling /
// freezing / back-forward cache) and which might be sent to the browser process
// for metrics-related purposes.
// When you add a feature, be sure to add it in the lists either to
// kDisallowedFeatures or kAllowedFeatures in BackForwardCacheImpl.
// When you remove a feature, add its index in removed_features in
// BackForwardCacheMetricsTest.AllFeaturesCovered.
enum class WebSchedulerTrackedFeature : uint32_t {
  kMinValue = 0,
  kWebSocket = 0,
  kWebRTC = 1,

  // TODO(rakina): Move tracking of cache-control usage from
  // WebSchedulerTrackedFeature to RenderFrameHost.
  kMainResourceHasCacheControlNoCache = 2,
  kMainResourceHasCacheControlNoStore = 3,
  kSubresourceHasCacheControlNoCache = 4,
  kSubresourceHasCacheControlNoStore = 5,

  // These are unused.
  // kPageShowEventListener = 6,
  // kPageHideEventListener = 7,
  // kBeforeUnloadEventListener = 8,
  // kUnloadEventListener = 9,
  // kFreezeEventListener = 10,
  // kResumeEventListener = 11,

  kContainsPlugins = 12,
  kDocumentLoaded = 13,
  kDedicatedWorkerOrWorklet = 14,

  // There are some other values defined for specific request context types
  // (e.g., XHR). This value corresponds to a network requests not covered by
  // specific context types down below.
  kOutstandingNetworkRequestOthers = 15,

  // kServiceWorkerControlledPage = 16. Removed after implementing ServiceWorker
  // support.

  kOutstandingIndexedDBTransaction = 17,

  // Whether the page tried to request a permission regardless of the outcome.
  // TODO(altimin): Track this more accurately depending on the data.
  // See permission.mojom for more details.
  // kRequestedGeolocationPermission = 19,   // No longer blocking.
  kRequestedNotificationsPermission = 20,
  kRequestedMIDIPermission = 21,
  kRequestedAudioCapturePermission = 22,
  kRequestedVideoCapturePermission = 23,
  kRequestedBackForwardCacheBlockedSensors = 24,
  // This covers all background-related permissions, including background sync,
  // background fetch and others.
  kRequestedBackgroundWorkPermission = 26,

  kBroadcastChannel = 27,

  kIndexedDBConnection = 28,

  // kWebGL = 29. Removed after implementing WebGL support.
  // kWebVR = 30. The entire feature has been deleted.
  kWebXR = 31,

  kSharedWorker = 32,

  kWebLocks = 33,
  kWebHID = 34,

  // kWakeLock = 35, Removed because clean-up is done upon visibility change.

  kWebShare = 36,

  kRequestedStorageAccessGrant = 37,
  kWebNfc = 38,
  // kWebFileSystem = 39. Removed after implementing WebFilesystem support in
  // back/forward cache.

  kOutstandingNetworkRequestFetch = 40,
  kOutstandingNetworkRequestXHR = 41,

  kAppBanner = 42,
  kPrinting = 43,
  kWebDatabase = 44,
  kPictureInPicture = 45,
  kPortal = 46,
  kSpeechRecognizer = 47,
  kIdleManager = 48,
  kPaymentManager = 49,
  kSpeechSynthesis = 50,
  kKeyboardLock = 51,
  kWebOTPService = 52,
  kOutstandingNetworkRequestDirectSocket = 53,
  kInjectedJavascript = 54,
  kInjectedStyleSheet = 55,
  // kMediaSessionImplOnServiceCreated = 56, Removed after implementing
  // MediaSessionImplOnServiceCreated support in back/forward cache.
  kWebTransport = 57,
  // This should be used only for testing.
  kDummy = 58,

  // Please keep in sync with WebSchedulerTrackedFeature in
  // tools/metrics/histograms/enums.xml. These values should not be renumbered.

  // NB: This enum is used in a bitmask, so kMaxValue must be less than 64.
  kMaxValue = kDummy,
};

using WebSchedulerTrackedFeatures =
    base::EnumSet<WebSchedulerTrackedFeature,
                  WebSchedulerTrackedFeature::kMinValue,
                  WebSchedulerTrackedFeature::kMaxValue>;

static_assert(static_cast<uint32_t>(WebSchedulerTrackedFeature::kMaxValue) < 64,
              "This enum is used in a bitmask, so the values should fit into a"
              "64-bit integer");

BLINK_COMMON_EXPORT std::string FeatureToHumanReadableString(
    WebSchedulerTrackedFeature feature);
BLINK_COMMON_EXPORT std::string FeatureToShortString(
    WebSchedulerTrackedFeature feature);

BLINK_COMMON_EXPORT absl::optional<WebSchedulerTrackedFeature> StringToFeature(
    const std::string& str);

// Converts a WebSchedulerTrackedFeature to a bit for use in a bitmask.
BLINK_COMMON_EXPORT constexpr uint64_t FeatureToBit(
    WebSchedulerTrackedFeature feature) {
  return 1ull << static_cast<uint32_t>(feature);
}

// Sticky features can't be unregistered and remain active for the rest of the
// lifetime of the page.
BLINK_COMMON_EXPORT bool IsFeatureSticky(WebSchedulerTrackedFeature feature);

// All the sticky features.
BLINK_COMMON_EXPORT WebSchedulerTrackedFeatures StickyFeatures();

// Disables wake up alignment permanently for the process. This is called when a
// feature that is incompatible with wake up alignment is used. Thread-safe.
BLINK_COMMON_EXPORT void DisableAlignWakeUpsForProcess();
BLINK_COMMON_EXPORT bool IsAlignWakeUpsDisabledForProcess();

}  // namespace scheduler
}  // namespace blink

#endif  // THIRD_PARTY_BLINK_PUBLIC_COMMON_SCHEDULER_WEB_SCHEDULER_TRACKED_FEATURE_H_


text:
from coursedashboards.models import CourseMedianGPA
from uw_sws.enrollment import get_grades_by_regid_and_term, \
    get_enrollment_by_regid_and_term, enrollment_search_by_regid
from uw_sws.models import Term
from uw_sws.person import get_person_by_regid
from uw_sws.registration import get_active_registrations_by_section

"""
Gets data about students e.g. students enrolled
in course X, students' majors and GPAs
"""

def get_students_in_section(section):
    students = []
    registrations = get_active_registrations_by_section(section)
    for registration in registrations:
        """
        #not available until uw_sws updated
        if registration.is_repeat:
            print "Repeat!"
        else:
            print "Not repeat!"
        """
        students.append(registration.person.json_data())
    return students

def get_concurrent_sections_all_students(students,
                                         curriculum, course_number,
                                         section_id, term):
    all_courses = []
    course_dict = {}

    this_course = curriculum + " " + course_number + " " + section_id
    total_students = len(students)

    for student in students:
        all_courses += get_concurrent_sections_by_student(student, term)

    for course in all_courses:
        if course != this_course:
            if course in course_dict:
                course_dict[course] += 1
            else:
                course_dict[course] = 1

    sorted_courses = sorted(course_dict, reverse=True, key=course_dict.get)
    top_courses = []

    for sort in sorted_courses:
        top_courses.append({
            "course": sort,
            "number_students": course_dict[sort],
            "percent_students":
                round(
                    (float(course_dict[sort]) / float(total_students)) *
                    100.0, 2)
        })

    return top_courses

def get_concurrent_sections_by_student(student, term):
    grades = get_grades_by_regid_and_term(student["uwregid"], term)
    concurrent_courses = []

    for course in grades.grades:
        concurrent_courses.append(
            course.section.curriculum_abbr +
            " " + course.section.course_number +
            " " + course.section.section_id)

    return concurrent_courses

def get_majors_all_students(students, term):
    majors_dict = {}
    total_students = len(students)

    for student in students:
        major = get_student_major(student, term)
        for m in major:
            if m.full_name in majors_dict:
                majors_dict[m.full_name] += 1
            else:
                majors_dict[m.full_name] = 1

    return order_majors(majors_dict, total_students)

def get_most_recent_majors_all_students(students):
    majors_dict = {}
    total_students = len(students)

    for student in students:
        person = get_person_by_regid(student["uwregid"])

        term = Term()
        term.quarter = person.last_enrolled.quarter
        term.year = person.last_enrolled.year

        majors = get_student_major(student, term)

        for m in majors:
            if m.full_name in majors_dict:
                majors_dict[m.full_name] += 1
            else:
                majors_dict[m.full_name] = 1

    return order_majors(majors_dict, total_students)

def get_student_major(student, term):
    """

    :param student:
    :param term:
    :return:
    """
    enrollment = get_enrollment_by_regid_and_term(student["uwregid"], term)

    return enrollment.majors

def calc_median_gpa(section, students):
    """

    :param section:
    :param students:
    :return:
    """
    saved_value = CourseMedianGPA.get_cached(section)

    if saved_value:
        return saved_value

    gpas = []

    for student in students:
        gpas.append(get_student_gpa(student))
    new_value = median(gpas)

    CourseMedianGPA.save_value(section, new_value)

    return new_value

def get_student_gpa(student):
    """
    Get enrollments for this student then calculate GPA for each enrollment,
    add up QtrGradePoints, and QtrGradedAttmp
    :param student: an SWS Student object
    :return:
    """
    #
    #

    enrollments = enrollment_search_by_regid(student["uwregid"])
    grade_points = 0
    credits_attempted = 0

    for term in enrollments:
        grades = get_grades_by_regid_and_term(student["uwregid"], term)
        grade_points += count_numeric_only(grades.grade_points)
        credits_attempted += count_numeric_only(grades.credits_attempted)

    return grade_points / credits_attempted

def count_numeric_only(num):
    try:
        ret = float(num)
        return ret
    except TypeError:
        return 0

# PLACEHOLDER until SWS client is updated
def get_all_course_grades(section):
    students = get_active_registrations_by_section(section)
    for student in students:
        student.grade = 3.5
    # ADD WHEN SWS CLIENT UPDATED print student.grade
    return students

def median(values):
    values = sorted(values)
    n = len(values)
    if n < 1:
        return 0
    if n % 2 == 1:
        return values[n//2]
    else:
        return sum(values[n//2-1:n//2+1]) / 2.0


text:
<?php

namespace Magento\Framework\Locale;

use Magento\Framework\App\Config\ScopeConfigInterface;

class Resolver implements ResolverInterface
{
    /**
     * Default locale
     */
    const DEFAULT_LOCALE = 'en_US';
    /**
     * Default locale code
     *
     * @var string
     */
    protected $defaultLocale;

    /**
     * Scope type
     *
     * @var string
     */
    protected $scopeType;

    /**
     * Locale code
     *
     * @var string
     */
    protected $locale;

    /**
     * @var ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * Emulated locales stack
     *
     * @var array
     */
    protected $emulatedLocales = [];

    /**
     * @param ScopeConfigInterface $scopeConfig
     * @param string $defaultLocalePath
     * @param string $scopeType
     * @param mixed $locale
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        $defaultLocalePath,
        $scopeType,
        $locale = null
    ) {
        $this->scopeConfig = $scopeConfig;
        $this->defaultLocalePath = $defaultLocalePath;
        $this->scopeType = $scopeType;
        $this->setLocale($locale);
    }

    /**
     * {@inheritdoc}
     */
    public function getDefaultLocalePath()
    {
        return $this->defaultLocalePath;
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultLocale($locale)
    {
        $this->defaultLocale = $locale;
        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getDefaultLocale()
    {
        if (!$this->defaultLocale) {
            $locale = $this->scopeConfig->getValue($this->getDefaultLocalePath(), $this->scopeType);
            if (!$locale) {
                $locale = self::DEFAULT_LOCALE;
            }
            $this->defaultLocale = $locale;
        }
        return $this->defaultLocale;
    }

    /**
     * {@inheritdoc}
     */
    public function setLocale($locale = null)
    {
        if ($locale !== null && is_string($locale)) {
            $this->locale = $locale;
        } else {
            $this->locale = $this->getDefaultLocale();
        }
        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getLocale()
    {
        if ($this->locale === null) {
            $this->setLocale();
        }
        return $this->locale;
    }

    /**
     * {@inheritdoc}
     */
    public function emulate($scopeId)
    {
        $result = null;
        if ($scopeId) {
            $this->emulatedLocales[] = $this->getLocale();
            $this->locale = $this->scopeConfig->getValue(
                $this->getDefaultLocalePath(),
                $this->scopeType,
                $scopeId
            );
            $result = $this->locale;
        } else {
            $this->emulatedLocales[] = false;
        }
        return $result;
    }

    /**
     * {@inheritdoc}
     */
    public function revert()
    {
        $result = null;
        $localeCode = array_pop($this->emulatedLocales);
        if ($localeCode) {
            $this->locale = $localeCode;
            $result = $this->locale;
        }
        return $result;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
backtype.storm.security.auth.authorizer Class Hierarchy (Storm Core 0.9.1-incubating-SNAPSHOT API)
</TITLE>

<META NAME="date" CONTENT="2014-02-04">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package backtype.storm.security.auth.authorizer

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

backtype.storm.security.auth.authorizer.DenyAuthorizer (implements backtype.storm.security.auth.IAuthorizer)

backtype.storm.security.auth.authorizer.NoopAuthorizer (implements backtype.storm.security.auth.IAuthorizer)

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2014 The Apache Software Foundation. All Rights Reserved.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>12. Data Compression and Archiving — Python 2.7.12 documentation</title>

    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.12 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python 2.7.12 documentation" href="../contents.html" />
    <link rel="up" title="The Python Standard Library" href="index.html" />
    <link rel="next" title="12.1. zlib — Compression compatible with gzip" href="zlib.html" />
    <link rel="prev" title="11.13. sqlite3 — DB-API 2.0 interface for SQLite databases" href="sqlite3.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />

Navigation

          index

          modules |

          next |

          previous |

Python »

          2.7.12
          Documentation »

The Python Standard Library »

12. Data Compression and Archiving¶

The modules described in this chapter support data compression with the zlib,
gzip, and bzip2 algorithms, and  the creation of ZIP- and tar-format archives.
See also Archiving operations provided by the shutil module.

12.1. zlib — Compression compatible with gzip

12.2. gzip — Support for gzip files

12.2.1. Examples of usage

12.3. bz2 — Compression compatible with bzip2

12.3.1. (De)compression of files

12.3.2. Sequential (de)compression

12.3.3. One-shot (de)compression

12.4. zipfile — Work with ZIP archives

12.4.1. ZipFile Objects

12.4.2. PyZipFile Objects

12.4.3. ZipInfo Objects

12.5. tarfile — Read and write tar archive files

12.5.1. TarFile Objects

12.5.2. TarInfo Objects

12.5.3. Examples

12.5.4. Supported tar formats

12.5.5. Unicode issues

Previous topic

11.13. sqlite3 — DB-API 2.0 interface for SQLite databases

Next topic

12.1. zlib — Compression compatible with gzip

This Page

Report a Bug

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

Python »

          2.7.12
          Documentation »

The Python Standard Library »

    © Copyright 1990-2016, Python Software Foundation.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on Jun 25, 2016.
    Found a bug?

    Created using Sphinx 1.3.3.


text:
package com.example.android.sunshine.data;

import android.provider.BaseColumns;

/**
 * Defines table and column names for the weather database. This class is not necessary, but keeps
 * the code organized.
 */
public class WeatherContract {

    /* Inner class that defines the table contents of the weather table */
    public static final class WeatherEntry implements BaseColumns {

        /* Used internally as the name of our weather table. */
        public static final String TABLE_NAME = "weather";

        /*
         * The date column will store the UTC date that correlates to the local date for which
         * each particular weather row represents. For example, if you live in the Eastern
         * Standard Time (EST) time zone and you load weather data at 9:00 PM on September 23, 2016,
         * the UTC time stamp for that particular time would be 1474678800000 in milliseconds.
         * However, due to time zone offsets, it would already be September 24th, 2016 in the GMT
         * time zone when it is 9:00 PM on the 23rd in the EST time zone. In this example, the date
         * column would hold the date representing September 23rd at midnight in GMT time.
         * (1474588800000)
         *
         * The reason we store GMT time and not local time is because it is best practice to have a
         * "normalized", or standard when storing the date and adjust as necessary when
         * displaying the date. Normalizing the date also allows us an easy way to convert to
         * local time at midnight, as all we have to do is add a particular time zone's GMT
         * offset to this date to get local time at midnight on the appropriate date.
         */
        public static final String COLUMN_DATE = "date";

        /* Weather ID as returned by API, used to identify the icon to be used */
        public static final String COLUMN_WEATHER_ID = "weather_id";

        /* Min and max temperatures in °C for the day (stored as floats in the database) */
        public static final String COLUMN_MIN_TEMP = "min";
        public static final String COLUMN_MAX_TEMP = "max";

        /* Humidity is stored as a float representing percentage */
        public static final String COLUMN_HUMIDITY = "humidity";

        /* Pressure is stored as a float representing percentage */
        public static final String COLUMN_PRESSURE = "pressure";

        /* Wind speed is stored as a float representing wind speed in mph */
        public static final String COLUMN_WIND_SPEED = "wind";

        /*
         * Degrees are meteorological degrees (e.g, 0 is north, 180 is south).
         * Stored as floats in the database.
         *
         * Note: These degrees are not to be confused with temperature degrees of the weather.
         */
        public static final String COLUMN_DEGREES = "degrees";
    }
}


text:
Welcome to CodeIgniter Skeleton!

The page you are looking at is being generated dynamically by CodeIgniter.

                If you would like to edit this page you'll find it located at:
                application/modules/skeleton/views/index.php

                The corresponding controller for this page is found at:
                application/modules/skeleton/controllers/skeleton.php

                If you are exploring CodeIgniter for the very first time, you should start by reading the
                User Guide.

                Page rendered in {elapsed_time} seconds.
                <?php echo (ENVIRONMENT === 'development') ? 'CodeIgniter Version ' . CI_VERSION . '' : '' ?>

            <?php
                // Show warning if the assets URL didn't set correctly
                if ( ! preg_match('/^http/', assets_url())):
            ?>

                    Please follow the guide
                    here
                    to setup your assets_url. You should use absolute path, including the protocol.

            <?php
                endif;
            ?>

        <?php foreach ($skeleton_data as $key => $items): ?>

                    <h1 id="<?php echo $key; ?>"><?php echo ucfirst(str_replace('-', ' ', $key)); ?>

                <?php if ( ! empty($items)): ?>

                    <?php foreach ($items as $sub_key => $label): ?>
                        <h2 id="<?php echo $sub_key; ?>"><?php echo $label; ?>

                        <?php echo $this->load->view('content/pagelet_' . str_replace('-', '_', $sub_key), TRUE); ?>
                    <?php endforeach; ?>

                <?php endif; ?>

        <?php endforeach; ?>

        <?php echo $pagelet_sidebar; ?>

                <button class="close" data-dismiss="modal" type="button">×</button>

Source Code


text:
FROM ubuntu:14.04

ENV TERM screen-256color

RUN locale-gen --no-purge en_US.UTF-8
ENV LC_ALL en_US.UTF-8
RUN update-locale LANG=en_US.UTF-8

RUN apt-get update -qq && apt-get install -y wget
RUN wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add -
RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ $(lsb_release -cs)-pgdg main 9.4" > /etc/apt/sources.list.d/pgdg.list

ADD conf/apt-packages.txt /tmp/apt-packages.txt
RUN apt-get update -qq && cat /tmp/apt-packages.txt | xargs apt-get --yes --force-yes install

ADD requirements.txt /tmp/requirements.txt
RUN pip3 install virtualenv
RUN pip install supervisor==3.2

RUN virtualenv -p python3 /var/env/
RUN /var/env/bin/pip install -r /tmp/requirements.txt

WORKDIR /code/

COPY ./ /code/

RUN mkdir -p /var/log/documentregister

ADD conf/entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh

RUN mkdir -p /etc/supervisor/conf.d && mkdir -p /var/log/supervisor
RUN ln -sf /code/conf/supervisor.documentregister.conf /etc/supervisor/conf.d/documentregister.conf
RUN ln -sf /code/conf/supervisord.conf /etc/supervisor/supervisord.conf

ADD conf/nginx.documentregister.conf /etc/nginx/sites-enabled/default

RUN mkdir -p /var/www/static && chmod -R 760 /var/www/static/ && chown -R www-data:www-data /var/www/static
RUN mkdir -p /opt/documentregister/attachments && chmod -R 700 /opt/documentregister/attachments && chown -R www-data:www-data /opt/documentregister/attachments

EXPOSE 5000
EXPOSE 8000

ENTRYPOINT ["entrypoint.sh"]
CMD ["start"]


text:
/**
 * Restfull Resources service for AngularJS apps
 * @version v0.3.2 - 2013-04-12
 * @link https://github.com/mgonto/restangular
 * @author Martin Gontovnikas <martin@gonto.com.ar>
 * @license MIT License, http://www.opensource.org/licenses/MIT
 */
var module = angular.module('restangular', ['ngResource']);

module.provider('Restangular', function() {
        // Configuration
        /**
         * This is the BaseURL to be used with Restangular
         */
        this.baseUrl = "";
        this.setBaseUrl = function(baseUrl) {
            this.baseUrl = baseUrl;
        }

        /**
         * Sets the extra fields to keep from the parents
         */
        this.extraFields = [];
        this.setExtraFields = function(extraFields) {
            this.extraFields = extraFields;
        }

        /**
         * Sets the URL creator type. For now, only Path is created. In the future we'll have queryParams
        **/
        this.urlCreator = "path";
        this.setUrlCreator = function(name) {
            if (!_.has(urlCreatorFactory, name)) {
                throw new Error("URL Path selected isn't valid");
            }
            this.urlCreator = name;
        }

        /**
         * Sets the Response parser. This is used in case your response isn't directly the data.
         * For example if you have a response like {meta: {'meta'}, data: {name: 'Gonto'}}
         * you can extract this data which is the one that needs wrapping
         *
         * The ResponseExtractor is a function that receives the response and the method executed.
         */
        this.responseExtractor = function(response, method) {
            return response;
        }
        this.setResponseExtractor = function(extractor) {
            this.responseExtractor = extractor;
        }

        //Internal values and functions
        var urlCreatorFactory = {};

        /**
         * This is the Path URL creator. It uses Path to show Hierarchy in the Rest API.
         * This means that if you have an Account that then has a set of Buildings, a URL to a building
         * would be /accounts/123/buildings/456
        **/
        var Path = function(baseUrl) {
            this.baseUrl = baseUrl;
        }

        Path.prototype.base = function(current) {
            return this.baseUrl + _.reduce(this.parentsArray(current), function(acum, elem) {
                var currUrl = acum + "/" + elem.route;
                if (elem.id) {
                    currUrl += "/" + elem.id;
                }
                return currUrl;
            }, '');
        }

        Path.prototype.parentsArray = function(current) {
            var parents = [];
            while(!_.isUndefined(current)) {
                parents.push(current);
                current = current.parentResource;
            }
            return parents.reverse();
        }

        Path.prototype.fetchUrl = function(what, current) {
            return this.base(current) + "/" + what.toLowerCase();
        }

        Path.prototype.resource = function(current, $resource, headers) {
            return $resource(this.base(current) + "/:what" , {}, {
                getArray: {method: 'GET', params: {}, isArray: true, headers: headers || {}},
                get: {method: 'GET', params: {}, isArray: false, headers: headers || {}},
                put: {method: 'PUT', params: {}, isArray: false, headers: headers || {}},
                post: {method: 'POST', params: {}, isArray: false, headers: headers || {}},
                remove: {method: 'DELETE', params: {}, isArray: false, headers: headers || {}}
            });
        }

        urlCreatorFactory.path = Path;

       this.$get = ['$resource', '$q', function($resource, $q) {
          var urlHandler = new urlCreatorFactory[this.urlCreator](this.baseUrl);
          var __extraFields = this.extraFields;
          var __responseExtractor = this.responseExtractor;

          function restangularize(parent, elem, route) {
              elem.route = route;
              elem.getList = _.bind(fetchFunction, elem);
              elem.get = _.bind(getFunction, elem);
              elem.put = _.bind(putFunction, elem);
              elem.post = _.bind(postFunction, elem);
              elem.remove = _.bind(deleteFunction, elem);

              if (parent) {
                  elem.parentResource = _.pick(parent, _.union(['id', 'route', 'parentResource'], __extraFields));
              }
              return elem;
          }

          function fetchFunction(what, params, headers) {
              var search = what ? {what: what} : {};
              var __this = this;
              var deferred = $q.defer();

              urlHandler.resource(this, $resource, headers).getArray(_.extend(search, params), function(resData) {
                  var data = __responseExtractor(resData, 'get');
                  var processedData = _.map(data, function(elem) {
                      if (what) {
                          return restangularize(__this, elem, what);
                      } else {
                          return restangularize(null, elem, __this.route);
                      }

                  });
                  deferred.resolve(processedData);
              }, function error() {
                  deferred.reject(arguments)
              });

              return deferred.promise;
          }

          function elemFunction(operation, params, obj, headers) {
              var __this = this;
              var deferred = $q.defer();
              var resParams = params || {};
              var resObj = obj || this;

              var okCallback = function(resData) {
                  var elem = __responseExtractor(resData, operation);
                  if (elem) {
                      deferred.resolve(restangularize(__this.parentResource, elem, __this.route));
                  } else {
                      deferred.resolve();
                  }
              };

              var errorCallback = function() {
                  deferred.reject(arguments)
              };

              if (operation === 'get') {
                  urlHandler.resource(this, $resource, headers)[operation](resParams, okCallback, errorCallback);
              } else {
                  urlHandler.resource(this, $resource, headers)[operation](resParams, resObj, okCallback, errorCallback);
              }

              return deferred.promise;
          }

          function getFunction(params, headers) {
              return _.bind(elemFunction, this)("get", params, undefined, headers);;
          }

          function deleteFunction(params, headers) {
              return _.bind(elemFunction, this)("remove", params, {}, headers);
          }

          function putFunction(params, headers) {
              return _.bind(elemFunction, this)("put", params, undefined, headers);
          }

          function postFunction(what, elem, params, headers) {
              return _.bind(elemFunction, this)("post", _.extend({what: what}, params), elem, headers);
          }

          var service = {};

          service.one = function(route, id) {
              return restangularize(null, {
                  id: id
              }, route);
          }

          service.all = function(route) {
              return restangularize(null, {} , route);
          }

          return service;

        }];
    }
);


text:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
	 android:id="@+id/rowTextView2"
	 android:layout_width="fill_parent"
	 android:layout_height="wrap_content"
	 android:padding="20dp"
	 android:textSize="20sp" >
</TextView>


text:
<!doctype html>

  <meta charset="utf-8">
  <title>Zones throttle</title>
  <link rel="stylesheet" href="css/style.css">

Throttle Example

  <button id="b2">Error</button>


text:
package com.iiordanov.bssh.util;

/**
 * @author kroot
 *
 */
public interface OnDbWrittenListener {
	public void onDbWritten();
}


text:
package org.jivesoftware.smackx;

import static org.junit.Assert.assertTrue;

import java.util.List;

import org.jivesoftware.smack.extensions.ExtensionsInitializer;
import org.junit.Test;

public class ExtensionsInitializerTest {

    @Test
    public void testExtensionInitializer() {
        ExtensionsInitializer ei = new ExtensionsInitializer();
        List<Exception> exceptions = ei.initialize();
        assertTrue(exceptions.size() == 0);
    }

}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>JavaScript Container</title>

Javascript


text:
package org.pac4j.core.matching;

import org.junit.Test;
import org.pac4j.core.context.MockWebContext;
import org.pac4j.core.exception.TechnicalException;
import org.pac4j.core.util.TestsHelper;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.PatternSyntaxException;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * Tests {@link PathMatcher}.
 *
 * @author Rob Ward
 * @since 2.0.0
 */
public class PathMatcherTests {

    @Test
    public void testBlankPath() {
        final PathMatcher pathMatcher = new PathMatcher();
        assertTrue(pathMatcher.matches(MockWebContext.create().setPath("/page.html")));
        assertTrue(pathMatcher.matches(MockWebContext.create()));
    }

    @Test
    public void testFixedPath() {
        final PathMatcher pathMatcher = new PathMatcher().excludePath("/foo");
        assertFalse(pathMatcher.matches(MockWebContext.create().setPath("/foo")));
        assertTrue(pathMatcher.matches(MockWebContext.create().setPath("/foo/bar")));
    }

    @Test
    public void testBranch() {
        final PathMatcher pathMatcher = new PathMatcher().excludeBranch("/foo");
        assertFalse(pathMatcher.matches(MockWebContext.create().setPath("/foo")));
        assertFalse(pathMatcher.matches(MockWebContext.create().setPath("/foo/")));
        assertFalse(pathMatcher.matches(MockWebContext.create().setPath("/foo/bar")));
    }

    @Test
    public void testMissingStartCharacterInRegexp() {
        TestsHelper.expectException(() -> new PathMatcher().excludeRegex("/img/.*$"), TechnicalException.class,
                "Your regular expression: '/img/.*$' must start with a ^ and end with a $ to define a full path matching");
    }

    @Test
    public void testMissingEndCharacterInRegexp() {
        TestsHelper.expectException(() -> new PathMatcher().excludeRegex("^/img/.*"), TechnicalException.class, "Your regular expression: '^/img/.*' must start with a ^ and end with a $ to define a full path matching");
    }

    @Test(expected = PatternSyntaxException.class)
    public void testBadRegexp() {
        new PathMatcher().excludeRegex("^/img/**$");
    }

    @Test
    public void testNoPath() {
        final PathMatcher pathMatcher = new PathMatcher().excludeRegex("^/$");
        assertFalse(pathMatcher.matches(MockWebContext.create().setPath("/")));
    }

    @Test
    public void testMatch() {
        final PathMatcher matcher = new PathMatcher().excludeRegex("^/(img/.*|css/.*|page\\.html)$");
        assertTrue(matcher.matches(MockWebContext.create().setPath("/js/app.js")));
        assertTrue(matcher.matches(MockWebContext.create().setPath("/")));
        assertTrue(matcher.matches(MockWebContext.create().setPath("/page.htm")));
    }

    @Test
    public void testDontMatch() {
        final PathMatcher matcher = new PathMatcher().excludeRegex("^/(img/.*|css/.*|page\\.html)$");
        assertFalse(matcher.matches(MockWebContext.create().setPath("/css/app.css")));
        assertFalse(matcher.matches(MockWebContext.create().setPath("/img/")));
        assertFalse(matcher.matches(MockWebContext.create().setPath("/page.html")));
    }

    @Test
    public void testSetters() {
        final Set<String> excludedPaths = new HashSet<>();
        excludedPaths.add("/foo");
        final Set<String> excludedRegexs = new HashSet<>();
        excludedRegexs.add("^/(img/.*|css/.*|page\\.html)$");

        final PathMatcher matcher = new PathMatcher();
        matcher.setExcludedPaths(excludedPaths);
        matcher.setExcludedPatterns(excludedRegexs);

        assertFalse(matcher.matches(MockWebContext.create().setPath("/foo")));
        assertTrue(matcher.matches(MockWebContext.create().setPath("/foo/"))); // because its a fixed path, not a regex

        assertTrue(matcher.matches(MockWebContext.create().setPath("/error/500.html")));
        assertFalse(matcher.matches(MockWebContext.create().setPath("/img/")));

    }
}


text:
Some Examples of the sensor-applet

GoIO Sensor Grapher


text:
<?php

$schema['top']['addons']['items']['searchanise'] = array(
    'href' => 'addons.update&addon=searchanise',
    'position' => 1000
);

return $schema;


text:
namespace ui {

class PlatformImeControllerAndroid : public PlatformImeController {
 public:
  static bool Register(JNIEnv* env);

  PlatformImeControllerAndroid();
  ~PlatformImeControllerAndroid() override;

  // Native methods called by Java code.
  void Init(JNIEnv* env, jobject jobj);

 private:
  // Overridden from PlatformImeController:
  void UpdateTextInputState(const TextInputState& state) override;
  void SetImeVisibility(bool visible) override;

  JavaObjectWeakGlobalRef java_platform_ime_controller_android_;

  DISALLOW_COPY_AND_ASSIGN(PlatformImeControllerAndroid);
};

}  // namespace ui

#endif  // UI_PLATFORM_WINDOW_ANDROID_PLATFORM_IME_CONTROLLER_ANDROID_H_


text:
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;
import java.lang.Integer;
import java.util.StringTokenizer;

// >>> Don't Change
public class OrphanPages extends Configured implements Tool {

    public static void main(String[] args) throws Exception {
        int res = ToolRunner.run(new Configuration(), new OrphanPages(), args);
        System.exit(res);
    }
// <<< Don't Change

    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = this.getConf();
        Job job = Job.getInstance(conf, "Orphan Pages");

        job.setOutputKeyClass(IntWritable.class);
        job.setOutputValueClass(NullWritable.class);

        job.setMapOutputKeyClass(IntWritable.class);
        job.setMapOutputValueClass(IntWritable.class);

        job.setMapperClass(LinkCountMap.class);
        job.setReducerClass(OrphanPageReduce.class);

        FileInputFormat.setInputPaths(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        job.setJarByClass(OrphanPages.class);
        return job.waitForCompletion(true) ? 0 : 1;
    }

    public static class LinkCountMap extends Mapper<Object, Text, IntWritable, IntWritable> {
        @Override
        public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            String delimiters = " :";
            String line = value.toString();
            StringTokenizer tokenizer = new StringTokenizer(line, delimiters);
            if (tokenizer.hasMoreTokens()) {
                Integer from = Integer.parseInt(tokenizer.nextToken().trim());
                context.write(new IntWritable(from), new IntWritable(0));
            }
            while (tokenizer.hasMoreTokens()) {
                Integer to = Integer.parseInt(tokenizer.nextToken().trim());
                context.write(new IntWritable(to), new IntWritable(1));
            }
        }
    }

    public static class OrphanPageReduce extends Reducer<IntWritable, IntWritable, IntWritable, NullWritable> {
        @Override
        public void reduce(IntWritable key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            boolean orphan = true;
            for (IntWritable val: values) {
                if (val.get() > 0) {
                    orphan = false;
                    break;
                }
            }
            if (orphan) {
                context.write(key, NullWritable.get());
            }
        }
    }
}


text:
package com.scaleunlimited.classify.vectors;

import static org.junit.Assert.assertEquals;

import org.apache.mahout.math.RandomAccessSparseVector;
import org.junit.Test;

public class SetNormalizerTest {

    @Test
    public void testNormalization() {

        BaseNormalizer normalizer = new SetNormalizer();

        RandomAccessSparseVector v = new RandomAccessSparseVector(3);
        v.setQuick(0, 2.0);
        v.setQuick(1, 8.0);
        v.setQuick(2, 0.0);
        normalizer.normalize(v);

        assertEquals(0.5, v.get(0), 0.001);
        assertEquals(0.5, v.get(1), 0.001);
        assertEquals(0.0, v.get(2), 0.001);

        v = new RandomAccessSparseVector(3);
        v.setQuick(0, 4.0);
        v.setQuick(1, 0.0);
        v.setQuick(2, 0.0);
        normalizer.normalize(v);

        assertEquals(1.0, v.get(0), 0.001);
        assertEquals(0.0, v.get(1), 0.001);
        assertEquals(0.0, v.get(2), 0.001);
    }

}


text:
zn.define([
    './DefaultController',
    './ErrorController',
    './APIController'
]);


text:
class BGFXDevice : public WinDisplayDevice
{
private:
   typedef WinDisplayDevice Parent;
public:
   BGFXDevice();

   virtual void initDevice();
   bool activate( U32 width, U32 height, U32 bpp, bool fullScreen );
   void shutdown();
   void destroy();
   bool setScreenMode( U32 width, U32 height, U32 bpp, bool fullScreen, bool forceIt = false, bool repaint = true );
   void swapBuffers();
   const char* getDriverInfo();
   bool getGammaCorrection(F32 &g);
   bool setGammaCorrection(F32 g);
   bool setVerticalSync( bool on );

   static DisplayDevice* create();
};

#endif // _H_WINBGFXVIDEO


text:
<metadata>
  <idinfo>
    <citation>
      <citeinfo>

        <origin>MENAUT, J.-C.</origin>

        <title>NPP GRASSLAND: LAMTO, IVORY COAST, 1965-1987</title>

     			<onlink>http://daac.ornl.gov/cgi-bin/dsviewer.pl?ds_id=150</onlink>

        <onlink>http://daac.ornl.gov/mercury_harvest/150.xml</onlink>
         <alt_onlink>http://daac.ornl.gov/mercury_harvest/150.xml</alt_onlink>

        <onlink>http://daac.ornl.gov//NPP/guides/lmt_guide.html</onlink>

        <geoform>metadata</geoform>
      </citeinfo>
    </citation>
    <descript>
      <abstract>Productivity of a humid grass savanna was determined at the Lamto Research Station, Cote Ivoire, operated in collaboration with CNRS (Centre Nationale de Recherche Scientifique) - Ecole Normale Superieure, Paris, France. Measurement of monthly dynamics of above-ground plant matter (live biomass and dead matter for some years, total biomass in other years), and total roots (live + dead), were monitored from 1969 to 1987. Net primary production has been estimated for both above and below-ground, although more data is available on the former.  Climate data for this site are also available: see Any Other Relevant Information in section 11 of this document.  More information on the entire Net Primary Production Project can be found at the NPP homepage.</abstract>
      <supplinf />
    </descript>
    <timeperd>
      <timeinfo>
        <rngdates>
          <begdate>19650115</begdate>
          <enddate>19870315</enddate>
        </rngdates>
      </timeinfo>
    </timeperd>
    <status>
      <progress>Complete</progress>
      <update> As appropriate</update>
    </status>
    <spdom>
      <bounding>
        <westbc>-5.03</westbc>
        <eastbc>-5.03</eastbc>
        <northbc>6.22</northbc>
        <southbc>6.22</southbc>
      </bounding>
    </spdom>
    <keywords>
      <theme>
        <themekt>Parameter_Sensor_Source</themekt>

        <themekey>BIOMASS|QUADRAT SAMPLING FRAME|FIELD INVESTIGATION</themekey>

        <themekey>BIOMASS|WEIGHING BALANCE|FIELD INVESTIGATION</themekey>

        <themekey>BIOMASS|SOIL CORING DEVICE|FIELD INVESTIGATION</themekey>

        <themekey>PRIMARY PRODUCTION|QUADRAT SAMPLING FRAME|FIELD INVESTIGATION</themekey>

        <themekey>PRIMARY PRODUCTION|WEIGHING BALANCE|FIELD INVESTIGATION</themekey>

        <themekey>PRIMARY PRODUCTION|SOIL CORING DEVICE|FIELD INVESTIGATION</themekey>

      </theme>
      <theme>
        <themekt>Parameter</themekt>

        <themekey>BIOMASS</themekey>

      </theme>
      <theme>
        <themekt>Source</themekt>

        <themekey>FIELD INVESTIGATION</themekey>

      </theme>
      <theme>
        <themekt>Sensor</themekt>

        <themekey>QUADRAT SAMPLING FRAME</themekey>

      </theme>

      <place>
        <placekt>Place Keywords</placekt>

        <placekey>LAMTO COTE IVOIRE</placekey>

      </place>
    </keywords>

    <ptcontac>
      <cntinfo>
        <cntperp>
          <cntper>MENAUT, J.-C.</cntper>
        </cntperp>
        <cntfax>6.1.10.8 Contact Electronic Mail: INTERNET &gt; </cntfax>
      </cntinfo>
    </ptcontac>
  </idinfo>
  <distinfo>
    <distrib>
      <cntinfo>
        <cntperp>
          <cntorg>The Oak Ridge National Laboratory (ORNL) Distributed Active Archive Center (DAAC)</cntorg>
          <cntper>ORNL DAAC User Services Office
        Oak Ridge National Laboratory
        Oak Ridge, Tennessee 37831 USA
        FAX: +1(865)574-4665</cntper>
        </cntperp>
        <cntvoice>+1(865)241-3952</cntvoice>
        <cntfax>6.1.10.8 Contact Electronic Mail: INTERNET &gt; </cntfax>
        <cntemail>ornldaac@ornl.gov</cntemail>
      </cntinfo>
    </distrib>
    <stdorder>
      <digform>
        <digtopt>
          <onlinopt>
            <computer>http://daac.ornl.gov/</computer>
            <accinstr>PUBLIC</accinstr>
          </onlinopt>
        </digtopt>
      </digform>
    </stdorder>
    <resdesc>Menaut, J.-C. 1996. NPP Grassland: Lamto, Ivory Coast, 1965-1987. Data set. Available on-line [http://www.daac.ornl.gov] from Oak Ridge National Laboratory Distributed Active Archive Center, Oak Ridge, Tennessee, U.S.A. doi:10.3334/ORNLDAAC/150</resdesc>
  </distinfo>
  <metainfo>
    <metd>19961024</metd>
    <metc>
      <cntinfo>
        <cntorgp>
          <cntper>ORNL DAAC Staff</cntper>
        </cntorgp>
        <cntperp>
          <cntper>ORNL DAAC Staff</cntper>
        </cntperp>
        <cntvoice>+1(865)241-3952</cntvoice>
        <cntemail>ornldaac@ornl.gov</cntemail>
      </cntinfo>
    </metc>
    <metstdn>FGDC Content Standard for Digital Geospatial Metadata</metstdn>
  </metainfo>
  <Local-Control-Number>Created 2012 05 22 21 30 06 1331736606 by 160.91.11.44</Local-Control-Number>

  <mercury>
    <begdate>19650115</begdate>
    <enddate>19870315</enddate>

    <Site_Information>
      <Site>LAMTO COTE IVOIRE</Site>
      <Westernmost_Longitude>-5.03</Westernmost_Longitude>
      <Easternmost_Longitude>-5.03</Easternmost_Longitude>
      <Northernmost_Latitude>6.22</Northernmost_Latitude>
      <Southernmost_Latitude>6.22</Southernmost_Latitude>
    </Site_Information>

    <Keywords>EOSDIS</Keywords>

    <Parameter_Description>
      <Parameter>BIOMASS </Parameter>
      <Sensor>QUADRAT SAMPLING FRAME </Sensor>
      <Source>FIELD INVESTIGATION </Source>
      <Term>ECOLOGICAL DYNAMICS </Term>
      <Topic>BIOSPHERE </Topic>
    </Parameter_Description>

    <Parameter_Description>
      <Parameter>BIOMASS </Parameter>
      <Sensor>WEIGHING BALANCE </Sensor>
      <Source>FIELD INVESTIGATION </Source>
      <Term>ECOLOGICAL DYNAMICS </Term>
      <Topic>BIOSPHERE </Topic>
    </Parameter_Description>

    <Parameter_Description>
      <Parameter>BIOMASS </Parameter>
      <Sensor>SOIL CORING DEVICE </Sensor>
      <Source>FIELD INVESTIGATION </Source>
      <Term>ECOLOGICAL DYNAMICS </Term>
      <Topic>BIOSPHERE </Topic>
    </Parameter_Description>

    <Parameter_Description>
      <Parameter>PRIMARY PRODUCTION </Parameter>
      <Sensor>QUADRAT SAMPLING FRAME </Sensor>
      <Source>FIELD INVESTIGATION </Source>
      <Term>ECOLOGICAL DYNAMICS </Term>
      <Topic>BIOSPHERE </Topic>
    </Parameter_Description>

    <Parameter_Description>
      <Parameter>PRIMARY PRODUCTION </Parameter>
      <Sensor>WEIGHING BALANCE </Sensor>
      <Source>FIELD INVESTIGATION </Source>
      <Term>ECOLOGICAL DYNAMICS </Term>
      <Topic>BIOSPHERE </Topic>
    </Parameter_Description>

    <Parameter_Description>
      <Parameter>PRIMARY PRODUCTION </Parameter>
      <Sensor>SOIL CORING DEVICE </Sensor>
      <Source>FIELD INVESTIGATION </Source>
      <Term>ECOLOGICAL DYNAMICS </Term>
      <Topic>BIOSPHERE </Topic>
    </Parameter_Description>

    <Project>NET PRIMARY PRODUCTIVITY (NPP)</Project>

    <Navpath>FIELD INVESTIGATION|QUADRAT SAMPLING FRAME|BIOMASS</Navpath>

    <Navpath>FIELD INVESTIGATION|WEIGHING BALANCE|BIOMASS</Navpath>

    <Navpath>FIELD INVESTIGATION|SOIL CORING DEVICE|BIOMASS</Navpath>

    <Navpath>FIELD INVESTIGATION|QUADRAT SAMPLING FRAME|PRIMARY PRODUCTION</Navpath>

    <Navpath>FIELD INVESTIGATION|WEIGHING BALANCE|PRIMARY PRODUCTION</Navpath>

    <Navpath>FIELD INVESTIGATION|SOIL CORING DEVICE|PRIMARY PRODUCTION</Navpath>

    <Principal_Investigator>
      <Name>MENAUT, J.-C.</Name>
      <Email />
    </Principal_Investigator>

    <Data_Set_Link>
      <URL>http://daac.ornl.gov/cgi-bin/dsviewer.pl?ds_id=150</URL>
      NPP GRASSLAND: LAMTO, IVORY COAST, 1965-1987
      <Link_Note />
    </Data_Set_Link>

    <Documentation_Link>
      <URL>http://daac.ornl.gov//NPP/guides/lmt_guide.html</URL>
      NPP GRASSLAND: LAMTO, IVORY COAST, 1965-1987
      <Text />
    </Documentation_Link>

    <OME_Software_Version>/home/web/mercury/write_mercury_xml.pl</OME_Software_Version>
    <OME_DTD_Version>mercury21.dtd</OME_DTD_Version>

    <Contact_Person>
      <Email>ornldaac@ornl.gov</Email>
      <Name>ORNL DAAC User Services Office
        Oak Ridge National Laboratory
        Oak Ridge, Tennessee 37831 USA
        FAX: +1(865)574-4665</Name>
      <Phone>+1(865)241-3952</Phone>
    </Contact_Person>

    <Temporal_Resolution />
    <enddate_blank />
    <File_ID>150</File_ID>
    <MD_Entry_id>NPP_LMT</MD_Entry_id>

    <Spatial_Extent>0</Spatial_Extent>

    <Search_Text_Link>
      <URL>http://daac.ornl.gov//NPP/guides/lmt_guide.html</URL>
      NPP GRASSLAND: LAMTO, IVORY COAST, 1965-1987
    </Search_Text_Link>

    <Granule_Details>

    </Granule_Details>
    <OGC_URL />
    <THREDDS_URL />

  </mercury>

</metadata>


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <script src="../../dist/browser.js"></script>
    <script src="standardised.js"></script>

    <title>Js Module - test page</title>
</head>
<body>

</body>
</html>


text:
package fr.univ.nantes.processor;

import fr.univ.nantes.Spoon;
import spoon.processing.AbstractProcessor;
import spoon.reflect.code.CtBlock;
import spoon.reflect.code.CtStatement;
import spoon.reflect.code.CtTry;
import spoon.reflect.declaration.CtConstructor;
import spoon.reflect.declaration.CtExecutable;
import spoon.reflect.declaration.CtMethod;

/**
 * @author Alexis Giraudet
 * @author Thomas Minier
 */
public class MethodCallTreeProcessor extends AbstractProcessor<CtExecutable<?>> {
    @Override
    public boolean isToBeProcessed(CtExecutable<?> executable) {
        return executable instanceof CtMethod || executable instanceof CtConstructor;
    }

    @Override
    public void process(CtExecutable<?> executable) {
        String enterCode = "fr.univ.nantes.logger.LogWriter.enterMethod(\"" + Spoon.getExecutableKey(executable) + "\")";
        String leaveCode = "fr.univ.nantes.logger.LogWriter.leaveMethod()";
        CtStatement enterCtStatement = getFactory().Code().createCodeSnippetStatement(enterCode);
        CtStatement leaveCtStatement = getFactory().Code().createCodeSnippetStatement(leaveCode);
        CtTry ctTry = getFactory().Core().createTry();
        CtBlock finallyCtBlock = getFactory().Core().createBlock();
        CtBlock bodyCtBlock = getFactory().Core().createBlock();

        finallyCtBlock.addStatement(leaveCtStatement);
        ctTry.setFinalizer(finallyCtBlock);
        ctTry.setBody(executable.getBody());
        bodyCtBlock.addStatement(enterCtStatement);
        bodyCtBlock.addStatement(ctTry);
        executable.setBody(bodyCtBlock);
    }
}


text:
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/err.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/remoteproc.h>
#include <linux/mailbox_client.h>
#include <linux/omap-mailbox.h>

#include <linux/platform_data/remoteproc-omap.h>

#include "omap_remoteproc.h"
#include "remoteproc_internal.h"

/**
 * struct omap_rproc - omap remote processor state
 * @mbox: mailbox channel handle
 * @client: mailbox client to request the mailbox channel
 * @rproc: rproc handle
 */
struct omap_rproc {
	struct mbox_chan *mbox;
	struct mbox_client client;
	struct rproc *rproc;
};

/**
 * omap_rproc_mbox_callback() - inbound mailbox message handler
 * @client: mailbox client pointer used for requesting the mailbox channel
 * @data: mailbox payload
 *
 * This handler is invoked by omap's mailbox driver whenever a mailbox
 * message is received. Usually, the mailbox payload simply contains
 * the index of the virtqueue that is kicked by the remote processor,
 * and we let remoteproc core handle it.
 *
 * In addition to virtqueue indices, we also have some out-of-band values
 * that indicates different events. Those values are deliberately very
 * big so they don't coincide with virtqueue indices.
 */
static void omap_rproc_mbox_callback(struct mbox_client *client, void *data)
{
	struct omap_rproc *oproc = container_of(client, struct omap_rproc,
						client);
	struct device *dev = oproc->rproc->dev.parent;
	const char *name = oproc->rproc->name;
	u32 msg = (u32)data;

	dev_dbg(dev, "mbox msg: 0x%x\n", msg);

	switch (msg) {
	case RP_MBOX_CRASH:
		/* just log this for now. later, we'll also do recovery */
		dev_err(dev, "omap rproc %s crashed\n", name);
		break;
	case RP_MBOX_ECHO_REPLY:
		dev_info(dev, "received echo reply from %s\n", name);
		break;
	default:
		/* msg contains the index of the triggered vring */
		if (rproc_vq_interrupt(oproc->rproc, msg) == IRQ_NONE)
			dev_dbg(dev, "no message was found in vqid %d\n", msg);
	}
}

/* kick a virtqueue */
static void omap_rproc_kick(struct rproc *rproc, int vqid)
{
	struct omap_rproc *oproc = rproc->priv;
	struct device *dev = rproc->dev.parent;
	int ret;

	/* send the index of the triggered virtqueue in the mailbox payload */
	ret = mbox_send_message(oproc->mbox, (void *)vqid);
	if (ret < 0)
		dev_err(dev, "omap_mbox_msg_send failed: %d\n", ret);
}

/*
 * Power up the remote processor.
 *
 * This function will be invoked only after the firmware for this rproc
 * was loaded, parsed successfully, and all of its resource requirements
 * were met.
 */
static int omap_rproc_start(struct rproc *rproc)
{
	struct omap_rproc *oproc = rproc->priv;
	struct device *dev = rproc->dev.parent;
	struct platform_device *pdev = to_platform_device(dev);
	struct omap_rproc_pdata *pdata = pdev->dev.platform_data;
	int ret;
	struct mbox_client *client = &oproc->client;

	if (pdata->set_bootaddr)
		pdata->set_bootaddr(rproc->bootaddr);

	client->dev = dev;
	client->tx_done = NULL;
	client->rx_callback = omap_rproc_mbox_callback;
	client->tx_block = false;
	client->knows_txdone = false;

	oproc->mbox = omap_mbox_request_channel(client, pdata->mbox_name);
	if (IS_ERR(oproc->mbox)) {
		ret = -EBUSY;
		dev_err(dev, "mbox_request_channel failed: %ld\n",
			PTR_ERR(oproc->mbox));
		return ret;
	}

	/*
	 * Ping the remote processor. this is only for sanity-sake;
	 * there is no functional effect whatsoever.
	 *
	 * Note that the reply will _not_ arrive immediately: this message
	 * will wait in the mailbox fifo until the remote processor is booted.
	 */
	ret = mbox_send_message(oproc->mbox, (void *)RP_MBOX_ECHO_REQUEST);
	if (ret < 0) {
		dev_err(dev, "mbox_send_message failed: %d\n", ret);
		goto put_mbox;
	}

	ret = pdata->device_enable(pdev);
	if (ret) {
		dev_err(dev, "omap_device_enable failed: %d\n", ret);
		goto put_mbox;
	}

	return 0;

put_mbox:
	mbox_free_channel(oproc->mbox);
	return ret;
}

/* power off the remote processor */
static int omap_rproc_stop(struct rproc *rproc)
{
	struct device *dev = rproc->dev.parent;
	struct platform_device *pdev = to_platform_device(dev);
	struct omap_rproc_pdata *pdata = pdev->dev.platform_data;
	struct omap_rproc *oproc = rproc->priv;
	int ret;

	ret = pdata->device_shutdown(pdev);
	if (ret)
		return ret;

	mbox_free_channel(oproc->mbox);

	return 0;
}

static struct rproc_ops omap_rproc_ops = {
	.start		= omap_rproc_start,
	.stop		= omap_rproc_stop,
	.kick		= omap_rproc_kick,
};

static int omap_rproc_probe(struct platform_device *pdev)
{
	struct omap_rproc_pdata *pdata = pdev->dev.platform_data;
	struct omap_rproc *oproc;
	struct rproc *rproc;
	int ret;

	ret = dma_set_coherent_mask(&pdev->dev, DMA_BIT_MASK(32));
	if (ret) {
		dev_err(&pdev->dev, "dma_set_coherent_mask: %d\n", ret);
		return ret;
	}

	rproc = rproc_alloc(&pdev->dev, pdata->name, &omap_rproc_ops,
				pdata->firmware, sizeof(*oproc));
	if (!rproc)
		return -ENOMEM;

	oproc = rproc->priv;
	oproc->rproc = rproc;
	/* All existing OMAP IPU and DSP processors have an MMU */
	rproc->has_iommu = true;

	platform_set_drvdata(pdev, rproc);

	ret = rproc_add(rproc);
	if (ret)
		goto free_rproc;

	return 0;

free_rproc:
	rproc_put(rproc);
	return ret;
}

static int omap_rproc_remove(struct platform_device *pdev)
{
	struct rproc *rproc = platform_get_drvdata(pdev);

	rproc_del(rproc);
	rproc_put(rproc);

	return 0;
}

static struct platform_driver omap_rproc_driver = {
	.probe = omap_rproc_probe,
	.remove = omap_rproc_remove,
	.driver = {
		.name = "omap-rproc",
	},
};

module_platform_driver(omap_rproc_driver);

MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("OMAP Remote Processor control driver");


text:
using System;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Elastic.Clients.Elasticsearch.Serialization;

internal sealed class IntermediateSourceConverter<T> : JsonConverter<T>
{
	public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
	{
		var converter = options.GetConverter(typeof(SourceMarker<>).MakeGenericType(typeToConvert));

		if (converter is SourceConverter<T> sourceConverter)
		{
			var source = sourceConverter.Read(ref reader, typeToConvert, options);
			return source.Source;
		}

		return default;
	}

	public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
	{
		var converter = options.GetConverter(typeof(SourceMarker<>).MakeGenericType(typeof(T)));

		if (converter is SourceConverter<T> sourceConverter)
		{
			sourceConverter.Write(writer, new SourceMarker<T> { Source = value }, options);
		}
	}
}


text:
'use strict';

require('./ava');
require('./changelog');
require('./check-links');
require('./clean');
require('./compile');
require('./compile-access-expr');
require('./compile-bind-expr');
require('./compile-css-expr');
require('./create-golden-css');
require('./csvify-size');
require('./dep-check');
require('./get-zindex');
require('./gen-codeowners');
require('./extension-generator');
require('./process-github-issues');
require('./json-check');
require('./lint');
require('./prepend-global');
require('./presubmit-checks');
require('./release-tagging');
require('./runtime-test');
require('./serve');
require('./size');
require('./todos');
require('./update-packages');
require('./validator');
require('./visual-diff');


text:
package memnets.core

class GameButtons extends GameControl {
  val buttons: Array[GameButton] = Array.tabulate(3) { i =>
    GameButton(id = i + 1, "ABCD".charAt(i).toString)
  }
  def reset(): Unit = {
    for (b <- buttons) {
      b.disabled = false
      b.pressed = false
    }
  }
  def apply(i: Int): GameButton = buttons(i)
}
object GameButtons {
  // max = 4
  def apply(numButtons: Int = 3)(implicit model: Model): GameButtons = {
    val gb = new GameButtons()
    for ((b, i) <- gb.buttons.zipWithIndex)
      b.visible = i < numButtons
    model.controls += gb
    gb
  }
}


text:
NSString *const kGPUImageVignetteFragmentShaderString = SHADER_STRING
(
 uniform sampler2D inputImageTexture;
 varying highp vec2 textureCoordinate;

 uniform lowp vec2 vignetteCenter;
 uniform lowp vec3 vignetteColor;
 uniform lowp float vignetteAlpha;
 uniform highp float vignetteStart;
 uniform highp float vignetteEnd;

 void main()
 {
     lowp vec4 sourceImageColor = texture2D(inputImageTexture, textureCoordinate);
     lowp float d = distance(textureCoordinate, vec2(vignetteCenter.x, vignetteCenter.y));
     lowp float percent = smoothstep(vignetteStart, vignetteEnd, d);
     gl_FragColor = vec4(mix(sourceImageColor.rgb, vignetteColor, vignetteAlpha * percent), sourceImageColor.a);
 }
);
#else
NSString *const kGPUImageVignetteFragmentShaderString = SHADER_STRING
(
 uniform sampler2D inputImageTexture;
 varying vec2 textureCoordinate;

 uniform vec2 vignetteCenter;
 uniform vec3 vignetteColor;
 uniform float vignetteAlpha;
 uniform float vignetteStart;
 uniform float vignetteEnd;

 void main()
 {
     vec4 sourceImageColor = texture2D(inputImageTexture, textureCoordinate);
     float d = distance(textureCoordinate, vec2(vignetteCenter.x, vignetteCenter.y));
     float percent = smoothstep(vignetteStart, vignetteEnd, d);
     gl_FragColor = vec4(mix(sourceImageColor.rgb, vignetteColor, vignetteAlpha * percent), sourceImageColor.a);
 }
);
#endif

@implementation GPUImageVignetteFilter

@synthesize vignetteCenter = _vignetteCenter;
@synthesize vignetteColor = _vignetteColor;
@synthesize vignetteAlpha =_vignetteAlpha;
@synthesize vignetteStart =_vignetteStart;
@synthesize vignetteEnd = _vignetteEnd;

#pragma mark -
#pragma mark Initialization and teardown

- (id)init;
{
    if (!(self = [super initWithFragmentShaderFromString:kGPUImageVignetteFragmentShaderString]))
    {
		return nil;
    }

    vignetteCenterUniform = [filterProgram uniformIndex:@"vignetteCenter"];
    vignetteColorUniform = [filterProgram uniformIndex:@"vignetteColor"];
    vignetteAlphaUniform = [filterProgram uniformIndex:@"vignetteAlpha"];
    vignetteStartUniform = [filterProgram uniformIndex:@"vignetteStart"];
    vignetteEndUniform = [filterProgram uniformIndex:@"vignetteEnd"];

    self.vignetteCenter = (CGPoint){ 0.5f, 0.5f };
    self.vignetteColor = (GPUVector3){ 0.0f, 0.0f, 0.0f };
    self.vignetteAlpha = 1.0;
    self.vignetteStart = 0.3;
    self.vignetteEnd = 0.75;

    return self;
}

#pragma mark -
#pragma mark Accessors

- (void)setVignetteCenter:(CGPoint)newValue
{
    _vignetteCenter = newValue;

    [self setPoint:newValue forUniform:vignetteCenterUniform program:filterProgram];
}

- (void)setVignetteColor:(GPUVector3)newValue
{
    _vignetteColor = newValue;

    [self setVec3:newValue forUniform:vignetteColorUniform program:filterProgram];
}

- (void)setVignetteAlpha:(CGFloat)newValue;
{
    _vignetteAlpha = newValue;

    [self setFloat:_vignetteAlpha forUniform:vignetteAlphaUniform program:filterProgram];
}

- (void)setVignetteStart:(CGFloat)newValue;
{
    _vignetteStart = newValue;

    [self setFloat:_vignetteStart forUniform:vignetteStartUniform program:filterProgram];
}

- (void)setVignetteEnd:(CGFloat)newValue;
{
    _vignetteEnd = newValue;

    [self setFloat:_vignetteEnd forUniform:vignetteEndUniform program:filterProgram];
}

@end


text:
process.env.NODE_ENV = 'test';

var chai     = require('chai');
var chaiHttp = require('chai-http');
var mongoose = require('mongoose');
var server   = require('../app.js');
var should   = chai.should();

chai.use(chaiHttp);

describe('test app.js', () => {

  describe('test 404 error', () => {
    it('should return 404 error', (done) => {
      chai.request(server)
        .get('/wattwattwatt')
        .end((error,res) => {
          res.status.should.equal(404);
          done();
        });
    });
  });

  describe('test port success : normal case', () => {
    it('should test normal port', (done) => {
      var value = 3002;
      var result = server.normalizePort(value);
      result.should.equal(value);
      done();
    });
  });

  describe('test port error : negative case', () => {
    it('should test negative port', (done) => {
      var value = -1;
      var result = server.normalizePort(value);
      result.should.equal(false);
      done();
    });
  });

  describe('test port error : NaN case', () => {
    it('should test NaN port', (done) => {
      var value = 'test';
      var result = server.normalizePort(value);
      result.should.equal(value);
      done();
    });
  });

  describe('test calling of onListening', () => {
    it('test onListening', (done) => {
      server.emit('listening');
      done();
    });
  });

  describe('test onError check default', () => {
    it('test onError default', (done) => {
      try {
        var fakeError = new Error('test');
        fakeError.syscall = 'listen';
        fakeError.code = 42;
        server.emit('error', fakeError);
      } catch (error) {
        done();
      }
    });
  });

  describe('test onError check syscall', () => {
    it('test onError syscall', (done) => {
      try {
        var fakeError = new Error('test');
        fakeError.syscall = 'test';
        server.emit('error', fakeError);
      } catch (error) {
        done();
      }
    });
  });

  describe('test onError EACCES', () => {
    it('test onError EACCES', (done) => {
      try {
        var fakeError = new Error('test');
        fakeError.syscall = 'listen';
        fakeError.code = 'EACCES';
        server.emit('error', fakeError);
      } catch (error) {
        done();
      }
    });
  });

  describe('test onError EADDRINUSE', () => {
    it('test onError EADDRINUSE', (done) => {
      try {
        var fakeError = new Error('test');
        fakeError.syscall = 'listen';
        fakeError.code = 'EADDRINUSE';
        server.emit('error', fakeError);
      } catch (error) {
        done();
      }
    });
  });

});


text:
package com.stratio.qa.cucumber.testng;

import cucumber.api.CucumberOptions;
import cucumber.runtime.ClassFinder;
import cucumber.runtime.CucumberException;
import cucumber.runtime.RuntimeOptions;
import cucumber.runtime.RuntimeOptionsFactory;
import cucumber.runtime.io.MultiLoader;
import cucumber.runtime.io.ResourceLoader;
import cucumber.runtime.io.ResourceLoaderClassFinder;
import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class CucumberRunner {

    private final cucumber.runtime.Runtime runtime;

    private ClassLoader classLoader;

    private RuntimeOptions runtimeOptions;

    private final Logger logger = LoggerFactory.getLogger(this.getClass()
            .getCanonicalName());

    /**
     * Default constructor for cucumber Runner.
     *
     * @param clazz class
     * @param feature feature to execute
     * @throws IOException exception
     * @throws ClassNotFoundException exception
     * @throws InstantiationException exception
     * @throws IllegalAccessException exception
     * @throws NoSuchMethodException exception
     * @throws InvocationTargetException exception
     */
    @SuppressWarnings("unused")
    public CucumberRunner(Class<?> clazz, String... feature) throws IOException, ClassNotFoundException,
            InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        classLoader = clazz.getClassLoader();
        ResourceLoader resourceLoader = new MultiLoader(classLoader);

        RuntimeOptionsFactory runtimeOptionsFactory = new RuntimeOptionsFactory(clazz,
                new Class[]{CucumberOptions.class});
        runtimeOptions = runtimeOptionsFactory.create();
        String testSuffix = System.getProperty("TESTSUFFIX");
        String targetExecutionsPath = "target/executions/";
        if (testSuffix != null) {
            targetExecutionsPath = targetExecutionsPath + testSuffix + "/";
        }
        boolean aux = new File(targetExecutionsPath).mkdirs();
        CucumberReporter reporterTestNG;

        if ((feature.length == 0)) {
            reporterTestNG = new CucumberReporter(targetExecutionsPath, clazz.getCanonicalName(), "");
        } else {
            List<String> features = new ArrayList<String>();
            String fPath = "src/test/resources/features/" + feature[0] + ".feature";
            features.add(fPath);
            runtimeOptions.getFeaturePaths().addAll(features);
            reporterTestNG = new CucumberReporter(targetExecutionsPath, clazz.getCanonicalName(), feature[0]);
        }

        List<String> uniqueGlue = new ArrayList<String>();
        uniqueGlue.add("classpath:com/stratio/qa/specs");
        uniqueGlue.add("classpath:com/stratio/sparta/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/gosecsso/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/dcos/crossdata/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/cct/configuration/api/specs");
        uniqueGlue.add("classpath:com/stratio/crossdata/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/streaming/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/ingestion/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/datavis/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/connectors/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/admin/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/explorer/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/manager/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/viewer/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/decision/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/paas/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/cassandra/lucene/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/analytic/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/exhibitor/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/intelligence/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/postgresbd/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/postgresql/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/zookeeper/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/universe/testsAT/specs");
        uniqueGlue.add("classpath:com/stratio/paas/dgDatadictionaryAT/specs");
        uniqueGlue.add("classpath:com/stratio/paas/dgtests/specs");
        uniqueGlue.add("classpath:com/stratio/elastic/specs");
        uniqueGlue.add("classpath:com/stratio/kafka/specs");
        uniqueGlue.add("classpath:com/stratio/hdfs/specs");
        uniqueGlue.add("classpath:com/stratio/cassandra/specs");
        uniqueGlue.add("classpath:com/stratio/schema_registry/specs");
        uniqueGlue.add("classpath:com/stratio/rest_proxy/specs");
        uniqueGlue.add("classpath:com/stratio/spark/tests/specs");
        uniqueGlue.add("classpath:com/stratio/schema/discovery/specs");

        runtimeOptions.getGlue().clear();
        runtimeOptions.getGlue().addAll(uniqueGlue);

        runtimeOptions.addFormatter(reporterTestNG);
        Set<Class<? extends ICucumberFormatter>> implementers = new Reflections("com.stratio.qa.utils")
                .getSubTypesOf(ICucumberFormatter.class);

        for (Class<? extends ICucumberFormatter> implementerClazz : implementers) {
            Constructor<?> ctor = implementerClazz.getConstructor();
            ctor.setAccessible(true);
            runtimeOptions.addFormatter((ICucumberFormatter) ctor.newInstance());
        }

        ClassFinder classFinder = new ResourceLoaderClassFinder(resourceLoader, classLoader);
        runtime = new cucumber.runtime.Runtime(resourceLoader, classFinder, classLoader, runtimeOptions);
    }

    /**
     * Run the testclases(Features).
     *
     * @throws IOException exception
     * @throws NoSuchMethodException exception
     * @throws InvocationTargetException exception
     * @throws IllegalAccessException exception
     */
    public void runCukes() throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        runtime.run();

        if (!runtime.getErrors().isEmpty()) {
            Iterator<Throwable> iterator = runtime.getErrors().iterator();
            while (iterator.hasNext()) {
                Throwable value = iterator.next();
                if (value.getMessage().contains("TESTS EXECUTION ABORTED!")) {
                    iterator.remove();
                }
            }
            logger.error ("Got {} exceptions", runtime.getErrors());
            throw new CucumberException(runtime.getErrors().get(0));
        }
    }
}


text:
package br.com.pelisoli.githubapp.presentation.search.repository;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.github.rahatarmanahmed.cpv.CircularProgressView;

import java.util.List;

import br.com.pelisoli.githubapp.GithubApplication;
import br.com.pelisoli.githubapp.R;
import br.com.pelisoli.githubapp.domain.api.GithubApi;
import br.com.pelisoli.githubapp.domain.model.Repository;
import br.com.pelisoli.githubapp.presentation.search.dialog.InfoDialog;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by pelisoli on 8/21/16.
 */
public class RepositoriesActivity extends AppCompatActivity implements RepositoriesContract.View{
    @BindView(R.id.recycler_repo)
    RecyclerView mRecyclerView;

    @BindView(R.id.rep_progress_view)
    CircularProgressView mProgress;

    private RepositoriesAdapter mRepositoriesAdapter;

    private List<Repository> mRepositories = null;

    private String userName = "";

    private RepositoriesContract.Presenter mPresenter;

    private GithubApplication application;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.repositories_activity);

        ButterKnife.bind(this);

        application =  (GithubApplication)getApplication();

        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {
            userName = bundle.getString("userName");
        }

        mRepositoriesAdapter = new RepositoriesAdapter(mRepositories);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mRepositoriesAdapter);

        mPresenter = new RepositoriesPresenter(GithubApi.getRetrofit(), application.getLog());
        mPresenter.attachView(this);
        mPresenter.searchRepository(userName);

    }

    @Override
    public void showProgress() {
            mProgress.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideProgress() {
        mProgress.setVisibility(View.GONE);
    }

    @Override
    public void showRepositoryList(List<Repository> repositoriesList) {
        mRepositoriesAdapter.addNewList(repositoriesList);
    }

    @Override
    public void showError() {
        DialogFragment dialog = InfoDialog.newInstance(getString(R.string.error));
        dialog.show(this.getSupportFragmentManager(), "InfoDialog");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.detachView();
    }
}


text:
layout: page
title: Lozano 25th Anniversary
date: 2016-05-24
author: Austin Nash
tags: weekly links, java
status: published
summary: Mauris sed metus vel lectus consectetur pulvinar. Vestibulum sit.
banner: images/banner/wedding.jpg
booking:
  startDate: 03/04/2018
  endDate: 03/09/2018
  ctyhocn: PARISHX
  groupCode: L2A
published: true
---
In posuere dui nec nisl elementum, eu viverra metus sagittis. Sed rhoncus rutrum dui, vel tincidunt nisi mattis id. Suspendisse iaculis mattis dolor nec convallis. In ut malesuada tellus. Phasellus et justo et felis pellentesque ultrices. Mauris quis mollis turpis. Suspendisse feugiat luctus lorem vitae vulputate. Curabitur ut mauris vitae tortor efficitur interdum.

* Praesent mattis risus nec mauris porta vulputate
* Etiam quis metus quis justo volutpat accumsan sed vel purus
* Maecenas lacinia nisi eu tellus tincidunt, non congue justo congue.

Mauris vel tellus nec neque lobortis ornare non quis tellus. Etiam non aliquam diam. Suspendisse bibendum tellus et dapibus tempus. Donec erat neque, euismod id eros nec, ultricies ultrices eros. Ut sed leo sit amet urna molestie vestibulum. Nunc ac ligula at purus varius placerat eu vel neque. Aliquam erat volutpat. Nulla imperdiet quam ac sollicitudin elementum. Vivamus eget dui a nibh tempor tincidunt. Praesent vitae lorem nisi. Mauris in tortor consectetur, tempus eros vitae, convallis ex. Cras vel iaculis mi, sed rhoncus diam. Nam eget lacus vestibulum, commodo elit molestie, accumsan nisi. Nunc gravida felis eu aliquet tincidunt.
Aenean eu neque suscipit, posuere erat vel, aliquam arcu. Cras ex sapien, pharetra non turpis facilisis, vulputate tempor leo. Etiam lacinia eget sem in ullamcorper. Vestibulum felis ex, rhoncus non nisl eget, pretium placerat ipsum. Ut posuere est tristique velit sodales tempor. Nunc hendrerit sapien nec magna efficitur pharetra. Integer semper libero malesuada ipsum ultricies, sit amet interdum felis posuere. Integer augue nibh, venenatis vel nunc et, ultrices dignissim ante.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>KaffeNative2Ascii (Apache Ant API)</title>
<meta name="date" content="2012-05-22">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.tools.ant.taskdefs.optional.native2ascii

Class KaffeNative2Ascii

java.lang.Object

org.apache.tools.ant.taskdefs.optional.native2ascii.DefaultNative2Ascii

org.apache.tools.ant.taskdefs.optional.native2ascii.KaffeNative2Ascii

All Implemented Interfaces:

Native2AsciiAdapter

public final class KaffeNative2Ascii
extends DefaultNative2Ascii

Adapter to kaffe.tools.native2ascii.Native2Ascii.

Since:

Ant 1.6.3

Field Summary

Fields

Modifier and Type
Field and Description

static java.lang.String
IMPLEMENTATION_NAME

Identifies this adapter.

Constructor Summary

Constructors

Constructor and Description

KaffeNative2Ascii()

Method Summary

Methods

Modifier and Type
Method and Description

protected boolean
run(Commandline cmd,
   ProjectComponent log)

Executes the command.

protected void
setup(Commandline cmd,
     Native2Ascii args)

Sets up the initial command line.

Methods inherited from class org.apache.tools.ant.taskdefs.optional.native2ascii.DefaultNative2Ascii

addFiles, convert

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

IMPLEMENTATION_NAME

public static final java.lang.String IMPLEMENTATION_NAME

Identifies this adapter.

See Also:

Constant Field Values

Constructor Detail

KaffeNative2Ascii

public KaffeNative2Ascii()

Method Detail

setup

protected void setup(Commandline cmd,
         Native2Ascii args)
              throws BuildException

Sets up the initial command line.

only the -encoding argument and nested arg elements get
 handled here.

Overrides:

setup in class DefaultNative2Ascii

Parameters:

cmd - Command line to add to

args - provides the user-setting and access to Ant's
 logging system.

Throws:

BuildException - if there was a problem.

run

protected boolean run(Commandline cmd,
          ProjectComponent log)
               throws BuildException

Executes the command.

Specified by:

run in class DefaultNative2Ascii

Parameters:

cmd - Command line to execute

log - provides access to Ant's logging system.

Returns:

whether execution was successful

Throws:

BuildException - if there was a problem.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
namespace py = boost::python;

struct UnitBase {
  int unit_id{};
  int hero_id{};
  int root_unit_id{};
  int unit_type{};
  int camp_type{};
  std::string unit_name;

  virtual void tick(double dt) {}
};

struct UnitBaseWrap : public UnitBase, public py::wrapper<UnitBase> {
  virtual void tick(double dt) override {
    if (py::override f = get_override("tick")) {
      f(dt);
    }
    else {
      UnitBase::tick(dt);
    }
  }

  void default_tick(double dt) {
    UnitBase::tick(dt);
  }
};