    void writeBytes(const void* data, int length) {
      const U8* dataPtr = (const U8*)data;
      const U8* dataEnd = dataPtr + length;
      while (dataPtr < dataEnd) {
        int n = check(1, dataEnd - dataPtr);
        memcpy(ptr, dataPtr, n);
        ptr += n;
        dataPtr += n;
      }
    }


TfLiteStatus PrepareHashtableFind(TfLiteContext* context, TfLiteNode* node) {
  TF_LITE_ENSURE_EQ(context, NumInputs(node), 3);
  TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);

  const TfLiteTensor* input_resource_id_tensor =
      GetInput(context, node, kInputResourceIdTensor);
  TF_LITE_ENSURE_EQ(context, input_resource_id_tensor->type, kTfLiteInt32);
  TF_LITE_ENSURE_EQ(context, NumDimensions(input_resource_id_tensor), 1);
  TF_LITE_ENSURE_EQ(context, SizeOfDimension(input_resource_id_tensor, 0), 1);

  const TfLiteTensor* default_value_tensor =
      GetInput(context, node, kDefaultValueTensor);

  const TfLiteTensor* key_tensor = GetInput(context, node, kKeyTensor);
  TfLiteTensor* output_tensor = GetOutput(context, node, kOutputTensor);
  TF_LITE_ENSURE_EQ(context, default_value_tensor->type, output_tensor->type);
  TF_LITE_ENSURE(context, (key_tensor->type == kTfLiteInt64 &&
                           output_tensor->type == kTfLiteString) ||
                              (key_tensor->type == kTfLiteString &&
                               output_tensor->type == kTfLiteInt64));
  return context->ResizeTensor(context, output_tensor,
                               TfLiteIntArrayCopy(key_tensor->dims));
}


bool AdminRequestHandler::handleDumpStaticStringsRequest(
  const std::string& /*cmd*/, const std::string& filename) {
  auto const& list = lookupDefinedStaticStrings();
  std::ofstream out(filename.c_str());
  SCOPE_EXIT { out.close(); };
  for (auto item : list) {
    out << formatStaticString(item);
    if (RuntimeOption::EvalPerfDataMap) {
      auto const len = std::min<size_t>(item->size(), 255);
      std::string str(item->data(), len);
      // Only print the first line (up to 255 characters). Since we want '\0' in
      // the list of characters to avoid, we need to use the version of
      // `find_first_of()' with explicit length.
      auto cutOffPos = str.find_first_of("\r\n", 0, 3);
      if (cutOffPos != std::string::npos) str.erase(cutOffPos);
      Debug::DebugInfo::recordDataMap(item->mutableData(),
                                      item->mutableData() + item->size(),
                                      "Str-" + str);
    }
  }
  return true;
}


def index
    html = <<~HTML
      <!DOCTYPE html>

          #{js_asset "jquery-1.8.2.js"}
          #{js_asset "react.js"}
          #{js_asset "react-dom.js"}
          #{js_asset "babel.min.js"}
          #{js_asset "message-bus.js"}
          #{js_asset "application.jsx", "text/jsx"}

    HTML

    [200, { "content-type" => "text/html;" }, [html]]
  end


  def self.get_tree(klass, tree, conditions, node_id, order_by)

    SqlHelper.validate_token([node_id])
    if conditions.nil?
      con = ''
    else
      con = Marshal.load(Marshal.dump(conditions)) + ' and '
    end
    con << "(parent_id=#{node_id})"

    tree[node_id] = klass.where(con).order(order_by).to_a

    tree[node_id].each do |node|
      tree = klass.get_tree(tree, conditions, node.id.to_s)
    end

    return tree
  end


  def tags_for_index(model)
    model.tags.inject("".html_safe) do |out, tag|
      query = controller.send(:current_query) || ""
      hashtag = "##{tag}"
      if query.empty?
        query = hashtag
      elsif !query.include?(hashtag)
        query += " #{hashtag}"
      end
      out << link_to_function(tag, "crm.search_tagged('#{query}', '#{model.class.to_s.tableize}')", title: tag)
    end
  end


  def self.find_term(user_id, start_date, end_date)
    con = "(user_id=#{user_id}) and (date >= '#{start_date}') and (date <= '#{end_date}')"
    ary = Timecard.where(con).order('date ASC').to_a
    timecards_h = Hash.new
    unless ary.nil?
      ary.each do |timecard|
        timecards_h[timecard.date.strftime(Schedule::SYS_DATE_FORM)] = timecard
      end
    end
    return timecards_h
  end


  def test_post
    uri = URI('http://localhost:6470/makeme')
    req = Net::HTTP::Post.new(uri)
    # Set the headers the way we want them.
    req['Accept-Encoding'] = '*'
    req['Accept'] = 'application/json'
    req['User-Agent'] = 'Ruby'

    res = Net::HTTP.start(uri.hostname, uri.port) { |h|
      h.request(req)
    }
    assert_equal(Net::HTTPNoContent, res.class)
  end


  def self.set_statistics_groups(group_ids)

    yaml = Research.get_config_yaml

    yaml = Hash.new if yaml.nil?

    if group_ids.nil?

      unless yaml[:statistics].nil?
        yaml[:statistics].delete :groups
      end

    else

      if yaml[:statistics].nil?
        yaml[:statistics] = Hash.new
      end

      yaml[:statistics][:groups] = group_ids.join('|')
    end

    Research.save_config_yaml yaml

    return ary
  end


  def self.get_group_value(group_id, category, key)

    SqlHelper.validate_token([group_id, category, key])

    con = []
    con << "(group_id=#{group_id})"
    con << "(category='#{category}')"
    con << "(xkey='#{key}')"

    setting = Setting.where(con.join(' and ')).first

    return setting.xvalue unless setting.nil?

    return nil
  end


  def add_statistics_group
    Log.add_info(request, params.inspect)

    current_id = params[:current_id]

    if !params[:thetisBoxSelKeeper].nil?
      group_id = params[:thetisBoxSelKeeper].split(':').last
    end

    if group_id.nil? or group_id.empty?
      @group_ids = Research.get_statistics_groups
      render(:partial => 'ajax_statistics_groups', :layout => false)
      return
    end

    unless current_id.nil? or current_id.empty?
      Research.delete_statistics_group current_id
    end

    @group_ids = Research.add_statistics_group group_id

    render(:partial => 'ajax_statistics_groups', :layout => false)
  end


        def parse_memory(data, encoding = "UTF-8")
          raise ArgumentError unless data
          return if data.empty?

          ctx = ParserContext.memory(data, encoding)
          yield ctx if block_given?
          ctx.parse_with(self)
        end


    it 'returns json error' do
      subject.content_type :json, 'application/json'
      subject.default_error_formatter :json
      subject.get '/something' do
        'foo'
      end
      get '/something'
      expect(last_response.status).to eq(406)
      expect(last_response.body).to eq("{\"error\":\"The requested format 'txt' is not supported.\"}")
    end


    def within_bounding_box(sw_lat, sw_lng, ne_lat, ne_lng, lat_attr, lon_attr)
      spans = "#{lat_attr} BETWEEN #{sw_lat} AND #{ne_lat} AND "
      # handle box that spans 180 longitude
      if sw_lng.to_f > ne_lng.to_f
        spans + "(#{lon_attr} BETWEEN #{sw_lng} AND 180 OR " +
        "#{lon_attr} BETWEEN -180 AND #{ne_lng})"
      else
        spans + "#{lon_attr} BETWEEN #{sw_lng} AND #{ne_lng}"
      end
    end


    it "renders email addresses in the body" do
      comment = build_stubbed(:comment, body: "foo@example.com")
      expect(comment.generate_html(:body)).to match(/mailto:/)
    end


    it "should raise a warning (and keep parsing) on having an incorrectly formatted header" do
      STDERR.should_receive(:puts).with("WARNING: Could not parse (and so ignoring) 'quite Delivered-To: xxx@xxx.xxx'")
      Mail.read(fixture('emails', 'plain_emails', 'raw_email_incorrect_header.eml'))
    end


  def self.get_for(user_id)

    SqlHelper.validate_token([user_id])

    return Research.where("user_id=#{user_id}").first
  end


