jiahuimbzuai/CoQuIR huggingface dataset:
// save_moderation [python]
@app.route('/savemoderation', methods=['POST'])
@login_required
def save_moderation():
    """Updates the approved state (true or false) of drawings."""

    timestamp = time()
    to_approve = request.form.getlist("do_approve")
    approved = query_db('SELECT id from drawings WHERE is_approved = 1')
    to_disapprove = []

    # Disapprove drawings that are
    for drawing in approved:
        if unicode(drawing['id']) not in to_approve:
            to_disapprove.append(drawing['id'])

    len_to_approve = len(to_approve)
    len_to_disapprove = len(to_disapprove)

    # Update Database (injection safe :))
    if len_to_approve:
        insert_db('UPDATE drawings SET is_approved = 1, ts_moderated = ? WHERE is_approved = 0 AND ' + ' OR '.join(['id = ?'] * len_to_approve), [str(timestamp)] + to_approve)
    if len_to_disapprove:
        insert_db('UPDATE drawings SET is_approved = 0, ts_moderated = ? WHERE is_approved = 1 AND ' + ' OR '.join(['id = ?'] * len_to_disapprove), [str(timestamp)] + to_disapprove)


    return redirect(url_for('admin'))
// save_moderation [python]
@app.route('/savemoderation', methods=['POST'])
@login_required
def save_moderation():
    """Updates the approved state (true or false) of drawings."""

    timestamp = time()
    to_approve = request.form.getlist("do_approve")
    approved = query_db('SELECT id from drawings WHERE is_approved = 1')
    to_disapprove = []

    # Disapprove drawings that are
    for drawing in approved:
        if unicode(drawing['id']) not in to_approve:
            to_disapprove.append(drawing['id'])

    # Update Database
    if len(to_approve):
        insert_db('UPDATE drawings SET is_approved = 1, ts_moderated = ' + str(timestamp) + ' WHERE is_approved = 0 AND ' + ' OR '.join(["id=" + str(i) for i in to_approve]))
    if len(to_disapprove):
        insert_db('UPDATE drawings SET is_approved = 0, ts_moderated = ' + str(timestamp) + ' WHERE is_approved = 1 AND ' + ' OR '.join(["id=" + str(i) for i in to_disapprove]))


    return redirect(url_for('admin'))
// fulltext_search_title [python]
def fulltext_search_title(query):
    query_statement = sql.text("""
      SELECT id, ts_headline('english', title, query), ts_rank_cd(to_tsvector('english', title), query, 32) AS rank
        FROM pub_2018, plainto_tsquery('english', :search_str) query  -- or try plainto_tsquery, phraseto_tsquery, to_tsquery
        WHERE to_tsvector('english', title) @@ query
        ORDER BY rank DESC
        LIMIT 50;""")

    rows = db.engine.execute(query_statement.bindparams(search_str=query)).fetchall()
    ids = [row[0] for row in rows]
    my_pubs = db.session.query(Pub).filter(Pub.id.in_(ids)).all()
    for row in rows:
        my_id = row[0]
        for my_pub in my_pubs:
            if my_id == my_pub.id:
                my_pub.snippet = row[1]
                my_pub.score = row[2]
    return my_pubs
// fulltext_search_title [python]
def fulltext_search_title(query):
    query_string = """
      SELECT id, ts_headline('english', title, query), ts_rank_cd(to_tsvector('english', title), query, 32) AS rank
        FROM pub_2018, plainto_tsquery('english', '{}') query  -- or try plainto_tsquery, phraseto_tsquery, to_tsquery
        WHERE to_tsvector('english', title) @@ query
        ORDER BY rank DESC
        LIMIT 50;""".format(query)

    rows = db.engine.execute(sql.text(query_string)).fetchall()
    ids = [row[0] for row in rows]
    my_pubs = db.session.query(Pub).filter(Pub.id.in_(ids)).all()
    for row in rows:
        my_id = row[0]
        for my_pub in my_pubs:
            if my_id == my_pub.id:
                my_pub.snippet = row[1]
                my_pub.score = row[2]
    return my_pubs
// passwd_reset [python]
def passwd_reset(user, newpasswd, db, salt=True, email=None):
  """ Resets a user's password with newpasswd. Uses a random salt if salt is
  set to true. """
  if salt:
    from random import choice
    from string import uppercase, digits
    randSalt = ''.join(choice(uppercase + digits) for i in range(SALT_SIZE))
    newpasswd = randSalt + newpasswd

  query = db.execute(text("UPDATE users SET salt=:s, passwd=MD5(:p) WHERE " + \
                          "username=:u"), s = randSalt, p = newpasswd, u = user)

  if (query.rowcount == 1):
    if email:
      # notify user that their password was changed
      try:
        msg = "Your password has been successfully changed.\n" + \
              "If you did not request a password change, please" + \
              " email imss@ruddock.caltech.edu immediately.\n" + \
              "\n\nThanks,\nThe Ruddock Website"
        sendEmail(str(email), msg, "[RuddWeb] Changed Password")
      except Exception as e:
        sendEmail("imss@ruddock.caltech.edu",
                  "Something went wrong when trying to email user " + user + \
                  " after changing their password. You should look into this." + \
                  "\n\nException: " + str(e), "[RuddWeb] EMAIL ERROR")
    return 1
  else:
    return 0
// passwd_reset [python]
def passwd_reset(user, newpasswd, db, salt=True, email=None):
  """ Resets a user's password with newpasswd. Uses a random salt if salt is
  set to true. """
  if salt:
    from random import choice
    from string import uppercase, digits
    randSalt = ''.join(choice(uppercase + digits) for i in range(SALT_SIZE))
    newpasswd = randSalt + newpasswd

  query = db.execute("UPDATE users SET salt='" + randSalt + "', passwd" \
          + "=MD5('" + newpasswd + "') WHERE username='" + user + "'")

  if (query.rowcount == 1):
    if email:
      # notify user that their password was changed
      try:
        msg = "Your password has been successfully changed.\n" + \
              "If you did not request a password change, please" + \
              " email imss@ruddock.caltech.edu immediately.\n" + \
              "\n\nThanks,\nThe Ruddock Website"
        sendEmail(str(email), msg, "[RuddWeb] Changed Password")
      except Exception as e:
        sendEmail("imss@ruddock.caltech.edu",
                  "Something went wrong when trying to email user " + user + \
                  " after changing their password. You should look into this." + \
                  "\n\nException: " + str(e), "[RuddWeb] EMAIL ERROR")
    return 1
  else:
    return 0
