<commit_before># Copyright 2013 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Logic for universities."""

from google.appengine.ext import ndb

from melange.models import universities as universities_model


#: Maximal number of universities that can be stored in one cluster.
MAX_UNIVERSITIES_PER_CLUSTER = 5000

# TODO(daniel): this class should be thread-safe
class _CachedUniversities(object):
  """Helper class that manages already cached lists of universities for
  particular programs.
  """

  def __init__(self):
    """Initializes a new instance of the class."""
    self._cached_map = {}

  def get(self, program_key):
    """Returns universities, which have been predefined for the specified
    program.

    Args:
      program_key: program key.

    Returns:
      list of university_model.Unversity entities.
    """
    if program_key not in self._cached_map:
      self._cached_map[program_key] = _fetchUniversitiesFromDB(program_key)
    return self._cached_map[program_key]

_CACHED_UNIVERSITIES = _CachedUniversities()


def _fetchUniversitiesFromDB(program_key):
  """Fetches universities, which have been predefined for the specified
  program, directly from datastore.

  Args:
    program_key: program key.

  Returns:
    list of university_model.Unversity entities.
  """
  university_clusters = ndb.Query(
      kind=universities_model.UniversityCluster._get_kind(),
      ancestor=ndb.Key.from_old_key(program_key)).fetch(1000)

  universities = []
  for university_cluster in university_clusters:
    universities.extend(university_cluster.universities)

  return universities


def getUniversitiesForProgram(program_key):
  """Returns universities that were defined for the specified program.

  Args:<commit_msg>Initialization of cached structures is now thread-safe.<commit_after># Copyright 2013 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Logic for universities."""

import threading

from google.appengine.ext import ndb

from melange.models import universities as universities_model


#: Maximal number of universities that can be stored in one cluster.
MAX_UNIVERSITIES_PER_CLUSTER = 5000

class _CachedUniversities(object):
  """Helper class that manages already cached lists of universities for
  particular programs.
  """

  def __init__(self):
    """Initializes a new instance of the class."""
    # makes sure that ndb.Future is created once per program
    self._init_lock = threading.Lock()

    # maps program keys to ndb.Future objects with universities
    self._cached_map = {}

  def get(self, program_key):
    """Returns universities, which have been predefined for the specified
    program.

    Args:
      program_key: program key.

    Returns:
      list of university_model.Unversity entities.
    """
    if program_key not in self._cached_map:
      with self._init_lock:
        if program_key not in self._cached_map:
          self._cached_map[program_key] = _universitiesFromDBFuture(
              program_key)

    return self._cached_map[program_key].get_result()

_CACHED_UNIVERSITIES = _CachedUniversities()

@ndb.tasklet
def _universitiesFromDBFuture(program_key):
  """Tasklet that fetches asynchronously all universities, which have been
  predefined for the specified program, directly from datastore.

  Args:
    program_key: program key.

  Returns:
    ndb.Future object whose result is a list of 
    university_model.Unversity entities.
  """
  university_clusters = yield ndb.Query(
      kind=universities_model.UniversityCluster._get_kind(),
      ancestor=ndb.Key.from_old_key(program_key)).fetch_async(1000)

  universities = []
  for university_cluster in university_clusters:
    universities.extend(university_cluster.universities)

  raise ndb.Return(universities)


def getUniversitiesForProgram(program_key):
  """Returns universities that were defined for the specified program.

  Args:
{'fraction_non_alphanumeric': 0.07202272266179753, 'fraction_numerical': 0.006492189085007101, 'mean_word_length': 4.2224576271186445, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '798393', 'n_tokens_mistral': 1378, 'n_tokens_neox': 1339, 'n_words': 482}