def test_attr_wrapper
    assert_equal("

\n", render("%p{ :strange => 'attrs'}", :attr_wrapper => '*'))
    assert_equal("

\n", render("%p{ :escaped => 'quo\"te'}", :attr_wrapper => '"'))
    assert_equal("

\n", render("%p{ :escaped => 'quo\\'te'}", :attr_wrapper => '"'))
    assert_equal("

\n", render("%p{ :escaped => 'q\\'uo\"te'}", :attr_wrapper => '"'))
    assert_equal("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n", render("!!! XML", :attr_wrapper => '"', :format => :xhtml))
  end


  def assemble_params(sanitized_params)
    sanitized_params.collect do |pair|
      pair_joiner = pair.first.to_s.end_with?("=") ? "" : " "
      pair.flatten.compact.join(pair_joiner)
    end.join(" ")
  end


      def quote_column_name(name) #:nodoc:
        @quoted_column_names[name] ||= "`#{name}`"
      end


  def get_path
    Log.add_info(request, params.inspect)

    if params[:thetisBoxSelKeeper].nil? or params[:thetisBoxSelKeeper].empty?
      @group_path = '/' + t('paren.unknown')
      render(:partial => 'ajax_group_path', :layout => false)
      return
    end

    @selected_id = params[:thetisBoxSelKeeper].split(':').last

    @group_path = Group.get_path(@selected_id)

    render(:partial => 'ajax_group_path', :layout => false)
  end


  def test_should_sanitize_illegal_style_properties
    raw      = %(display:block; position:absolute; left:0; top:0; width:100%; height:100%; z-index:1; background-color:black; background-image:url(http://www.ragingplatypus.com/i/cam-full.jpg); background-x:center; background-y:center; background-repeat:repeat;)
    expected = %(display: block; width: 100%; height: 100%; background-color: black; background-x: center; background-y: center;)
    assert_equal expected, sanitize_css(raw)
  end


  def set_description
    Log.add_info(request, params.inspect)

    if params[:id].nil? or params[:id].empty?
      @item = Item.new_info(0)
      @item.attributes = params.require(:item).permit(Item::PERMIT_BASE)
      @item.user_id = @login_user.id
      @item.title = t('paren.no_title')
      @item.save
    else
      @item = Item.find(params[:id])
      @item.update_attributes(params.require(:item).permit(Item::PERMIT_BASE))
    end

    render(:partial => 'ajax_item_description', :layout => false)

  rescue => evar
    Log.add_error(request, evar)
    render(:partial => 'ajax_item_description', :layout => false)
  end


  def stub_jwks
    stub_request(:get, 'https://samples.auth0.com/.well-known/jwks.json')
      .to_return(
        headers: { 'Content-Type' => 'application/json' },
        body: jwks.to_json,
        status: 200
      )
  end


  def update_groups_order
    Log.add_info(request, params.inspect)

    order_ary = params[:groups_order]

    Research.set_statistics_groups order_ary

    render(:text => '')
  end


  def send_password
    Log.add_info(request, params.inspect)

    begin
      users = User.where("email='#{params[:thetisBoxEdit]}'").to_a
    rescue => evar
    end

    if users.nil? or users.empty?
      Log.add_error(request, evar)
      flash[:notice] = 'ERROR:' + t('email.address_not_found')
    else
      user_passwords_h = {}
      users.each do |user|
        newpass = UsersHelper.generate_password
        user.update_attribute(:pass_md5, UsersHelper.generate_digest_pass(user.name, newpass))

        user_passwords_h[user] = newpass
      end

      NoticeMailer.password(user_passwords_h, ApplicationHelper.root_url(request)).deliver;
      flash[:notice] = t('email.sent')
    end

    render(:controller => 'login', :action => 'index')
  end


  def self.update_xorder(title, order)

    if title.nil?
      con = nil
    else
      con = ['title=?', title]
    end

    SqlHelper.validate_token([order])
    User.update_all("xorder=#{order}", con)
  end


  def get_auth_groups
    Log.add_info(request, params.inspect)

    begin
      @folder = Folder.find(params[:id])
    rescue
      @folder = nil
    end

    @groups = Group.where(nil).to_a

    session[:folder_id] = params[:id]

    render(:partial => 'ajax_auth_groups', :layout => false)
  end


  def self.get_childs(klass, node_id, recursive, ret_obj)

    SqlHelper.validate_token([node_id])

    array = []

    if recursive

      tree = klass.get_tree(Hash.new, nil, node_id)
      return array if tree.nil?

      tree.each do |parent_id, childs|
        if ret_obj
          array |= childs
        else
          childs.each do |node|
            node_id = node.id.to_s
            array << node_id unless array.include?(node_id)
          end
        end
      end

    else

      nodes = klass.where("parent_id=#{node_id}").order('xorder ASC, id ASC').to_a
      if ret_obj
        array = nodes
      else
        nodes.each do |node|
          array << node.id.to_s
        end
      end
    end

    return array
  end


        def self.search_by_user(key, operator, value)
          key_name = key.sub(/^.*\./,'')
          users = User.all(:conditions => "#{key_name} #{operator} '#{value_to_sql(operator, value)}'")
          hosts = users.map(&:hosts).flatten
          opts  = hosts.empty? ? "= 'nil'" : "IN (#{hosts.map(&:id).join(',')})"

          return {:conditions => " hosts.id #{opts} " }
        end


  def self.count_ack_users(item_id)
    SqlHelper.validate_token([item_id])
    return Comment.where("(item_id=#{item_id}) and (xtype='#{Comment::XTYPE_DIST_ACK}')").count
  end


  def self.trim(user_id, mail_account_id, max)

    SqlHelper.validate_token([user_id, mail_account_id])

    begin
      count = Email.where("mail_account_id=#{mail_account_id}").count
      if count > max
#logger.fatal("[INFO] Email.trim(user_id:#{user_id}, mail_account_id:#{mail_account_id}, max:#{max})")
        over_num = count - max
        emails = []

        # First, empty Trashbox
        user = User.find(user_id)
        trashbox = MailFolder.get_for(user, mail_account_id, MailFolder::XTYPE_TRASH)
        trash_nodes = [trashbox.id.to_s]
        trash_nodes += MailFolder.get_childs(trash_nodes.first, true, false)
        con = "mail_folder_id in (#{trash_nodes.join(',')})"
        emails = Email.where(con).order('updated_at ASC').limit(over_num).to_a

        # Now, remove others
        if emails.length < over_num
          over_num -= emails.length
          emails += Email.where("mail_account_id=#{mail_account_id}").order('updated_at ASC').limit(over_num).to_a
        end

        emails.each do |email|
          email.destroy
        end
      end
    rescue
    end
  end


  def get_folder_items
    Log.add_info(request, params.inspect)

    unless params[:thetisBoxSelKeeper].nil? or params[:thetisBoxSelKeeper].empty?
      @folder_id = params[:thetisBoxSelKeeper].split(':').last
    end

    begin
      if Folder.check_user_auth(@folder_id, @login_user, 'r', true)
        @items = Folder.get_items(@login_user, @folder_id)
      end
    rescue => evar
      Log.add_error(request, evar)
    end

    submit_url = url_for(:controller => 'schedules', :action => 'get_folder_items')
    render(:partial => 'common/select_items', :layout => false, :locals => {:target_attr => :id, :submit_url => submit_url})
  end


  def get_group_users
    Log.add_info(request, params.inspect)

    @group_id = nil
    if !params[:thetisBoxSelKeeper].nil?
      @group_id = params[:thetisBoxSelKeeper].split(':').last
    elsif !params[:group_id].nil? and !params[:group_id].empty?
      @group_id = params[:group_id]
    end

    @users = Group.get_users @group_id

    render(:partial => 'ajax_select_users', :layout => false)
  end


    it 'authenticates successfuly' do
      basic_authorize 'a', 'b'

      get '/'

      assert_equal 200, last_response.status
    end


  def delete_attachment
    Log.add_info(request, '')   # Not to show passwords.

    target_user = nil

    user_id = params[:user_id]
    zeptair_id = params[:zeptair_id]
    attachment_id = params[:attachment_id]
    SqlHelper.validate_token([user_id, zeptair_id, attachment_id])

    unless user_id.blank?
      if @login_user.admin?(User::AUTH_ZEPTAIR) or @login_user.id.to_s == user_id.to_s
        target_user = User.find(user_id)
      end
    end

    unless zeptair_id.blank?

      target_user = User.where("zeptair_id=#{zeptair_id}").first

      unless @login_user.admin?(User::AUTH_ZEPTAIR) or @login_user.id == target_user.id
        target_user = nil
      end
    end

    if target_user.nil?
      if attachment_id.blank?

        query
        unless @post_items.nil?
          @post_items.each do |post_item|
            post_item.attachments_without_content.each do |attach|
              attach.destroy
            end
            post_item.update_attribute(:updated_at, Time.now)
          end
        end

      else
        attach = Attachment.find(attachment_id)

        item = Item.find(attach.item_id)

        if !@login_user.admin?(User::AUTH_ZEPTAIR) and item.user_id != @login_user.id
          raise t('msg.need_to_be_owner')
        end

        if item.xtype != Item::XTYPE_ZEPTAIR_POST
          raise t('msg.system_error')
        end

        attach.destroy

        item.update_attribute(:updated_at, Time.now)
      end
    else

      post_item = ZeptairPostHelper.get_item_for(target_user)
      post_item.attachments_without_content.each do |attach|
        attach.destroy
      end
      post_item.update_attribute(:updated_at, Time.now)
    end

    render(:text => t('msg.delete_success'))

  rescue => evar
    Log.add_error(request, evar)
    render(:text => 'ERROR:' + t('msg.system_error'))
  end


  it "raises an error when trying to download a local file" do
    expect { subject.download('/etc/passwd') }.to raise_error(CarrierWave::DownloadError)
  end


    it "raises with a valid SSRF attack" do
      @api_key = "-attacker.net/test/?"
      @gibbon.api_key = @api_key
      expect {@gibbon.try.retrieve}.to raise_error(Gibbon::MailChimpError, /SSRF attempt/)
    end


      def filename_from_uri
        CGI.unescape(File.basename(file.base_uri.path))
      end


  def self.update_for(user_id, fiscal_year, num)

    if num <= 0
      PaidHoliday.destroy_all(['user_id=? and year=?', user_id, fiscal_year])
      return
    end

    paid_holiday = PaidHoliday.get_for(user_id, fiscal_year)

    if paid_holiday.nil?
      paid_holiday = PaidHoliday.new
      paid_holiday.user_id = user_id
      paid_holiday.year = fiscal_year
      paid_holiday.num = num
      paid_holiday.save!
    else
      paid_holiday.update_attribute(:num, num)
    end
  end


def initialize(locale, key, options = nil)
        @key, @locale, @options = key, locale, options.dup || {}
        options.each { |k, v| self.options[k] = v.inspect if v.is_a?(Proc) }
      end

      def html_message
        key = keys.last.to_s.gsub('_', ' ').gsub(/\b('?[a-z])/) { $1.capitalize }
        %(#{key})
      end

      def keys
        @keys ||= I18n.normalize_keys(locale, key, options[:scope]).tap do |keys|
          keys << 'no key' if keys.size < 2
        end
      end

      def message
        "translation missing: #{keys.join('.')}"
      end


  def set_image
    Log.add_info(request, params.inspect)

    created = false

    if params[:id].nil? or params[:id].empty?
      @item = Item.new_info(0)
      @item.attributes = params[:item]
      @item.user_id = @login_user.id
      @item.title = t('paren.no_title')

      [:image0, :image1].each do |img|

        next if params[img].nil? or params[img][:file].size == 0

        @item.save!
        created = true
        break
      end
    else
      @item = Item.find(params[:id])
    end

    modified = false

    item_images = @item.images_without_content
    [:image0, :image1].each do |img|
      next if params[img].nil? or params[img][:file].nil? or params[img][:file].size == 0
      image = Image.new
      image.item_id = @item.id
      image.file = params[img][:file]
      image.title = params[img][:title]
      image.memo = params[img][:memo]
      image.xorder = item_images.length
      image.save!

      modified = true
      item_images << image
    end

    if modified and !created
      @item.update_attribute(:updated_at, Time.now)
    end

    render(:partial => 'ajax_item_image', :layout => false)

  rescue => evar
    Log.add_error(request, evar)

    @image = Image.new
    @image.errors.add_to_base(evar.to_s[0, 256])

    render(:partial => 'ajax_item_image', :layout => false)
  end


func (h *Handler) DefaultLogoutHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	h.L.Warnln("A client requested the default logout URL, environment variable OAUTH2_LOGOUT_REDIRECT_URL is probably not set.")

	fmt.Fprintf(w, `

	<title>You logged out successfully</title>

	You logged out successfully!

	You are seeing this default page because the administrator did not specify a redirect URL (environment variable OAUTH2_LOGOUT_REDIRECT_URL is not set).
	If you are an administrator, please read the guide to understand what you
	need to do. If you are a user, please contact the administrator.

`)
}


func newSessionService() {
	SessionProvider = Cfg.MustValueRange("session", "PROVIDER", "memory",
		[]string{"memory", "file", "redis", "mysql"})

	SessionConfig = new(session.Config)
	SessionConfig.ProviderConfig = strings.Trim(Cfg.MustValue("session", "PROVIDER_CONFIG"), "\" ")
	SessionConfig.CookieName = Cfg.MustValue("session", "COOKIE_NAME", "i_like_gogits")
	SessionConfig.CookiePath = AppSubUrl
	SessionConfig.Secure = Cfg.MustBool("session", "COOKIE_SECURE")
	SessionConfig.EnableSetCookie = Cfg.MustBool("session", "ENABLE_SET_COOKIE", true)
	SessionConfig.Gclifetime = Cfg.MustInt64("session", "GC_INTERVAL_TIME", 86400)
	SessionConfig.Maxlifetime = Cfg.MustInt64("session", "SESSION_LIFE_TIME", 86400)
	SessionConfig.SessionIDHashFunc = Cfg.MustValueRange("session", "SESSION_ID_HASHFUNC",
		"sha1", []string{"sha1", "sha256", "md5"})
	SessionConfig.SessionIDHashKey = Cfg.MustValue("session", "SESSION_ID_HASHKEY", string(com.RandomCreateBytes(16)))

	if SessionProvider == "file" {
		os.MkdirAll(path.Dir(SessionConfig.ProviderConfig), os.ModePerm)
	}

	log.Info("Session Service Enabled")
}


func (x *UserList_User) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[48]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (*ListAccountsRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{26}
}


func TimestampFileMetaEqual(actual data.TimestampFileMeta, expected data.TimestampFileMeta) error {
	// As opposed to snapshots, the length and hashes are still required in
	// TUF-1.0. See:
	// https://github.com/theupdateframework/specification/issues/38
	if err := FileMetaEqual(actual.FileMeta, expected.FileMeta); err != nil {
		return err
	}

	if err := versionEqual(actual.Version, expected.Version); err != nil {
		return err
	}

	return nil
}


func (x *MatchStateRequest) Reset() {
	*x = MatchStateRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[32]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func TestEscapeJSONString(t *testing.T) {
	for _, str := range []string{"", "foobar", `foo"bar`, `foo\bar`, "foo\n\tbar"} {
		escaped := EscapeJSONString(str)
		var unmarshaled string
		err := json.Unmarshal([]byte(`"` + escaped + `"`), &unmarshaled)
		require.NoError(t, err, str)
		assert.Equal(t, str, unmarshaled, str)
	}
}


func extractTarDirectory(root, prefix string, r io.Reader) error {
	tr := tar.NewReader(r)
	for {
		header, err := tr.Next()
		if err != nil {
			if err == io.EOF {
				return nil
			}
			return err
		}

		// Name check
		name := header.Name
		path, err := filepath.Rel(prefix, name)
		if err != nil {
			return err
		}
		if strings.HasPrefix(path, "../") {
			return fmt.Errorf("%q does not have prefix %q", name, prefix)
		}
		path = filepath.Join(root, path)

		// Create content
		switch header.Typeflag {
		case tar.TypeReg:
			err = writeFile(path, tr, header.FileInfo().Mode())
		case tar.TypeDir:
			err = os.MkdirAll(path, header.FileInfo().Mode())
		case tar.TypeLink:
			err = os.Link(header.Linkname, path)
		case tar.TypeSymlink:
			err = os.Symlink(header.Linkname, path)
		default:
			continue // Non-regular files are skipped
		}
		if err != nil {
			return err
		}

		// Change access time and modification time if possible (error ignored)
		os.Chtimes(path, header.AccessTime, header.ModTime)
	}
}


func Token(user model.TableUser) (string, error) {

	tNow := time.Now()
	tUTC := tNow

	newTUTC := tUTC.Add(time.Duration(TokenExpiryTime) * time.Minute)

	// Set custom claims
	claims := &JwtUserClaim{
		user.UserName,
		user.IsAdmin,
		user.UserGroup,
		user.ExternalAuth,
		user.ExternalProfile,
		user.FirstName + " " + user.LastName,
		user.Avatar,
		jwt.StandardClaims{
			ExpiresAt: newTUTC.Unix(),
		},
	}

	logger.Debug("Current time : ", tNow)
	logger.Debug("Local time : ", tUTC)
	logger.Debug("Expire Local time : ", newTUTC)

	// Create token with claims
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	// Generate encoded token and send it as response.
	t, err := token.SignedString([]byte(JwtSecret))
	if err != nil {
		return "", err
	}

	return t, nil
}


func (x *LeaderboardList) Reset() {
	*x = LeaderboardList{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[24]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func newSignV4ChunkedReader(req *http.Request) (io.ReadCloser, APIErrorCode) {
	cred, seedSignature, region, seedDate, errCode := calculateSeedSignature(req)
	if errCode != ErrNone {
		return nil, errCode
	}

	return &s3ChunkedReader{
		reader:            bufio.NewReader(req.Body),
		cred:              cred,
		seedSignature:     seedSignature,
		seedDate:          seedDate,
		region:            region,
		chunkSHA256Writer: sha256.New(),
		state:             readChunkHeader,
	}, ErrNone
}


func TestTruncatedCiphertext(t *testing.T) {
	key := make([]byte, 32)
	nonce := make([]byte, 16)
	data := make([]byte, 32)

	io.ReadFull(rand.Reader, key)
	io.ReadFull(rand.Reader, nonce)

	aead, err := NewCBCHMAC(key, aes.NewCipher)
	if err != nil {
		panic(err)
	}

	ctx := aead.(*cbcAEAD)
	ct := aead.Seal(nil, nonce, data, nil)

	// Truncated ciphertext, but with correct auth tag
	truncated, tail := resize(ct[:len(ct)-ctx.authtagBytes-2], len(ct)-2)
	copy(tail, ctx.computeAuthTag(nil, nonce, truncated[:len(truncated)-ctx.authtagBytes]))

	// Open should fail
	_, err = aead.Open(nil, nonce, truncated, nil)
	if err == nil {
		t.Error("open on truncated ciphertext should fail")
	}
}


		private HandshakeMessage createServerHandshakeMessage(
			HandshakeType type, byte[] buffer)
		{
			ClientContext context = (ClientContext)this.context;

			switch (type)
			{
				case HandshakeType.HelloRequest:
					if (context.HandshakeState != HandshakeState.Started)
					{
						context.HandshakeState = HandshakeState.None;
						// re-negotiation will occur at next read/write
						// (i.e. not during an existing encode/decode op)
					}
					else
					{
						this.SendAlert(
							AlertLevel.Warning,
							AlertDescription.NoRenegotiation);
					}
					return null;

				case HandshakeType.ServerHello:
					return new TlsServerHello(this.context, buffer);

				case HandshakeType.Certificate:
					return new TlsServerCertificate(this.context, buffer);

				case HandshakeType.ServerKeyExchange:
					return new TlsServerKeyExchange(this.context, buffer);

				case HandshakeType.CertificateRequest:
					return new TlsServerCertificateRequest(this.context, buffer);

				case HandshakeType.ServerHelloDone:
					return new TlsServerHelloDone(this.context, buffer);

				case HandshakeType.Finished:
					return new TlsServerFinished(this.context, buffer);

				default:
					throw new TlsException(
						AlertDescription.UnexpectedMessage,
						String.Format(CultureInfo.CurrentUICulture,
							"Unknown server handshake message received ({0})",
							type.ToString()));
			}
		}


func (g DashboardHandler) Append(router *mux.Router) {
	if g.Assets == nil {
		log.WithoutContext().Error("No assets for dashboard")
		return
	}

	// Expose dashboard
	router.Methods(http.MethodGet).
		Path("/").
		HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
			http.Redirect(response, request, request.Header.Get("X-Forwarded-Prefix")+"/dashboard/", http.StatusFound)
		})

	router.Methods(http.MethodGet).
		PathPrefix("/dashboard/").
		Handler(http.StripPrefix("/dashboard/", http.FileServer(g.Assets)))
}


func (x *StorageCollectionsList) Reset() {
	*x = StorageCollectionsList{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[34]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (x *UserList_User) Reset() {
	*x = UserList_User{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[48]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (x *ListStorageRequest) Reset() {
	*x = ListStorageRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[30]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (s *ConsoleServer) lookupConsoleUser(ctx context.Context, unameOrEmail, password string) (uname string, email string, role console.UserRole, err error) {
	role = console.UserRole_USER_ROLE_UNKNOWN
	query := "SELECT username, email, role, password, disable_time FROM console_user WHERE username = $1 OR email = $1"
	var dbPassword []byte
	var dbDisableTime pgtype.Timestamptz
	err = s.db.QueryRowContext(ctx, query, unameOrEmail).Scan(&uname, &email, &role, &dbPassword, &dbDisableTime)
	if err != nil {
		if err == sql.ErrNoRows {
			err = nil
		}
		return
	}

	// Check if it's disabled.
	if dbDisableTime.Status == pgtype.Present && dbDisableTime.Time.Unix() != 0 {
		s.logger.Info("Console user account is disabled.", zap.String("username", unameOrEmail))
		err = status.Error(codes.PermissionDenied, "Invalid credentials.")
		return
	}

	// Check password
	err = bcrypt.CompareHashAndPassword(dbPassword, []byte(password))
	if err != nil {
		err = status.Error(codes.Unauthenticated, "Invalid credentials.")
		return
	}

	return

}


func (e ErrLatestSnapshot) Error() string {
	return fmt.Sprintf("tuf: the local snapshot version (%d) is the latest", e.Version)
}


func (s *Service) loadCsvFile(fileName string) (*data.Frame, error) {
	validFileName := regexp.MustCompile(`([\w_]+)\.csv`)

	if !validFileName.MatchString(fileName) {
		return nil, fmt.Errorf("invalid csv file name: %q", fileName)
	}

	filePath := filepath.Join(s.cfg.StaticRootPath, "testdata", fileName)

	// Can ignore gosec G304 here, because we check the file pattern above
	// nolint:gosec
	fileReader, err := os.Open(filePath)
	if err != nil {
		return nil, fmt.Errorf("failed open file: %v", err)
	}

	defer func() {
		if err := fileReader.Close(); err != nil {
			s.logger.Warn("Failed to close file", "err", err, "path", fileName)
		}
	}()

	return LoadCsvContent(fileReader, fileName)
}


func (x *UpdateAccountRequest) Reset() {
	*x = UpdateAccountRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[36]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (x *UserList) Reset() {
	*x = UserList{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[39]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (x *Config) Reset() {
	*x = Config{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[14]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (r ResourceServer) ValidateAccessToken(ctx context.Context, expectedAudience, tokenStr string) (interfaces.IdentityContext, error) {
	raw, err := r.signatureVerifier.VerifySignature(ctx, tokenStr)
	if err != nil {
		return nil, err
	}

	claimsRaw := map[string]interface{}{}
	if err = json.Unmarshal(raw, &claimsRaw); err != nil {
		return nil, fmt.Errorf("failed to unmarshal user info claim into UserInfo type. Error: %w", err)
	}

	return verifyClaims(sets.NewString(append(r.allowedAudience, expectedAudience)...), claimsRaw)
}


func (c *linuxContainer) newInitProcess(p *Process, cmd *exec.Cmd, messageSockPair, logFilePair filePair) (*initProcess, error) {
	cmd.Env = append(cmd.Env, "_LIBCONTAINER_INITTYPE="+string(initStandard))
	nsMaps := make(map[configs.NamespaceType]string)
	for _, ns := range c.config.Namespaces {
		if ns.Path != "" {
			nsMaps[ns.Type] = ns.Path
		}
	}
	_, sharePidns := nsMaps[configs.NEWPID]
	data, err := c.bootstrapData(c.config.Namespaces.CloneFlags(), nsMaps)
	if err != nil {
		return nil, err
	}
	init := &initProcess{
		cmd:             cmd,
		messageSockPair: messageSockPair,
		logFilePair:     logFilePair,
		manager:         c.cgroupManager,
		intelRdtManager: c.intelRdtManager,
		config:          c.newInitConfig(p),
		container:       c,
		process:         p,
		bootstrapData:   data,
		sharePidns:      sharePidns,
	}
	c.initProcess = init
	return init, nil
}


func sendCode(id string) (err error) {

	a, err := account.SelectAccount(id, 0)
	if err != nil {
		logger.Error("发送验证码失败", zap.Error(err))
		return
	}

	if len(a) == 0 {
		return errors.New("账号不存在")
	}

	rand.Seed(time.Now().UnixNano())
	c := strconv.FormatFloat(rand.Float64(), 'f', -1, 64)[2:6]

	client.GetClient().SendMessage(
		message.NewTextMessage("您的验证码是：" + c + "，请勿泄露给他人。有效期5分钟").
			SetTarget(&message.Target{ID: a[0].QQ}),
	)

	account.WriteCode(id, c)

	go func() {
		timer := time.NewTimer(5 * time.Minute)
		defer timer.Stop()
		<-timer.C
		account.DeleteCode(id)
	}()

	return
}


static bool anal_fcn_data (RCore *core, const char *input) {
	RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
	ut32 fcn_size = r_anal_function_size_from_entry (fcn);
	if (fcn) {
		int i;
		bool gap = false;
		ut64 gap_addr = UT64_MAX;
		char *bitmap = calloc (1, fcn_size);
		if (bitmap) {
			RAnalBlock *b;
			RListIter *iter;
			r_list_foreach (fcn->bbs, iter, b) {
				int f = b->addr - fcn->addr;
				int t = R_MIN (f + b->size, fcn_size);
				if (f >= 0) {
					while (f < t) {
						bitmap[f++] = 1;
					}
				}
			}
		}
		for (i = 0; i < fcn_size; i++) {
			ut64 here = fcn->addr + i;
			if (bitmap && bitmap[i]) {
				if (gap) {
					r_cons_printf ("Cd %d @ 0x%08"PFMT64x"\n", here - gap_addr, gap_addr);
					gap = false;
				}
				gap_addr = UT64_MAX;
			} else {
				if (!gap) {
					gap = true;
					gap_addr = here;
				}
			}
		}
		if (gap) {
			r_cons_printf ("Cd %d @ 0x%08"PFMT64x"\n", fcn->addr + fcn_size - gap_addr, gap_addr);
		}
		free (bitmap);
		return true;
	}
	return false;
}


func (o *casaService) GetServerList(index, size, tp, categoryId, key string) (recommend, list, community []model.ServerAppList) {

	keyName := fmt.Sprintf("list_%s_%s_%s_%s", index, size, tp, categoryId)

	if result, ok := Cache.Get(keyName); ok {
		res, ok := result.(string)
		if ok {
			json2.Unmarshal([]byte(gjson.Get(res, "data.list").String()), &list)
			json2.Unmarshal([]byte(gjson.Get(res, "data.recommend").String()), &recommend)
			json2.Unmarshal([]byte(gjson.Get(res, "data.community").String()), &community)
			return
		}
	}

	head := make(map[string]string)

	head["Authorization"] = GetToken()

	listS := httper2.Get(config.ServerInfo.ServerApi+"/v2/app/newlist?index="+index+"&size="+size+"&rank="+tp+"&category_id="+categoryId+"&key="+key, head)

	json2.Unmarshal([]byte(gjson.Get(listS, "data.list").String()), &list)
	json2.Unmarshal([]byte(gjson.Get(listS, "data.recommend").String()), &recommend)
	json2.Unmarshal([]byte(gjson.Get(listS, "data.community").String()), &community)

	if len(list) > 0 {
		Cache.SetDefault(keyName, listS)
	}
	return
}


func (c *linuxContainer) newSetnsProcess(p *Process, cmd *exec.Cmd, messageSockPair, logFilePair filePair) (*setnsProcess, error) {
	cmd.Env = append(cmd.Env, "_LIBCONTAINER_INITTYPE="+string(initSetns))
	state, err := c.currentState()
	if err != nil {
		return nil, fmt.Errorf("unable to get container state: %w", err)
	}
	// for setns process, we don't have to set cloneflags as the process namespaces
	// will only be set via setns syscall
	data, err := c.bootstrapData(0, state.NamespacePaths)
	if err != nil {
		return nil, err
	}
	proc := &setnsProcess{
		cmd:             cmd,
		cgroupPaths:     state.CgroupPaths,
		rootlessCgroups: c.config.RootlessCgroups,
		intelRdtPath:    state.IntelRdtPath,
		messageSockPair: messageSockPair,
		logFilePair:     logFilePair,
		manager:         c.cgroupManager,
		config:          c.newInitConfig(p),
		process:         p,
		bootstrapData:   data,
		initProcessPid:  state.InitProcessPid,
	}
	if len(p.SubCgroupPaths) > 0 {
		if add, ok := p.SubCgroupPaths[""]; ok {
			// cgroup v1: using the same path for all controllers.
			// cgroup v2: the only possible way.
			for k := range proc.cgroupPaths {
				proc.cgroupPaths[k] = path.Join(proc.cgroupPaths[k], add)
			}
			// cgroup v2: do not try to join init process's cgroup
			// as a fallback (see (*setnsProcess).start).
			proc.initProcessPid = 0
		} else {
			// Per-controller paths.
			for ctrl, add := range p.SubCgroupPaths {
				if val, ok := proc.cgroupPaths[ctrl]; ok {
					proc.cgroupPaths[ctrl] = path.Join(val, add)
				} else {
					return nil, fmt.Errorf("unknown controller %s in SubCgroupPaths", ctrl)
				}
			}
		}
	}
	return proc, nil
}


func TestReadRequest_BadConnectHost(t *testing.T) {
	data := []byte("CONNECT []%20%48%54%54%50%2f%31%2e%31%0a%4d%79%48%65%61%64%65%72%3a%20%31%32%33%0a%0a HTTP/1.0\n\n")
	r, err := ReadRequest(bufio.NewReader(bytes.NewReader(data)))
	if err == nil {
		t.Fatal("Got unexpected request = %#v", r)
	}
}


func HTTP(c *HTTPContext) {
	for _, route := range routes {
		reqPath := strings.ToLower(c.Req.URL.Path)
		m := route.re.FindStringSubmatch(reqPath)
		if m == nil {
			continue
		}

		// We perform check here because route matched in cmd/web.go is wider than needed,
		// but we only want to output this message only if user is really trying to access
		// Git HTTP endpoints.
		if conf.Repository.DisableHTTPGit {
			c.Error(http.StatusForbidden, "Interacting with repositories by HTTP protocol is disabled")
			return
		}

		if route.method != c.Req.Method {
			c.NotFound()
			return
		}

		file := strings.TrimPrefix(reqPath, m[1]+"/")
		dir, err := getGitRepoPath(m[1])
		if err != nil {
			log.Warn("HTTP.getGitRepoPath: %v", err)
			c.NotFound()
			return
		}

		route.handler(serviceHandler{
			w:    c.Resp,
			r:    c.Req.Request,
			dir:  dir,
			file: file,

			authUser:  c.AuthUser,
			ownerName: c.OwnerName,
			ownerSalt: c.OwnerSalt,
			repoID:    c.RepoID,
			repoName:  c.RepoName,
		})
		return
	}

	c.NotFound()
}


func SearchUserByName(opt SearchOption) (us []*User, err error) {
	// Prevent SQL inject.
	opt.Keyword = strings.TrimSpace(opt.Keyword)
	if len(opt.Keyword) == 0 {
		return us, nil
	}

	opt.Keyword = strings.Split(opt.Keyword, " ")[0]
	if len(opt.Keyword) == 0 {
		return us, nil
	}
	opt.Keyword = strings.ToLower(opt.Keyword)

	us = make([]*User, 0, opt.Limit)
	err = x.Limit(opt.Limit).Where("type=0").And("lower_name like '%" + opt.Keyword + "%'").Find(&us)
	return us, err
}


func (x *UpdateGroupUserStateRequest) Reset() {
	*x = UpdateGroupUserStateRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[19]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (sg *SecureGet) Do(ctx context.Context) error {
	ref, err := name.ParseReference(sg.ImageRef)
	if err != nil {
		return err
	}

	opts := []remote.Option{
		remote.WithAuthFromKeychain(authn.DefaultKeychain),
		remote.WithContext(ctx),
	}

	co := &cosign.CheckOpts{
		ClaimVerifier:      cosign.SimpleClaimVerifier,
		RegistryClientOpts: []ociremote.Option{ociremote.WithRemoteOptions(opts...)},
	}
	if _, ok := ref.(name.Tag); ok {
		if sg.KeyRef == "" && !options.EnableExperimental() {
			return errors.New("public key must be specified when fetching by tag, you must fetch by digest or supply a public key")
		}
	}
	// Overwrite "ref" with a digest to avoid a race where we verify the tag,
	// and then access the file through the tag.  This has a race where we
	// might download content that isn't what we verified.
	ref, err = ociremote.ResolveDigest(ref, co.RegistryClientOpts...)
	if err != nil {
		return err
	}

	if sg.KeyRef != "" {
		pub, err := sigs.LoadPublicKey(ctx, sg.KeyRef)
		if err != nil {
			return err
		}
		co.SigVerifier = pub
	}

	if co.SigVerifier != nil || options.EnableExperimental() {
		co.RootCerts = fulcio.GetRoots()

		sp, bundleVerified, err := cosign.VerifyImageSignatures(ctx, ref, co)
		if err != nil {
			return err
		}
		verify.PrintVerificationHeader(sg.ImageRef, co, bundleVerified)
		verify.PrintVerification(sg.ImageRef, sp, "text")
	}

	// TODO(mattmoor): Depending on what this is, use the higher-level stuff.
	img, err := remote.Image(ref, opts...)
	if err != nil {
		return err
	}
	layers, err := img.Layers()
	if err != nil {
		return err
	}
	if len(layers) != 1 {
		return errors.New("invalid artifact")
	}
	rc, err := layers[0].Compressed()
	if err != nil {
		return err
	}

	_, err = io.Copy(sg.Out, rc)
	return err
}


func (x *WalletLedger) Reset() {
	*x = WalletLedger{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[42]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (net *Network) checkTopicRegister(data *topicRegister) (*pong, error) {
	var pongpkt ingressPacket
	if err := decodePacket(data.Pong, &pongpkt); err != nil {
		return nil, err
	}
	if pongpkt.ev != pongPacket {
		return nil, errors.New("is not pong packet")
	}
	if pongpkt.remoteID != net.tab.self.ID {
		return nil, errors.New("not signed by us")
	}
	// check that we previously authorised all topics
	// that the other side is trying to register.
	hash, _, _ := wireHash(data.Topics)
	if hash != pongpkt.data.(*pong).TopicHash {
		return nil, errors.New("topic hash mismatch")
	}
	if data.Idx < 0 || int(data.Idx) >= len(data.Topics) {
		return nil, errors.New("topic index out of range")
	}
	return pongpkt.data.(*pong), nil
}


func Test_isRepositoryGitPath(t *testing.T) {
	tests := []struct {
		path    string
		wantVal bool
	}{
		{path: filepath.Join(".", ".git"), wantVal: true},
		{path: filepath.Join(".", ".git", ""), wantVal: true},
		{path: filepath.Join(".", ".git", "hooks", "pre-commit"), wantVal: true},
		{path: filepath.Join(".git", "hooks"), wantVal: true},
		{path: filepath.Join("dir", ".git"), wantVal: true},

		{path: filepath.Join(".", ".git."), wantVal: true},
		{path: filepath.Join(".", ".git.", ""), wantVal: true},
		{path: filepath.Join(".", ".git.", "hooks", "pre-commit"), wantVal: true},
		{path: filepath.Join(".git.", "hooks"), wantVal: true},
		{path: filepath.Join("dir", ".git."), wantVal: true},

		{path: filepath.Join(".gitignore"), wantVal: false},
		{path: filepath.Join("dir", ".gitkeep"), wantVal: false},
	}
	for _, test := range tests {
		t.Run("", func(t *testing.T) {
			assert.Equal(t, test.wantVal, isRepositoryGitPath(test.path))
		})
	}
}


func (x *DeleteWalletLedgerRequest) Reset() {
	*x = DeleteWalletLedgerRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[22]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name,


function set(target, path, val) {
    "use strict";
    try {
        return add(target, path, val);
    } catch(ex) {
        console.error(ex);
        return;
    }
}


  constructor({ log, port }: { log: LogEntry; port?: number }) {
    this.log = log
    this.debugLog = this.log.placeholder({ level: LogLevel.debug, childEntriesInheritLevel: true })
    this.garden = undefined
    this.port = port
    this.authKey = randomString(64)
    this.incomingEvents = new EventBus()
    this.activePersistentRequests = {}

    this.serversUpdatedListener = ({ servers }) => {
      // Update status log line with new `garden dashboard` server, if any
      for (const { host, command } of servers) {
        if (command === "dashboard") {
          this.showUrl(host)
          return
        }
      }

      // No active explicit dashboard processes, show own URL instead
      this.showUrl(this.getUrl())
    }
  }


export function suspendUser(userId: UserId, numDays: number, reason: string, success: () => void) {


      return { kind: 'redirect', to: `/signin?from=${encodeURIComponent(req!.url!)}` };
    }
  };


search.stats = function(files) {
												if(files.length) {
													var file = files.shift();
													fs.stat(relativePath + '/' + file, function(err, stats) {
														if(err) { writeError(err); }
														else {
															stats.name = file;
															stats.isFile = stats.isFile();
															stats.isDirectory = stats.isDirectory();
															stats.isBlockDevice = stats.isBlockDevice();
															stats.isFIFO = stats.isFIFO();
															stats.isSocket = stats.isSocket();
															results.push(stats);
															search.stats(files);
														}
													});
												} else {
													if(query.type == 'json' || query.dir == 'json') {
														res.setHeader('Content-Type', 'application/json');
														res.write(JSON.stringify(results));
														res.end();
													} else {
														res.setHeader('Content-Type', 'text/html');
														res.write('');
														for(var f = 0; f < results.length; f++) {
															var name = results[f].name;
															var normalized = url + '/' + name;
															while(normalized[0] == '/') { normalized = normalized.slice(1, normalized.length); }
															res.write('\r\n
' + name + '
');
														}
														res.end('\r\n');
													}
												}
											};


  constructor (
    private sanitizer: DomSanitizer,
    private serverService: ServerService,
    private notifier: Notifier
  ) { }


    Object.keys(data).forEach((key) => {
      obj.set(key, deserializer(data[key], baseType) as T);
    });


    userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name,
    totalHours,
  }


function setDeepProperty(obj, propertyPath, value) {
    const a = splitPath(propertyPath);
    const n = a.length;
    for (let i = 0; i < n - 1; i++) {
        const k = a[i];
        if (!(k in obj)) {
            obj[k] = {};
        }
        obj = obj[k];
    }
    obj[a[n - 1]] = value;
    return;
}


  async start() {
    if (this.server) {
      return
    }

    this.app = await this.createApp()

    if (this.port) {
      this.server = this.app.listen(this.port)
    } else {
      do {
        try {
          this.port = await getPort({ port: defaultWatchServerPort })
          this.server = this.app.listen(this.port)
        } catch {}
      } while (!this.server)
    }

    this.log.info("")
    this.statusLog = this.log.placeholder()
  }


  function addSockListeners() {
    if (!accept && !reject) {
      sock.once('connect', onconnect);
      sock.on('data', ondata);
      sock.once('error', onerror);
      sock.once('close', onclose);
    } else {
      var chan;
      sock.once('connect', function() {
        chan = accept();
        var isDone = false;
        function onDone() {
          if (isDone)
            return;
          sock.destroy();
          isDone = true;
        }
        chan.once('end', onDone)
            .once('close', onDone)
            .on('data', function(data) {
          sock.write(data);
        });
        sock.on('data', function(data) {
          chan.write(data);
        });
      });
      sock.once('close', function() {
        if (!chan)
          reject();
      });
    }
  }


function indexer(set) {
    return function(obj, i) {
        "use strict";
        try {
            if (obj && i && obj.hasOwnProperty(i)) {
                return obj[i];
            } else if (obj && i && set) {
                obj[i] = {};
                return obj[i];
            }
            return;
        } catch(ex) {
            console.error(ex);
            return;
        }
    };
}


        getDownloadUrl(id, accessToken) {
            return this.importExport.getDownloadUrl(id, accessToken);
        },


function add(obj, str, val) {
    "use strict";
    try {
        if ( typeof str !== "string") {
            return;
        }
        if ( typeof obj !== "object") {
            return;
        }
        if (!val) {
            return;
        }
        var items = str.split('.');
        var initial = items.slice(0, items.length - 1);
        var last = items.slice(items.length - 1);
        var test = initial.reduce(indexTrue, obj);
        test[last] = val;
    } catch(ex) {
        console.error(ex);
        return;
    }
}


return { session: new Capnp.Capability(new ExternalWebSession(this.url, options), ApiSession) };


  onAvatarChange (input: HTMLInputElement) {
    this.avatarfileInput = new ElementRef(input)

    const avatarfile = this.avatarfileInput.nativeElement.files[0]
    if (avatarfile.size > this.maxAvatarSize) {
      this.notifier.error('Error', $localize`This image is too large.`)
      return
    }

    const formData = new FormData()
    formData.append('avatarfile', avatarfile)
    this.avatarPopover?.close()
    this.avatarChange.emit(formData)

    if (this.previewImage) {
      this.preview = this.sanitizer.bypassSecurityTrustResourceUrl(URL.createObjectURL(avatarfile))
    }
  }


  function PageantSock() {
    this.proc = undefined;
    this.buffer = null;
  }


      return txt.replace(/[&<>]/gm, (str) => {
        if (str === "&") return "&";
        if (str === "<") return "<";
        if (str === ">") return ">";
      });


    return `[${renderType(type.ofType)}]`;
  }
  return `<a class="typeName">${type.name}</a>`;
}


export function add_attribute(name, value, boolean) {
	if (value == null || (boolean && !value)) return '';
	const assignment = (boolean && value === true) ? '' : `="${escape_attribute_value(value.toString())}"`;
	return ` ${name}${assignment}`;
}