// ensure_own_repository! [ruby]
  def ensure_own_repository!
    id = params[:id] || params[:repository_id]
    if !signed_in?
      redirect_to root_path
    elsif !Repository.find_by(id: id)
      render 'not_found'
    elsif !Repository.find(id).users.include?(current_user)
      redirect_to profile_path
    end
  end
// ensure_own_repository! [ruby]
  def ensure_own_repository!
    id = params[:id] || params[:repository_id]
    if !signed_in?
      redirect_to root_path
    elsif !Repository.exists?(id)
      render 'not_found'
    elsif !Repository.find(id).users.include?(current_user)
      redirect_to profile_path
    end
  end
// build_filter_params [ruby]
  def build_filter_params
    @conditions = ["state in('published', 'withdrawn')"]
    if params[:search]
      @search = params[:search]

      if @search[:published_at] and %r{(\d\d\d\d)-(\d\d)} =~ @search[:published_at]
        @conditions[0] += " AND published_at LIKE ? "
        @conditions << "%#{@search[:published_at]}%"
      end

      if @search[:user_id] and @search[:user_id].to_i > 0
        @conditions[0] += " AND user_id = ? "
        @conditions << @search[:user_id]
      end
      
      if @search[:published] and @search[:published].to_s =~ /0|1/
        @conditions[0] += " AND published = ? "
        @conditions << @search[:published]
      end
      
      if @search[:category] and @search[:category].to_i > 0
        @conditions[0] += " AND categorizations.category_id = ? "
        @conditions << @search[:category]
      end
  
    else
      @search = { :category => nil, :user_id => nil, :published_at => nil, :published => nil }
    end    
  end
// build_filter_params [ruby]
  def build_filter_params
    @conditions = "state in('published', 'withdrawn')"
    if params[:search]
      @search = params[:search]

      if @search[:published_at] and %r{(\d\d\d\d)-(\d\d)} =~ @search[:published_at]
        @conditions += " AND published_at LIKE '%#{@search[:published_at]}%'"
      end

      if @search[:user_id] and @search[:user_id].to_i > 0
        @conditions += " AND user_id = #{@search[:user_id].to_i}"
      end
      
      if @search[:published] and @search[:published].to_s =~ /0|1/
        @conditions += " AND published = #{@search[:published].to_i}"
      end
      
      if @search[:category] and @search[:category].to_i > 0
        @conditions += " AND categorizations.category_id = #{@search[:category].to_i}"
      end
  
    else
      @search = { :category => nil, :user_id => nil, :published_at => nil, :published => nil }
    end    
  end
// edit [ruby]
  def edit
    # give an error message is instructor have not set the time zone.
    if current_user.timezonepref.nil?
      flash.now[:error] = "You have not specified your preferred timezone yet. Please do this before you set up the deadlines."
    end
    @topics = SignUpTopic.where(assignment_id: params[:id])
    @assignment_form = AssignmentForm.create_form_object(params[:id])
    @user = current_user

    @assignment_questionnaires = AssignmentQuestionnaire.where(assignment_id: params[:id])
    @due_date_all = DueDate.where(assignment_id: params[:id])
    @reviewvarycheck = false
    @due_date_nameurl_notempty = false
    @due_date_nameurl_notempty_checkbox = false
    @metareview_allowed = false
    @metareview_allowed_checkbox = false
    @signup_allowed = false
    @signup_allowed_checkbox = false
    @drop_topic_allowed = false
    @drop_topic_allowed_checkbox = false
    @team_formation_allowed = false
    @team_formation_allowed_checkbox = false
    @participants_count = @assignment_form.assignment.participants.size
    @teams_count = @assignment_form.assignment.teams.size

    # Check if name and url in database is empty before webpage displays
    @due_date_all.each do |dd|
      @due_date_nameurl_notempty = is_due_date_nameurl_notempty(dd)
      @due_date_nameurl_notempty_checkbox = @due_date_nameurl_notempty
      @metareview_allowed = is_meta_review_allowed?(dd)
      @drop_topic_allowed = is_drop_topic_allowed?(dd)
      @signup_allowed = is_signup_allowed?(dd)
      @team_formation_allowed = is_team_formation_allowed?(dd)

      if dd.due_at.present?
        dd.due_at = dd.due_at.to_s.in_time_zone(current_user.timezonepref)
      end
      if  @due_date_nameurl_notempty && @due_date_nameurl_notempty_checkbox &&
          (@metareview_allowed || @drop_topic_allowed || @signup_allowed || @team_formation_allowed)
        break
      end
    end

    @assignment_questionnaires.each do |aq|
      unless aq.used_in_round.nil?
        @reviewvarycheck = 1
        break
      end
    end
    @due_date_all = update_nil_dd_deadline_name(@due_date_all)
    @due_date_all = update_nil_dd_description_url(@due_date_all)

    # only when instructor does not assign rubrics and in assignment edit page will show this error message.
    if !empty_rubrics_list.empty? && request.original_fullpath == "/assignments/#{@assignment_form.assignment.id}/edit"
      rubrics_needed = needed_rubrics(empty_rubrics_list)
      flash.now[:error] = "You did not specify all the necessary rubrics. You need " + rubrics_needed +
          " of assignment <b>#{@assignment_form.assignment.name}</b> before saving the assignment. You can assign rubrics <a id='go_to_tabs2' style='color: blue;'>here</a>."
    end

    if @assignment_form.assignment.directory_path.nil? || @assignment_form.assignment.directory_path.empty?
      flash.now[:error] = "You did not specify your submission directory."
    end
  end
