code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
it "returns the count" do database.stub(command: { "n" => 4 }) query.count.should eq 4 end
Class
2
def self.extract_events(post) cooked = PrettyText.cook(post.raw, topic_id: post.topic_id, user_id: post.user_id) valid_options = VALID_OPTIONS.map { |o| "data-#{o}" } valid_custom_fields = [] SiteSetting.discourse_post_event_allowed_custom_fields.split('|').each do |setting| valid_custom_fields << { original: "data-#{setting}", normalized: "data-#{setting.gsub(/_/, '-')}" } end Nokogiri::HTML(cooked).css('div.discourse-post-event').map do |doc| event = nil doc.attributes.values.each do |attribute| name = attribute.name value = attribute.value if value && valid_options.include?(name) event ||= {} event[name.sub('data-', '').to_sym] = CGI.escapeHTML(value) end valid_custom_fields.each do |valid_custom_field| if value && valid_custom_field[:normalized] == name event ||= {} event[valid_custom_field[:original].sub('data-', '').to_sym] = CGI.escapeHTML(value) end end end event end.compact end
Base
1
def add_to_group Log.add_info(request, params.inspect) if params[:thetisBoxSelKeeper].nil? or params[:thetisBoxSelKeeper].empty? render(:partial => 'ajax_groups', :layout => false) return end group_id = params[:thetisBoxSelKeeper].split(':').last unless group_id == '0' # '0' for ROOT begin group = Group.find(group_id) rescue => evar Log.add_error(request, evar) ensure if group.nil? render(:partial => 'ajax_groups', :layout => false) return end end end begin @user = User.find(params[:user_id]) rescue => evar Log.add_error(request, evar) end unless @user.nil? is_modified = false # Change, not simply Add unless params[:current_id] == nil or params[:current_id].empty? if @user.exclude_from(params[:current_id]) is_modified = true end end is_modified = true if @user.add_to(group_id) if is_modified == true # @user.update_attribute(:groups, @user.groups) @user.save! if @user.id == @login_user.id @login_user = @user end end end render(:partial => 'ajax_groups', :layout => false) end
Base
1
it "returns nothing" do socket.stub(connect: false) cluster.sync_server(server).should be_empty end
Class
2
it "memoizes the database" do database = session.current_database session.current_database.should equal(database) end
Class
2
it "returns nothing" do socket.stub(connect: false) cluster.sync_server(server).should be_empty end
Class
2
it "creates an index with the provided name" do indexes.create(key, name: "custom_index_name") indexes[key]["name"].should eq "custom_index_name" end
Class
2
it 'should return nil if the key ID is invalid' do expect(jwt_validator.jwks_key(:alg, "#{jwks_kid}_invalid")).to eq(nil) end
Base
1
it "with Pathname command and params" do cl = subject.build_command_line(Pathname.new("/usr/bin/ruby"), "-v" => nil) expect(cl).to eq "/usr/bin/ruby -v" end
Base
1
it "removes the socket" do cluster.should_receive(:remove).with(dead_server) cluster.socket_for :write end
Class
2
def update_order Log.add_info(request, params.inspect) mail_account_id = params[:mail_account_id] order_ary = params[:mail_filters_order] @mail_account = MailAccount.find_by_id(mail_account_id) if @mail_account.user_id != @login_user.id render(:text => 'ERROR:' + t('msg.need_to_be_owner')) return end filters = MailFilter.get_for(mail_account_id) # filters must be ordered by xorder ASC. filters.sort! { |filter_a, filter_b| id_a = filter_a.id.to_s id_b = filter_b.id.to_s idx_a = order_ary.index(id_a) idx_b = order_ary.index(id_b) if idx_a.nil? or idx_b.nil? idx_a = filters.index(id_a) idx_b = filters.index(id_b) end idx_a - idx_b } idx = 1 filters.each do |filter| next if filter.mail_account_id != mail_account_id.to_i filter.update_attribute(:xorder, idx) idx += 1 end render(:text => '') end
Base
1
def get_group_users Log.add_info(request, params.inspect) begin @folder = Folder.find(params[:id]) rescue => evar Log.add_error(request, evar) end @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
Base
1
it "sets the query operation's fields" do query.select(a: 1) query.operation.fields.should eq(a: 1) end
Class
2
def approve_account_if_needed if invited_user.present? && reviewable_user = ReviewableUser.find_by(target: invited_user, status: Reviewable.statuses[:pending]) reviewable_user.perform( invite.invited_by, :approve_user, send_email: false, approved_by_invite: true ) end end
Class
2
it "sets the object id's data" do Moped::BSON::ObjectId.new(bytes).data.should == bytes end
Class
2
def socket_for(mode) if options[:retain_socket] @socket ||= cluster.socket_for(mode) else cluster.socket_for(mode) end end
Class
2
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
Base
1
it "creates an index" do indexes.create(key, background: true) indexes[key]["background"].should eq true end
Class
2
def update_attachments_order Log.add_info(request, params.inspect) order_ary = params[:attachments_order] item = Item.find(params[:id]) item.attachments_without_content.each do |attach| class << attach def record_timestamps; false; end end attach.update_attribute(:xorder, order_ary.index(attach.id.to_s) + 1) class << attach remove_method :record_timestamps end end render(:text => '') rescue => evar Log.add_error(request, evar) render(:text => evar.to_s) end
Base
1
def package_index valid_http_methods :get required_parameters :project, :repository, :arch, :package # read access permission check if params[:package] == "_repository" prj = DbProject.get_by_name params[:project], use_source=false else pkg = DbPackage.get_by_project_and_name params[:project], params[:package], use_source=false end pass_to_backend end
Base
1
def each cursor = Cursor.new(session.with(retain_socket: true), operation) cursor.to_enum.tap do |enum| enum.each do |document| yield document end if block_given? end end
Class
2
def self.parse_csv_row(row, book, idxs, user) imp_id = (idxs[0].nil? or row[idxs[0]].nil?)?(nil):(row[idxs[0]].strip) SqlHelper.validate_token([imp_id]) unless imp_id.blank? org_address = Address.find_by_id(imp_id) end if org_address.nil? address = Address.new else address = org_address end address.id = imp_id attr_names = [ :name, :name_ruby, :nickname, :screenname, :email1, :email2, :email3, :postalcode, :address, :tel1_note, :tel1, :tel2_note, :tel2, :tel3_note, :tel3, :fax, :url, :organization, :title, :memo, :xorder, :groups, :teams ] attr_names.each_with_index do |attr_name, idx| row_idx = idxs[idx+1] break if row_idx.nil? val = (row[row_idx].nil?)?(nil):(row[row_idx].strip) address.send(attr_name.to_s + '=', val) end if (address.groups == Address::EXP_IMP_FOR_ALL) \ or (book == Address::BOOK_COMMON and address.groups.blank? and address.teams.blank?) address.groups = nil address.teams = nil address.owner_id = 0 elsif !address.groups.blank? or !address.teams.blank? address.owner_id = 0 else address.owner_id = user.id end return address end
Base
1
def add_node_attr_remote(params, request, session) if not allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end retval = add_node_attr( session, params["node"], params["key"], params["value"] ) # retval = 2 if removing attr which doesn't exist if retval == 0 or retval == 2 return [200, "Successfully added attribute to node"] else return [400, "Error adding attribute to node"] end end
Compound
4
def redirect_back_or_default(default, options={}) back_url = params[:back_url].to_s if back_url.present? begin uri = URI.parse(back_url) # do not redirect user to another host or to the login or register page if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)}) redirect_to(back_url) return end rescue URI::InvalidURIError logger.warn("Could not redirect to invalid URL #{back_url}") # redirect to default end elsif options[:referer] redirect_to_referer_or default return end redirect_to default false end
Class
2
def self.get_sql_like(attr_names, keyword) key = ActiveRecord::Base.connection.quote("%#{SqlHelper.escape_for_like(keyword)}%") con = [] attr_names.each do |attr_name| con << "(#{attr_name} like #{key})" end sql = con.join(' or ') sql = '(' + sql + ')' if con.length > 1 return sql end
Base
1
def check_owner return if params[:id].nil? or params[:id].empty? or @login_user.nil? begin owner_id = Location.find(params[:id]).user_id rescue owner_id = -1 end if !@login_user.admin?(User::AUTH_LOCATION) and owner_id != @login_user.id Log.add_check(request, '[check_owner]'+request.to_s) flash[:notice] = t('msg.need_to_be_owner') redirect_to(:controller => 'desktop', :action => 'show') end end
Base
1
it "should should be a subclass of Base" do Puppet::FileServing::Content.superclass.should equal(Puppet::FileServing::Base) end
Class
2
def initialize(image_path, colors=16, depth=8) output = `convert #{image_path} -resize 400x400 -format %c -dither None -quantize YIQ -colors #{colors} -depth #{depth} histogram:info:-` @lines = output.lines.sort.reverse.map(&:strip).reject(&:empty?) end
Class
2
def verify_signature(string, signature) if signature.nil? fail InvalidSignature, "missing \"signature\" param" elsif signature != generate_signature(string) fail InvalidSignature, "provided signature does not match the calculated signature" end end
Base
1
def install_location filename, destination_dir # :nodoc: raise Gem::Package::PathError.new(filename, destination_dir) if filename.start_with? '/' destination_dir = File.realpath destination_dir if File.respond_to? :realpath destination_dir = File.expand_path destination_dir destination = File.join destination_dir, filename destination = File.realpath destination if File.respond_to? :realpath destination = File.expand_path destination raise Gem::Package::PathError.new(destination, destination_dir) unless destination.start_with? destination_dir + '/' destination.untaint destination end
Base
1
it "queries the master node" do session.should_receive(:socket_for).with(:write). and_return(socket) session.query(query) end
Class
2
def get_mail_attachments Log.add_info(request, params.inspect) email_id = params[:id] email = Email.find_by_id(email_id) if email.nil? or email.user_id != @login_user.id render(:text => '') return end download_name = "mail_attachments#{email.id}.zip" zip_file = email.zip_attachments(params[:enc]) if zip_file.nil? send_data('', :type => 'application/octet-stream;', :disposition => 'attachment;filename="'+download_name+'"') else filepath = zip_file.path send_file(filepath, :filename => download_name, :stream => true, :disposition => 'attachment') end end
Base
1
def initialize(session, config_classes, nodes, cluster_name) @config_classes = config_classes @nodes = nodes @cluster_name = cluster_name @session = session end
Compound
4
def self.get_my_folder(user_id) return Folder.where("(owner_id=#{user_id}) and (xtype='#{Folder::XTYPE_USER}')").first end
Base
1
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 submit_url = url_for(:controller => 'schedules', :action => 'get_group_users') render(:partial => 'common/select_users', :layout => false, :locals => {:target_attr => :id, :submit_url => submit_url}) end
Base
1
def update_by_ajax Log.add_info(request, params.inspect) cat_h = {:desktop => User::AUTH_DESKTOP, :user => User::AUTH_USER, :log => User::AUTH_LOG} yaml = ApplicationHelper.get_config_yaml cat_h.keys.each do |cat| next if params[cat].nil? or params[cat].empty? unless @login_user.admin?(cat_h[cat]) render(:text => t('msg.need_to_be_admin')) return end yaml[cat] ||= {} params[cat].each do |key, val| yaml[cat][key] = val end end ApplicationHelper.save_config_yaml(yaml) render(:text => '') end
Base
1
def self.delete_statistics_group(group_id) yaml = Research.get_config_yaml if yaml.nil? or yaml[:statistics].nil? return [] end groups = yaml[:statistics][:groups] return [] if groups.nil? ary = groups.split('|') ary.delete group_id.to_s ary.compact! ary.delete '' yaml[:statistics][:groups] = ary.join('|') Research.save_config_yaml yaml return ary end
Base
1
def update if @application.update(application_params) flash[:notice] = I18n.t(:notice, scope: i18n_scope(:update)) respond_to do |format| format.html { redirect_to oauth_application_url(@application) } format.json { render json: @application } end else respond_to do |format| format.html { render :edit } format.json do errors = @application.errors.full_messages render json: { errors: errors }, status: :unprocessable_entity end end end end
Class
2
def split_header self.fields = unfolded_header.split(CRLF) end
Base
1
def column_content(column, item) value = column.value_object(item) if value.is_a?(Array) value.collect {|v| column_value(column, item, v)}.compact.join(', ').html_safe else column_value(column, item, value) end end
Base
1
def match_resource(env) path = env[PATH_INFO] origin = env[HTTP_ORIGIN] origin_matched = false all_resources.each do |r| if r.allow_origin?(origin, env) origin_matched = true if found = r.match_resource(path, env) return [found, nil] end end end [nil, origin_matched ? Result::MISS_NO_PATH : Result::MISS_NO_ORIGIN] end
Base
1
it "with dofollowify disabled, links should be nofollowed" do @blog.dofollowify = false @blog.save expect(nofollowify_links('<a href="http://myblog.net">my blog</a>')). to eq('<a href="http://myblog.net" rel="nofollow">my blog</a>') end
Base
1
def get_acls(session, cib_dom=nil) unless cib_dom cib_dom = get_cib_dom(session) return {} unless cib_dom end acls = { 'role' => {}, 'group' => {}, 'user' => {}, 'target' => {} } cib_dom.elements.each('/cib/configuration/acls/*') { |e| type = e.name[4..-1] if e.name == 'acl_role' role_id = e.attributes['id'] desc = e.attributes['description'] acls[type][role_id] = {} acls[type][role_id]['description'] = desc ? desc : '' acls[type][role_id]['permissions'] = [] e.elements.each('acl_permission') { |p| p_id = p.attributes['id'] p_kind = p.attributes['kind'] val = '' if p.attributes['xpath'] val = "xpath #{p.attributes['xpath']}" elsif p.attributes['reference'] val = "id #{p.attributes['reference']}" else next end acls[type][role_id]['permissions'] << "#{p_kind} #{val} (#{p_id})" } elsif ['acl_target', 'acl_group'].include?(e.name) id = e.attributes['id'] acls[type][id] = [] e.elements.each('role') { |r| acls[type][id] << r.attributes['id'] } end } acls['user'] = acls['target'] return acls end
Compound
4
def set_cluster_conf(params, request, session) if not allowed_for_local_cluster(session, Permissions::FULL) return 403, 'Permission denied' end if params[:cluster_conf] != nil and params[:cluster_conf].strip != "" Cfgsync::ClusterConf.backup() Cfgsync::ClusterConf.from_text(params[:cluster_conf]).save() return 200, 'Updated cluster.conf...' else $logger.info "Invalid cluster.conf file" return 400, 'Failed to update cluster.conf...' end end
Compound
4
def html_message key = keys.last.to_s.gsub('_', ' ').gsub(/\b('?[a-z])/) { $1.capitalize } %(<span class="translation_missing" title="translation missing: #{keys.join('.')}">#{key}</span>)
Base
1
def cluster_enable(params, request, session) if params[:name] code, response = send_request_with_token( session, params[:name], 'cluster_enable', true ) else if not allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end success = enable_cluster(session) if not success return JSON.generate({"error" => "true"}) end return "Cluster Enabled" end end
Compound
4
def group_link(uniqueid, data) notification = t( "notifications.group.#{data[:type]}", name: data[:user], group_name: data[:group] ) link = "/groups/#{data[:group_id]}" notification_link(uniqueid, link, notification) end
Base
1
def RelaxNG string_or_io RelaxNG.new(string_or_io) end
Base
1
def socket_for(mode) sync unless primaries.any? || (secondaries.any? && mode == :read) server = nil while primaries.any? || (secondaries.any? && mode == :read) if mode == :write || secondaries.empty? server = primaries.sample else server = secondaries.sample end if server socket = server.socket socket.connect unless socket.connection if socket.alive? break server else remove server end end end
Class
2
it "returns a new session" do session.with(new_options).should_not eql session end
Class
2
it "stores the collection name" do collection.name.should eq :users end
Class
2
it "should choose :rest when a server is specified" do @request.stubs(:protocol).returns "puppet" @request.expects(:server).returns "foo" @object.select_terminus(@request).should == :rest end
Class
2
def secondaries servers.select(&:secondary?) end
Class
2
def load_file(filename) Gem.load_yaml yaml_errors = [ArgumentError] yaml_errors << Psych::SyntaxError if defined?(Psych::SyntaxError) return {} unless filename and File.exist? filename begin content = YAML.load(File.read(filename)) unless content.kind_of? Hash warn "Failed to load #{filename} because it doesn't contain valid YAML hash" return {} end return content rescue *yaml_errors => e warn "Failed to load #{filename}, #{e}" rescue Errno::EACCES warn "Failed to load #{filename} due to permissions problem." end {} end
Base
1
it "limits the query" do session.should_receive(:query) do |query| query.limit.should eq(-1) reply end session.simple_query(query) end
Class
2
def test_new_attribute_interpolation assert_equal("<a href='12'>bar</a>\n", render('%a(href="1#{1 + 1}") bar')) assert_equal("<a href='2: 2, 3: 3'>bar</a>\n", render(%q{%a(href='2: #{1 + 1}, 3: #{foo}') bar}, :locals => {:foo => 3})) assert_equal(%Q{<a href='1\#{1 + 1}'>bar</a>\n}, render('%a(href="1\#{1 + 1}") bar')) end def test_truthy_new_attributes assert_equal("<a href='href'>bar</a>\n", render("%a(href) bar", :format => :xhtml)) assert_equal("<a bar='baz' href>bar</a>\n", render("%a(href bar='baz') bar", :format => :html5)) assert_equal("<a href>bar</a>\n", render("%a(href=true) bar")) assert_equal("<a>bar</a>\n", render("%a(href=false) bar")) end def test_new_attribute_parsing assert_equal("<a a2='b2'>bar</a>\n", render("%a(a2=b2) bar", :locals => {:b2 => 'b2'})) assert_equal(%Q{<a a='foo"bar'>bar</a>\n}, render(%q{%a(a="#{'foo"bar'}") bar})) #' assert_equal(%Q{<a a="foo'bar">bar</a>\n}, render(%q{%a(a="#{"foo'bar"}") bar})) #' assert_equal(%Q{<a a='foo"bar'>bar</a>\n}, render(%q{%a(a='foo"bar') bar})) assert_equal(%Q{<a a="foo'bar">bar</a>\n}, render(%q{%a(a="foo'bar") bar})) assert_equal("<a a:b='foo'>bar</a>\n", render("%a(a:b='foo') bar")) assert_equal("<a a='foo' b='bar'>bar</a>\n", render("%a(a = 'foo' b = 'bar') bar")) assert_equal("<a a='foo' b='bar'>bar</a>\n", render("%a(a = foo b = bar) bar", :locals => {:foo => 'foo', :bar => 'bar'})) assert_equal("<a a='foo'>(b='bar')</a>\n", render("%a(a='foo')(b='bar')")) assert_equal("<a a='foo)bar'>baz</a>\n", render("%a(a='foo)bar') baz")) assert_equal("<a a='foo'>baz</a>\n", render("%a( a = 'foo' ) baz")) end def test_new_attribute_escaping assert_equal(%Q{<a a='foo " bar'>bar</a>\n}, render(%q{%a(a="foo \" bar") bar})) assert_equal(%Q{<a a='foo \\" bar'>bar</a>\n}, render(%q{%a(a="foo \\\\\" bar") bar}))
Base
1
it 'does not log in with incorrect two factor' do post "/session/email-login/#{email_token.token}", params: { second_factor_token: "0000", second_factor_method: UserSecondFactor.methods[:totp] } expect(response.status).to eq(200) expect(CGI.unescapeHTML(response.body)).to include(I18n.t( "login.invalid_second_factor_code" )) end
Class
2
def get_cluster_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 on, off = get_nodes nodes = on + off nodes.uniq! return [200, JSON.generate(get_tokens_of_nodes(nodes))] end
Compound
4
it "removes the stored credentials" do cluster.logout :admin cluster.auth.should be_empty end
Class
2
def create_fixed_clamp_code(nbits, signed) if nbits == 1 && signed == :signed raise "signed bitfield must have more than one bit" end if signed == :signed max = (1 << (nbits - 1)) - 1 min = -(max + 1) else min = 0 max = (1 << nbits) - 1 end clamp = "(val < #{min}) ? #{min} : (val > #{max}) ? #{max} : val" if nbits == 1 # allow single bits to be used as booleans clamp = "(val == true) ? 1 : (not val) ? 0 : #{clamp}" end "val = #{clamp}" end
Class
2
def deliver!(mail) envelope_from = mail.return_path || mail.sender || mail.from_addrs.first return_path = "-f \"#{envelope_from.to_s.gsub('"', '\"')}\"" if envelope_from arguments = [settings[:arguments], return_path].compact.join(" ") Sendmail.call(settings[:location], arguments, mail.destinations.collect(&:shellescape).join(" "), mail) end
Class
2
def primaries servers.select(&:primary?) end
Class
2
def one_time_password otp_username = $redis.get "otp_#{params[:token]}" if otp_username && user = User.find_by_username(otp_username) log_on_user(user) $redis.del "otp_#{params[:token]}" return redirect_to path("/") else @error = I18n.t('user_api_key.invalid_token') end render layout: 'no_ember' end
Class
2
it "with params as empty Hash" do cl = subject.build_command_line("true", {}) expect(cl).to eq "true" end
Base
1
def get_pacemaker_version() begin stdout, stderror, retval = run_cmd( PCSAuth.getSuperuserSession, PACEMAKERD, "-$" ) rescue stdout = [] end if retval == 0 match = /(\d+)\.(\d+)\.(\d+)/.match(stdout.join()) if match return match[1..3].collect { | x | x.to_i } end end return nil end
Compound
4
it "returns the database from the options" do session.current_database.should eq(database) end
Class
2
def current_database return @current_database if defined? @current_database if database = options[:database] set_current_database(database) else raise "No database set for session. Call #use or #with before accessing the database" end end
Class
2
it "returns the living socket" do cluster.socket_for(:write).should eq socket end
Class
2
it "syncs each seed node" do server = Moped::Server.allocate Moped::Server.should_receive(:new).with("127.0.0.1:27017").and_return(server) cluster.should_receive(:sync_server).with(server).and_return([]) cluster.sync end
Class
2
def next now = Time.new.to_i counter = @mutex.synchronize do last_timestamp, @last_timestamp = @last_timestamp, now if last_timestamp == now @counter += 1 else @counter = 0 end end generate(now, counter) end
Class
2
def initialize(attribute = nil, direction = nil) @attribute = attribute @direction = direction || :asc end
Base
1
it "returns the database from the options" do session.current_database.should eq(database) end
Class
2
def extract_tar_gz io, destination_dir, pattern = "*" # :nodoc: open_tar_gz io do |tar| tar.each do |entry| next unless File.fnmatch pattern, entry.full_name, File::FNM_DOTMATCH destination = install_location entry.full_name, destination_dir FileUtils.rm_rf destination mkdir_options = {} mkdir_options[:mode] = entry.header.mode if entry.directory? mkdir = if entry.directory? then destination else File.dirname destination end FileUtils.mkdir_p mkdir, mkdir_options File.open destination, 'wb' do |out| out.write entry.read FileUtils.chmod entry.header.mode, destination end if entry.file? File.symlink(entry.header.linkname, destination) if entry.symlink? verbose destination end end end
Base
1
def self.publish_unread(post) return unless post.topic.regular? # TODO at high scale we are going to have to defer this, # perhaps cut down to users that are around in the last 7 days as well group_ids = if post.post_type == Post.types[:whisper] [Group::AUTO_GROUPS[:staff]] else post.topic.category && post.topic.category.secure_group_ids end tags = nil tag_ids = nil if include_tags_in_report? tag_ids, tags = post.topic.tags.pluck(:id, :name).transpose end TopicUser .tracking(post.topic_id) .includes(user: :user_stat) .select([:user_id, :last_read_post_number, :notification_level]) .each do |tu| payload = { last_read_post_number: tu.last_read_post_number, highest_post_number: post.post_number, updated_at: post.topic.updated_at, created_at: post.created_at, category_id: post.topic.category_id, notification_level: tu.notification_level, archetype: post.topic.archetype, first_unread_at: tu.user.user_stat.first_unread_at, unread_not_too_old: true } if tags payload[:tags] = tags payload[:topic_tag_ids] = tag_ids end message = { topic_id: post.topic_id, message_type: UNREAD_MESSAGE_TYPE, payload: payload } MessageBus.publish(self.unread_channel_key(tu.user_id), message.as_json, group_ids: group_ids) end end
Class
2
def check_action_permission!(skip_source = nil) super(skip_source) # only perform the following check, if we are called from # BsRequest.permission_check_change_state! (that is, if # skip_source is set to true). Always executing this check # would be a regression, because this code is also executed # if a new request is created (which could fail if User.current # cannot modify the source_package). return unless skip_source target_project = Project.get_by_name(self.target_project) return unless target_project && target_project.is_a?(Project) target_package = target_project.packages.find_by_name(self.target_package) initialize_devel_package = target_project.find_attribute('OBS', 'InitializeDevelPackage') return if target_package || !initialize_devel_package source_package = Package.get_by_project_and_name(source_project, self.source_package) return if !source_package || User.current.can_modify?(source_package) msg = 'No permission to initialize the source package as a devel package' raise PostRequestNoPermission, msg end
Class
2
def team_organize Log.add_info(request, params.inspect) team_id = params[:team_id] unless team_id.nil? or team_id.empty? begin @team = Team.find(team_id) rescue @team = nil ensure if @team.nil? flash[:notice] = t('msg.already_deleted', :name => Team.model_name.human) return end end users = @team.get_users_a end team_members = params[:team_members] created = false modified = false if team_members.nil? or team_members.empty? unless team_id.nil? or team_id.empty? # @team must not be nil. @team.save if modified = @team.clear_users end else if team_members != users if team_id.nil? or team_id.empty? item = Item.find(params[:id]) created = true @team = Team.new @team.name = item.title @team.item_id = params[:id] @team.status = Team::STATUS_STANDBY else @team.clear_users end @team.add_users team_members @team.save @team.remove_application team_members modified = true end end if created @team.create_team_folder end @item = @team.item if modified flash[:notice] = t('msg.register_success') end render(:partial => 'ajax_team_info', :layout => false) rescue => evar Log.add_error(request, evar) render(:partial => 'ajax_team_info', :layout => false) end
Base
1
def simple_query(query) query.limit = -1 query(query).documents.first end
Class
2
def opposite_direction direction.to_sym == :asc ? :desc : :asc end
Base
1
def logout(database) auth.delete(database.to_s) end
Class
2
def accepted_ally_link(uniqueid, data) notification = t( 'notifications.ally.accepted', name: data[:user] ) link = "/profile?uid=#{data[:uid]}" notification_link(uniqueid, link, notification) end
Base
1
def is_a_copy?(folder_obj_cache=nil) return false if self.source_id.nil? # Exclude those created from system templates. src_item = Item.find_by_id(self.source_id) if src_item.nil? return true else return !src_item.in_system_folder?(folder_obj_cache) end end
Base
1
it "stores the collection" do query.collection.should eq collection end
Class
2
it "returns the index with the provided key" do indexes[name: 1]["name"].should eq "name_1" end
Class
2
def name FIELD_NAME_MAP[@name.to_s.downcase] || @name end
Base
1
def test_should_not_fall_for_xss_image_hack_with_uppercase_tags assert_sanitized %(<IMG """><SCRIPT>alert("XSS")</SCRIPT>">), "<img>\"&gt;" end
Base
1
def test_destroy subnet = Subnet.first subnet.hosts.clear subnet.interfaces.clear subnet.domains.clear delete :destroy, {:id => subnet}, set_session_user assert_redirected_to subnets_url assert !Subnet.exists?(subnet.id) end
Class
2
def send_nodes_request_with_token(session, nodes, request, post=false, data={}, remote=true, raw_data=nil) out = "" code = 0 $logger.info("SNRWT: " + request) # If we're removing nodes, we don't send this to one of the nodes we're # removing, unless we're removing all nodes if request == "/remove_nodes" new_nodes = nodes.dup data.each {|k,v| if new_nodes.include? v new_nodes.delete v end } if new_nodes.length > 0 nodes = new_nodes end end for node in nodes $logger.info "SNRWT Node: #{node} Request: #{request}" code, out = send_request_with_token( session, node, request, post, data, remote, raw_data ) # try next node if: # - current node does not support the request (old version of pcsd?) (404) # - an exception or other error occurred (5xx) # - we don't have a token for the node (401, notoken) # - we didn't get a response form the node (e.g. an exception occurred) # - pacemaker is not running on the node # do not try next node if # - node returned 400 - it means the request cannot be processed because of # invalid arguments or another known issue, no node would be able to # process the request (e.g. removing a non-existing resource) # - node returned 403 - permission denied, no node should allow to process # the request log = "SNRWT Node #{node} Request #{request}" if (404 == code) or (code >= 500 and code <= 599) $logger.info("#{log}: HTTP code #{code}") next end if (401 == code) or ('{"notoken":true}' == out) $logger.info("#{log}: Bad or missing token") next end if '{"pacemaker_not_running":true}' == out $logger.info("#{log}: Pacemaker not running") next end if '{"noresponse":true}' == out $logger.info("#{log}: No response") next end $logger.info("#{log}: HTTP code #{code}") break end return code, out end
Compound
4
def known_addresses [].tap do |addresses| addresses.concat seeds addresses.concat dynamic_seeds addresses.concat servers.map { |server| server.address } end.uniq end
Class
2
def select_terminus(request) # We rely on the request's parsing of the URI. # Short-circuit to :file if it's a fully-qualified path or specifies a 'file' protocol. return PROTOCOL_MAP["file"] if Puppet::Util.absolute_path?(request.key) return PROTOCOL_MAP["file"] if request.protocol == "file" # We're heading over the wire the protocol is 'puppet' and we've got a server name or we're not named 'apply' or 'puppet' if request.protocol == "puppet" and (request.server or !["puppet","apply"].include?(Puppet.settings[:name])) return PROTOCOL_MAP["puppet"] end if request.protocol and PROTOCOL_MAP[request.protocol].nil? raise(ArgumentError, "URI protocol '#{request.protocol}' is not currently supported for file serving") end # If we're still here, we're using the file_server or modules. :file_server end
Class
2
it "returns the result of the block" do session.with(new_options) { false }.should eq false end
Class
2
def each cursor = Cursor.new(session.with(retain_socket: true), operation) cursor.to_enum.tap do |enum| enum.each do |document| yield document end if block_given? end end
Class
2
def file_list io # :nodoc: header = String.new read_until_dashes io do |line| header << line end YAML.load header end
Base
1
def enable_cluster(session) stdout, stderror, retval = run_cmd(session, PCS, "cluster", "enable") return false if retval != 0 return true end
Compound
4
it 'should return an x5c key' do expect(jwt_validator.jwks_key(:x5c, jwks_kid).length).to eq(1) end
Base
1
def get_avail_resource_agents(params, request, session) if not allowed_for_local_cluster(session, Permissions::READ) return 403, 'Permission denied' end agents = getResourceAgents(session) return JSON.generate(agents) end
Compound
4
def sync_server(server) [].tap do |hosts| socket = server.socket if socket.connect info = socket.simple_query Protocol::Command.new(:admin, ismaster: 1) if info["ismaster"] server.primary = true end if info["secondary"] server.secondary = true end if info["primary"] hosts.push info["primary"] end if info["hosts"] hosts.concat info["hosts"] end if info["passives"] hosts.concat info["passives"] end merge(server) end end.uniq end
Class
2
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
Base
1
it "raises a QueryFailure exception" do expect { session.query(query) }.to raise_exception(Moped::Errors::QueryFailure) end
Class
2
it "yields all documents in the cursor" do cursor = Moped::Cursor.allocate cursor.stub(:to_enum).and_return([1, 2].to_enum) Moped::Cursor.stub(new: cursor) query.to_a.should eq [1, 2] end
Class
2
def allowed_for_local_cluster(session, action) pcs_config = PCSConfig.new(Cfgsync::PcsdSettings.from_file('{}').text()) return pcs_config.permissions_local.allows?( session[:username], session[:usergroups], action ) end
Compound
4