code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
def process_cors(env) resource, error = match_resource(env) if resource Result.hit(env) cors = resource.to_headers(env) cors else Result.miss(env, error) nil end end
Base
1
it "drops the collection" do database.should_receive(:command).with(drop: :users) collection.drop end
Class
2
def delete_statistics_group Log.add_info(request, params.inspect) group_id = params[:group_id] if group_id.nil? or group_id.empty? @group_ids = Research.get_statistics_groups render(:partial => 'ajax_statistics_groups', :layout => false) return end @group_ids = Research.delete_statistics_group group_id render(:partial => 'ajax_statistics_groups', :layout => false) end
Base
1
def protected! if not PCSAuth.loginByToken(session, cookies) and not PCSAuth.isLoggedIn(session) # If we're on /managec/<cluster_name>/main we redirect match_expr = "/managec/(.*)/(.*)" mymatch = request.path.match(match_expr) on_managec_main = false if mymatch and mymatch.length >= 3 and mymatch[2] == "main" on_managec_main = true end if request.path.start_with?('/remote') or (request.path.match(match_expr) and not on_managec_main) or '/run_pcs' == request.path or '/clusters_overview' == request.path or request.path.start_with?('/permissions_') then $logger.info "ERROR: Request without authentication" halt [401, '{"notauthorized":"true"}'] else session[:pre_login_path] = request.path redirect '/login' end end end
Compound
4
it "creates an index with a generated name" do indexes.create(key) indexes[key]["name"].should eq "location.latlong_2d_name_1_age_-1" end
Class
2
it "sets the :database option" do session.use :admin session.options[:database].should eq(:admin) end
Class
2
it "returns the query" do query.limit(5).should eql query end
Class
2
def self.destroy_by_user(user_id, add_con=nil) SqlHelper.validate_token([user_id]) con = "user_id=#{user_id}" con << " and (#{add_con})" unless add_con.nil? or add_con.empty? mail_accounts = MailAccount.where(con).to_a mail_accounts.each do |mail_account| mail_account.destroy end end
Base
1
it 'correctly exports the CategoryUser table' do data, _csv_out = make_component_csv expect(data.find { |r| r['category_id'] == category.id }).to be_nil expect(data.length).to eq(4) data.sort! { |a, b| a['category_id'].to_i <=> b['category_id'].to_i } expect(data[0][:category_id]).to eq(subcategory.id.to_s) expect(data[0][:notification_level].to_s).to eq('tracking') expect(DateTime.parse(data[0][:dismiss_new_timestamp])).to eq(reset_at) expect(data[1][:category_id]).to eq(subsubcategory.id.to_s) expect(data[1][:category_names]).to eq("#{category.name}|#{subcategory.name}|#{subsubcategory.name}") expect(data[1][:notification_level]).to eq('regular') expect(DateTime.parse(data[1][:dismiss_new_timestamp])).to eq(reset_at) expect(data[2][:category_id]).to eq(announcements.id.to_s) expect(data[2][:category_names]).to eq(announcements.name) expect(data[2][:notification_level]).to eq('watching_first_post') expect(data[2][:dismiss_new_timestamp]).to eq('') expect(data[3][:category_names]).to eq(data[3][:category_id]) end
Class
2
def get_node_status(session, cib_dom) node_status = { :cluster_name => $cluster_name, :groups => [], :constraints => { # :rsc_location => [], # :rcs_colocation => [], # :rcs_order => [] }, :cluster_settings => {}, :need_ring1_address => need_ring1_address?, :is_cman_with_udpu_transport => is_cman_with_udpu_transport?, :acls => get_acls(session, cib_dom), :username => session[:username], :fence_levels => get_fence_levels(session, cib_dom), :node_attr => node_attrs_to_v2(get_node_attributes(session, cib_dom)), :nodes_utilization => get_nodes_utilization(cib_dom), :known_nodes => [] } nodes = get_nodes_status() known_nodes = [] nodes.each { |_, node_list| known_nodes.concat node_list } node_status[:known_nodes] = known_nodes.uniq nodes.each do |k,v| node_status[k.to_sym] = v end if cib_dom node_status[:groups] = get_resource_groups(cib_dom) node_status[:constraints] = getAllConstraints(cib_dom.elements['/cib/configuration/constraints']) end node_status[:cluster_settings] = getAllSettings(session, cib_dom) return node_status end
Compound
4
def set_attachment 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') [:attachment0, :attachment1].each do |attach| next if params[attach].nil? or params[attach][:file].nil? or params[attach][:file].size == 0 @item.save! created = true break end else @item = Item.find(params[:id]) end modified = false item_attachments = @item.attachments_without_content [:attachment0, :attachment1].each do |attach| next if params[attach].nil? or params[attach][:file].nil? or params[attach][:file].size == 0 attachment = Attachment.create(params[attach], @item, item_attachments.length) modified = true item_attachments << attachment end if modified and !created @item.update_attribute(:updated_at, Time.now) end render(:partial => 'ajax_item_attachment', :layout => false) rescue => evar Log.add_error(request, evar) @attachment = Attachment.new @attachment.errors.add_to_base(evar.to_s[0, 256]) render(:partial => 'ajax_item_attachment', :layout => false) end
Base
1
def add_acl_permission(session, acl_role_id, perm_type, xpath_id, query_id) stdout, stderror, retval = run_cmd( session, PCS, "acl", "permission", "add", acl_role_id.to_s, perm_type.to_s, xpath_id.to_s, query_id.to_s ) if retval != 0 if stderror.empty? return "Error adding permission" else return stderror.join("\n").strip end end return "" end
Compound
4
def verify_signature(jwt) head = token_head(jwt) # Make sure the algorithm is supported and get the decode key. if head[:alg] == 'RS256' [rs256_decode_key(head[:kid]), head[:alg]] elsif head[:alg] == 'HS256' [@client_secret, head[:alg]] else raise OmniAuth::Auth0::TokenValidationError.new("Signature algorithm of #{head[:alg]} is not supported. Expected the ID token to be signed with RS256 or HS256") end end
Base
1
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
Base
1
def remove delete = Protocol::Delete.new( operation.database, operation.collection, operation.selector, flags: [:remove_first] ) session.with(consistency: :strong) do |session| session.execute delete end end
Class
2
def remove_acl_permission(session, acl_perm_id) stdout, stderror, retval = run_cmd( session, PCS, "acl", "permission", "delete", acl_perm_id.to_s ) if retval != 0 if stderror.empty? return "Error removing permission" else return stderror.join("\n").strip end end return "" end
Compound
4
def quote_column_name(name) #:nodoc: %Q("#{name}") end
Base
1
def process_invitation approve_account_if_needed add_to_private_topics_if_invited add_user_to_groups send_welcome_message notify_invitee end
Class
2
def generation_time Time.at(@data.pack("C4").unpack("N")[0]).utc end
Class
2
it "executes the operation on the master node" do session.should_receive(:socket_for).with(:write). and_return(socket) socket.should_receive(:execute).with(operation) session.execute(operation) end
Class
2
def get_current_node_name() stdout, stderror, retval = run_cmd( PCSAuth.getSuperuserSession, CRM_NODE, "-n" ) if retval == 0 and stdout.length > 0 return stdout[0].chomp() end return "" end
Compound
4
def self.getUsersGroups(username) stdout, stderr, retval = run_cmd( getSuperuserSession, "id", "-Gn", username ) if retval != 0 $logger.info( "Unable to determine groups of user '#{username}': #{stderr.join(' ').strip}" ) return [false, []] end return [true, stdout.join(' ').split(nil)] end
Compound
4
def self.get_account_roots_for(user) return nil if user.nil? if user.kind_of?(User) user_id = user.id else user_id = user.to_s end SqlHelper.validate_token([user_id]) con = [] con << "(user_id=#{user_id})" con << "(xtype='#{MailFolder::XTYPE_ACCOUNT_ROOT}')" order_by = 'xorder ASC, id ASC' return MailFolder.where(con.join(' and ')).order(order_by).to_a end
Base
1
it "inserts the document" do session.should_receive(:execute).with do |insert| insert.documents.should eq [{a: 1}] end collection.insert(a: 1) end
Class
2
def get_fence_levels(session, cib_dom=nil) unless cib_dom cib_dom = get_cib_dom(session) return {} unless cib_dom end fence_levels = {} cib_dom.elements.each( '/cib/configuration/fencing-topology/fencing-level' ) { |e| target = e.attributes['target'] fence_levels[target] ||= [] fence_levels[target] << { 'level' => e.attributes['index'], 'devices' => e.attributes['devices'] } } fence_levels.each { |_, val| val.sort_by! { |obj| obj['level'].to_i }} return fence_levels end
Compound
4
def fast_forward_to_first_boundary loop do read_buffer = @io.gets break if read_buffer == full_boundary raise EOFError, "bad content body" if read_buffer.nil? end end
Class
2
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
Base
1
def parse(socket=nil) @socket = socket begin @peeraddr = socket.respond_to?(:peeraddr) ? socket.peeraddr : [] @addr = socket.respond_to?(:addr) ? socket.addr : [] rescue Errno::ENOTCONN raise HTTPStatus::EOFError end read_request_line(socket) if @http_version.major > 0 read_header(socket) @header['cookie'].each{|cookie| @cookies += Cookie::parse(cookie) } @accept = HTTPUtils.parse_qvalues(self['accept']) @accept_charset = HTTPUtils.parse_qvalues(self['accept-charset']) @accept_encoding = HTTPUtils.parse_qvalues(self['accept-encoding']) @accept_language = HTTPUtils.parse_qvalues(self['accept-language']) end return if @request_method == "CONNECT" return if @unparsed_uri == "*" begin setup_forwarded_info @request_uri = parse_uri(@unparsed_uri) @path = HTTPUtils::unescape(@request_uri.path) @path = HTTPUtils::normalize_path(@path) @host = @request_uri.host @port = @request_uri.port @query_string = @request_uri.query @script_name = "" @path_info = @path.dup rescue raise HTTPStatus::BadRequest, "bad URI `#{@unparsed_uri}'." end if /close/io =~ self["connection"] @keep_alive = false elsif /keep-alive/io =~ self["connection"] @keep_alive = true elsif @http_version < "1.1" @keep_alive = false else @keep_alive = true end end
Base
1
def protected! gui_request = ( # these are URLs for web pages request.path == '/' or request.path == '/manage' or request.path == '/permissions' or request.path.match('/managec/.+/main') ) if request.path.start_with?('/remote/') or request.path == '/run_pcs' @auth_user = PCSAuth.loginByToken(cookies) unless @auth_user halt [401, '{"notauthorized":"true"}'] end else #/managec/* /manage/* /permissions if !gui_request and request.env['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' then # Accept non GUI requests only with header # "X_REQUESTED_WITH: XMLHttpRequest". (check if they are send via AJAX). # This prevents CSRF attack. halt [401, '{"notauthorized":"true"}'] elsif not PCSAuth.isLoggedIn(session) if gui_request session[:pre_login_path] = request.path redirect '/login' else halt [401, '{"notauthorized":"true"}'] end end end end
Compound
4
def gate_process HistoryHelper.keep_last(request) @login_user = User.find(session[:login_user_id]) begin if @login_user.nil? \ or @login_user.time_zone.nil? or @login_user.time_zone.empty? unless THETIS_USER_TIMEZONE_DEFAULT.nil? or THETIS_USER_TIMEZONE_DEFAULT.empty? Time.zone = THETIS_USER_TIMEZONE_DEFAULT end else Time.zone = @login_user.time_zone end rescue => evar logger.fatal(evar.to_s) end end
Base
1
def sanitize(html, options = {}) return unless html return html if html.empty? Loofah.fragment(html).tap do |fragment| remove_xpaths(fragment, XPATHS_TO_REMOVE) end.text(options) end
Base
1
def spoofed? if has_name? && has_extension? && media_type_mismatch? && mapping_override_mismatch? Paperclip.log("Content Type Spoof: Filename #{File.basename(@name)} (#{supplied_file_content_types}), content type discovered from file command: #{calculated_content_type}. See documentation to allow this combination.") true end end
Base
1
def remove(server) servers.delete(server) end
Class
2
def test_update_valid put :update, {:id => Hostgroup.first, :hostgroup => { :name => Hostgroup.first.name }}, set_session_user assert_redirected_to hostgroups_url end
Class
2
it "yields a new session" do session.with(new_options) do |new_session| new_session.should_not eql session end end
Class
2
it 'authenticates successfuly' do basic_authorize 'a', 'b' get '/' assert_equal 200, last_response.status end
Base
1
def self.find_term(user_id, start_date, end_date) SqlHelper.validate_token([user_id]) start_s = start_date.strftime(Schedule::SYS_DATE_FORM) end_s = end_date.strftime(Schedule::SYS_DATE_FORM) con = "(user_id=#{user_id}) and (date >= '#{start_s}') and (date <= '#{end_s}')" 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
Base
1
def destroy Log.add_info(request, params.inspect) if params[:check_user].nil? list render(:action => 'list') return end count = 0 params[:check_user].each do |user_id, value| if value == '1' begin User.destroy(user_id) rescue => evar Log.add_error(request, evar) end count += 1 end end flash[:notice] = count.to_s + t('user.deleted') redirect_to(:action => 'list') end
Base
1
detectMimeType(filename) { if (!filename) { return defaultMimeType; } let parsed = path.parse(filename); let extension = (parsed.ext.substr(1) || parsed.name || '') .split('?') .shift() .trim() .toLowerCase(); let value = defaultMimeType; if (extensions.has(extension)) { value = extensions.get(extension); } if (Array.isArray(value)) { return value[0]; } return value; },
Base
1
def get_crm_mon_dom(session) begin stdout, _, retval = run_cmd( session, CRM_MON, '--one-shot', '-r', '--as-xml' ) if retval == 0 return REXML::Document.new(stdout.join("\n")) end rescue $logger.error 'Failed to parse crm_mon.' end return nil end
Compound
4
def build_command_line(command, params = nil) return command.to_s if params.nil? || params.empty? "#{command} #{assemble_params(sanitize(params))}" end
Base
1
def create Log.add_info(request, params.inspect) parent_id = params[:selectedFolderId] unless Folder.check_user_auth(parent_id, @login_user, 'w', true) flash[:notice] = 'ERROR:' + t('folder.need_auth_to_modify') render(:partial => 'ajax_folder_entry', :layout => false) return end if params[:thetisBoxEdit].nil? or params[:thetisBoxEdit].empty? @folder = nil else @folder = Folder.new @folder.name = params[:thetisBoxEdit] @folder.xorder = Folder.get_order_max(parent_id) + 1 @folder.parent_id = parent_id @folder.inherit_parent_auth @folder.save! end render(:partial => 'ajax_folder_entry', :layout => false) end
Base
1
def each documents = query @query_op documents.each { |doc| yield doc } while more? return kill if limited? && @get_more_op.limit <= 0 documents = query @get_more_op documents.each { |doc| yield doc } end end
Class
2
it "inserts the documents" do session.should_receive(:execute).with do |insert| insert.documents.should eq [{a: 1}, {b: 2}] end collection.insert([{a: 1}, {b: 2}]) end
Class
2
def add_fence_level_remote(params, request, session) if not allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end retval, stdout, stderr = add_fence_level( session, params["level"], params["devices"], params["node"], params["remove"] ) if retval == 0 return [200, "Successfully added fence level"] else return [400, stderr] end end
Compound
4
it "does not raise error if record is not pending" do reviewable = ReviewableUser.needs_review!(target: Fabricate(:user, email: invite.email), created_by: invite.invited_by) reviewable.status = Reviewable.statuses[:ignored] reviewable.save! invite_redeemer.redeem reviewable.reload expect(reviewable.status).to eq(Reviewable.statuses[:ignored]) end
Class
2
it "returns the index with the provided key" do indexes[name: 1]["name"].should eq "name_1" end
Class
2
it "delegates to the current database" do database = mock(Moped::Database) session.should_receive(:current_database).and_return(database) database.should_receive(:drop) session.drop end
Class
2
it "has an empty list of servers" do cluster.servers.should be_empty end
Class
2
it "yields all indexes on the collection" do indexes.to_a.should eq \ session[:"system.indexes"].find(ns: "moped_test.users").to_a end
Class
2
def get_tokens(params, request, session) # pcsd runs as root thus always returns hacluster's tokens if not allowed_for_local_cluster(session, Permissions::FULL) return 403, 'Permission denied' end return [200, JSON.generate(read_tokens)] end
Compound
4
def deliver!(mail) envelope_from = mail.return_path || mail.sender || mail.from_addrs.first return_path = "-f " + '"' + envelope_from.escape_for_shell + '"' if envelope_from arguments = [settings[:arguments], return_path].compact.join(" ") self.class.call(settings[:location], arguments, mail.destinations.collect(&:shellescape).join(" "), mail) end
Class
2
def target_uri?(target) ::Asciidoctor::Helpers.uriish?(target) end
Base
1
it "instructs the cluster to reconnect" do session.stub(with: new_session) new_session.cluster.should_receive(:reconnect) session.new(new_options) end
Class
2
it "queries a slave node" do session.should_receive(:socket_for).with(:read). and_return(socket) session.query(query) end
Class
2
it "should raise an error if the image fails an integrity check when downloaded" do stub_request(:get, "www.example.com/test.jpg").to_return(body: File.read(file_path("test.jpg"))) expect(running { @instance.remote_image_url = "http://www.example.com/test.jpg" }).to raise_error(CarrierWave::IntegrityError) end
Base
1
it 'returns correct link' do data = { cutoff: false, user: 'Julia Nguyen', comment: 'Hello', typename: 'typename', type: 'type_comment_moment', typeid: 1, commentable_id: 1 } expect(comment_link(uniqueid, data)).to eq('<a id="uniqueid" href="/moments/1">Julia Nguyen commented "Hello" on typename</a>') end
Base
1
def self.get_default_for(user_id, xtype=nil) SqlHelper.validate_token([user_id, xtype]) con = [] con << "(user_id=#{user_id})" con << '(is_default=1)' con << "(xtype='#{xtype}')" unless xtype.blank? where = '' unless con.nil? or con.empty? where = 'where ' + con.join(' and ') end mail_accounts = MailAccount.find_by_sql('select * from mail_accounts ' + where + ' order by xorder ASC, title ASC') if mail_accounts.nil? or mail_accounts.empty? return nil else return mail_accounts.first end end
Base
1
def resource_master(params, request, session) if not allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end unless params[:resource_id] return [400, 'resource_id has to be specified.'] end _, stderr, retval = run_cmd( session, PCS, 'resource', 'master', params[:resource_id] ) if retval != 0 return [400, 'Unable to create master/slave resource from ' + "'#{params[:resource_id]}': #{stderr.join('')}" ] end return 200 end
Compound
4
it "does not drop other indexes" do indexes[age: -1].should_not be_nil end
Class
2
def escape_javascript(javascript) javascript = javascript.to_s if javascript.empty? result = "" else result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|\342\200\251|[\n\r"'])/u, JS_ESCAPE_MAP) end javascript.html_safe? ? result.html_safe : result end
Variant
0
def self.reminders(options={}) days = options[:days] || 7 project = options[:project] ? Project.find(options[:project]) : nil tracker = options[:tracker] ? Tracker.find(options[:tracker]) : nil target_version_id = options[:version] ? Version.named(options[:version]).pluck(:id) : nil if options[:version] && target_version_id.blank? raise ActiveRecord::RecordNotFound.new("Couldn't find Version with named #{options[:version]}") end user_ids = options[:users] scope = Issue.open.where("#{Issue.table_name}.assigned_to_id IS NOT NULL" + " AND #{Project.table_name}.status = #{Project::STATUS_ACTIVE}" + " AND #{Issue.table_name}.due_date <= ?", days.day.from_now.to_date ) scope = scope.where(:assigned_to_id => user_ids) if user_ids.present? scope = scope.where(:project_id => project.id) if project scope = scope.where(:fixed_version_id => target_version_id) if target_version_id.present? scope = scope.where(:tracker_id => tracker.id) if tracker issues_by_assignee = scope.includes(:status, :assigned_to, :project, :tracker). group_by(&:assigned_to) issues_by_assignee.keys.each do |assignee| if assignee.is_a?(Group) assignee.users.each do |user| issues_by_assignee[user] ||= [] issues_by_assignee[user] += issues_by_assignee[assignee] end end end issues_by_assignee.each do |assignee, issues| reminder(assignee, issues, days).deliver if assignee.is_a?(User) && assignee.active? end end
Class
2
def get_sw_versions(params, request, session) versions = { "rhel" => get_rhel_version(), "pcs" => get_pcsd_version(), "pacemaker" => get_pacemaker_version(), "corosync" => get_corosync_version(), "cman" => get_cman_version(), } return JSON.generate(versions) end
Compound
4
def unfold(string) string.gsub(/#{CRLF}#{WSP}+/, ' ').gsub(/#{WSP}+/, ' ') end
Base
1
it "upserts the record matching selector with change" do query.should_receive(:update).with(change, [:upsert]) query.upsert change end
Class
2
it "sets the current database" do session.should_receive(:set_current_database).with(:admin) session.use :admin end
Class
2
def getResourceAgents(session) resource_agent_list = {} stdout, stderr, retval = run_cmd(session, PCS, "resource", "list", "--nodesc") if retval != 0 $logger.error("Error running 'pcs resource list --nodesc") $logger.error(stdout + stderr) return {} end agents = stdout agents.each { |a| ra = ResourceAgent.new ra.name = a.chomp resource_agent_list[ra.name] = ra } return resource_agent_list end
Compound
4
def get_configs(params, request, session) if not allowed_for_local_cluster(session, Permissions::FULL) return 403, 'Permission denied' end if not $cluster_name or $cluster_name.empty? return JSON.generate({'status' => 'not_in_cluster'}) end if params[:cluster_name] != $cluster_name return JSON.generate({'status' => 'wrong_cluster_name'}) end out = { 'status' => 'ok', 'cluster_name' => $cluster_name, 'configs' => {}, } Cfgsync::get_configs_local.each { |name, cfg| out['configs'][cfg.class.name] = { 'type' => 'file', 'text' => cfg.text, } } return JSON.generate(out) end
Compound
4
def node_standby(params, request, session) if params[:name] code, response = send_request_with_token( session, params[:name], 'node_standby', true, {"node"=>params[:name]} ) # data={"node"=>params[:name]} for backward compatibility with older versions of pcs/pcsd else if not allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end $logger.info "Standby Node" stdout, stderr, retval = run_cmd(session, PCS, "cluster", "standby") return stdout end end
Compound
4
def self.run_gpg(*args) fragments = [ 'gpg', '--no-default-keyring' ] + args command_line = fragments.join(' ') output_file = Tempfile.new('gpg-output') begin output_file.close result = system("#{command_line} > #{output_file.path} 2>&1") ensure output_file.unlink end raise RuntimeError.new('gpg failed') unless result end
Base
1
def reactions_given params.require(:username) user = fetch_user_from_params(include_inactive: current_user.try(:staff?) || (current_user && SiteSetting.show_inactive_accounts)) raise Discourse::NotFound unless guardian.can_see_profile?(user) reaction_users = DiscourseReactions::ReactionUser .joins(:reaction, :post) .includes(:user, :post, :reaction) .where(user_id: user.id) .where('discourse_reactions_reactions.reaction_users_count IS NOT NULL') if params[:before_reaction_user_id] reaction_users = reaction_users .where('discourse_reactions_reaction_users.id < ?', params[:before_reaction_user_id].to_i) end reaction_users = reaction_users .order(created_at: :desc) .limit(20) render_serialized(reaction_users.to_a, UserReactionSerializer) end
Class
2
it "sets the generation time" do time = Time.at((Time.now.utc - 64800).to_i).utc Moped::BSON::ObjectId.new(nil, time).generation_time.should == time end
Class
2
def self.new string_or_io from_document Nokogiri::XML(string_or_io) end
Base
1
def activity_user user = current_user.pref[:activity_user] if user && user != "all_users" user = if user =~ /@/ # email User.where(:email => user).first else # first_name middle_name last_name any_name name_query = if user.include?(" ") user.name_permutations.map{ |first, last| "(upper(first_name) LIKE upper('%#{first}%') AND upper(last_name) LIKE upper('%#{last}%'))" }.join(" OR ") else "upper(first_name) LIKE upper('%#{user}%') OR upper(last_name) LIKE upper('%#{user}%')" end User.where(name_query).first end
Base
1
it "stores the collection name" do collection.name.should eq :users end
Class
2
it "should redeem the invite if invited by non staff and approve if staff not required to approve" do inviter = invite.invited_by user = invite_redeemer.redeem expect(user.name).to eq(name) expect(user.username).to eq(username) expect(user.invited_by).to eq(inviter) expect(inviter.notifications.count).to eq(1) expect(user.approved).to eq(true) end
Class
2
def cluster_stop(params, request, session) if params[:name] params_without_name = params.reject {|key, value| key == "name" or key == :name } code, response = send_request_with_token( session, params[:name], 'cluster_stop', true, params_without_name ) else if not allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end options = [] if params.has_key?("component") if params["component"].downcase == "pacemaker" options << "--pacemaker" elsif params["component"].downcase == "corosync" options << "--corosync" end end options << "--force" if params["force"] $logger.info "Stopping Daemons" stdout, stderr, retval = run_cmd(session, PCS, "cluster", "stop", *options) if retval != 0 return [400, stderr.join] else return stdout.join end end end
Compound
4
def query(operation) reply = session.query operation @get_more_op.limit -= reply.count if limited? @get_more_op.cursor_id = reply.cursor_id @kill_cursor_op.cursor_ids = [reply.cursor_id] reply.documents end
Class
2
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
Base
1
it "only aquires the socket once" do session.cluster.should_receive(:socket_for). with(:read).once.and_return(mock(Moped::Socket)) session.send(:socket_for, :read) session.send(:socket_for, :read) end
Class
2
def validate_each(record, attribute, value) adapter = Paperclip.io_adapters.for(value) if Paperclip::MediaTypeSpoofDetector.using(adapter, value.original_filename).spoofed? record.errors.add(attribute, :spoofed_media_type) end end
Base
1
it "can set password" do user = InviteRedeemer.new(invite: invite, email: invite.email, username: username, name: name, password: password).redeem expect(user).to have_password expect(user.confirm_password?(password)).to eq(true) expect(user.approved).to eq(true) end
Class
2
def setup_user(operation, type = "", search = nil, user = :one) @one = users(user) as_admin do permission = Permission.find_by_name("#{operation}_#{type}") || FactoryGirl.create(:permission, :name => "#{operation}_#{type}") filter = FactoryGirl.build(:filter, :search => search) filter.permissions = [ permission ] role = Role.where(:name => "#{operation}_#{type}").first_or_create role.filters = [ filter ] role.save! filter.role = role filter.save! @one.roles << role yield(@one) if block_given? @one.save! end User.current = @one end
Class
2
it "only aquires the socket once" do session.cluster.should_receive(:socket_for). with(:read).once.and_return(mock(Moped::Socket)) session.send(:socket_for, :read) session.send(:socket_for, :read) end
Class
2
it "returns a random slave connection" do secondaries = [server] cluster.stub(secondaries: secondaries) secondaries.should_receive(:sample).and_return(server) cluster.socket_for(:read).should eq socket end
Class
2
def initialize(string) super("'#{string}' is not a valid object id.") end
Class
2
def self.exists_copies_folder?(user_id) my_folder = User.get_my_folder(user_id) unless my_folder.nil? con = "(parent_id=#{my_folder.id}) and (name='#{Item.copies_folder}')" begin copies_folder = Folder.where(con).first rescue end end return !copies_folder.nil? end
Base
1
it "handles Symbol keys" do cl = subject.build_command_line("true", :abc => "def") expect(cl).to eq "true --abc def" end
Base
1
it "returns only published articles" do article = create(:article) create(:comment, article: article) unpublished_article = create(:article, state: "draft") create(:comment, article: unpublished_article) expect(described_class.published).to eq([article]) expect(described_class.bestof).to eq([article]) end
Class
2
def require_smart_proxy_or_login(features = nil) features = features.call if features.respond_to?(:call) allowed_smart_proxies = features.blank? ? SmartProxy.all : SmartProxy.with_features(*features) if !Setting[:restrict_registered_smart_proxies] || auth_smart_proxy(allowed_smart_proxies, Setting[:require_ssl_smart_proxies]) set_admin_user return true end require_login unless User.current render_error 'access_denied', :status => :forbidden unless performed? && api_request? return false end authorize end
Class
2
it 'should return nil if there is not key' do expect(jwt_validator.jwks_key(:auth0, jwks_kid)).to eq(nil) end
Base
1
def process # We don't want any tracking back in the fs. Unlikely, but there # you go. client = self.host.gsub("..",".") dir = File.join(Puppet[:reportdir], client) if ! FileTest.exists?(dir) FileUtils.mkdir_p(dir) FileUtils.chmod_R(0750, dir) end # Now store the report. now = Time.now.gmtime name = %w{year month day hour min}.collect do |method| # Make sure we're at least two digits everywhere "%02d" % now.send(method).to_s end.join("") + ".yaml" file = File.join(dir, name) f = Tempfile.new(name, dir) begin begin f.chmod(0640) f.print to_yaml ensure f.close end FileUtils.mv(f.path, file) rescue => detail puts detail.backtrace if Puppet[:trace] Puppet.warning "Could not write report for #{client} at #{file}: #{detail}" end # Only testing cares about the return value file end
Base
1
it "recognizes and generates #destroy" do { :delete => "/users/1" }.should route_to(:controller => "users", :action => "destroy", :id => "1") end
Class
2
def set_corosync_conf(params, request, session) if not allowed_for_local_cluster(session, Permissions::FULL) return 403, 'Permission denied' end if params[:corosync_conf] != nil and params[:corosync_conf].strip != "" Cfgsync::CorosyncConf.backup() Cfgsync::CorosyncConf.from_text(params[:corosync_conf]).save() return 200, "Succeeded" else $logger.info "Invalid corosync.conf file" return 400, "Failed" end end
Compound
4
def show_tree Log.add_info(request, params.inspect) if !@login_user.nil? and @login_user.admin?(User::AUTH_FOLDER) @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 @folder_tree = Folder.get_tree_by_group_for_admin(@group_id || '0') else @folder_tree = Folder.get_tree_for(@login_user) end end
Base
1
it "should choose :file_server when the settings name is 'puppet' and no server is specified" do modules = mock 'modules' @request.expects(:protocol).returns "puppet" @request.expects(:server).returns nil Puppet.settings.expects(:value).with(:name).returns "puppet" @object.select_terminus(@request).should == :file_server end
Class
2
def spree_current_user @spree_current_user ||= Spree.user_class.find_by(id: doorkeeper_token.resource_owner_id) if doorkeeper_token end
Base
1
def test_execute_details_cleans_text spec_fetcher do |fetcher| fetcher.spec 'a', 2 do |s| s.summary = 'This is a lot of text. ' * 4 s.authors = ["Abraham Lincoln \u0001", "\u0002 Hirohito"] s.homepage = "http://a.example.com/\u0003" end fetcher.legacy_platform end @cmd.handle_options %w[-r -d] use_ui @ui do @cmd.execute end expected = <<-EOF *** REMOTE GEMS *** a (2) Authors: Abraham Lincoln ., . Hirohito Homepage: http://a.example.com/. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. pl (1) Platform: i386-linux Author: A User Homepage: http://example.com this is a summary EOF assert_equal expected, @ui.output assert_equal '', @ui.error end
Base
1
it "stores the selector" do query.selector.should eq selector end
Class
2
it "returns false" do session.should_not be_safe end
Class
2