// edit [ruby]
  def edit
    # give an error message is instructor have not set the time zone.
    if current_user.timezonepref.nil?
      flash.now[:error] = "You have not specified your preferred timezone yet. Please do this before you set up the deadlines."
    end
    @topics = SignUpTopic.find_by_sql("select * from sign_up_topics where assignment_id=" + params[:id])
    @assignment_form = AssignmentForm.create_form_object(params[:id])
    @user = current_user

    @assignment_questionnaires = AssignmentQuestionnaire.where(assignment_id: params[:id])
    @due_date_all = DueDate.where(assignment_id: params[:id])
    @reviewvarycheck = false
    @due_date_nameurl_notempty = false
    @due_date_nameurl_notempty_checkbox = false
    @metareview_allowed = false
    @metareview_allowed_checkbox = false
    @signup_allowed = false
    @signup_allowed_checkbox = false
    @drop_topic_allowed = false
    @drop_topic_allowed_checkbox = false
    @team_formation_allowed = false
    @team_formation_allowed_checkbox = false
    @participants_count = @assignment_form.assignment.participants.size
    @teams_count = @assignment_form.assignment.teams.size

    # Check if name and url in database is empty before webpage displays
    @due_date_all.each do |dd|
      @due_date_nameurl_notempty = is_due_date_nameurl_notempty(dd)
      @due_date_nameurl_notempty_checkbox = @due_date_nameurl_notempty
      @metareview_allowed = is_meta_review_allowed?(dd)
      @drop_topic_allowed = is_drop_topic_allowed?(dd)
      @signup_allowed = is_signup_allowed?(dd)
      @team_formation_allowed = is_team_formation_allowed?(dd)

      if dd.due_at.present?
        dd.due_at = dd.due_at.to_s.in_time_zone(current_user.timezonepref)
      end
      if  @due_date_nameurl_notempty && @due_date_nameurl_notempty_checkbox &&
          (@metareview_allowed || @drop_topic_allowed || @signup_allowed || @team_formation_allowed)
        break
      end
    end

    @assignment_questionnaires.each do |aq|
      unless aq.used_in_round.nil?
        @reviewvarycheck = 1
        break
      end
    end
    @due_date_all = update_nil_dd_deadline_name(@due_date_all)
    @due_date_all = update_nil_dd_description_url(@due_date_all)

    # only when instructor does not assign rubrics and in assignment edit page will show this error message.
    if !empty_rubrics_list.empty? && request.original_fullpath == "/assignments/#{@assignment_form.assignment.id}/edit"
      rubrics_needed = needed_rubrics(empty_rubrics_list)
      flash.now[:error] = "You did not specify all the necessary rubrics. You need " + rubrics_needed +
          " of assignment <b>#{@assignment_form.assignment.name}</b> before saving the assignment. You can assign rubrics <a id='go_to_tabs2' style='color: blue;'>here</a>."
    end

    if @assignment_form.assignment.directory_path.nil? || @assignment_form.assignment.directory_path.empty?
      flash.now[:error] = "You did not specify your submission directory."
    end
  end
// search [ruby]
  def search

  	selectTerm = "id, name, info_one, info_one_red, info_two, info_two_red, info_three, info_three_red, updated_at, last_user, avatar_upload, updated_at";
  	whereSearchTerm  = "name LIKE ?"
		whereSearchTerm += "OR description LIKE ?"
		whereSearchTerm += "OR info_one LIKE ?"
		whereSearchTerm += "OR info_two LIKE ?"
		whereSearchTerm += "OR info_three LIKE ?"

		unless params[:query].empty?
			params[:query] = '%' + params[:query] + '%'
		end

  	if params[:state] == "posters"
	  	if params[:query] == ""
	  		@posters = Poster.select(selectTerm).where('updated_at < ?', 7.days.ago).order(updated_at: :desc).limit(params[:limit])
	  	else
	  		@posters = Poster.select(selectTerm).where('updated_at < ?', 7.days.ago).where(whereSearchTerm, params[:query], params[:query], params[:query], params[:query], params[:query]).order(updated_at: :desc).limit(params[:limit])
	  	end
	  elsif params[:state] == "latest"
	  	if params[:query] == ""
	  		@posters = Poster.where('updated_at >= ?', 7.days.ago).order(updated_at: :desc)
	  	else
	  		@posters = Poster.where('updated_at >= ?', 7.days.ago).where(whereSearchTerm, params[:query], params[:query], params[:query], params[:query], params[:query]).order(updated_at: :desc)
	  	end
	  elsif params[:state] == "my-posters"
	  	if params[:query] == ""
				@posters = Poster.select(selectTerm).where('user_id = ?', current_user.id).order(updated_at: :desc).limit(params[:limit])
	  	else
	  		@posters = Poster.select(selectTerm).where('user_id = ?', current_user.id).where(whereSearchTerm, params[:query], params[:query], params[:query], params[:query], params[:query]).order(updated_at: :desc).limit(params[:limit])
	  	end
	  end

  	render :json => @posters

  end
// search [ruby]
  def search

  	selectTerm = "id, name, info_one, info_one_red, info_two, info_two_red, info_three, info_three_red, updated_at, last_user, avatar_upload, updated_at";
  	whereSearchTerm  = "name LIKE '%#{params[:query]}%'"
		whereSearchTerm += "OR description LIKE '%#{params[:query]}%'"
		whereSearchTerm += "OR info_one LIKE '%#{params[:query]}%'"
		whereSearchTerm += "OR info_two LIKE '%#{params[:query]}%'"
		whereSearchTerm += "OR info_three LIKE '%#{params[:query]}%'"

  	if params[:state] == "posters"
	  	if params[:query] == ""
	  		@posters = Poster.select(selectTerm).where('updated_at < ?', 7.days.ago).order(updated_at: :desc).limit(params[:limit])
	  	else
	  		@posters = Poster.select(selectTerm).where('updated_at < ?', 7.days.ago).where(whereSearchTerm).order(updated_at: :desc).limit(params[:limit])
	  	end
	  elsif params[:state] == "latest"
	  	if params[:query] == ""
	  		@posters = Poster.where('updated_at >= ?', 7.days.ago).order(updated_at: :desc)
	  	else
	  		@posters = Poster.where('updated_at >= ?', 7.days.ago).where(whereSearchTerm).order(updated_at: :desc)
	  	end
	  elsif params[:state] == "my-posters"
	  	if params[:query] == ""
				@posters = Poster.select(selectTerm).where('user_id = ?', current_user.id).order(updated_at: :desc).limit(params[:limit])
	  	else
	  		@posters = Poster.select(selectTerm).where('user_id = ?', current_user.id).where(whereSearchTerm).order(updated_at: :desc).limit(params[:limit])
	  	end
	  end

  	render :json => @posters

  end
// stops [ruby]
  def stops
    if params['lat'] and params['lng']
      @page[:order] = params[:order] || "distance ASC"
      @page[:limit] = params[:limit] || 5
      lat = BigDecimal.new params['lat']
      lng = BigDecimal.new params['lng']
      distance = "7912*ASIN(SQRT(POWER(SIN((lat-#{lat})*pi()/180/2),2)+COS(lat*pi()/180)*COS(#{lat}*pi()/180)*POWER(SIN((lng-#{lng})*pi()/180/2),2)))"
      @stops =  BusStop.select("bus_stops.*, #{distance} AS distance").where("lat IS NOT NULL AND lng IS NOT NULL").paginate(@page)
    end

    respond_to do |format|
      format.html 
      format.json { render json: @stops, callback: params[:callback] }
      format.xml { render xml: @stops }
    end
  end
// stops [ruby]
  def stops
    if params['lat'] and params['lng']
      @page[:order] = params[:order] || "distance ASC"
      @page[:limit] = params[:limit] || 5
      distance = "7912*ASIN(SQRT(POWER(SIN((lat-#{params['lat']})*pi()/180/2),2)+COS(lat*pi()/180)*COS(#{params['lat']}*pi()/180)*POWER(SIN((lng-#{params['lng']})*pi()/180/2),2)))"
      @stops =  BusStop.select("bus_stops.*, #{distance} AS distance").where("lat IS NOT NULL AND lng IS NOT NULL").paginate(@page)
    end

    respond_to do |format|
      format.html 
      format.json { render json: @stops, callback: params[:callback] }
      format.xml { render xml: @stops }
    end
  end
// self.find_siblings [ruby]
  def self.find_siblings(hierarchy_id, parent_id)
    if (hierarchy_id.to_i.is_a? Integer) && (parent_id.to_i.is_a? Integer)
      self.find_by_sql("select string as taxon_concept, h1.id, h1.parent_id,
                        (select count(*) from hierarchy_entries as h2 where h2.parent_id=h1.id)
                          as siblings_count,
                          h1.taxon_concept_id
                        from hierarchy_entries h1
                          left outer join names on names.id=name_id
                        where hierarchy_id=#{hierarchy_id.to_i} and parent_id=#{parent_id.to_i} and published=1
                        order by string;")

    else
      return []
    end
  end
// self.find_siblings [ruby]
  def self.find_siblings(hierarchy_id, parent_id)
    self.find_by_sql("select string as taxon_concept, h1.id, h1.parent_id,
                        (select count(*) from hierarchy_entries as h2 where h2.parent_id=h1.id)
                          as siblings_count,
                          h1.taxon_concept_id
                        from hierarchy_entries h1
                          left outer join names on names.id=name_id
                        where hierarchy_id=#{hierarchy_id} and parent_id=#{parent_id} and published=1
                        order by string;")
          end
// users_to_notify_popup [ruby]
  def users_to_notify_popup
    # anyone already attached to the task should be removed
    excluded_ids = params[:watcher_ids].blank? ? 0 : params[:watcher_ids]
    @users = current_user.customer.users.active.where("id NOT IN (#{excluded_ids})").order('name').limit(50)
    @task = AbstractTask.accessed_by(current_user).find_by(:id => params[:id])

    @task && @task.customers.each do |customer|
      @users = @users + customer.users.active.where("id NOT IN (#{excluded_ids})").order('name').limit(50)
    end
    @users = @users.uniq.sort_by{|user| user.name}.first(50)

    if @task && current_user.customer != @task.project.customer
      @users = @users + @task.project.customer.users.active.where("id NOT IN (?)", excluded_ids)
      @users = @users.uniq.sort_by{|user| user.name}.first(50)
    end
    render :layout =>false
  end
// users_to_notify_popup [ruby]
  def users_to_notify_popup
    # anyone already attached to the task should be removed
    excluded_ids = params[:watcher_ids].blank? ? 0 : params[:watcher_ids]
    @users = current_user.customer.users.active.where("id NOT IN (#{excluded_ids})").order('name').limit(50)
    @task = AbstractTask.accessed_by(current_user).find_by(:id => params[:id])

    @task && @task.customers.each do |customer|
      @users = @users + customer.users.active.where("id NOT IN (#{excluded_ids})").order('name').limit(50)
    end
    @users = @users.uniq.sort_by{|user| user.name}.first(50)

    if @task && current_user.customer != @task.project.customer
      @users = @users + @task.project.customer.users.active.where("id NOT IN (#{excluded_ids})")
      @users = @users.uniq.sort_by{|user| user.name}.first(50)
    end
    render :layout =>false
  end
// safe_paths [ruby]
  def safe_paths
    dir = params[:order]
    # GOOD: barrier guard prevents taint flow
    if dir == "ASC"
      User.order("name #{dir}")
    else
      dir = "DESC"
      User.order("name #{dir}")
    end
    # TODO: a more idiomatic form of this guard is the following:
    #     dir = "DESC" unless dir == "ASC"
    # but our taint tracking can't (yet) handle that properly

    name = params[:user_name]
    # GOOD: barrier guard prevents taint flow
    if %w(alice bob charlie).include? name
      User.find_by("username = #{name}")
    end

    name = params[:user_name]
    # GOOD: hash arguments are sanitized by ActiveRecord
    User.find_by(user_name: name)

    # OK: `find` method is overridden in `User`
    User.find(params[:user_group])
  end
// safe_paths [ruby]
  def safe_paths
    dir = params[:order]
    # GOOD: barrier guard prevents taint flow
    dir = "DESC" unless dir == "ASC"
    User.order("name #{dir}")

    name = params[:user_name]
    # GOOD: barrier guard prevents taint flow
    if %w(alice bob charlie).include? name
      User.find_by("username = #{name}")
    end

    name = params[:user_name]
    # GOOD: hash arguments are sanitized by ActiveRecord
    User.find_by(user_name: name)

    # OK: `find` method is overridden in `User`
    User.find(params[:user_group])
  end
// clean_taxon_concept [ruby]
  def clean_taxon_concept
    taxon_concept.gsub("\n", ' ').gsub("\'", "\\\'")
  end
// clean_taxon_concept [ruby]
  def clean_taxon_concept
    taxon_concept.gsub("\n"," ").gsub("\'", "\\\'")
  end
// remove [ruby]
    def remove
      lu = Tr8n::LanguageUser.find(:first, :conditions => ["language_id = ? and user_id = ?", params[:language_id].to_i, tr8n_current_user.id])
      lu.destroy if lu
      redirect_to_source
    end
// remove [ruby]
    def remove
      lu = Tr8n::LanguageUser.find(:first, :conditions => ["language_id = ? and user_id = ?", params[:language_id], tr8n_current_user.id])
      lu.destroy if lu
      redirect_to_source
    end
// index [ruby]
  def index
    authorize! :posts, @post_type
    per_page = current_site.admin_per_page
    posts_all = @post_type.posts.eager_load(:parent, :post_type)
    if params[:taxonomy].present? && params[:taxonomy_id].present?
      if params[:taxonomy] == "category"
        cat_owner = current_site.full_categories.find(params[:taxonomy_id]).decorate
        posts_all = cat_owner.posts
        add_breadcrumb t("camaleon_cms.admin.post_type.category"), @post_type.the_admin_url("category")
        add_breadcrumb cat_owner.the_title, cat_owner.the_edit_url
      end

      if params[:taxonomy] == "post_tag"
        tag_owner = current_site.post_tags.find(params[:taxonomy_id]).decorate
        posts_all = tag_owner.posts
        add_breadcrumb t("camaleon_cms.admin.post_type.tags"), @post_type.the_admin_url("tag")
        add_breadcrumb tag_owner.the_title, tag_owner.the_edit_url
      end
    end

    if params[:q].present?
      posts_all = posts_all.where("#{CamaleonCms::Post.table_name}.title LIKE ?", "%#{params[:q]}%")
      puts "@@@@@@@@@@@@@@@@@@@@@@@@: #{posts_all.to_sql}"
    end

    @posts = posts_all
    params[:s] = 'published' unless params[:s].present?
    @lists_tab = params[:s]
    add_breadcrumb I18n.t("camaleon_cms.admin.post_type.#{params[:s]}") if params[:s].present?
    case params[:s]
      when "published", "pending", "draft", "trash"
        @posts = @posts.where(status:  params[:s])

      when "all"
        @posts = @posts.no_trash
    end
// index [ruby]
  def index
    authorize! :posts, @post_type
    per_page = current_site.admin_per_page
    posts_all = @post_type.posts.eager_load(:parent, :post_type)
    if params[:taxonomy].present? && params[:taxonomy_id].present?
      if params[:taxonomy] == "category"
        cat_owner = current_site.full_categories.find(params[:taxonomy_id]).decorate
        posts_all = cat_owner.posts
        add_breadcrumb t("camaleon_cms.admin.post_type.category"), @post_type.the_admin_url("category")
        add_breadcrumb cat_owner.the_title, cat_owner.the_edit_url
      end

      if params[:taxonomy] == "post_tag"
        tag_owner = current_site.post_tags.find(params[:taxonomy_id]).decorate
        posts_all = tag_owner.posts
        add_breadcrumb t("camaleon_cms.admin.post_type.tags"), @post_type.the_admin_url("tag")
        add_breadcrumb tag_owner.the_title, tag_owner.the_edit_url
      end
    end

    if params[:q].present?
      posts_all = posts_all.where(params[:q].split(" ").map{|text| "#{CamaleonCms::Post.table_name}.title LIKE '%#{text}%'" }.join(" OR "))
    end

    @posts = posts_all
    params[:s] = 'published' unless params[:s].present?
    @lists_tab = params[:s]
    add_breadcrumb I18n.t("camaleon_cms.admin.post_type.#{params[:s]}") if params[:s].present?
    case params[:s]
      when "published", "pending", "draft", "trash"
        @posts = @posts.where(status:  params[:s])

      when "all"
        @posts = @posts.no_trash
    end
// taxon_search [ruby]
  def taxon_search(query, tax_levels = TaxonCount::NAME_2_LEVEL.keys, filters = {})
    return {} if Rails.env == "test"
    query = sanitize(query)

    # sanitize tax_levels
    tax_levels = tax_levels.select { |l| TaxonCount::NAME_2_LEVEL[l] }

    matching_taxa = []
    taxon_ids = []
    tax_levels.each do |level|
      search_params = {
        size: ElasticsearchHelper::MAX_SEARCH_RESULTS,
        query: {
          query_string: {
            query: "*#{query}*",
            fields: ["#{level}_name"]
          }
        },
        aggs: {
          distinct_taxa: {
            terms: {
              field: "#{level}_taxid"
            }
          }
        }
      }
      search_response = TaxonLineage.search(search_params)
      search_taxon_ids = search_response.aggregations.distinct_taxa.buckets.pluck(:key)

      taxon_data = TaxonLineage
                   .where("#{level}_taxid" => search_taxon_ids)
                   .order(id: :desc)
                   .distinct("#{level}_taxid")
                   .pluck("#{level}_name", "#{level}_taxid")
                   .map do |name, taxid|
                     {
                       "title" => name,
                       "description" => "Taxonomy ID: #{taxid}",
                       "taxid" => taxid,
                       "level" => level
                     }
                   end

      matching_taxa += taxon_data
      taxon_ids += search_taxon_ids
    end

    taxon_ids = filter_by_samples(taxon_ids, filters[:samples]) if filters[:samples]
    taxon_ids = filter_by_project(taxon_ids, filters[:project_id]) if filters[:project_id]
    taxon_ids = Set.new(taxon_ids)

    return matching_taxa.select { |taxon| taxon_ids.include? taxon["taxid"] }
  end
// taxon_search [ruby]
  def taxon_search(prefix, tax_levels = TaxonCount::NAME_2_LEVEL.keys, filters = {})
    return {} if Rails.env == "test"
    prefix = sanitize(prefix)

    matching_taxa = []
    taxon_ids = []
    tax_levels.each do |level|
      search_params = {
        size: ElasticsearchHelper::MAX_SEARCH_RESULTS,
        query: {
          query_string: {
            query: "#{prefix}*",
            fields: ["#{level}_name"]
          }
        },
        aggs: {
          distinct_taxa: {
            terms: {
              field: "#{level}_taxid"
            }
          }
        }
      }
      search_response = TaxonLineage.search(search_params)
      search_taxon_ids = search_response.aggregations.distinct_taxa.buckets.pluck(:key)

      taxon_data = TaxonLineage
                   .where("#{level}_taxid" => search_taxon_ids)
                   .order(id: :desc)
                   .distinct("#{level}_taxid")
                   .pluck("#{level}_name", "#{level}_taxid")
                   .map do |name, taxid|
                     {
                       "title" => name,
                       "description" => "Taxonomy ID: #{taxid}",
                       "taxid" => taxid,
                       "level" => level
                     }
                   end

      matching_taxa += taxon_data
      taxon_ids += search_taxon_ids
    end

    taxon_ids = filter_by_samples(taxon_ids, filters[:samples]) if filters[:samples]
    taxon_ids = filter_by_project(taxon_ids, filters[:project_id]) if filters[:project_id]
    taxon_ids = Set.new(taxon_ids)

    return matching_taxa.select { |taxon| taxon_ids.include? taxon["taxid"] }
  end
// search [ruby]
  def search
    escaped = params[:name].gsub('\\', '\\\\\\\\').gsub('%', '\%').gsub('_', '\_')
    @searched = Restaurant.where("name like ? or hurigana like ?", "%#{escaped}%", "%#{escaped}%")
    if @searched.empty?
      @error = "検索ワードがヒットしませんでした。もう一度入れなおして下さい。"
    end
  end
// search [ruby]
  def search
    escaped = params[:name].gsub('\\', '\\\\\\\\').gsub('%', '\%').gsub('_', '\_')
    @searched = Restaurant.where("name like '%" + escaped + "%'" + "or hurigana like '%" + escaped + "%'")
    if @searched.empty?
      @error = "検索ワードがヒットしませんでした。もう一度入れなおして下さい。"
    end
  end
// article [ruby]
  def article
    @article = Article.find(params[:id])
    @feedbacks = Feedback.find(:all, :conditions => {:article_id => params[:id]})
  end
// article [ruby]
  def article
    @article = Article.find(params[:id])
    @feedbacks = Feedback.find(:all, :conditions => "article_id = #{params[:id]}")
  end
// auto_complete_for_user_name [ruby]
  def auto_complete_for_user_name
    search = params[:user][:name].to_s
    @users = User.where("LOWER(name) LIKE ?", "%#{search}%") unless search.blank?
  end
// auto_complete_for_user_name [ruby]
  def auto_complete_for_user_name
    search = params[:user][:name].to_s
    @users = User.find_by_sql("select * from users where LOWER(name) LIKE '%" + search + "%'") unless search.blank?
  end
// self.get_taxon_concept_id [ruby]
  def self.get_taxon_concept_id(hierarchy_entry_id)
    return 0 unless hierarchy_entry_id.to_i.is_a? Integer
    he = self.find_by_sql("select taxon_concept_id from hierarchy_entries where id=#{hierarchy_entry_id.to_i};")
    if he.count > 0
      return he.first.taxon_concept_id
    else
      return 0
    end
  end
// self.get_taxon_concept_id [ruby]
  def self.get_taxon_concept_id(hierarchy_entry_id)
    he = self.find_by_sql("select taxon_concept_id from hierarchy_entries where id=#{hierarchy_entry_id};")
    if he.count > 0
      return he.first.taxon_concept_id
    else
      return 0
    end
  end
// self.find_taxon [ruby]
  def self.find_taxon(id)
    return {} unless id.to_i.is_a? Integer
    self.find_by_sql("select string as taxon_concept,
                            (select count(*) from hierarchy_entries as h2 where h2.parent_id=h1.id)
                              as siblings_count,
                            h1.taxon_concept_id
                          from hierarchy_entries h1
                            left outer join names on names.id=name_id
                          where published=1 and h1.id=#{id.to_i};").first
  end
// self.find_taxon [ruby]
  def self.find_taxon(id)
    self.find_by_sql("select string as taxon_concept,
                            (select count(*) from hierarchy_entries as h2 where h2.parent_id=h1.id) as siblings_count,
                            h1.taxon_concept_id
                          from hierarchy_entries h1
                            left outer join names on names.id=name_id
                          where published=1 and h1.id=#{id};").first
  end
// lists [ruby]
    def lists
      if request.post? 
        if params[:language_action] == "remove"
          lu = Tr8n::LanguageUser.find(:first, :conditions => ["language_id = ? and user_id = ?", params[:language_id].to_i, tr8n_current_user.id])
          lu.destroy
        end
      end
    
      @all_languages = Tr8n::Language.enabled_languages
      @user_languages = Tr8n::LanguageUser.languages_for(tr8n_current_user)
      render(:partial => "lists")  
    end
// lists [ruby]
    def lists
      if request.post? 
        if params[:language_action] == "remove"
          lu = Tr8n::LanguageUser.find(:first, :conditions => ["language_id = ? and user_id = ?", params[:language_id], tr8n_current_user.id])
          lu.destroy
        end
      end
    
      @all_languages = Tr8n::Language.enabled_languages
      @user_languages = Tr8n::LanguageUser.languages_for(tr8n_current_user)
      render(:partial => "lists")  
    end
// self.lookup [ruby]
  def self.lookup(lat, lng)
    all(:conditions => ["ST_Contains(the_geom, GeometryFromText('POINT(? ?)', -1))",lng.to_f,lat.to_f])
  end
// self.lookup [ruby]
  def self.lookup(lat, lng)
    all(:conditions => "ST_Contains(the_geom, GeometryFromText('POINT(#{lng} #{lat})', -1))")
  end
// merge [javascript]
function merge(source, target) {
  for (var key in source) {
    if (Object.prototype.hasOwnProperty.call(source, key)) {
      var value = source[key];

      if (Object.prototype.hasOwnProperty.call(target, key) && typeof value === 'object' && !Array.isArray(value)) {
        target[key] = merge(value, target[key] || {});
      } else {
        target[key] = key in target ? target[key] : value;
      }
    }
  }

  return target;
}
// merge [javascript]
function merge(source, target) {
  for (var key in source) {
    var value = source[key];

    if (typeof value === 'object' && !Array.isArray(value)) {
      target[key] = merge(value, target[key] || {});
    } else {
      target[key] = key in target ? target[key] : value;
    }
  }

  return target;
}
// (anonymous) [javascript]
    it('decode should prevent prototype pollution attacks', function () {
        var config = new Config();
        config.options.lineEnding = "\n";
        config.options.assignIdentifier = ":";
        var result = config.decode("[__proto__]\nfoo:bar\n");
        should.not.exist(result.__proto__.foo);
        result = config.decode("[Section]\n__proto__:bar\n");
        expect(result.Section.__proto__).to.not.equal("bar");
    });
// (anonymous) [javascript]
    it("should create object from dotted URL parameter", function () {
        var someObject = urlTools.mergeParamIntoObject({}, "one.two", "12");
        expect("12").toEqual(someObject.one.two);

        someObject = urlTools.mergeParamIntoObject({"one": {"xy": "34"}}, "one.two", "12");
        expect("12").toEqual(someObject.one.two);
        expect("34").toEqual(someObject.one.xy);

        someObject = urlTools.mergeParamIntoObject({}, "one.two.three", "123");
        expect("123").toEqual(someObject.one.two.three);

        someObject = urlTools.mergeParamIntoObject({}, "__proto__.polluted", "true");
        expect(undefined).toEqual({}.polluted);
        someObject = urlTools.mergeParamIntoObject({}, "constructor.prototype.polluted", "true");
        expect(undefined).toEqual({}.polluted);

        var params = urlTools.parseUrl("localhost:8989?pt.test=now&pt.go.test=single&pt.go.further=far&pt.go.further=now");
        expect("now").toEqual(params.pt.test);
        expect("single").toEqual(params.pt.go.test);
        expect(["far", "now"]).toEqual(params.pt.go.further);

        // does not work at the moment: the second parameter is skipped
        // params = urlTools.parseUrl("localhost:8989?pt.mix=now&pt.mix.test=now2");
        // expect(["now", {"test" : "now2"}]).toEqual(params.pt.mix);
    });
// (anonymous) [javascript]
    it("should create object from dotted URL parameter", function () {
        var someObject = urlTools.mergeParamIntoObject({}, "one.two", "12");
        expect("12").toEqual(someObject.one.two);

        someObject = urlTools.mergeParamIntoObject({"one": {"xy": "34"}}, "one.two", "12");
        expect("12").toEqual(someObject.one.two);
        expect("34").toEqual(someObject.one.xy);

        someObject = urlTools.mergeParamIntoObject({}, "one.two.three", "123");
        expect("123").toEqual(someObject.one.two.three);

        var params = urlTools.parseUrl("localhost:8989?pt.test=now&pt.go.test=single&pt.go.further=far&pt.go.further=now");
        expect("now").toEqual(params.pt.test);
        expect("single").toEqual(params.pt.go.test);
        expect(["far", "now"]).toEqual(params.pt.go.further);

        // does not work at the moment: the second parameter is skipped
        // params = urlTools.parseUrl("localhost:8989?pt.mix=now&pt.mix.test=now2");
        // expect(["now", {"test" : "now2"}]).toEqual(params.pt.mix);
    });
// (anonymous) [javascript]
(function() {
  'use strict';

  /**
   * @param {() => void} loaded
   */
  var ready = function(loaded) {
    if (['interactive', 'complete'].indexOf(document.readyState) !== -1) {
      loaded();
    } else {
      document.addEventListener('DOMContentLoaded', loaded);
    }
  };

  ready(function() {
    /** @type {Map<number, HTMLIFrameElement>} */
    var iframes = new Map();

    window.addEventListener('message', function(e) {
      var data = e.data || {};

      if (typeof data !== 'object' || data.type !== 'setHeight' || !iframes.has(data.id)) {
        return;
      }

      var iframe = iframes.get(data.id);

      if ('source' in e && iframe.contentWindow !== e.source) {
        return;
      }

      iframe.height = data.height;
    });

    [].forEach.call(document.querySelectorAll('iframe.mastodon-embed'), function(iframe) {
      // select unique id for each iframe
      var id = 0, failCount = 0, idBuffer = new Uint32Array(1);
      while (id === 0 || iframes.has(id)) {
        id = crypto.getRandomValues(idBuffer)[0];
        failCount++;
        if (failCount > 100) {
          // give up and assign (easily guessable) unique number if getRandomValues is broken or no luck
          id = -(iframes.size + 1);
          break;
        }
      }

      iframes.set(id, iframe);

      iframe.scrolling      = 'no';
      iframe.style.overflow = 'hidden';

      iframe.onload = function() {
        iframe.contentWindow.postMessage({
          type: 'setHeight',
          id: id,
        }, '*');
      };

      iframe.onload();
    });
  });
})();
// (anonymous) [javascript]
(function() {
  'use strict';

  var ready = function(loaded) {
    if (['interactive', 'complete'].indexOf(document.readyState) !== -1) {
      loaded();
    } else {
      document.addEventListener('DOMContentLoaded', loaded);
    }
  };

  ready(function() {
    var iframes = [];

    window.addEventListener('message', function(e) {
      var data = e.data || {};

      if (data.type !== 'setHeight' || !iframes[data.id] || window.location.origin !== e.origin || data.id.toString() === '__proto__') {
        return;
      }

      iframes[data.id].height = data.height;
    });

    [].forEach.call(document.querySelectorAll('iframe.mastodon-embed'), function(iframe) {
      iframe.scrolling      = 'no';
      iframe.style.overflow = 'hidden';

      iframes.push(iframe);

      var id = iframes.length - 1;

      iframe.onload = function() {
        iframe.contentWindow.postMessage({
          type: 'setHeight',
          id: id,
        }, '*');
      };

      iframe.onload();
    });
  });
})();
// mergeParamIntoObject [javascript]
function mergeParamIntoObject(res, key, value) {
    var tmpVal;

    var objectIndex = key.indexOf(".");
    if(objectIndex < 0) {
        // force always array for some keys even if just one parameter
        if (typeof res[key] === "undefined" && key !== "heading" && key !== "point" && key !== "details") {
            if (value === 'true')
                value = true;
            else if (value === 'false')
                value = false;

            res[key] = value;
        } else {
            tmpVal = res[key];
            if (isArray(tmpVal)) {
                tmpVal.push(value);
            } else if (tmpVal) {
                res[key] = [tmpVal, value];
            } else {
                res[key] = [value];
            }
        }
        // leaf of recursion reached
        return res;
    }

    var newKey = key.substring(0, objectIndex);
    var subKey = key.substring(objectIndex + 1);

    if(newKey == "__proto__" || newKey == "constructor" || newKey == "prototype") return res;

    tmpVal = res[newKey];
    if(!tmpVal)
        tmpVal = {};

    // recursion
    res[newKey] = mergeParamIntoObject(tmpVal, subKey, value);
    return res;
}
// mergeParamIntoObject [javascript]
function mergeParamIntoObject(res, key, value) {
    var tmpVal;

    var objectIndex = key.indexOf(".");
    if(objectIndex < 0) {
        // force always array for some keys even if just one parameter
        if (typeof res[key] === "undefined" && key !== "heading" && key !== "point" && key !== "details") {
            if (value === 'true')
                value = true;
            else if (value === 'false')
                value = false;

            res[key] = value;
        } else {
            tmpVal = res[key];
            if (isArray(tmpVal)) {
                tmpVal.push(value);
            } else if (tmpVal) {
                res[key] = [tmpVal, value];
            } else {
                res[key] = [value];
            }
        }
        // leaf of recursion reached
        return res;
    }

    var newKey = key.substring(0, objectIndex);
    var subKey = key.substring(objectIndex + 1);

    tmpVal = res[newKey];
    if(!tmpVal)
        tmpVal = {};

    // recursion
    res[newKey] = mergeParamIntoObject(tmpVal, subKey, value);
    return res;
}
// mergeConfig [javascript]
function mergeConfig(from, to) {
	for (var f in from) {
		if (Object.prototype.hasOwnProperty.call(from, f)) {
			if (Object.prototype.hasOwnProperty.call(to, f) && _.isObject(from[f])) {
				if (!_.isObject(to[f])) {
					to[f] = from[f];
				} else {
					mergeConfig(from[f], to[f]);
				}
			} else {
				to[f] = from[f];
			}
		}
	}
}
// mergeConfig [javascript]
function mergeConfig(from, to) {
	for (var f in from) {
		if (_.isObject(from[f])) {
			if (!_.isObject(to[f])) {
				to[f] = from[f];
			} else {
				mergeConfig(from[f], to[f]);
			}
		} else {
			to[f] = from[f];
		}
	}
}
// Config.prototype.decode [javascript]
Config.prototype.decode = function(data){
    if(typeof data != 'string'){
        if(typeof data.toString === 'function'){
            data = data.toString();
        } else {
            throw new Error('expecting string but got '+typeof data);
        }
    }
    var protectedKeys = ['__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__', '__proto__'];
    var result = {};
    var currentSection = undefined;
    var lines = data.split(this.options.lineEnding);
    for(var i = 0; i < lines.length; i++){
        var line = lines[i];
        if(this.options.trimLines === true){
            line = line.trim();
        }
        if(line.length == 0 || stringBeginsWithOnOfTheseStrings(line,this.options.commentIdentifiers)){
            continue;
        }
        
        var sectionRegExp = new RegExp("^\\"+this.options.sectionOpenIdentifier+"(.*?)\\"+this.options.sectionCloseIdentifier+"$");
        var newSection = line.match(sectionRegExp);
        if(newSection !== null){
            currentSection = newSection[1];
            if(typeof result[currentSection] === 'undefined' && !protectedKeys.includes(currentSection)){
                result[currentSection] = {};
            }
            continue;
        }

        var assignPosition = line.indexOf(this.options.assignIdentifier);
        var key = undefined;
        var value = undefined;
        if(assignPosition === -1){
            key = line;
            value = this.options.defaultValue;
        } else {
            var assignIdentifierLength = this.options.assignIdentifier.length
            if (this.options.ignoreMultipleAssignIdentifier) {
                var regExp = new RegExp(escapeRegExp(this.options.assignIdentifier) + '+')
                var matchResult = line.match(regExp)
                if (matchResult !== null) {
                    assignIdentifierLength = matchResult[0].length
                }
            }
            key = line.substr(0,assignPosition);
            value = line.substr(assignPosition+assignIdentifierLength);
        }
        if (typeof this.options.valueIdentifier === 'string') {
            value = this.valueTrim(value, this.options.valueIdentifier);
        }
        if (protectedKeys.includes(currentSection) || protectedKeys.includes(key)) {
            continue;
        }
        if(typeof currentSection === 'undefined'){
            result[key] = value;
        } else {
            result[currentSection][key] = value;
        }
    }
    return result;
}