query
stringlengths
7
9.5k
document
stringlengths
10
1.07M
negatives
listlengths
19
19
metadata
dict
DELETE /accession_location_entries/1 DELETE /accession_location_entries/1.json
def destroy @accession_location_entry = AccessionLocationEntry.find(params[:id]) @accession_location_entry.destroy respond_to do |format| format.html { redirect_to accession_location_entries_url } format.json { head :no_content } end end
[ "def destroy\n @collection_location_entry = CollectionLocationEntry.find(params[:id])\n @collection_location_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to collection_location_entries_url }\n format.json { head :no_content }\n end\n end", "def delete_location(id)\n return @client.raw(\"delete\", \"/ecommerce/locations/#{id}\")\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to adm_locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n record = Location.find(params[:id])\n record.destroy\n\n respond_to do |format| \n format.json { head :no_content }\n end\n end", "def destroy\n @internal_location.destroy\n respond_to do |format|\n format.html { redirect_to internal_locations_url, notice: 'Item Eliminado.' }\n format.json { head :no_content }\n end\n end", "def destroy\r\n @location = Location.find(params[:id])\r\n @location.destroy\r\n\r\n respond_to do |format|\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\n @storage_location = StorageLocation.find(params[:id])\n @storage_location.destroy\n\n respond_to do |format|\n format.html { redirect_to storage_locations_url }\n format.json { head :ok }\n end\n end", "def destroy\n dns_entry_response = RestClient.delete('https://api.cloudflare.com/client/v4/zones/:zone_identifier/dns_records/:identifier',:content_type => :json, :accept => :json, :'x-auth-key' => session[:key] :'x-auth-email' => session[:email])\n @dns_entry.destroy\n respond_to do |format|\n format.html { redirect_to dns_entries_url, notice: \"Dns entry was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @location_datum = LocationDatum.find(params[:id])\n @location_datum.destroy\n\n respond_to do |format|\n format.html { redirect_to location_data_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @geo_entry.destroy\n respond_to do |format|\n format.html { redirect_to geo_entries_url, notice: 'Geo entry was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @corp_location = CorpLocation.get(params[:id])\n @corp_location.destroy\n\n respond_to do |format|\n format.html { redirect_to corp_locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @apiv1_location.destroy\n respond_to do |format|\n format.html { redirect_to apiv1_locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @map_location = Map::Location.find(params[:id])\n @map_location.destroy\n\n respond_to do |format|\n format.html { redirect_to map_locations_url }\n format.json { head :ok }\n end\n end", "def destroy\n @admin_location = Admin::Location.find(params[:id])\n @admin_location.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @location_level.destroy\n respond_to do |format|\n format.html { redirect_to location_levels_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @accessablemarker.destroy\n respond_to do |format|\n format.html { redirect_to accessablemarkers_url }\n format.json { head :no_content }\n end\n end", "def destroy\n\n @service_location = @contract.service_locations.find(params[:id])\n @contract.service_locations.destroy(@service_location)\n\n respond_to do |format|\n format.html { redirect_to contract_url(@contract) }\n format.json { head :ok }\n end\n end", "def destroy\n @cofee_loc.destroy\n respond_to do |format|\n format.html { redirect_to cofee_locs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @locationmap = Locationmap.find(params[:id])\n @locationmap.destroy\n\n respond_to do |format|\n format.html { redirect_to locationmaps_url }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Require attribute to be set. Return attribute value.
def require_attr(name) send(name).tap do |_| raise AttributeError, "Attribute must be set: #{name}" if _.nil? end end
[ "def require_attr(name)\n send(name).tap do |_|\n raise \"Attribute must be set: #{name}\" if _.nil?\n end\n end", "def require_attr(name)\n send(name).tap do |_|\n if _.respond_to?(:body)\n raise AttributeError, \"Attribute must be set: #{name}\" if _.body.nil? || _.body.empty?\n else\n raise AttributeError, \"Attribute must be set: #{name}\" if _.nil?\n end\n end\n end", "def require(key)\n value = attrs_hash[key]\n if value.nil?\n raise MissingReqiredAttribute.new(\"Missing attribute #{key}\", key)\n end\n\n value\n end", "def may_not_be_set(attribute)\n value = model.send(attribute)\n if value.blank?\n \"#{attribute.capitalize} not specified\"\n else\n value\n end\n end", "def attribute_value\n validatable.send(options[:attribute])\n end", "def require_attr(attr, expression = {})\n value = send(attr)\n\n # NOTE: There's some written philosophy on the subject.\n # See notes \"#ruby `Feature::RequireAttr`\", something like that.\n\n # IMPORTANT: Execution speed is important. Carefully consider it in the implementation logic below.\n\n # NOTE: There are 2 types of exceptions below: 1) true \"production\" exceptions;\n # 2) exceptions caused by programmer's mis-use of our method as such.\n # For added clarity, programmer errors are commented \"PE\".\n\n # Validate expression. It's important to avoid confusion below.\n raise ArgumentError, \"Expression must be Hash: #{expression.inspect}\" if not expression.is_a? Hash\n\n if expression.empty?\n # Trivial case.\n raise \"Attribute must be set: #{attr}\" if value.nil?\n else\n # NOTE: At the moment there are no options other than predicates. When options appear, this will need to be removed.\n raise ArgumentError, \"Expression too long: #{expression.inspect}\" if expression.size > 1 # PE.\n\n # NOTE: Some predicates assume other predicates.\n\n # We've got an exactly 1-key hash.\n if (cls = expression[:to_be_a])\n if cls.is_a? Array\n raise \"Attribute `#{attr}` must be a #{cls.join(' or ')} (value:#{value.inspect})\" if not cls.any? {|c| value.is_a? c}\n else\n # NOTE: We don't check `cls` for being a Class, Ruby will take care of that.\n raise \"Attribute `#{attr}` must be a #{cls} (value:#{value.inspect})\" if not value.is_a? cls\n end\n elsif (m = expression[:to_respond_to])\n raise \"Attribute `#{attr}` must respond to `#{m}` (value:#{value.inspect})\" if not value.respond_to? m\n elsif (cond = expression[:to_be])\n m = \"#{cond}?\"\n require_attr(attr, to_respond_to: m)\n raise \"Attribute `#{attr}` must be #{cond} (value:#{value.inspect})\" if not value.send(m)\n elsif (cond = expression[:not_to_be])\n m = \"#{cond}?\"\n require_attr(attr, to_respond_to: m)\n raise \"Attribute `#{attr}` must not be #{cond} (value:#{value.inspect})\" if value.send(m)\n else\n raise ArgumentError, \"Invalid expression: #{expression.inspect}\"\n end\n end # if expression.empty?\n\n nil\n end", "def attribute_value\n end", "def read_attribute_value()\n #This is a stub, used for indexing\n end", "def accept_attribute attrname, value, force=false\n attrname = attrname.to_s\n return if attrib_ready?(attrname) && !(attrib_needed?(attrname) || force)\n if block_given?\n # For any side-effects as a result of changing the attribute, call the block\n previous = self.send attrname.to_sym\n self.send (attrname+'=').to_sym, value\n # NB: it's possible that the accepted value is NOT the same as the provided value, so we compare\n # changes on the attribute.\n yield value if self.send(attrname.to_sym) != previous\n else # No block? Just set the value\n self.send (attrname+'=').to_sym, value\n end\n if all_attr_trackers.include?((attrname+'_needed').to_sym)\n # This attribute is tracked => clear 'needed' bit and set the 'ready' bit\n self.send (attrname+'_needed=').to_sym, false\n self.send (attrname+'_ready=').to_sym, true\n end\n end", "def check_attribute!(attribute)\n raise \"Unexpected attribute #{attribute} used\" unless self.class.attributes && self.class.attributes.include?(attribute)\n end", "def attribute_value\n end", "def mark_required?(attribute)\n self.class.mark_required?(attribute)\n end", "def set_attribute(name, value); end", "def set_Attribute(value)\n set_input(\"Attribute\", value)\n end", "def ensure_attribute(root_element, key, type = nil, prefix = nil)\n value = get_attribute(root_element, key, type, prefix)\n label = prefix ? \"#{prefix}.#{key}\" : key\n raise \"Attribute '#{label}' is missing\" if value.nil?\n value\n end", "def attribute_required?(attribute)\n validates_presence?(attribute) || validates_inclusion?(attribute)\n end", "def attribute_required?(attribute, options = {})\n (options.stringify_keys!.delete('required') === true)\n end", "def requires_attribute(element_selector, attribute_selector, options)\n element = requires(element_selector, allow_blank: options[:allow_blank])\n return unless element\n\n attribute = element[attribute_selector]\n\n unless attribute\n epp_errors.add(:epp_errors,\n code: '2003',\n msg: I18n.t('errors.messages.required_parameter_missing',\n key: attribute_selector))\n return\n end\n\n return if options[:values].include?(attribute)\n\n if options[:policy]\n epp_errors.add(:epp_errors,\n code: '2306',\n msg: I18n.t('attribute_is_invalid', attribute: attribute_selector))\n else\n epp_errors.add(:epp_errors,\n code: '2004',\n msg: I18n.t('parameter_value_range_error', key: attribute_selector))\n end\n end", "def required=(value)\n @required = value\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A bigram is a pair of consecutive words. Given a string, return the longest bigram in that string. Include the space between the words. Assume there will be no punctuation. In the case of a tie, return the earlier bigram.
def longest_bigram(str) bigram_hash = Hash.new bigram_str = str.split(" ") bigram_str.each_with_index do |word, i| if i == bigram_str.length - 1 next else bigram_hash[word + " " + bigram_str[i + 1]] = (word + " " + bigram_str[i + 1]).length end end temp_str = "" temp_str_length = 0 bigram_hash.keys.each do |compound| if compound.length > temp_str_length temp_str = compound temp_str_length = compound.length end end p temp_str end
[ "def longest_bigram(sentence)\n sentence_array = Array.new\n sentence.split(\" \").each_index do |idx|\n if idx != sentence.split(\" \").length - 1\n sentence_array.push(sentence.split(\" \")[idx] + \" \" + sentence.split(\" \")[idx + 1])\n end\n end\n # find longest Bigram\n bigram_length = 0\n bigram_words = \"\"\n sentence_array.each do |bigram|\n if bigram.length > bigram_length\n bigram_length = bigram.length\n bigram_words = bigram\n end\n end\n bigram_words\nend", "def bigram_with_string(str)\n res = 0\n words = find_indexes_for(str.chomp.split(' '))\n\n last_word = ''\n words.each_with_index {|(word, index), i|\n if i == 0\n res = compute_unigram_for(word)\n else\n res *= compute_bigram_for(word, last_word)\n end\n last_word = word\n }\n\n return Math.log(res)\nend", "def most_frequent_bigram(str)\n bigrams_hash = biagram_hash(str)\n bigrams_hash.key(bigrams_hash.values.max)\nend", "def most_frequent_bigram(str)\n counter = Hash.new\n bigrams = str.substrings(2)\n bigrams.max_by {|ele| bigrams.count(ele)}\nend", "def get_ending_of_bigram bigram\n return bigram.split(\"_\")[1]\n end", "def most_frequent_bigram(str)\n\nend", "def most_frequent_bigram(str)\n adjacent_letter={}\n letter=\"\"\n (0...str.length-1).each do |i|\n letter=str[i]+str[i+1]\n if adjacent_letter.has_key?(letter)\n adjacent_letter[letter]+=1\n else\n adjacent_letter[letter]=1\n end\n end\n\n max=0\n max_aj=\"\"\n adjacent_letter.each do |k,v|\n if v>max\n max=v\n max_aj=k\n end\n end\n max_aj\n\n\nend", "def find_bigrams(str, bigrams)\n letters = str.split(\"\")\n pairs = []\n (0...letters.length-1).each do |idx|\n pairs << letters[idx] + letters[idx+1]\n end\n bigrams.select { |bigram| pairs.any?(bigram) }\nend", "def find_longest_word(string)\n string_split = string.split(' ')\n string_split.max_by { |a| a.length }\nend", "def longest_word(string)\n\t\n\tsplitted_string = string.split(\" \")\n\tword_length = []\n\t\n\tsplitted_string.each { |word| word_length << word.length }\n\t\n\tmax = word_length.max\n\tidx = word_length.index(max)\n\tsplitted_string[idx]\n\t\nend", "def bigram_similarity_to_mashing(string)\n bigrams = bigrams(string)\n\n freqs = bigrams.\n each_with_object(Hash.new(0)) { |bigram, counts| counts[bigram] += 1 }.\n each_with_object({}) do |(bigram,count), freqs|\n freqs[bigram] = count.to_f / bigrams.length\n end\n\n numerator = freqs.map{ |bigram, freq| freq * mashing_bigram_frequencies[bigram].to_f }.inject(&:+)\n denominator = mashing_bigram_magnitude * ((freqs.values.map{ |v| v**2 }.inject(&:+)) ** 0.5)\n\n numerator / denominator\n end", "def get_starting_of_bigram bigram\n return bigram.split(\"_\")[0]\n end", "def longest_palindrome(string)\n longest=\"\"\n string.each_char.with_index do |ch1,idx|\n string.each_char.with_index do |ch2,idy|\n next if idx >= idy\n word=string[idx..idy]\n if word==word.reverse && word.length > longest.length\n longest = word\n end\n end\n end\n longest.length > 2 ? longest.length : false\nend", "def largest_palindrome?(sentence)\n array_of_words = sentence.split(\" \")\n ret = []\n array_of_words.each do |word|\n if palindrome?(word)\n if word.length > ret.length\n ret.pop\n ret << word\n end\n end\n end\nend", "def bigramify(text)\n text_array = text.upcase.split('')\n\n text_array.each_with_index do |char, index|\n if index.even?\n if char == text_array[index + 1]\n text_array.insert(index + 1, 'X')\n text = text_array.join('')\n bigramify(text)\n end\n end\n end\n\n text_array << 'X' if text_array.length.odd?\n text = text_array.join('')\n text.gsub!('Q', 'X')\n\n text.split(/(.{2})/).reject { |pair| pair if pair.empty? }\n end", "def longest_subsequence(str)\n # return if input parameter is nil, empty or forms a complete word\n return str if str == nil || str.length == 0 || DICTIONARY[str] != nil\n\n len = str.length\n # remove minimum characters starting with 1 character\n # if it forms a word, return immediately and do not explore further\n (len-1).times do |i|\n ret = check_word(str, i+1)\n return ret if ret.length == len-i-1 # ret forms a word\n end\n\n return \"\" # no words found in str\nend", "def longest_two_words(string)\n\n words = string.split.sort_by {|word| word.length}.reverse[0..1]\n\nend", "def scramble_word(str)\n return str if [0, 1, 2, 3].include?(str.size)\n letters = \"\"\n new_arr = []\n idx = 0\n \n str.each_char { |char| letters << char if char =~ /[a-z]/ }\n \n sorted_middle_chars = letters[1..-2].chars.sort\n new_str = letters[0] + sorted_middle_chars.join + letters[-1]\n \n str.chars.each do |char|\n if char =~ /[^a-z]/\n new_arr << char\n else\n new_arr << new_str[idx]\n idx += 1\n end\n end\n new_arr.join\nend", "def LongestWord(sen)\n str = sen.split(\" \")\n longest_word = str[0]\n str.each do |word|\n word.sub(/[\\w\\s]/, '')\n if longest_word.length < word.length\n longest_word = word\n end\n end\n longest_word\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve one API Secret.
def get(secret_id) request('/accounts/' + account_id + '/secrets/' + secret_id) end
[ "def get_secret(secret_name, vault_name, resource_group = configuration.resource_group)\n url = build_url(resource_group, vault_name, 'secrets', secret_name)\n model_class.new(rest_get(url))\n end", "def secretkey(apikey)\n get 'secretkey', {apikey: apikey} { |x| x['secretkey'] }\n end", "def get_secret(secret_name, secret_version = nil)\n url = @vault_url.get_url(clean(secret_name), secret_version, @api_version)\n headers = { 'Authorization' => @bearer_token }\n response = RestClient.get(url, headers)\n JSON.parse(response)['value']\n rescue RestClient::NotFound\n return nil\n end", "def secret\n @secret or raise MissingSecret\n end", "def get_secret(secret_id)\n @client.call(\n :get_secret,\n message: {\n token: @token,\n secretId: secret_id\n }\n ).to_hash.dig(:get_secret_response, :get_secret_result)\n end", "def get_secret(key)\n secret node['openstack']['secret']['secrets_data_bag'], key\n end", "def secret_key\n current_user.api_keys.each do |key|\n if (key.access_type == ApiKey::ACCESS_TYPE_WRITE)\n return key.key\n end\n end\n nil\n end", "def secret_access_key\n obtain_credentials\n @secret_access_key\n end", "def secret\n @secret\n end", "def get_value(secret_id)\n fail 'Not allowed env' unless config.is_allowed_env.call\n response = secrets_manager.get_secret_value(secret_id: secret_name(secret_id))\n response.secret_string\n rescue StandardError => err\n logger.warn(\"[Sekreto] Failed to get value!\\n#{err}\")\n config.fallback_lookup.call(secret_id)\n end", "def secret\n secret_value or raise 'secret is only available for new access keys'\n end", "def get_secret(secret_name, backend_name = nil)\n __safekeeper_backend(backend_name).get(secret_name)\n end", "def fetch_secret(service)\n uri = \"#{connector.url}/services/#{service.uuid}/secret\"\n HTTParty.get(uri, :format => :json)\n end", "def decrypt_api_secret\n @api_secret_d = @client_api_detail.decrypted_api_secret\n success\n end", "def secret\n decrypt_secret\n end", "def read_secret_string(key)\n read(key)[:secret]\n end", "def fetch_admin_secret_obj\n @admin_secret_obj = AdminSecret.get_active_from_memcache(@admin.admin_secret_id)\n\n success\n end", "def get_secret(secret_name, secret_version, api_version, opts = {})\n data, _status_code, _headers = get_secret_with_http_info(secret_name, secret_version, api_version, opts)\n data\n end", "def get_secret\n\t\t\tif Jiralicious.oauth_secret.nil?\n\t\t\t\tIO.read(Jiralicious.config_path + Jiralicious.oauth_secret_filename)\n\t\t\telse\n\t\t\t\tJiralicious.oauth_secret\n\t\t\tend\n\t\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Revoke an API Secret.
def revoke(secret_id) request('/accounts/' + account_id + '/secrets/' + secret_id, type: Delete) end
[ "def revoke\n post('/api/revoke')\n end", "def revoke_token\n prepare_and_invoke_api_call 'auth/v1/keys/token', :method=>:delete\n @api_token = nil\n end", "def revoke\n @auth.revoke(@access)\n @access = nil\n end", "def revoke\n Lib.keyctl_revoke id\n self\n end", "def decrypt_api_secret\n @api_secret_d = @client_api_detail.decrypted_api_secret\n success\n end", "def revoke(access_token)\n option = {\n url: \"#{api_origin}/api/revoke\",\n header: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Authorization: \"Bearer #{access_token}\",\n }\n }\n response = post(option)\n JSON.parse(response.body)\n end", "def revoke_token\n # entry point\n url = \"#{@client.app_info[:launcher_server]}#{API_VERSION}/auth\"\n\n # api call\n uri = URI(url)\n http = Net::HTTP.new(uri.host, uri.port)\n req = Net::HTTP::Delete.new(uri.path, {\n 'Authorization' => \"Bearer #{@client.key_helper.get_valid_token()}\"\n })\n res = http.request(req)\n res.code == \"200\"\n end", "def revoke_token\n # not supported\n end", "def revoke!\n self.class.transaction do\n update_attribute :revoked, Time.now\n client.increment! :tokens_revoked\n end\n end", "def destroy\n @secret = Secret.find(params[:id])\n @secret.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_secrets_url }\n format.json { head :no_content }\n end\n end", "def revoke_token\n raise 'To be implemented in child classes'\n end", "def revoke\n return if !access_token\n\n client = Octokit::Client.new(client_id: Rails.configuration.x.github.client_id,\n client_secret: Rails.configuration.x.github.client_secret)\n client.revoke_application_authorization(access_token)\n end", "def delete_api_key(id)\n @client.raw('delete', \"/config/api-keys/#{id}\")\n end", "def delete_secret_key\n\t\takey = GPGME::Key.find(:secret, @dname)\n\t\takey.each do |akey|\n\t\takey.delete!(allow_secret = true)\n\t\tend\n\tend", "def destroy_secret_version project_id:, secret_id:, version_id:\n # Create a Secret Manager client.\n client = Google::Cloud::SecretManager.secret_manager_service\n\n # Build the resource name of the secret version.\n name = client.secret_version_path(\n project: project_id,\n secret: secret_id,\n secret_version: version_id\n )\n\n # Destroy the secret version.\n response = client.destroy_secret_version name: name\n\n # Print a success message.\n puts \"Destroyed secret version: #{response.name}\"\nend", "def revoke_oauth_token\n current_user.revoke_token\n end", "def reset_secret_key\n service_response = ClientManagement::WebhookSetting::ResetSecretKey.new(params).perform\n render_api_response(service_response)\n end", "def revoke_token(refresh_token_or_access_token)\n query_api '/auth/revoke', 'token': refresh_token_or_access_token\n end", "def revoke!\n return if revoked?\n update(revoked_at: Time.now)\n tokens.update_all(revoked_at: Time.now, updated_at: Time.now)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute the statement. This creates a new ResultSet object for the statement's virtual machine. If a block was given, the new ResultSet will be yielded to it; otherwise, the ResultSet will be returned. Any parameters will be bound to the statement using bind_params. Example: stmt = db.prepare( "select from table" ) stmt.execute do |result| ... end See also bind_params, execute!.
def execute( *bind_vars ) reset! if active? || done? bind_params(*bind_vars) unless bind_vars.empty? @results = ResultSet.new(@connection, self) step if 0 == column_count yield @results if block_given? @results end
[ "def execute( *bind_vars )\n bind_params *bind_vars unless bind_vars.empty?\n results = ResultSet.new( @db, @statement.to_s )\n\n if block_given?\n begin\n yield results\n ensure\n results.close\n end\n else\n return results\n end\n end", "def execute(stmt, bindvars={})\n sanity_check(stmt)\n\n if @convert_types\n bindvars = DBI::Utils::ConvParam.conv_param(driver_name, bindvars)\n end\n\n sth = StatementHandle.new(@handle.execute(stmt, bindvars), true, true, @convert_types, true)\n # FIXME trace sth.trace(@trace_mode, @trace_output)\n sth.dbh = self\n sth.raise_error = raise_error\n\n if block_given?\n begin\n yield sth\n ensure\n sth.finish unless sth.finished?\n end\n else\n return sth\n end\n end", "def execute( *bind_vars )\n reset! if active? || done?\n\n bind_params(*bind_vars) unless bind_vars.empty?\n @results = ResultSet.new(@connection, self)\n\n yield @results if block_given?\n @results\n end", "def execute\n results = ResultSet.new( @db, @statement.to_s )\n\n if block_given?\n begin\n yield results\n ensure\n results.close\n end\n else\n return results\n end\n end", "def query( sql, *bind_vars )\n result = prepare( sql ).execute( *bind_vars )\n if block_given?\n begin\n yield result\n ensure\n result.close\n end\n else\n return result\n end\n end", "def execute!( *bind_vars )\n result = execute( *bind_vars )\n rows = [] unless block_given?\n while row = result.next\n if block_given?\n yield row\n else\n rows << row\n end\n end\n rows\n ensure\n result.close if result\n end", "def execute(statement, bindvars={})\n stmt = prepare(statement)\n stmt.bind_params(bindvars) \n stmt.execute\n stmt\n end", "def execute( *params )\n bind( *params )\n begin\n # save the error state at the beginning of the execution. We only want to\n # reraise the error if it was raised during this execution.\n s_before = $!\n if block_given? then\n while row = next_row\n yield row\n end\n else\n all_rows\n end\n ensure\n s = $!\n begin\n reset_for_next_execute!\n rescue\n # rescuing nothing on purpose\n end\n raise s if s != s_before\n end\n end", "def execute(statement, args=[])\n connect do |client|\n stmt = client.prepare(statement)\n results = stmt.execute(*args, symbolize_keys: true)\n yield(results) if block_given?\n stmt.close\n end\n end", "def execute(&block)\n if execution_engine\n execution_engine.execute(&block)\n else\n yield\n end\n end", "def execute(sql, bind_vars = T.unsafe(nil), *args, &block); end", "def execute(&block)\n TempTableContext.with_context(db) {|context| execute_in_context(context, &block)}\n end", "def run(&block)\n case prepared_type\n when :select, :all\n # Most common scenario, so listed first\n all(&block)\n when :each\n each(&block)\n when :insert_select\n with_sql(prepared_sql).first\n when :first\n first\n when :insert, :update, :delete\n if opts[:returning] && supports_returning?(prepared_type)\n returning_fetch_rows(prepared_sql)\n elsif prepared_type == :delete\n delete\n else\n send(prepared_type, *prepared_modify_values)\n end\n when :insert_pk\n fetch_rows(prepared_sql){|r| return r.values.first}\n when Array\n case prepared_type[0]\n when :map, :as_hash, :to_hash, :to_hash_groups\n send(*prepared_type, &block) \n end\n else\n Sequel::Deprecation.deprecate(\"Using an unsupported prepared statement type (#{prepared_type.inspect})\", 'Switch to using :select as the prepared statement type')\n all(&block)\n end\n end", "def execute(&block)\n plan.execute(&block)\n end", "def exec(&block)\n @db.exec(&block)\n end", "def do(statement, bindvars)\n stmt = execute(statement, bindvars)\n res = stmt.rows\n stmt.finish\n return res\n end", "def execute(sql, opts=OPTS, &block)\n return call_sproc(sql, opts, &block) if opts[:sproc]\n\n statement(conn) do |stmt|\n if block\n if size = fetch_size\n stmt.setFetchSize(size)\n end\n yield log_connection_yield(sql, conn){stmt.executeQuery(sql)}\n else\n case opts[:type]\n when :ddl\n log_connection_yield(sql, conn){stmt.execute(sql)}\n when :insert\n log_connection_yield(sql, conn){stmt.executeUpdate(sql)}\n last_insert_id(conn, Hash[opts].merge!(:stmt=>stmt))\n else\n log_connection_yield(sql, conn){stmt.executeUpdate(sql)}\n end\n end\n end\n end", "def execute(sql, *params)\n self.connect\n return nil if ! self.connected? && self.interpreter.preview?\n begin\n sth = self.dbh.prepare(sql)\n if params.empty?\n sth.execute\n else\n sth.execute(*params)\n end\n return sth\n rescue ::DBI::ProgrammingError => e\n raise \"#{e.message} -- #{sql}\"\n end\n end", "def execute(sql, *params)\n self.connect\n return nil if not self.connected? and self.interpreter.preview?\n begin\n sth = self.dbh.prepare(sql)\n if params.empty?\n sth.execute\n else\n sth.execute(*params)\n end\n return sth\n rescue DBI::ProgrammingError => e\n raise \"#{e.message} -- #{sql}\"\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs a sanity check to ensure that the statement is not closed. If it is, an exception is raised.
def must_be_open! # :nodoc: if closed? raise Thredis::Exception, "cannot use a closed statement" end end
[ "def must_be_open! # :nodoc:\n if @closed\n raise SQLite3::Exception, \"cannot use a closed statement\"\n end\n end", "def must_be_open! # :nodoc:\n if closed?\n raise SQLite3::Exception, \"cannot use a closed statement\"\n end\n end", "def check_statement(stmt)\n raise InterfaceError, \"Statement is empty, or contains nothing but whitespace\" if stmt !~ /\\S/\n end", "def integrity_check\n execute( \"PRAGMA integrity_check\" ) do |row|\n raise DatabaseException, row[0] if row[0] != \"ok\"\n end\n end", "def integrity_check\n execute( \"PRAGMA integrity_check\" ) do |row|\n raise Exceptions::DatabaseException, row[0] if row[0] != \"ok\"\n end\n end", "def closed?\n @stmt.closed?\n end", "def closed?\n @stmt.closed?\n end", "def integrity_check\n execute( \"PRAGMA integrity_check\" ) do |row|\n raise Exception, row[0] if row[0] != \"ok\"\n end\n end", "def on_ensure(statements); end", "def check_db_connection\n raise \"Database connection not initialized\" if @db == nil\n end", "def ensure_clause; end", "def execute_query?\n !@execute.nil?\n end", "def query_statement(sql)\n return @conn.query(sql)\n rescue SQLite3::BusyException\n sleep(@busy_timeout)\n retry\n end", "def read_violation?(sql)\n WRITE_QUERIES.include?(first_word(sql))\n end", "def check_execute\n unless executed?\n execute\n end\n end", "def statement(conn)\n stmt = conn.createStatement\n yield stmt\n rescue NativeException, JavaSQL::SQLException => e\n raise e\n ensure\n stmt.close if stmt\n end", "def safe_query()\n ret = yield if block_given?\n return ( ret ? ret : true ) # return not nil, otherwise return true\n rescue ::Mysql::Error => e\n Logger.<<(__FILE__,\"ERROR\",\"#{e.errno} : #{e.error} (#{e})\")\n raise e \n end", "def test_commit_not_connected()\n t = Scalaroid::Transaction.new()\n t.close_connection()\n #assert_raises( Scalaroid::ConnectionError ) { t.commit() }\n t.commit()\n t.close_connection()\n end", "def sanity_check\n begin\n sanity_check!\n rescue Exception => e\n warn e\n nil\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Public: Adds a Line and returns it. Also sets the parent on the line and for simplicity adds the current_line number. Returns the line that was added.
def add_line(line) @lines << line line end
[ "def add(context, line)\n\t\t\t@lines << @line.new(context, line)\n\t\tend", "def add_line(al)\n @asset_location_lines.add al.merge!({parent: self.asset_location_lines})\n end", "def add_line\n @layout.add_widget(HLine.new)\n end", "def add_line(line)\n\t\t@lines << line\n\tend", "def line\n @line ||= Line.get(@attrs['Line'])\n end", "def line\n @line ||= Line.get(@attrs['LineCode'])\n end", "def add_order_line(line)\n line.index = lines.size + 1\n lines << line\n end", "def line_break\n self.store(CommandNode.new(self, '\\line', nil, false))\n nil\n end", "def add_line_item(args=nil)\n line_item = Wheretocard::LineItem.new(args)\n line_items << line_item\n return line_item\n end", "def add_line(line)\n @tip.string_content += line.slice(@offset, line.length) + '\\n'\n end", "def line n = UNASSIGNED\n if n != UNASSIGNED then\n raise ArgumentError, \"setting %p.line %p\" % [self, n] unless Integer === n\n @line = n\n self\n else\n @line ||= nil\n end\n end", "def addLineNum(lineNum)\n @lineNum << lineNum\n end", "def append(line)\n self.add(OrderedListItem.new(line))\n end", "def add_comment( line )\n self << CommentBlock.new unless last.is_a? CommentBlock\n last << line\n end", "def dup_adding_state(line)\n self.class.new(path, input).add_state(line)\n end", "def line_break\n self.store(CommandNode.new(self, '\\line', nil, false))\n nil\n end", "def line\n @line ||= @buffer[@line_number].dup\n end", "def line(node = @current_node)\n\t\treturn is_valid(node) ? node.line : nil\n\tend", "def add line\n\t\t\t@table << line\n\t\t\t@height += 1\n\t\t\tindex_col_widths\n\t\t\tcreate\n\t\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal: Given an array of parsed blocks, converts the properties within the blocks into a single hash. Returns a hash.
def blocks_to_hash(blocks) blocks.each_with_object({}) do |block, hash| hash.merge!(block.to_hash) end end
[ "def object_properties_hash\n h = {}\n File.readlines(File.join(@path, CONFIG.dig('bag', 'item', 'object_properties_file'))).each do |line|\n key, *rest = line.split(' ')\n h[key] = rest.map { |e| e.split(',') }.flatten\n end\n h\n end", "def to_hash(prop_headings)\n h = {\n manufacturer_part_no: @manufacturer_part_no,\n supplier_part_no: @supplier_part_no,\n brand_name: @brand_name,\n description: @description,\n weblink: @weblink\n }\n h[:properties] = properties_to_hash_array(prop_headings)\n h[:prices] = prices_to_hash_array\n h\n end", "def hash_css(css_array)\n\t\traw_hash = {'selector' => css_array.shift.strip, 'contents' => []}\n\t\tif css_array[0] == \"\" \n\t\t\treturn raw_hash\n\t\tend\n\t\tcss_array.pop\n\t\tcss_array.each{ |i| \n\t\t\tprops = i.split(':').map(&:strip)\n\t\t\traw_hash['contents'].push({props[0] => props[1]})\n\t\t}\n\t\treturn raw_hash\n\tend", "def to_hash\n conf = {}\n\n [:unit, :install, conf_type].each do |section|\n # some unit types don't have type-specific config blocks\n next if Systemd::Helpers::STUB_UNITS.include?(section)\n conf[section] = section_values(section)\n end\n\n conf\n end", "def to_hash(parts_array)\n \n parts_array.collect! { |p|\n p.to_hash\n }\n \n end", "def hash\n last_block.hash\n end", "def cms_blocks_attributes\n self.cms_blocks.inject([]) do |arr, block|\n block_attr = {}\n block_attr[:label] = block.label\n block_attr[:content] = block.content\n block_attr[:id] = block.id\n arr << block_attr\n end\n end", "def block_hash\n data = Utils::DataWriter.new\n serialize_header data\n hash1 = Digest::SHA256.digest(data.io.string)\n hash2 = Digest::SHA256.hexdigest(hash1)\n Utils.reverse_hex_string(hash2)\n end", "def parse_info(block)\r\n\t\tinfo = Hash.new\r\n\t\tinfo['original'] = block\r\n\r\n\t\tblock = block.split('|')\t# splits the block by the regex '|'\r\n\t\tif block.length != 5\r\n\t\t\tputs 'Invalid block format, should consist of only 5 elements'\r\n\t\t\tputs 'BLOCKCHAIN INVALID'\r\n\t\t\texit()\r\n\t\tend\t\t\r\n\r\n\t\tinfo['id'] = block[0].to_i\r\n\t\tinfo['prev_hash'] = block[1]\r\n\t\tinfo['transaction'] = block[2].split(':')\t# splits transaction by the regex ':'\r\n\t\tinfo['ts'] = {'sec': block[3].split('.')[0].to_i, 'nsec': block[3].split('.')[1].to_i}\r\n\t\t#puts info['ts']\r\n\t\tinfo['self_hash'] = block[4]\r\n\t\treturn info\r\n\tend", "def to_hash\n JSON.parse(properties).to_h\n end", "def hash(last_block)\n block_string = last_block.sort.to_h.to_json\n return Digest::SHA256.hexdigest(block_string)\n end", "def to_configurable_hash(properties, type, &block)\n assertion_hash = {}\n assertion_hash.merge! block: block if block_given?\n assertion_hash.merge! type: type if type\n\n zip_to_hash(assertion_hash, *properties)\n end", "def all_property_hash\n hash = {}\n items = @all_properties\n for prop in items\n hash[prop] = {}\n end\n return hash\n end", "def to_configurable_hash(properties, type, &block)\n assertion_hash = {}\n assertion_hash.merge! block: block if block_given?\n assertion_hash.merge! type: type if type\n\n assertions = ([assertion_hash] * properties.size)\n Hash[properties.zip(assertions)]\n end", "def to_hash\n Hash[sort_tuples(section_tuples)]\n end", "def to_hash\n @content.map do |section|\n h = {}\n section.map do |key, value|\n convert(h, key, value)\n end\n @hashes << h\n end\n return @hashes\n end", "def properties_to_hash(properties)\n property_hash = {}\n index = 0\n properties_valid = properties || ''\n props = properties_valid.split(\":\")\n props.each do |p|\n eachProp = p.split(\"=\")\n property_hash[eachProp[0]] = eachProp[1]\n index = index + 1\n end\n return property_hash\nend", "def groupProperties(sblock, index, properties)\n if properties[:net].nil?\n return sblock;\n end\n start = index\n properties[:net].each do |k,v|\n v.each do |pkey, pvalue|\n next if (pvalue.size == 0)\n sblock[start] = node_property(k, pkey, pvalue)\n start += 1;\n end\n end\n return sblock;\n end", "def generic_hashes_for_notes(note_title, parsed_rows)\n parsed_rows.map do |row|\n text_from_fields = generic_text_from_fields(row[:source_json])\n text = \"#{note_title}\\n\\n#{text_from_fields}\"\n {\n student_id: row[:student_id],\n educator_id: row[:educator_id],\n recorded_at: row[:source_timestamp],\n is_restricted: false,\n event_note_type_id: 304,\n text: text\n }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write encoded record to the handle
def write(record) @fh.puts(encode(record)) self end
[ "def write(record)\n @fh.write(self.class.encode(record))\n end", "def write(record)\n @fh.write(MARC::Writer.encode(record))\n end", "def write(handle, offset, data); end", "def writeencoding; end", "def write(record)\n @worker.enqueue record\n end", "def _write(obj)\n obj.Write()\n end", "def _write(obj)\n obj.Write()\n end", "def write(value)\n record.send(\"#{name}_data=\", value)\n end", "def write_raw(obj,encoding = 3)\n\t @stream = \"\" #new output stream\n\t RequestStore.amf_encoding = (encoding == 3) ? 'amf3' : 'amf0'\n\t reset_referencables\n\t write(obj)\n\t @stream\n\tend", "def native_write_to(io, encoding, options)\n #This is a stub, used for indexing\n end", "def process record\n $stdout.puts record\n $stdout.flush\n end", "def extract_record( record )\n @writer.write(record)\n @record_count = @record_count + 1\n end", "def write\n\n # output to disk\n File.open(@outfile, 'w:UTF-8') { |file|\n file.write(@buffer)\n }\n end", "def write(handle, offset, data)\n send_request(FXP_WRITE, :string, handle, :int64, offset, :string, data)\n end", "def serialize(record)\n raise UnnacceptableDataError, 'key and data must be defined' unless record[0] && record[1]\n s = key_data_string(record)\n s << crc_string(s)\n end", "def write(bytes)\r\n end", "def write_struct\n @struct.connection.set(@struct.key, 'foo')\n end", "def write(datum)\n writer.write(datum)\n end", "def perform( handle, data, offset=0 )\n @handle = handle\n @offset = offset\n @data = data\n @pos = 0\n\n @driver.write( nil, handle, offset, data[0,CHUNK_SIZE] )\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
combine bishop and rook for queen moves
def bishop_moves(x, y, game) own_spaces = game[game[:turn]].keys opponent_spaces = game[@opp_turn[game[:turn]]].keys moves = [] # up right temp_x = x + 1 temp_y = y + 1 while temp_x < 5 && temp_y < 5 && !own_spaces.include?([temp_x, temp_y]) moves.push([temp_x, temp_y]) break if opponent_spaces.include?([temp_x, temp_y]) temp_x += 1 temp_y += 1 end # up left temp_x = x - 1 temp_y = y + 1 while temp_x > 0 && temp_y < 5 && !own_spaces.include?([temp_x, temp_y]) moves.push([temp_x, temp_y]) break if opponent_spaces.include?([temp_x, temp_y]) temp_x -= 1 temp_y += 1 end # down right temp_x = x + 1 temp_y = y - 1 while temp_x < 5 && temp_y > 0 && !own_spaces.include?([temp_x, temp_y]) moves.push([temp_x, temp_y]) break if opponent_spaces.include?([temp_x, temp_y]) temp_x += 1 temp_y -= 1 end # down left temp_x = x - 1 temp_y = y - 1 while temp_x > 0 && temp_y > 0 && !own_spaces.include?([temp_x, temp_y]) moves.push([temp_x, temp_y]) break if opponent_spaces.include?([temp_x, temp_y]) temp_x -= 1 temp_y -= 1 end moves end
[ "def moves_queen(color, a, b)\n\t\t_moves = []\n\t\t(continue_left(color, a, b)).each{|move| _moves << move}\n\t\t(continue_right(color, a, b)).each{|move| _moves << move}\n\t\t(continue_up(color, a, b)).each{|move| _moves << move}\n\t\t(continue_down(color, a, b)).each{|move| _moves << move}\n\t\t(continue_up_left(color, a, b)).each{|move| _moves << move}\n\t\t(continue_up_right(color, a, b)).each{|move| _moves << move}\n\t\t(continue_down_left(color, a, b)).each{|move| _moves << move}\n\t\t(continue_down_right(color, a, b)).each{|move| _moves << move}\n\t\t_moves.compact\n\tend", "def gen_bishop_moves(color, piece=:bishop)\n moves = []\n if color == :white\n position = @position.white \n comrades = @position.white_pieces\n enemy = @position.black_pieces\n else\n position = @position.black\n comrades = @position.black_pieces\n enemy = @position.white_pieces\n end\n\n # no work to do when there are no pieces\n return moves if position[piece].nil?\n \n # for each piece\n position[piece].set_bits.each do |from| \n # [i,j] = current position\n i = from / 8\n j = from % 8\n\n #dirs flags which directions the piece is blocked\n dirs = 0\n for k in 1..7\n break if dirs == 0xf\n \n # try moving north-east\n if (dirs & 0x1) != 0x1\n to = from+k*9\n if i+k>7 || j+k>7 || comrades.set?(to)\n # no further north-east moves possible\n dirs = dirs | 0x1\n else\n moves.push [Square.index(from), Square.index(to)]\n # if it's occupied by the enemy, no further north moves possible\n dirs = dirs | 0x1 if enemy.set?(to) \n end\n end\n \n # try moving south-west\n if (dirs & 0x2) != 0x2\n to = from-k*9\n if i<k || j<k || comrades.set?(to)\n # no further south-west moves possible\n dirs = dirs | 0x2\n else\n moves.push [Square.index(from), Square.index(to)]\n # if it's occupied by the enemy, no further south-west moves possible\n dirs = dirs | 0x2 if enemy.set?(to) \n end\n end\n \n # try moving north-west\n if (dirs & 0x4) != 0x4\n to = from+k*7\n if i+k>7 || j<k || comrades.set?(to)\n # no further north-west moves possible\n dirs = dirs | 0x4\n else\n moves.push [Square.index(from), Square.index(to)]\n # if it's occupied by the enemy, no further north-west moves possible\n dirs = dirs | 0x4 if enemy.set?(to) \n end\n end \n \n # try moving south-east\n if (dirs & 0x8) != 0x8\n to = from-k*7\n if i<k || j+k>7 || comrades.set?(to)\n # no further south-east moves possible\n dirs = dirs | 0x8\n else\n moves.push [Square.index(from), Square.index(to)]\n # if it's occupied by the enemy, no further south-east moves possible\n dirs = dirs | 0x8 if enemy.set?(to) \n end\n end\n \n end\n end \n moves\n end", "def move( from_square, to_square, promote_to = nil )\n\t\t\t@squares[to_square] = @squares[from_square]\n\t\t\t@squares[from_square] = nil\n\t\t\n\t\t\t@squares[to_square].square = to_square\n\n\t\t\t# handle en-passant captures\n\t\t\tif @squares[to_square].is_a?(Pawn) and to_square == @en_passant\n\t\t\t\t@squares[\"#{to_square[0, 1]}#{from_square[1, 1]}\"] = nil\n\t\t\tend\n\t\t\t# track last move for future en-passant captures\n\t\t\tif @squares[to_square].is_a?(Pawn) and\n\t\t\t (from_square[1, 1].to_i - to_square[1, 1].to_i).abs == 2\n\t\t\t\tif from_square[1, 1] == \"2\"\n\t\t\t\t\t@en_passant = \"#{from_square[0, 1]}3\"\n\t\t\t\telse\n\t\t\t\t\t@en_passant = \"#{from_square[0, 1]}6\"\n\t\t\t\tend\n\t\t\telse\n\t\t\t\t@en_passant = nil\n\t\t\tend\n\t\t\t\n\t\t\tif @squares[to_square].is_a?(King) and # queenside castles\n\t\t\t from_square[0, 1] == \"e\" and to_square[0, 1] == \"c\"\n\t\t\t\trank = to_square[1, 1]\n\t\t\t\t@squares[\"d#{rank}\"] = @squares[\"a#{rank}\"]\n\t\t\t\t@squares[\"a#{rank}\"] = nil\n\n\t\t\t\t@squares[\"d#{rank}\"].square = \"d#{rank}\"\n\t\t\telsif @squares[to_square].is_a?(King) and # kingside castles\n\t\t\t from_square[0, 1] == \"e\" and to_square[0, 1] == \"g\"\n\t\t\t\trank = to_square[1, 1]\n\t\t\t\t@squares[\"f#{rank}\"] = @squares[\"h#{rank}\"]\n\t\t\t \t@squares[\"h#{rank}\"] = nil\n\n\t\t\t\t@squares[\"f#{rank}\"].square = \"f#{rank}\"\n\t\t\telsif not promote_to.nil? # pawn promotion\n\t\t\t\t@squares[to_square] = promote_to.new(self, to_square, @turn)\n\t\t\tend\n\t\t\t\n\t\t\t# advance the turn indicator\n\t\t\tnext_turn\n\t\t\t\n\t\t\tself\n\t\tend", "def place_bishops\r\n $board[2][0] = Bishop.new('white')\r\n\t\t$board[5][0] = Bishop.new('white')\r\n\t\t$board[2][7] = Bishop.new('black')\r\n\t\t$board[5][7] = Bishop.new('black')\r\n end", "def gen_rook_moves(color, piece=:rook)\n moves = []\n if color == :white\n position = @position.white \n comrades = @position.white_pieces\n enemy = @position.black_pieces\n else\n position = @position.black\n comrades = @position.black_pieces\n enemy = @position.white_pieces\n end\n\n # no work to do when there are no pieces\n return moves if position[piece].nil?\n \n # for each piece\n position[piece].set_bits.each do |from| \n # [i,j] = current position\n i = from / 8\n j = from % 8\n\n #dirs flags which directions the piece is blocked\n dirs = 0\n for k in 1..7\n break if dirs == 0xf\n \n # try moving north\n if (dirs & 0x1) != 0x1\n to = from+k*8\n if i+k>7 || comrades.set?(to)\n # no further north moves possible\n dirs = dirs | 0x1\n else\n moves.push [Square.index(from), Square.index(to)]\n # if it's occupied by the enemy, no further north moves possible\n dirs = dirs | 0x1 if enemy.set?(to) \n end\n end\n \n # try moving south\n if (dirs & 0x2) != 0x2\n to = from-k*8\n if i<k || comrades.set?(to)\n # no further south moves possible\n dirs = dirs | 0x2\n else\n moves.push [Square.index(from), Square.index(to)]\n # if it's occupied by the enemy, no further north moves possible\n dirs = dirs | 0x2 if enemy.set?(to) \n end\n end\n \n # try moving east\n if (dirs & 0x4) != 0x4\n to = from+k\n if j+k>7 || comrades.set?(to)\n # no further east moves possible\n dirs = dirs | 0x4\n else\n moves.push [Square.index(from), Square.index(to)]\n # if it's occupied by the enemy, no further east moves possible\n dirs = dirs | 0x4 if enemy.set?(to) \n end\n end\n \n # try moving west\n if (dirs & 0x8) != 0x8\n to = from-k\n if j-k<0 || comrades.set?(to)\n # no further east moves possible\n dirs = dirs | 0x8\n else\n moves.push [Square.index(from), Square.index(to)]\n # if it's occupied by the enemy, no further west moves possible\n dirs = dirs | 0x8 if enemy.set?(to) \n end\n end \n end\n end \n moves\n end", "def next_state(state, move)\n # Deep copy position (is this the easiest way?)\n position = Marshal.load(Marshal.dump(state[:position]))\n player = state[:player]\n opp = opponent(player)\n pieces = Marshal.load(Marshal.dump(state[:pieces]))\n from = move[0]\n to = move[1]\n force_analysis = false\n check = false\n moving_piece = pieces[player].find { |piece| piece.location == from }\n if !moving_piece\n puts \"ERROR--no piece to move!\"\n end\n # Check for capture\n if position[to[0]][to[1]] != \".\"\n # Remove enemy piece\n pieces[opp].delete_if { |piece| piece.location == to }\n # Force AI to continue analysis\n force_analysis = true\n end\n # Check for promotion\n if moving_piece.class == Pawn && to[0] == end_row(player)\n # Replace pawn with queen\n # (Underpromotion not yet implemented)\n pieces[player].delete(moving_piece)\n moving_piece = Queen.new(self, to, player)\n pieces[player] << moving_piece\n end\n # Move piece\n position[from[0]][from[1]] = \".\"\n position[to[0]][to[1]] = moving_piece.icon\n moving_piece.location = to\n # Complete castling by moving rook\n if moving_piece.class == ChessKing && (from[1] - to[1]).abs == 2\n rook_column = to[1] == 6 ? 7 : 0\n castling_rook = pieces[player].find { |piece| piece.location == [from[0], rook_column] }\n if castling_rook\n rook_dest = to[1] == 6 ? 5 : 3\n position[from[0]][rook_column] = \".\"\n position[to[0]][rook_dest] = castling_rook.icon\n castling_rook.location = [to[0], rook_dest]\n else\n puts \"Castling error -- can't find rook!\"\n end\n end\n # Switch active player\n next_player = opp\n # # Create new state for testing whether king is in check\n # new_position_state = {\n # :position => position,\n # :player => player,\n # :pieces => pieces,\n # :check => false,\n # :force_analysis => false\n # }\n # # Test whether opponent's king is now in check\n # check = check?(new_position_state)\n # force_analysis = true if check\n # Return new state\n {\n :position => position,\n :player => next_player,\n :pieces => pieces,\n :check => check,\n :force_analysis => force_analysis\n }\n end", "def knight_moves(src_sqr = [0, 0], tgt_sqr = [0, 0])\n # Init the board and a Knight piece\n board = Board.new\n knight = Knight.new\n \n puts \"\\nFrom #{src_sqr} to #{tgt_sqr}...\"\n \n unless board.valid_position?(src_sqr[0], src_sqr[1]) && board.valid_position?(tgt_sqr[0], tgt_sqr[1])\n puts \"Invalid starting or ending positions!\\nPlease, provide only valid positions in range [0, 0] to [7, 7] to find a solution!\"\n\treturn\n end\n \n # Mark the source square on the board and set its distance to 0\n board.mark_square(src_sqr[0], src_sqr[1], knight.to_sym)\n board.set_square_distance(src_sqr[0], src_sqr[1], 0)\n # Enqueue the source square\n queue = [src_sqr]\n \n # BFS algorithm \n while !queue.empty?\n cur_sqr = queue.shift \n \n\tbreak if cur_sqr == tgt_sqr\n\t\n # Get all possible moves from current position\t\n\tknight.set_position(cur_sqr[0], cur_sqr[1])\n\tknight.get_possible_moves.each do |move| \n\t next unless board.is_square_empty?(move[0], move[1]) \n\t \n\t # Enqueue all possible moves whose related squares are not visited yet\n\t queue << move \n\t board.mark_square(move[0], move[1], knight.to_sym)\n\t board.set_square_distance(move[0], move[1], board.get_square_distance(cur_sqr[0], cur_sqr[1]) + 1)\n\t board.set_square_parent(move[0], move[1], cur_sqr)\n\tend\n end\n \n # Build the reverse path from src_sqr to tgt_sqr, starting from tgt_sqr\n path = [tgt_sqr]\n parent = board.get_square_parent(tgt_sqr[0], tgt_sqr[1])\n while !parent.nil?\n path << parent\n\tparent = board.get_square_parent(parent[0], parent[1])\n end\n \n # Print the solution\n puts \"Solution obtained in #{path.length - 1} move#{path.length - 1 != 1 ? 's' : ''}! The path is:\"\n path.reverse.each {|move| p move}\n \nend", "def move_king(king,white)\n \t ind = king.table.find_vertice(king.pos)\n \t if white\n k = king.posible_moves(king.table.vertices[ind],@board.wpos,@board.bpos,white)\n else\n k = king.posible_moves(king.table.vertices[ind],@board.bpos,@board.wpos,white)\n end\n posible_m =[]\n k.neighbours.each do |element|\n if element\n \tposible_m .push(element)\n end \n end\n\n blocked_m =[]\n final_m =[]\n posible_m.each_with_index do |element,index|\n if check(element,white,true)\n blocked_m.push(element)\n else\n final_m.push(element)\n end\n end\n\n\t if white && blocked_m == posible_m && check(@board.wking.pos,true)\n\t \tcheckmate(white)\n\t elsif blocked_m == posible_m && check(@board.bking.pos,false)\n\t \tcheckmate(white)\n\t else\n\n\t \tif final_m.length ==0 \n puts \" sorry, there not moves avaible for this piece , press start to choose another piece\"\n gets\n white_play\n else \n\t strings_m = final_m.map do |element|\n\t \telement = king.string_pos(element)\n\t end\n\t old_pos = king.pos.dup\n king.pos_choice(strings_m)\n pos_change(old_pos,white,true)\n end \n\n\t end\n\n end", "def play_move!( m )\n self.delete_if { |pos, piece| pos == m.to_coord || pos == m.captured_piece_coord }\n\n piece_moved = self.delete(m.from_coord)\n self[m.to_coord] = piece_moved\n\n if m.castled==1\n castling_rank = m.to_coord.rank.to_s\n [['g', 'f', 'h'], ['c', 'd', 'a']].each do |king_file, new_rook_file, orig_rook_file|\n #update the position of the rook corresponding to the square the king landed on\n\tif m.to_coord.file == king_file \n\t rook = self.delete(\"#{orig_rook_file}#{castling_rank}\")\n\t self[\"#{new_rook_file}#{castling_rank}\"] = rook\n\tend\n end\n end\n \n #TODO investigate why this method is getting called multiply per moves << Move.new\n return unless piece_moved\n ep_from_rank, ep_to_rank, ep_rank = EN_PASSANT_CONFIG[ piece_moved.side ]\n @en_passant_square = ( piece_moved.function == :pawn &&\n m.from_coord.rank == ep_from_rank && \n m.to_coord.rank == ep_to_rank ) ? m.from_coord.file + ep_rank.to_s : nil\n\n #reflect promotion\n if piece_moved && piece_moved.function == :pawn && m.to_coord.to_s.rank == piece_moved.promotion_rank\n self.delete(m.to_coord)\n self[m.to_coord] = Queen.new(piece_moved.side, :promoted)\n #puts self.to_s if m.to_coord == 'a8'\n #debugger if m.to_coord == 'a8'\n end\n \n self\n end", "def move_pile(play1, play2)\n if play2.empty?\n play2.concat(play1)\n play1.clear\n elsif (within_one?(play1[0].rank.to_i, play2[-1].rank.to_i))\n play2.concat(play1)\n play1.clear\n else\n end\nend", "def put_black\n i = 0\n while i<=7 do\n n = Pawn.new([i,6],\"\\u265F\",false)\n put_piece(n)\n i+=1\n end\n n = Rook.new([0,7],\"\\u265C\",false)\n put_piece(n)\n n = Rook.new([7,7],\"\\u265C\",false)\n put_piece(n)\n n = Knight.new([1,7],\"\\u265E\",false)\n put_piece(n)\n n = Knight.new([6,7],\"\\u265E\",false)\n put_piece(n)\n n = Bishop.new([2,7],\"\\u265D\",false)\n put_piece(n)\n n = Bishop.new([5,7],\"\\u265D\",false)\n put_piece(n)\n n = Queen.new([3,7],\"\\u265B\",false)\n put_piece(n)\n n = King.new([4,7],\"\\u265A\",false)\n put_piece(n,true)\n end", "def place_rooks\r\n $board[0][0] = Rook.new('white')\r\n\t\t$board[7][0] = Rook.new('white')\r\n\t\t$board[0][7] = Rook.new('black')\r\n\t\t$board[7][7] = Rook.new('black')\r\n end", "def move_castling(short, color)\n\n if short\n if color == 'black'\n board[0][5].piece, board[0][6].piece = board[0][7].piece, board[0][4].piece\n board[0][7].piece, board[0][4].piece = nil, nil\n board[0][5].piece.position, board[0][6].piece.position = [0,5], [0,6]\n update_possible_movement_all_pieces()\n turns[board[0][5].piece.COLOR.to_sym] += 1\n board[0][5].piece.number_of_move += 1 if board[0][5].piece.instance_of?(Rook)\n board[0][6].piece.number_of_move += 1 if board[0][6].piece.instance_of?(King)\n \n return board[0][5].piece\n else\n board[7][5].piece, board[7][6].piece = board[7][7].piece, board[7][4].piece\n board[7][7].piece, board[7][4].piece = nil, nil\n board[7][5].piece.position, board[7][6].piece.position = [7,5], [7,6]\n update_possible_movement_all_pieces()\n turns[board[7][5].piece.COLOR.to_sym] += 1\n board[7][5].piece.number_of_move += 1 if board[7][5].piece.instance_of?(Rook)\n board[7][6].piece.number_of_move += 1 if board[7][6].piece.instance_of?(King)\n \n return board[7][5].piece\n end\n else\n if color == 'black'\n board[0][3].piece, board[0][2].piece = board[0][0].piece, board[0][4].piece\n board[0][0].piece, board[0][4].piece = nil, nil\n board[0][3].piece.position, board[0][2].piece.position = [0,3], [0,2]\n update_possible_movement_all_pieces()\n\n turns[board[0][3].piece.COLOR.to_sym] += 1\n board[0][3].piece.number_of_move += 1 if board[0][3].piece.instance_of?(Rook)\n board[0][2].piece.number_of_move += 1 if board[0][2].piece.instance_of?(King)\n\n return board[0][3].piece\n else\n board[7][3].piece, board[7][2].piece = board[7][0].piece, board[7][4].piece\n board[7][0].piece, board[7][4].piece = nil, nil\n board[7][3].piece.position, board[7][2].piece.position = [7,3], [7,2]\n update_possible_movement_all_pieces()\n \n turns[board[7][3].piece.COLOR.to_sym] += 1\n board[7][3].piece.number_of_move += 1 if board[7][3].piece.instance_of?(Rook)\n board[7][2].piece.number_of_move += 1 if board[7][2].piece.instance_of?(King)\n\n return board[7][3].piece\n end\n end\n\n end", "def play_in_check(white=false)\n \tif white\n\t \tn = @wks\n\t else\n\t n = @bks\n\t end\n\t if n <2 \n\t can_move =[]\n\t if white\n\t \t@board.whites.each do |element|\t\n\t \t if element.class != King \t \n\t\t\t if save_king(element,white)\n\t\t\t \tcan_move.push(element)\n\t\t\t end\n\t\t end \n\t \tend\n\t \t can_move.push(@board.wking)\n\t \t puts \"you can move only:\"\n\t \t avaible_pieces(can_move,true)\n choice=gets.chomp.upcase \n if choice ==\"\"\n puts \"there is not piece in that place, press start to try again\"\n\t\t\t\t gets\n\t\t\t\t white_play\n end \n\t \t begin\n\t\t\t move_piece(choice,white,true)\n\t\t\t rescue TypeError \n\t\t\t\t puts \"there is not piece in that place, press start to try again\"\n\t\t\t\t gets\n\t\t\t\t white_play\n\t\t\t end\n\t else\n\t \t@board.blacks.each do |element| \n\t\t if element.class != King \t \n\t\t\t if save_king(element,white)\n\t\t\t \tcan_move.push(element)\n\t\t\t end\n\t\t end \n\t \tend\n\t \tcan_move.push(@board.bking)\n\t \tputs \"you can move only:\"\n\t \tavaible_pieces(can_move,false)\n\t\t\t choice=gets.chomp.upcase \n\t\t\t if choice ==\"\"\n puts \"there is not piece in that place, press start to try again\"\n\t\t\t\t gets\n\t\t\t\t white_play\n end \n\t \t begin\n\t\t\t move_piece(choice,white,true)\n\t\t\t rescue TypeError\n\t\t\t\t puts \"there is not piece in that place, press start to try again\"\n\t\t\t\t gets\n\t\t\t\t black_play\n\t\t\t end\n\n\t end\n else \n checkmate\n end \n \n end", "def queen_check?(piece, column, row)\n if piece.is_a?(Queen)\n blocking_up_right = false\n blocking_up_left = false\n blocking_down_left = false\n blocking_down_right = false\n count_up_right = 1\n count_up_left = 1\n count_down_left = 1\n count_down_right = 1\n \n until column + count_up_right > 7 && row + count_up_right > 7\n if column + count_up_right <= 7 && row + count_up_right <= 7\n up_right = @board.check(column + count_up_right, row + count_up_right)\n if up_right != \"___\" && !up_right.is_a?(King)\n blocking_up_right = true\n elsif up_right.is_a?(King) && up_right.color != piece.color &&\n blocking_up_right == false\n @in_check = up_right\n return true\n end\n end\n count_up_right += 1\n end\n\n until column + count_up_left > 7 && row - count_up_left < 0\n if column + count_up_left <= 7 && row - count_up_left >= 0\n up_left = @board.check(column + count_up_left, row - count_up_left)\n if up_left != \"___\" && !up_left.is_a?(King)\n blocking_up_left = true\n elsif up_left.is_a?(King) && up_left.color != piece.color &&\n blocking_up_left == false\n @in_check = up_left\n return true\n end\n end\n count_up_left += 1\n end\n\n until column - count_down_left < 0 && row - count_down_left < 0\n if column - count_down_left >= 0 && row - count_down_left >= 0\n down_left = @board.check(column - count_down_left, row - count_down_left) \n if down_left != \"___\" && !down_left.is_a?(King)\n blocking_down_left = true\n elsif down_left.is_a?(King) && down_left.color != piece.color &&\n blocking_down_left == false\n @in_check = down_left\n return true\n end\n end\n count_down_left += 1\n end\n\n until column - count_down_right < 0 && row + count_down_right > 7\n if column - count_down_right >= 0 && row + count_down_right <= 7\n down_right = @board.check(column - count_down_right, row + count_down_right) \n if down_right != \"___\" && !down_right.is_a?(King)\n blocking_down_right = true\n elsif down_right.is_a?(King) && down_right.color != piece.color &&\n blocking_down_right == false\n @in_check = down_right\n return true\n end\n end\n count_down_right += 1\n end\n\n blocking_up = false\n blocking_left = false\n blocking_down = false\n blocking_right = false\n count_up = 1\n count_left = 1\n count_down = 1\n count_right = 1\n\n until column + count_up > 7 \n if column + count_up <= 7\n up = @board.check(column + count_up, row)\n if up != \"___\" && !up.is_a?(King)\n blocking_up = true\n elsif up.is_a?(King) && up.color != piece.color &&\n blocking_up == false\n @in_check = up\n return true\n end\n end\n count_up += 1\n end\n\n until row - count_left < 0\n if row - count_left >= 0\n left = @board.check(column, row - count_left)\n if left != \"___\" && !left.is_a?(King)\n blocking_left = true\n elsif left.is_a?(King) && left.color != piece.color &&\n blocking_left == false\n @in_check = left\n return true\n end\n end\n count_left += 1\n end\n\n until column - count_down < 0\n if column - count_down >= 0 \n down = @board.check(column - count_down, row) \n if down != \"___\" && !down.is_a?(King)\n blocking_down = true\n elsif down.is_a?(King) && down.color != piece.color &&\n blocking_down == false\n @in_check = down\n return true\n end\n end\n count_down += 1\n end\n\n until row + count_right > 7\n if row + count_right <= 7\n right = @board.check(column, row + count_right) \n if right != \"___\" && !right.is_a?(King)\n blocking_right = true\n elsif right.is_a?(King) && right.color != piece.color &&\n blocking_right == false\n @in_check = right\n return true\n end\n end\n count_right += 1\n end\n end\n return false\n end", "def move(move)\n\n # First, it checks whether or not the move it has recieved is found \n # in the board's array of valid moves (i.e., Board.finalList).\n\n if finalList.include? move\n\n # Second, it uses the movePiece function to manipulate the board\n # according to the validated move. \n\n movePiece(move, @data)\n\n # Third, if the raw move data contains a promotion command then\n # edit the board data accordingly. \n\n if move - ((move/1000) * 1000) > 99\n case ((move - ((move/1000) * 1000)) / 100) * 100\n when 100\n if @white_to_play\n @data[move - ((move/100) * 100)] = 120\n else\n @data[move - ((move/100) * 100)] = 220\n end\n when 200\n if @white_to_play\n @data[move - ((move/100) * 100)] = 130\n else\n @data[move - ((move/100) * 100)] = 230\n end\n when 300\n if @white_to_play\n @data[move - ((move/100) * 100)] = 140\n else\n @data[move - ((move/100) * 100)] = 240\n end\n when 400\n if @white_to_play\n @data[move - ((move/100) * 100)] = 150\n else\n @data[move - ((move/100) * 100)] = 250\n end\n end\n end\n\n if move == 51071 then movePiece(81061, @data) end\n if move == 51031 then movePiece(11041, @data) end\n if move == 58078 then movePiece(88068, @data) end\n if move == 58038 then movePiece(18048, @data) end \n\n # Fouth, if the move involves a pawn, rook, or king edit the board \n # such that the piece has its special status updated (if it has not\n # already been marked as having moved).\n\n if (pieceType(@data[move - ((move/100) * 100)]) == \"pawn\" || pieceType(@data[move - ((move/100) * 100)]) == \"king\" || pieceType(@data[move - ((move/100) * 100)]) == \"rook\") && specialStatus(@data[move - ((move/100) * 100)]) == \"none\" \n @data[move - ((move/100) * 100)] = @data[move - ((move/100) * 100)] + 1\n end\n\n # Fifth, roll over the player turn counter such that if it was\n # white to play it becomes black to play and if it was black to\n # play it becomes white to play.\n\n @white_to_play = !@white_to_play\n\n # And finally, after all the necessary updates to the board\n # data have been made construct a new list of available moves\n # (i.e., finalList) for the next time the move function is called. \n\n initial_list_constructor\n final_list_constructor\n else\n\n # If the move passed to this function is not in list of available\n # moves then return the number 0. \n\n return(0)\n end\n end", "def move_piece(move)\n curr_piece = settings.game.board[move[0]]\n if curr_piece.non_check_moves.include?(move[1])\n #if en passant, remove captured piece\n if curr_piece.class == Pawn\n #puts curr_piece.can_en_passant?\n #puts \"HELKFDSJLFKD\"\n if curr_piece.can_en_passant?\n #puts \"HOMFDMSKFDFLSJFKDSLFJSDKLF JDSFKLSJFKLEJ FE FJSKLF\"\n rank = move[0][0]\n col = move[1][1]\n captured_pawn_pos = [rank,col]\n #puts captured_pawn_pos.inspect\n settings.game.board[captured_pawn_pos] = nil\n end\n end\n settings.game.board[move[1]] = curr_piece\n settings.game.board[move[0]] = nil\n curr_piece.move_history << move\n curr_piece.pos = move[1]\n #if castling, move rook too\n if curr_piece.class == King && (move[0][1] - move[1][1]).abs == 2\n #find the appropriate rook to move\n start_rank = move[0][0]\n start_file = move[1][1] == 2 ? 0 : 7\n start_pos = [start_rank, start_file]\n rook = settings.game.board[start_pos]\n #determine its final location, then move it.\n end_file = start_file == 0 ? 3 : 5\n end_pos = [start_rank, end_file]\n settings.game.board[end_pos] = rook\n settings.game.board[start_pos] = nil\n rook.move_history << end_pos\n rook.pos = end_pos\n end\n return true\n else\n settings.move_error = [true, \"Your king is still in check!\"] if settings.game.board.in_check?(curr_piece.color)\n settings.move_error = [true, \"Not a legal move for this #{curr_piece.color} #{curr_piece.class}!\"]\n puts\n return false\n end\nend", "def get_all_grasshopper_moves(q,r)\n movments = list_nieghbors(q,r)\n list = []\n movments.each do |move|\n next_q = move[0]\n next_r = move[1]\n list.push push_forward(next_q,next_r,next_q-q,next_r-r)\n end\n return list\n end", "def queensAttack(n, k, r_q, c_q, obstacles)\n # make board\n board = Board.new(n)\n # make pieces and add to board immediately after creating\n queen = Piece.new([r_q, c_q], true)\n board.add_cell(queen.cell)\n\n obstacle_pieces = []\n obstacles.each do |ob|\n obstacle_piece = Piece.new(ob)\n board.add_cell(obstacle_piece.cell)\n obstacle_pieces.push(obstacle_piece)\n end\n\n # fill in the empty cells of the board\n board.fill_in_empty_cells\n\n # find all empty cells on the board\n empty_cells = board.empty_cells\n\n # validate queen moves on board: 1. cell is empty 2. cell is on same row, column, or diagonal as queen\n queen_moves = board.valid_queen_moves(queen)\n require 'pry'; binding.pry\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
need to order through the hash according to the assigned key in the point_values method hash
def point_values { "A"=>1, "B"=>3, "C"=>3, "D"=>2, "E"=>1, "F"=>4, "G"=>2, "H"=>4, "I"=>1, "J"=>8, "K"=>5, "L"=>1, "M"=>3, "N"=>1, "O"=>1, "P"=>3, "Q"=>10, "R"=>1, "S"=>1, "T"=>1, "U"=>1, "V"=>4, "W"=>4, "X"=>8, "Y"=>4, "Z"=>10 } end
[ "def hash_point(point)\n @group.generator * hash_array(point.coords)\n end", "def ordered_teachers_hash\n @teachers_hash = @teachers_hash.sort_by { |teacher_name, points| points }.reverse.to_h\n # puts \"xxx\"\n # p teachers_hash\n end", "def in_order_of(key, series); end", "def point_keys\n @_point_keys\n end", "def sorted_keys; end", "def sort_points(args)\n points\n .sort_by { |point| point[:distance] }\n .first(args[:k])\n .map do |point|\n point[:weight] = calc_point_weight(args[:weight], point[:distance])\n point\n end\n end", "def getLastPoint myhash\n\t\t\t#sort the hash and get the x values\n\t\t\tdummy = myhash.keys.sort\n\t\t\t#save the x value of the last point \n\t\t\txval = dummy.last\n\t\t\t#get the y value of the last point\n\t\t\tyval = myhash[xval]\n\t\t\treturn [xval, yval]\n\tend", "def in_order_of(key, series)\n group_by(&key).values_at(*series).flatten(1).compact\n end", "def sort_dimension_keys_values(serieses_results)\n dimension_keys_values_list = serieses_results.values\n sorted_dimension_keys_values = dimension_keys_values_list.map do |dimension_keys_values|\n dimension_keys_values = dimension_keys_values.sort_by do |dimension_key, value|\n is_boolean = dimension_key.is_a?(TrueClass) || dimension_key.is_a?(FalseClass)\n is_boolean ? (dimension_key ? 0 : 1) : dimension_key\n end\n Hash[dimension_keys_values]\n end\n sorted_dimension_keys_values\n end", "def print_value_table(points_hash)\n 10.times do |y|\n 10.times do |x|\n print format(\"%3i \",points_hash[[y,x]])\n end\n print \"\\n\"\n end\n end", "def make_new_xy_hash_keys\n x = $game_map.loop_horizontal? ? @x.round % $game_map.width : @x.round\n y = $game_map.loop_vertical? ? @y.round % $game_map.height : @y.round\n return [x,y]\n end", "def hash_pos\n return (@x * 1000 + @y)\n end", "def basic_values_keys\n basic_values_tuple.keys.sort{|a,b| a.to_s <=> b.to_s}\n end", "def save_hash_field_order; end", "def ordered_entity_hash\n hash = ActiveSupport::OrderedHash.new\n DC::VALID_KINDS.each {|kind| hash[kind] = [] }\n entities.each do |e|\n hash[e.kind].push :value => e.value, :relevance => e.relevance\n end\n hash.each do |key, list|\n hash[key] = list.sort_by {|e| -e[:relevance] }\n end\n hash\n end", "def make_histograms_by_hour\n _by_hour = samples_by_hour.dup\n _by_hour.each_key do |hour|\n hour_samples = _by_hour[hour]\n next if hour_samples.length < 2\n histogram = PointHistogram.new(hour_samples)\n buckets = histogram.calculate\n\n point_infos = buckets.map do |bucket|\n {\n :name => bucket[:count],\n :lat => bucket[:lat],\n :lon => bucket[:lon]\n }\n end\n\n _by_hour[hour] = point_infos\n end\n\nrequire 'pry'; binding.pry\n _by_hour\n end", "def divide_and_conquer_sorted_xy\n points.sort_by!{ |point| point[0] }\n\n points_y_sorted = Hash.new\n points.sort_by{ |point| point[1] }.each do |point|\n points_y_sorted[point[0]] = [point, nil]\n end\n\n dac_sorted_xy_recursively(points, points_y_sorted)\n end", "def to_ordered_hash\n self\n end", "def points\n @points ||= begin\n h = Hash.new\n Point::ABS_POINTS_DATA.each do |pt_name|\n h.merge!(pt_name => Point.new(film, pt_name))\n end\n h\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
multiply that sum by the provided 3rd argument multiplier
def multiply_sum_by_3rd_argument end
[ "def mult(*args)\n\tprod = 1\n\targs.each do |arg|\n\t\tprod *= arg\n\tend\n\tprod\nend", "def mult_then_add(n_1, n_2, n_3)\n\tn_1 * n_2 + n_3\nend", "def mul(*args)\n\t\targs.inject(:*)\n\tend", "def multiply\n match '*'\n factor\n emit_ln 'MULS (SP)+,D0'\nend", "def mod_mul(p0, p1) end", "def Multiply(val)\n self.value *= val\n end", "def multiply(*nums)\n return nums.reduce(:*)\nend", "def multiply(*nums)\n\t# inject(1) to make result start at 1, otherwise we'd always be multiplying by zero!\n\tnums.inject(1) { |result, num| result * num}\nend", "def multiply\n\t22*44\nend", "def mul(lhs, rhs)\n numeric_operation(:mul, lhs, rhs)\n end", "def multiply!(rhs)\n multiply rhs, self\n end", "def * (x) (!numeric?&&x.is_a?(Integer))?mult(x):to_f*x.to_f end", "def multiply(array)\n\ttotal = 1\n\tarray.each { |x|\n\t\ttotal *= x\n\t}\n\treturn total\nend", "def Multiply(x)\n (x * 3)\nend", "def transmogrifier num1,num2,num3\n\t(num1 * num2) ** num3\nend", "def multiply\n 22*44\nend", "def product\n foldl(1) { |x, y| x * y }\n end", "def multiplier\n self.decimal.value\n end", "def multiply(arr_in)\n\treturn nil if arr_in.empty?\n\ttotal = arr_in.first\n\tarr_in.delete_at(0)\n\tarr_in.each { |elem| total *= elem }\n\ttotal\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
directories and files from /home/account_name/www/project_name folder (using ex. FileZilla) but it left some folders with symlinks, such as: www ` project_name | current > /home/account_name/www/project_name/releases/20131014083207 ` releases | 20131014081055 | | log > /home/account_name/www/project_name/shared/log | | public | | ` system > /home/account_name/www/project_name/shared/system | ` tmp | ` pids > /home/account_name/www/project_name/shared/pids ` 20131014083207 | log > /home/account_name/www/project_name/shared/log | public | ` system > /home/account_name/www/project_name/shared/system ` tmp ` pids > /home/account_name/www/project_name/shared/pids Before run change change project_name and account_name variables below. Than connect to your alwaysdata account with ssh, copy this file wherever you want and run: ruby r './ad_cleanup.rb' e 'cleanup'
def cleanup # ---------------------------------------------- account_name = 'your account name' # <-- change this! project_name = 'your project name' # <-- change this! # ---------------------------------------------- project_dir = "/home/#{account_name}/www" Dir.chdir(project_dir) Dir.entries(project_name).select do |entry1| dir1 = File.join(project_name,entry1) #dir2 = "#{project_name}/#{entry1}" if is_directory?(dir1) Dir.entries(dir1).select do |entry2| dir2 = File.join(dir1,entry2) #dir2 = "#{project_name}/#{entry1}/#{entry2}" if is_directory?(dir2) Dir.entries(dir2).select do |entry3| dir3 = File.join(dir2,entry3) #dir3 = "#{project_name}/#{entry1}/#{entry2}/#{entry3}" if is_directory?(dir3) Dir.entries(dir3).select do |entry4| delete_file(File.join(dir3,entry4)) end end delete_file(dir3) delete_dir(dir3) end end delete_file(dir2) delete_dir(dir2) end end delete_file(dir1) delete_dir(dir1) end delete_dir(project_name) end
[ "def tidy_up\n return if DEBUG\n\n puts heading(\"Tidying up PWD\")\n\n FileUtils.remove(Dir[\"#{FileUtils.pwd}/bugsnag-*.tgz\"])\nend", "def remove_dead_symlinks\n base_paths.each do |path|\n command = \"find #{path} -xtype l -delete\"\n Pkg::Util::Net.remote_execute(Pkg::Config.staging_server, command)\n end\n end", "def cleanup_files(host)\n unless host.dir.blank? || (host.dir =~ /[\\*\\?]/)\n @logger.debug { \"#{host.name}: rm -rf #{host.dir}\"}\n host.sh(\"rm -rf #{host.dir}\") unless @user_choices[:leave]\n end\n end", "def clean()\n rels = releases()\n rels.pop()\n\n unless rels.empty?\n rm = ['rm', '-rf'].concat(rels.map {|r| release_dir(r)})\n rm << release_dir('skip-*')\n cmd.ssh(rm)\n end\n end", "def clean\n require 'fileutils'\n\n list = [\n '.zsh_history',\n '.viminfo',\n '.lesshst',\n '.cache',\n '.irb-history',\n '.mysql_history']\n\n dir = '/root/'\n list.each { |f|\n FileUtils.rm_rf(dir + f)\n }\n\n dir = \"#{@home}/\"\n list.each { |f|\n FileUtils.rm_rf(dir + f)\n }\n # Remove all cache files.\n `sudo find #{dir} -name '._*' -exec sudo rm {} \\\\;`\n `sudo find #{dir} -name '.DS_Store' -exec sudo rm {} \\\\;`\n\n # Remove logs\n `sudo find /var/log -iname '*.log' -exec sudo rm {} \\\\;`\n `sudo find /var/log -iname '*.log.*' -exec sudo rm {} \\\\;`\n `sudo find /var/log -iname 'log.*' -exec sudo rm {} \\\\;`\n `sudo find /var/log -iname '*.err' -exec sudo rm {} \\\\;`\n end", "def clean_paths\n FileUtils.rm_rf(tmp_path)\n\n # Call these methods only to rebuild the directories\n tmp_path\n home_path\n boxes_path\n end", "def cleanup_dirs\n @cleanup_dirs ||= ['.']\n end", "def clean(root_dir)\n\t# delete all files in log dir\n\t(root_dir + \"log\").children.each{|f| f.delete if f.file?}\n\t# delete pkg dir (from rake package)\n\tFileUtils.rm_r((root_dir + \"pkg\").to_s) rescue nil\t# ignore failures\n\t# delete all files in db dir\n\t(root_dir + \"db\").children.each{|f| f.delete if f.file?}\n\t# delete clamav.html report\n\t(root_dir + \"clamav.html\").delete rescue nil\t# ignore failures\nend", "def cleanUpWorkingFiles()\n system(\"rm -f #{@tripFile} #{routeFile} #{routeAltFile}\") ;\n end", "def clean_temporary_files\n Dir.chdir(self.root) do\n `rm -f *.distances *.pdistances *.common *.pcommon`\n end\n end", "def cleanup_leftover_files()\r\n FileUtils.rm_rf('vids/')\r\n File.delete('files.txt') if File.exist?('files.txt')\r\n File.delete('output') if File.exist?('output')\r\nend", "def cleanup\n if Dir.exists?(WORKFOLDER)\n FileUtils.remove_dir(WORKFOLDER)\n print_status(\"Workspace \\\"#{WORKFOLDER}\\\" deleted.\")\n end\nend", "def clean_deploy\n FileUtils.rm_rf(Dir.glob('*'), secure: true)\n end", "def cleanup_app_caches(app_name, instance_name)\n Dir.chdir RailsPwnerer::Config[app_name, instance_name][:app_path] do\n if File.exist?('Gemfile')\n Kernel.system 'bundle exec rake assets:clean RAILS_ENV=production'\n else\n Kernel.system 'rake assets:clean RAILS_ENV=production'\n end\n end\n end", "def purge_puppet_created_files\n FileUtils.rm_f Dir[path('settings.d/puppet-managed/*.php')]\n FileUtils.rm_rf path('settings.d/multiwiki')\n FileUtils.rm_rf path('settings.d/wikis')\n FileUtils.rm_rf path('settings.d/composer')\n FileUtils.rm_rf path('vagrant.d')\n FileUtils.rm_f path('mediawiki/LocalSettings.php')\n end", "def delete_nsec3_files()\n w = Dir.new(@working)\n w.each {|f|\n if ((f.index(\"audit\")) && (f.index(\"#{Process.pid}\")))\n begin\n File.delete(@working + File::SEPARATOR + f.untaint)\n rescue Exception => e\n print \"Can't delete temporary auditor file #{f}, error : #{e}\\n\"\n end\n end\n }\n end", "def clean_up \n FileUtils.rm self.post_file_path\n FileUtils.rm self.site_file_path \n FileUtils.rm self.push_file_path\n end", "def clean_up_pantry_root\n Dir[\"#{Pantry.root}/**/*\"].each do |file|\n FileUtils.rm_rf file\n end\n end", "def cleanTmp\n ts_str = \"/tmp/d\" + Date.today.strftime(\"%Y%m%d\") + \"-*\"\n Gitchefsync.logger.info \"clean up of #{ts_str}\"\n FS.cmdNoError \"sudo rm -fr #{ts_str}\"\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an erased flash.
def createflashimage flashdata = "\xff" * FLASHSIZE Flashimage.write(flashdata) end
[ "def initialize_flash_types\n flash.clear\n end", "def flash_destroyed_message\n flash_message_builder(:destroy, flash_status_type, 'destroyed')\n end", "def keep_flash\n @keep_flash = true\n end", "def flash_clear\n flash.clear\n end", "def _roda_after_40__flash(_)\n if f = @_flash\n f = f.next\n if f.empty?\n session.delete('_flash')\n else\n session['_flash'] = f\n end\n end\n end", "def flash=(_arg0); end", "def destroy\n @flashcard = Flashcard.find(params[:id])\n @flashcard.destroy\n end", "def delete_flash_cache\n begin\n @flash_cache.delete_flash_cache\n rescue => ex\n Util.log_exception(ex, caller_locations(1, 1)[0].label)\n raise ex\n end\n end", "def destroy_flash\n if @class_des1.destroy\n flash[:notice] = t('del_class')\n redirect_to new_exam_setting_path\n else\n flash[:notice] = t('not_del_class')\n end\n end", "def render_flash\n return if state.flash_at.elapsed_time > 10 # return if more than 10 frames have passed since flash.\n # Transparency gradually changes (or eases) during the 10 frames of flash.\n outputs.primitives << [grid.rect, 255, 255, 255, 255 * state.flash_at.ease(10, :flip)].solid\n end", "def destroy\n @flashlight.destroy\n respond_to do |format|\n format.html { redirect_to flashlights_url }\n format.json { head :no_content }\n end\n end", "def flash_reset\n @flash_reset = true if @flash_reset.nil?\n @flash_reset\n end", "def flash\n @messages.values.each {|v| v.delete_if {|m| m.options[:flash]}}\n @by_id.delete_if {|k, v| v.first.options[:flash]}\n end", "def create_flash\n if @class_des1.save\n flash[:notice] = t('create_class')\n else\n flash[:notice] = t('not_create_class')\n end\n end", "def flash(evt = nil)\n @notice = evt[:notice] rescue ''\n @alert = evt[:alert] rescue ''\n render :text => update(\"##{dom_id}_flash\"), :layout => 'flash_effect.js.erb',\n :locals => {:flashid => \"#{dom_id}_flash\"}\n end", "def destroy\n @current_user.flashcards.where(id: flashcards_destroy_params[:ids]).delete_all\n\n head :ok\n end", "def destroy\n @flashcard.destroy\n respond_to do |format|\n format.html { redirect_to flashcards_url }\n format.json { head :no_content }\n end\n end", "def generate_flash_tag( url, swf_path, swf_file, options )\n # Setup options for opaque mode\n setup_wmode( options ) \n \n # setup width and height\n setup_movie_size( options )\n \n color_param = tag( 'param', {:name => 'bgcolor', :value => options[:bgcolor]}, true )\n color_param += tag( 'param', {:name => \"wmode\", :value => options[:wmode]}, true )\n\n xml_swf_path = gen_swf_path( swf_path, options[:swf_path], url )\n xml_swf_path << \"&timestamp=#{Time.now.to_i}\" if options[:cache] == false\n xml_swf_path << \"&timeout=#{options[:timeout]}\" if options[:timeout]\n xml_swf_path << \"&stage_width=#{options[:width]}&stage_height=#{options[:height]}\" if options[:use_stage] == true \n \n tags = <<-TAGS\n <object codebase=\"#{codebase}\" classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" id=\"#{options[:id]}\" height=\"#{options[:height]}\" width=\"#{options[:width]}\">\n <param name=\"scale\" value=\"noscale\">\n <param name=\"salign\" value=\"#{options[:salign]}\"> \n <param name=\"bgcolor\" value=\"#{options[:bgcolor]}\">\n <param name=\"wmode\" value=\"#{options[:wmode]}\"> \n <param name=\"movie\" value=\"#{options[:swf_path]}/#{swf_file}\">\n <param name=\"Flashvars\" value=\"#{xml_swf_path}&chart_id=#{options[:id]}\">\n <param name=\"menu\" value=\"true\">\n <param name=\"allowFullScreen\" value=\"true\">\n <param name=\"allowScriptAccess\" value=\"sameDomain\"> \n <param name=\"quality\" value=\"high\">\n <param name=\"play\" value=\"true\"> \n <param name=\"devicefont\" value=\"false\">\n <embed scale=\"noscale\" \n allowfullscreen = \"true\" \n allowscriptaccess = \"sameDomain\" \n bgcolor = \"#{options[:bgcolor]}\" \n devicefont = \"false\" \n flashvars = \"#{xml_swf_path}&chart_id=#{options[:id]}\" \n menu = \"true\" \n name = \"#{options[:id]}\" \n play = \"true\" \n pluginspage = \"http://www.macromedia.com/go/getflashplayer\" \n quality = \"high\" \n salign = \"#{options[:salign]}\" \n src = \"#{options[:swf_path]}/#{swf_file}\" \n type = \"application/x-shockwave-flash\" \n wmode = \"#{options[:wmode]}\" \n align = \"#{options[:align]}\" \n height = \"#{options[:height]}\" \n width = \"#{options[:width]}\"/> \n </object> \n TAGS\n end", "def flash\n return @flash if @flash\n\n session['__flash__'] ||= {}\n @flash = FlashHash.new(session['__flash__'])\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Split flash image in partitions.
def splitflashimage flashdata = Flashimage.read size = flashdata.size puts("Flash image size: #{size / MiB} MiB = #{size} B.") raise('Flash size is unexpected.') if (size != FLASHSIZE) baseaddress = PARTITIONS['boot'][START] PARTITIONS.each { |label, partition| first = partition[START] - baseaddress last = first + partition[SIZE] filename = "#{File.dirname(FLASHIMAGE)}/#{partition[FILE]}" Flashimage.write(flashdata[first ... last], filename) } end
[ "def mergepartitions\n\tflashdata = \"\\xff\" * FLASHSIZE\n\tbaseaddress = PARTITIONS['boot'][START]\n\tPARTITIONS.each { |label, partition|\n\t\tfirst = partition[START] - baseaddress\n\t\tlast = first + partition[SIZE]\n\t\tfilename = \"#{File.dirname(FLASHIMAGE)}/#{partition[FILE]}\"\n\t\tpartdata = Flashimage.read(filename)\n\t\tsize = partdata.size\n\t\tputs(\"Partition size: #{size / KiB} KiB = #{size} B (#{label}).\")\n\t\traise('Partition size is unexpected.') if (size != partition[SIZE])\n\t\tflashdata[first ... last] = partdata\n\t}\n\tFlashimage.write(flashdata)\nend", "def draw_split\n lh = (@image.height / 67).ceil\n row = ->(y) { (y * lh) > @image.height ? @image.height : (y * lh) }\n MiniMagick::Tool::Convert.new do |convert|\n convert << @master_file.path\n (1..67).each { |i| convert.merge! red_line(row.call(i), @image.height) }\n convert << working_path(\"#{@column.number}_split.png\")\n end\n save_split_image\n end", "def partitions\n parts = []\n self.partition {|p| parts << p }\n parts\n end", "def changepartition(partition, filename)\n\tbaseaddress = PARTITIONS['boot'][START]\t\n\tsize = partition[SIZE]\n\tpartdata = Flashimage.read(filename)\n\tlength = partdata.size\n\tlast = partition[SIZE]\n\traise('Input file too large.') if length + 12 > last\n\tcrc32 = Zlib.crc32(partdata)\n\tpartdata[length ... last - 12] = \"\\xff\" * (last - length - 12)\n\tpartdata[last - 12 ... last] = [length, 0x12345678, crc32].pack('V3')\n\tfilename = \"#{File.dirname(FLASHIMAGE)}/#{partition[FILE]}\"\n\tFlashimage.write(partdata, filename)\nend", "def partition(dev, parts, verbose=false, ids=Array.new)\n if dev == nil or parts == nil then raise \"bad args\" end\n if verbose\n parts.each_index do |i|\n puts \"creating partition #{i} size #{parts[i]}MB\"\n end\n end\n input = create_sfdisk_input(parts, ids)\n\n #get the size of the drive\n cmd = \"{\\n #{input} } | sudo /sbin/sfdisk -uS --force #{dev}; sleep 5;\"\n puts cmd\n shell = SwrShell.new\n return shell.execute(cmd,verbose)\n end", "def divide_parts\n logger.info(\"Begin divide parts, object: #{@object}\")\n\n max_parts = 100\n object_size = @object_meta[:size]\n part_size =\n [@options[:part_size] || PART_SIZE, object_size / max_parts].max\n num_parts = (object_size - 1) / part_size + 1\n @parts = (1..num_parts).map do |i|\n {\n :number => i,\n :range => [(i - 1) * part_size, [i * part_size, object_size].min],\n :done => false\n }\n end\n\n checkpoint\n\n logger.info(\"Done divide parts, parts: #{@parts}\")\n end", "def use_data_partitioning\n FFMpegCommand << \"-part\"\n end", "def split_tile_set_into_tiles\n number_of_tiles = @tile_set[0].columns/32\n\n number_of_tiles.times do |i|\n image = @tile_set[0].crop((i*32), 0, 32, 32)\n image.write(\"media/tmp/tile#{i}.png\")\n end\n end", "def loadpart(partname, filename)\n\tflashimage = Flashimage.new\n\tfirmware = Flashimage.read(filename)\n\tsize = firmware.size\n\toffset_signature = size - 10\n\tsignature = firmware[offset_signature .. -1]\n\tputs(\"signature: #{signature.inspect}\")\n\tlength, magic, crc32, offset = getblock(partname, firmware, offset_signature)\n\tpartition = Partition.new(partname)\n\tpartition.update(firmware[offset ... offset + length])\n\tflashimage.update(partition)\n\tflashimage.write\nend", "def subdivide\n smallerFaces = Array.new\n\n @faces.each { |t| smallerFaces.concat t.subdivide }\n\n @faces = smallerFaces\n end", "def split_into_parts(*sizes); end", "def split2(ratio)\n lines = File.read(@path).split(\"\\n\")\n split_point = (lines.size*ratio).to_i\n file1 = lines[0..split_point].join(\"\\n\")\n file2 = lines[split_point+1..lines.size-1].join(\"\\n\")\n\n\n basename = File.basename(@path)\n file1name = basename + \".part.1\"\n file2name = basename + \".part.2\"\n path1 = File.join(@tmpdir, file1name)\n path2 = File.join(@tmpdir, file2name)\n File.open(path1, 'w') { |f| f.write(file1) }\n File.open(path2, 'w') { |f| f.write(file2) }\n\n [path1, path2]\n end", "def index\n @image_to_parts = ImageToPart.all\n end", "def split_partitions\n partition_names = @list.map { |bin| bin.partition_names }.flatten\n partition_names.select { |name| partition_names.index(name) != partition_names.rindex(name) }.uniq\n end", "def subdivide\n smallerFaces = Array.new\n @faces.each{|t| smallerFaces.concat t.subdivide}\n @faces = smallerFaces\n end", "def splitMultiPage( multiPageSheet, assignmentID, num_pages )\n newSheets = Array.new()\n pg = 1\n oldPath = multiPageSheet.image.path\n pathDir = oldPath.split(\"/\")\n pathDir.pop\n pathDirStr = pathDir.join(\"/\")\n pathDirStr += \"/\"\n\n #Change directory to the path. Needed for docsplit or else\n #it extracts to the current directory (rails root by default)\n Dir.chdir(pathDirStr)\n\n # OLD method - use extract_images to split and convert each image to jpg\n # Replaced becasue of compatability issues with GhostScript \n #Docsplit.extract_images(oldPath, :format => [:jpg])\n\n\n Docsplit.extract_pages(oldPath)\n\n\n num_pages.times do\n newSheet = Scansheet.new\n newPathArr = oldPath.split(\".\")\n newPathStrPdf = \"#{newPathArr[0]}_#{pg}.pdf\"\n newPathStr = \"#{newPathArr[0]}_#{pg}.jpg\"\n system(\"convert -density 175 #{newPathStrPdf} #{newPathStr}\")\n newSheet.image = File.open(newPathStr)\n newSheet.assignment_id = assignmentID\n newSheet.save\n newSheets.push( newSheet )\n pg += 1\n end\n #Scansheet.destroy( multiPageSheet )\n Dir.chdir(Rails.root)\n newSheets\n end", "def format_image\n mtab = EC2::Platform::Linux::Mtab.load\n root = mtab.entries[Pathname(@volume).realpath.to_s].device rescue nil\n info = fsinfo( root )\n label= info[:label]\n uuid = info[:uuid]\n type = info[:type] || 'ext3'\n execute('modprobe loop') unless File.blockdev?('/dev/loop0')\n\n target = nil\n if self.is_disk_image?\n cmd = []\n img = @image_filename\n size = (@mb_image_size * 1024 * 1024 / 512)\n case @part_type\n when EC2::Platform::PartitionType::MBR\n # Add a partition table and leave space to install a boot-loader.\n # The boot partition fills up the disk. Note that '-1s' indicates\n # the end of disk (and not 1 sector in from the end.\n # Note: Grub2 can have core.img larger than 64 blocks - increasing to 2048 for grub2\n @grub2 ? head = 2047 : head = 63\n cmd << ['unit s']\n cmd << ['mklabel msdos']\n cmd << ['mkpart primary %s -1s' % head]\n cmd << ['set 1 boot on print quit']\n cmd = \"parted --script %s -- '%s'\" % [img, cmd.join(' ')]\n execute(cmd)\n self.settle\n when EC2::Platform::PartitionType::GPT\n # Add a 1M (2048 sector) BIOS Boot Partition (BPP) to hold the\n # GRUB bootloader and then fill the rest of the disk with the\n # boot partition.\n #\n # * GRUB2 is BBP-aware and will automatically use this partition for\n # stage2.\n #\n # * Legacy GRUB is not smart enough to use the BBP for stage 1.5.\n # We deal with that during GRUB setup in #finalize_image.\n #\n # * Legacy GRUB knows enough about GPT partitions to reference\n # them by number (avoiding the need for the hybrid MBR hack), so\n # we set this partition to the maximum partition available to\n # avoid incrementing the root partition number.\n last = evaluate('sgdisk --print %s |grep \"^Partition table holds up to\"|cut -d\" \" -f6 ||:' % img).strip\n last = 4 if last.empty? # fallback to 4.\n execute('sgdisk --new %s:1M:+1M --change-name %s:\"BIOS Boot Partition\" --typecode %s:ef02 %s' % [last,last,last, img])\n self.settle\n execute('sgdisk --largest-new=1 --change-name 1:\"Linux\" --typecode 1:8300 %s' % img)\n self.settle\n execute('sgdisk --print %s' % img)\n self.settle\n else\n raise NotImplementedError, \"Partition table type %s not supported\" % @part_type\n end\n self.settle\n\n # The series of activities below are to ensure we can workaround\n # the vagaries of various versions of GRUB. After we have created\n # partition table above, we fake an hda-named device by leveraging\n # device mapper to create a linear device named \"/dev/mapper/hda\".\n # We then set @target to its first partition. This makes @target\n # easy to manipulate pretty much in the same way that we handle\n # non-partitioned images. All cleanup happens during #cleanup.\n @diskloop = evaluate('losetup -f').strip\n execute('losetup %s %s' % [@diskloop, @image_filename])\n @diskdev = '/dev/mapper/hda'\n @partdev = '%s1' % [ @diskdev]\n diskname = File.basename(@diskdev)\n loopname = File.basename(@diskloop)\n majmin = IO.read('/sys/block/%s/dev' % loopname).strip\n execute( 'echo 0 %s linear %s 0|dmsetup create %s' % [size, majmin, diskname] )\n execute( 'kpartx -a %s' % [ @diskdev ] )\n self.settle\n @target = @partdev\n @fstype = type\n else\n # Not creating a disk image.\n @target = @image_filename\n end\n\n tune = nil\n mkfs = [ '/sbin/mkfs.' + type ]\n case type\n when 'btrfs'\n mkfs << [ '-L', label] unless label.to_s.empty?\n mkfs << [ @target ]\n when 'xfs'\n mkfs << [ '-L', label] unless label.to_s.empty?\n mkfs << [ @target ]\n tune = [ '/usr/sbin/xfs_admin' ]\n tune << [ '-U', uuid ] unless uuid.to_s.empty?\n tune << [ @target ]\n else\n # Type unknown or ext2 or ext3 or ext4\n # New e2fsprogs changed the default inode size to 256 which is\n # incompatible with some older kernels, and older versions of\n # grub. The options below change the behavior back to the\n # expected RHEL5 behavior if we are bundling disk images. This\n # is not ideal, but oh well.\n if ['ext2', 'ext3', 'ext4'].include?(type)\n # Clear all the defaults specified in /etc/mke2fs.conf\n features = ['none']\n\n # Get Filesytem Features as reported by dumpe2fs\n output = evaluate(\"dumpe2fs -h %s | grep 'Filesystem features'\" % root)\n parts = output.split(':')[1].lstrip.split(' ')\n features.concat(parts)\n features.delete('needs_recovery')\n if features.include?('64bit')\n puts \"WARNING: 64bit filesystem flag detected on root device (#{root}), resulting image may not boot\"\n end\n\n if self.is_disk_image?\n mkfs = [ '/sbin/mke2fs -t %s -v -m 1' % type ]\n mkfs << ['-O', features.join(',')]\n if ['ext2', 'ext3',].include?(type)\n mkfs << [ '-I 128 -i 8192' ]\n end\n else\n mkfs << ['-F']\n mkfs << ['-O', features.join(',')]\n end\n else\n # Unknown case\n mkfs << ['-F']\n end\n mkfs << [ '-L', label] unless label.to_s.empty?\n mkfs << [ @target ]\n tune = [ '/sbin/tune2fs -i 0' ]\n tune << [ '-U', uuid ] unless uuid.to_s.empty?\n tune << [ @target ]\n end\n execute( mkfs.join( ' ' ) )\n execute( tune.join( ' ' ) ) if tune\n end", "def split_image(filename, image, center, options)\n image_both = image #Magick::ImageList.new(input_file)\n half = center # image_both.columns / 2\n \n # allow the percentage of slop to be variable rather than hard-wired to 2%\n two_percent = image_both.columns * ( options[:fudge_factor] / 100 )\n# print \"lhs = image_both.crop(0, 0, #{half+two_percent}, #{image_both.rows})\\n\"\n lhs = image_both.crop(0, 0, half+two_percent, image_both.rows, true)\n \n ext = File.extname(filename)\n\n if options[:vertical]\n lhs.rotate(270).write(filename.sub(ext, \"_below#{ext}\")) \n else\n if options[:spine_side] == \"right\" || options[:spine_side] == \"center\"\n lhs.write(filename.sub(ext, \"_left#{ext}\")) \n end\n end\n\n\n start = half - two_percent\n width = image_both.columns - start\n# print \"rhs = image_both.crop(#{start}, 0, #{width}, #{image_both.rows})\\n\"\n rhs = image_both.crop(start, 0, width, image_both.rows, true)\n\n if options[:vertical]\n rhs.rotate(270).write(filename.sub(ext, \"_above#{ext}\")) \n else\n if options[:spine_side] == \"left\" || options[:spine_side] == \"center\"\n rhs.write(filename.sub(ext, \"_right#{ext}\")) \n end\n end\n\n GC.start\nend", "def splitProgramme()\n @media_operation = :split\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make flash image from partitions.
def mergepartitions flashdata = "\xff" * FLASHSIZE baseaddress = PARTITIONS['boot'][START] PARTITIONS.each { |label, partition| first = partition[START] - baseaddress last = first + partition[SIZE] filename = "#{File.dirname(FLASHIMAGE)}/#{partition[FILE]}" partdata = Flashimage.read(filename) size = partdata.size puts("Partition size: #{size / KiB} KiB = #{size} B (#{label}).") raise('Partition size is unexpected.') if (size != partition[SIZE]) flashdata[first ... last] = partdata } Flashimage.write(flashdata) end
[ "def splitflashimage\n\tflashdata = Flashimage.read\n\tsize = flashdata.size\n\tputs(\"Flash image size: #{size / MiB} MiB = #{size} B.\")\n\traise('Flash size is unexpected.') if (size != FLASHSIZE)\n\tbaseaddress = PARTITIONS['boot'][START]\n\tPARTITIONS.each { |label, partition|\n\t\tfirst = partition[START] - baseaddress\n\t\tlast = first + partition[SIZE]\n\t\tfilename = \"#{File.dirname(FLASHIMAGE)}/#{partition[FILE]}\"\n\t\tFlashimage.write(flashdata[first ... last], filename)\n\t}\nend", "def changepartition(partition, filename)\n\tbaseaddress = PARTITIONS['boot'][START]\t\n\tsize = partition[SIZE]\n\tpartdata = Flashimage.read(filename)\n\tlength = partdata.size\n\tlast = partition[SIZE]\n\traise('Input file too large.') if length + 12 > last\n\tcrc32 = Zlib.crc32(partdata)\n\tpartdata[length ... last - 12] = \"\\xff\" * (last - length - 12)\n\tpartdata[last - 12 ... last] = [length, 0x12345678, crc32].pack('V3')\n\tfilename = \"#{File.dirname(FLASHIMAGE)}/#{partition[FILE]}\"\n\tFlashimage.write(partdata, filename)\nend", "def loadpart(partname, filename)\n\tflashimage = Flashimage.new\n\tfirmware = Flashimage.read(filename)\n\tsize = firmware.size\n\toffset_signature = size - 10\n\tsignature = firmware[offset_signature .. -1]\n\tputs(\"signature: #{signature.inspect}\")\n\tlength, magic, crc32, offset = getblock(partname, firmware, offset_signature)\n\tpartition = Partition.new(partname)\n\tpartition.update(firmware[offset ... offset + length])\n\tflashimage.update(partition)\n\tflashimage.write\nend", "def format_image\n mtab = EC2::Platform::Linux::Mtab.load\n root = mtab.entries[Pathname(@volume).realpath.to_s].device rescue nil\n info = fsinfo( root )\n label= info[:label]\n uuid = info[:uuid]\n type = info[:type] || 'ext3'\n execute('modprobe loop') unless File.blockdev?('/dev/loop0')\n\n target = nil\n if self.is_disk_image?\n cmd = []\n img = @image_filename\n size = (@mb_image_size * 1024 * 1024 / 512)\n case @part_type\n when EC2::Platform::PartitionType::MBR\n # Add a partition table and leave space to install a boot-loader.\n # The boot partition fills up the disk. Note that '-1s' indicates\n # the end of disk (and not 1 sector in from the end.\n # Note: Grub2 can have core.img larger than 64 blocks - increasing to 2048 for grub2\n @grub2 ? head = 2047 : head = 63\n cmd << ['unit s']\n cmd << ['mklabel msdos']\n cmd << ['mkpart primary %s -1s' % head]\n cmd << ['set 1 boot on print quit']\n cmd = \"parted --script %s -- '%s'\" % [img, cmd.join(' ')]\n execute(cmd)\n self.settle\n when EC2::Platform::PartitionType::GPT\n # Add a 1M (2048 sector) BIOS Boot Partition (BPP) to hold the\n # GRUB bootloader and then fill the rest of the disk with the\n # boot partition.\n #\n # * GRUB2 is BBP-aware and will automatically use this partition for\n # stage2.\n #\n # * Legacy GRUB is not smart enough to use the BBP for stage 1.5.\n # We deal with that during GRUB setup in #finalize_image.\n #\n # * Legacy GRUB knows enough about GPT partitions to reference\n # them by number (avoiding the need for the hybrid MBR hack), so\n # we set this partition to the maximum partition available to\n # avoid incrementing the root partition number.\n last = evaluate('sgdisk --print %s |grep \"^Partition table holds up to\"|cut -d\" \" -f6 ||:' % img).strip\n last = 4 if last.empty? # fallback to 4.\n execute('sgdisk --new %s:1M:+1M --change-name %s:\"BIOS Boot Partition\" --typecode %s:ef02 %s' % [last,last,last, img])\n self.settle\n execute('sgdisk --largest-new=1 --change-name 1:\"Linux\" --typecode 1:8300 %s' % img)\n self.settle\n execute('sgdisk --print %s' % img)\n self.settle\n else\n raise NotImplementedError, \"Partition table type %s not supported\" % @part_type\n end\n self.settle\n\n # The series of activities below are to ensure we can workaround\n # the vagaries of various versions of GRUB. After we have created\n # partition table above, we fake an hda-named device by leveraging\n # device mapper to create a linear device named \"/dev/mapper/hda\".\n # We then set @target to its first partition. This makes @target\n # easy to manipulate pretty much in the same way that we handle\n # non-partitioned images. All cleanup happens during #cleanup.\n @diskloop = evaluate('losetup -f').strip\n execute('losetup %s %s' % [@diskloop, @image_filename])\n @diskdev = '/dev/mapper/hda'\n @partdev = '%s1' % [ @diskdev]\n diskname = File.basename(@diskdev)\n loopname = File.basename(@diskloop)\n majmin = IO.read('/sys/block/%s/dev' % loopname).strip\n execute( 'echo 0 %s linear %s 0|dmsetup create %s' % [size, majmin, diskname] )\n execute( 'kpartx -a %s' % [ @diskdev ] )\n self.settle\n @target = @partdev\n @fstype = type\n else\n # Not creating a disk image.\n @target = @image_filename\n end\n\n tune = nil\n mkfs = [ '/sbin/mkfs.' + type ]\n case type\n when 'btrfs'\n mkfs << [ '-L', label] unless label.to_s.empty?\n mkfs << [ @target ]\n when 'xfs'\n mkfs << [ '-L', label] unless label.to_s.empty?\n mkfs << [ @target ]\n tune = [ '/usr/sbin/xfs_admin' ]\n tune << [ '-U', uuid ] unless uuid.to_s.empty?\n tune << [ @target ]\n else\n # Type unknown or ext2 or ext3 or ext4\n # New e2fsprogs changed the default inode size to 256 which is\n # incompatible with some older kernels, and older versions of\n # grub. The options below change the behavior back to the\n # expected RHEL5 behavior if we are bundling disk images. This\n # is not ideal, but oh well.\n if ['ext2', 'ext3', 'ext4'].include?(type)\n # Clear all the defaults specified in /etc/mke2fs.conf\n features = ['none']\n\n # Get Filesytem Features as reported by dumpe2fs\n output = evaluate(\"dumpe2fs -h %s | grep 'Filesystem features'\" % root)\n parts = output.split(':')[1].lstrip.split(' ')\n features.concat(parts)\n features.delete('needs_recovery')\n if features.include?('64bit')\n puts \"WARNING: 64bit filesystem flag detected on root device (#{root}), resulting image may not boot\"\n end\n\n if self.is_disk_image?\n mkfs = [ '/sbin/mke2fs -t %s -v -m 1' % type ]\n mkfs << ['-O', features.join(',')]\n if ['ext2', 'ext3',].include?(type)\n mkfs << [ '-I 128 -i 8192' ]\n end\n else\n mkfs << ['-F']\n mkfs << ['-O', features.join(',')]\n end\n else\n # Unknown case\n mkfs << ['-F']\n end\n mkfs << [ '-L', label] unless label.to_s.empty?\n mkfs << [ @target ]\n tune = [ '/sbin/tune2fs -i 0' ]\n tune << [ '-U', uuid ] unless uuid.to_s.empty?\n tune << [ @target ]\n end\n execute( mkfs.join( ' ' ) )\n execute( tune.join( ' ' ) ) if tune\n end", "def createflashimage\n\tflashdata = \"\\xff\" * FLASHSIZE\n\tFlashimage.write(flashdata)\nend", "def partition(dev, parts, verbose=false, ids=Array.new)\n if dev == nil or parts == nil then raise \"bad args\" end\n if verbose\n parts.each_index do |i|\n puts \"creating partition #{i} size #{parts[i]}MB\"\n end\n end\n input = create_sfdisk_input(parts, ids)\n\n #get the size of the drive\n cmd = \"{\\n #{input} } | sudo /sbin/sfdisk -uS --force #{dev}; sleep 5;\"\n puts cmd\n shell = SwrShell.new\n return shell.execute(cmd,verbose)\n end", "def create\n begin\n # Set the partition (/dev/sdb1), device (/dev/sdb) and alignment (optimal,minimal,none etc.) variables\n partition= resource[:name]\n device=partition[0,(partition.length-1)]\n alignment= resource[:alignment]\n\n # Now we can create the partition\n partitions = parted('-a', resource[:alignment],'--script',device,'mklabel',resource[:part_label],'mkpart', resource[:part_type],resource[:fs_type],resource[:p_begin],resource[:p_end])\n rescue Puppet::ExecutionFailure => e\n false\n end\n end", "def make\n puts \"Generating image file #{@img_filename} from path #{@volume}\"\n\n if not @exclude_dirs.nil?\n puts \"WARNING: Excluding directories operation is not supported.\"\n puts \"The following directories will NOT be excluded from \" \\\n \"image file:\"\n @exclude_dirs.each { |dir| puts(\"#{dir}\\t\") }\n end\n\n ### TODO Update fstab, etc... (do the extreme\n\t ### minimum here, the script should not alter the install tree too\n\t ### heavily)\n \n execute(\"makefs -s '#{@img_size}m' -B le -o density=32k \" \\\n \"'#{@img_filename}' '#{@volume}'\")\n\n puts \"Image #{@img_filename} successfully created.\"\n end", "def build_ftk_disk_items(coll_pid, disk_image_files_dir, computer_media_photos_dir)\n assembler = FtkDiskImageItemAssembler.new(:collection_pid => coll_pid, :disk_image_files_dir => disk_image_files_dir, :computer_media_photos_dir => computer_media_photos_dir)\n assembler.process\nend", "def loadfw(filename)\n\tflashimage = Flashimage.new\n\tfirmware = Flashimage.read(filename)\n\tsize = firmware.size\n\toffset_signature = size - 10\n\tsignature = firmware[offset_signature .. -1]\n\tputs(\"signature: #{signature.inspect}\")\n\tlength, magic, crc32, offset_code = getblock('code', firmware, offset_signature)\n\tcode = Partition.new('code')\n\tcode.update(firmware[offset_code ... offset_code + length])\n\tputs code.size\n\tlength, magic, crc32, offset_web = getblock('web', firmware, offset_code)\n\tweb = Partition.new('web')\n\tputs web.size\n\tweb.update(firmware[offset_web ... offset_web + length])\n\tflashimage.update(code)\n\tflashimage.update(web)\n\tflashimage.write\nend", "def create_images\n # draw the front side\n t_front = send(\"draw_by_#{custom_layout}\", front=true)\n\n # the overall image is just a snapshot of the front side right now\n # This image should go away there is no reason to use it since\n # it is a duplicate of the Front Side\n # at some point i guess it should be an image made up of the front and back\n image.store_file!(t_front.path)\n\n # draw the back side\n send(\"draw_by_#{custom_layout}\", front=false) if baby_got_back\n\n # save our offer record\n save\n end", "def install_partition(progress)\n\tprogress.text = \"Start der Installation\"\n\ttargetsize = @drivehash[@drivelist[@drivecombo.active]][2]\n\tputs \"Target has size: \" + targetsize.to_s \n\tputs \"Target is \" + @drivelist[@drivecombo.active]\n\tddcommand = \"dd if=/dev/zero bs=1024 count=10 of=/dev/\" + @drivelist[@drivecombo.active]\n\tprogress.text = \"Lösche USB-Speicherstift\"\n\twhile (Gtk.events_pending?)\n\t\tGtk.main_iteration\n\tend\n\tsystem ddcommand\n\tputs \"Deleting drive: \" + ddcommand \n\tptcommand = \"parted -s /dev/\" + @drivelist[@drivecombo.active] + \" unit B mklabel msdos\"\n\tputs \"Creating table: \" + ptcommand \n\tsystem ptcommand\n\tp1min = 0\n\tp2min = 300_000_000\n\t# calculate sizes:\n\t@distroorder.each { |d|\n\t\tif @distrocheck[d].active?\n\t\t\tp1min += @syssizes[d][0]\n\t\t\tp2min += @syssizes[d][1]\n\t\tend\n\t}\n\tp1min = ((p1min / 8192).to_i + 1) * 8192\n\tp2min = ((p2min / 8192).to_i + 1) * 8192\n\tprogress.text = \"Partitioniere USB-Speicherstift\"\n\twhile (Gtk.events_pending?)\n\t\tGtk.main_iteration\n\tend\n\tputs \"Minimal sizes: \" + p1min.to_s + \" \" + p2min.to_s \n\tp1cmd = \"parted -s /dev/\" + @drivelist[@drivecombo.active] + \" unit B mkpart primary fat32 32256 \" + (targetsize - p2min - 1048577).to_s \n\tputs \"Creating part1: \" + p1cmd\n\tsystem p1cmd\n\tp2cmd = \"parted -s /dev/\" + @drivelist[@drivecombo.active] + \" unit B mkpart primary ext2 \" + (targetsize - p2min - 1048576).to_s + \" \" + (targetsize - 1048577).to_s \n\tputs \"Creating part2: \" + p2cmd \n\tsystem p2cmd\n\tsystem(\"parted -s /dev/\" + @drivelist[@drivecombo.active] + \" unit B set 1 lba on\")\n\tsystem(\"parted -s /dev/\" + @drivelist[@drivecombo.active] + \" unit B set 2 boot on\")\n\tsystem(\"cat /usr/share/syslinux/mbr.bin > /dev/\" + @drivelist[@drivecombo.active])\n\tprogress.text = \"Erstelle Dateisystem auf Partition 1\" \n\twhile (Gtk.events_pending?)\n\t\tGtk.main_iteration\n\tend\n\tsystem(\"mkfs.msdos -F32 /dev/\" + @drivelist[@drivecombo.active] + \"1\")\n\tprogress.text = \"Erstelle Dateisystem auf Partition 2\" \n\twhile (Gtk.events_pending?)\n\t\tGtk.main_iteration\n\tend\n\tsystem(\"mkfs.ext4 /dev/\" + @drivelist[@drivecombo.active] + \"2\")\n\tsystem(\"mkdir -p /lesslinux/install/target_part1\")\n\tsystem(\"mount -t vfat /dev/\" + @drivelist[@drivecombo.active] + \"1 /lesslinux/install/target_part1\")\n\tsystem(\"mkdir -p /lesslinux/install/target_part2\")\n\tsystem(\"mount -t ext4 /dev/\" + @drivelist[@drivecombo.active] + \"2 /lesslinux/install/target_part2\")\nend", "def convert(volume, number, part = \"sbr\")\n tmp_imgs_dir = \"tmp_imgs\"\n ext = \"jpg\"\n init_dir = Dir.pwd\n pages_location = \"#{Dir.home}/tmp/volume_#{number}\"\n\n if File.extname(volume) == \".zip\"\n `unzip -d #{pages_location} \"#{volume}\"`\n puts \"Unzipped #{volume}\"\n Dir.chdir(pages_location)\n puts Dir.pwd\n FileUtils.remove_dir(\"__MACOSX\") if Dir.exist?(\"__MACOSX\")\n elsif File.directory?(volume)\n Dir.chdir(volume)\n else\n $stderr.puts \"Image jpgs must be in a directory or zip file.\"\n exit(1)\n end\n\n extracted_dirs = Pathname.new(pages_location)\n .children.select { |c| c.directory? }\n .map { |p| p.to_s }\n until extracted_dirs.empty?\n extracted_dirs.each do |dir_name|\n mv_files_up(dir_name)\n end\n\n extracted_dirs = Pathname.new(pages_location)\n .children.select { |c| c.directory? }\n .map { |p| p.to_s }\n end\n\n Dir.mkdir(tmp_imgs_dir) unless Dir.exist?(tmp_imgs_dir)\n\n imgs = `ls -v *.#{ext}`.split(\"\\n\")\n formatted_img_num = 0\n imgs.each do |img|\n img_dimensions = `identify #{img}`.split(\" \")[2]\n\n # Jojolion colored img_dimensions == \"1773x1400\" or \"1774x1400\"\n # Steel Ball Run img_dimensions == \"1520x1200\"\n if img_dimensions == \"1520x1200\"\n `convert -crop 50%x100% +repage #{img} #{tmp_imgs_dir}/tmp_img.#{ext}`\n\n # Switches image order because manga is designed to be read right to left\n File.rename(\"#{tmp_imgs_dir}/tmp_img-1.#{ext}\", \"#{tmp_imgs_dir}/formatted_img-#{formatted_img_num}.#{ext}\")\n File.rename(\"#{tmp_imgs_dir}/tmp_img-0.#{ext}\", \"#{tmp_imgs_dir}/formatted_img-#{formatted_img_num += 1}.#{ext}\")\n else\n File.rename(img, \"#{tmp_imgs_dir}/formatted_img-#{formatted_img_num}.#{ext}\")\n end\n\n formatted_img_num += 1\n\n\n puts \"Converted #{img}...\"\n end\n\n formatted_imgs = Dir.glob(\"#{tmp_imgs_dir}/formatted_img-*\")\n .sort_by { |f| f.split(\"-\").last.to_i }.join(\" \")\n # formatted_imgs = `ls -v #{tmp_imgs_dir}/formatted_img-*`.split(\"\\n\").join(\" \")\n\n puts \"Converting JoJo volume...\"\n `convert #{formatted_imgs} #{init_dir}/#{part}_volume_#{number}.pdf`\n # puts `ls -v #{tmp_imgs_dir}`\n unless $? == 0\n puts \"Something went wrong with converting the formatted images to a pdf!\"\n return 1\n end\n\n puts \"JoJo volume converted.\"\n Dir.chdir(init_dir)\nend", "def capture_image(source_lpar,mksysb_name,path)\n #Pull mksysb from a NIM client, give it a name and place it in some location on the NIM\n execute_cmd \"nim -o define -t mksysb -F -a server=master -a location=#{path} -a source=#{source_lpar.name} -a mk_image=yes -a mksysb_flags=XAe #{mksysb_name}\"\n \n #Create SPOT resource from this mksysb, giving it a name and a location on the NIM to store it\n extract_spot(mksysb_name) \n end", "def use_data_partitioning\n FFMpegCommand << \"-part\"\n end", "def install_bootloader\n if @use_systemwide_grub_tools\n info(\"Using existing grub tools\")\n tools_dir = '/'\n else\n tools_dir = File.join(File.dirname(__FILE__), \"tools\")\n execute!(\"mkdir -p #{tools_dir}\", false) # Don't be root for this dir\n self.download_bootloader_tools(tools_dir)\n end\n\n esp_part = @partition_layout.find { |p| p.esp }\n raise RuntimeError, \"Missing ESP partition\" if not esp_part\n\n # mount it at some temp location, and write our files to it\n Dir.mktmpdir do |mountdir|\n begin\n grub_part = File.join('/dev/disk/by-label', esp_part.label)\n execute!(\"mount #{grub_part} #{mountdir}\")\n\n boot_dir = File.join(mountdir, 'EFI', 'BOOT')\n execute!(\"mkdir -p #{boot_dir}\")\n\n grub_cfg_filepath = File.join(boot_dir, 'grub.cfg')\n boot_efi_filepath = File.join(boot_dir, 'bootx64.efi')\n\n # Create the bootloader with the embedded configutation file (load.cfg)\n info(\"creating bootx64.efi (with embedded load.cfg)\")\n Tempfile.open('load.cfg') do |f|\n f.puts(load_cfg_contents)\n f.sync; f.fsync # flush ruby buffers and OS buffers\n\n execute!([\n \"#{tools_dir}/usr/bin/grub-mkimage\",\n \"--config=#{f.path}\",\n \"--output=#{boot_efi_filepath}\",\n \"--directory=#{tools_dir}/usr/lib/grub/#{GRUB_ARCHITECTURE}\",\n # core.img needs to know which dir to pick up grub.cfg from\n \"--prefix=\\\"/EFI/BOOT\\\"\",\n \"--format=#{GRUB_ARCHITECTURE}\",\n # modules to bake into the img\n \"efifwsetup efi_gop efi_uga linuxefi\",\n \"ext2 fat part_gpt part_msdos lvm\",\n \"gfxterm gfxterm_background gfxterm_menu test all_video\",\n \"loadenv normal boot configfile linux cat echo search\",\n \"sh quit help reboot datetime\",\n ].join(' '))\n end\n\n unless File.exists?(boot_efi_filepath)\n raise RuntimeError, 'No file output from grub-mkimage'\n end\n ensure\n # Always unmount it\n execute!(\"umount #{mountdir}\")\n end\n end # Dir.mktempdir, mount partition on tempdir\n ensure\n # Clean up temp dir where we downloaded grub tools\n execute!(\"rm -rf #{tools_dir}\") unless @use_systemwide_grub_tools\n end", "def index\n @image_to_parts = ImageToPart.all\n end", "def convert_frames\n MiniMagick.configure do |config|\n config.validate_on_create = false\n end\n\n Dir[\"#{templates_path}/**/*.psd\"].each do |psd|\n resulting_path = psd.gsub('.psd', '.png')\n next if File.exist?(resulting_path)\n\n UI.important \"Converting PSD file '#{psd}'\"\n image = MiniMagick::Image.open(psd)\n\n if psd =~ /iPhone-SE/\n UI.success \"Removing white background 🚫 ⬜️\"\n\n # The iPhone-SE screenshots from April 2016 have\n # 3 layers, a background, a product, and the 'put your image here' layer\n # imagemagick seems to add an additional layer with no label which this the\n # composite of all three. We want to remove the background and composite layer\n good_layers = image.layers.reject do |layer|\n label = layer.details['Properties']['label']\n label.to_s.length == 0 || label =~ /White B/i\n end\n product_layer = good_layers.shift\n\n good_layers.each do |layer|\n product_layer.layers << layer\n end\n\n image = product_layer\n end\n\n if image\n image.format 'png'\n image.trim\n\n image.write(resulting_path)\n else\n UI.error \"Could not parse PSD file at path '#{psd}'\"\n end\n end\n end", "def create_image_tempfiles()\n # {{{\n open_image()\n id = @media_asset.media_asset_id\n @img.write(Aurita.project_path + 'public/assets/tmp/asset_' << id + '_org.jpg')\n @img.write(Aurita.project_path + 'public/assets/tmp/asset_' << id + '_work.jpg')\n @img.resize_to_fit!(@preview_width, @preview_height)\n @img.write(Aurita.project_path + 'public/assets/tmp/asset_' << id + '_show.jpg')\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change partition (configuration, web or code).
def changepartition(partition, filename) baseaddress = PARTITIONS['boot'][START] size = partition[SIZE] partdata = Flashimage.read(filename) length = partdata.size last = partition[SIZE] raise('Input file too large.') if length + 12 > last crc32 = Zlib.crc32(partdata) partdata[length ... last - 12] = "\xff" * (last - length - 12) partdata[last - 12 ... last] = [length, 0x12345678, crc32].pack('V3') filename = "#{File.dirname(FLASHIMAGE)}/#{partition[FILE]}" Flashimage.write(partdata, filename) end
[ "def setPartitionType(settings)\n settings = deep_copy(settings)\n tm = Storage.GetTargetMap\n settings = Builtins.maplist(settings) do |d|\n if Ops.get_symbol(d, \"type\", :x) == :CT_DISK\n mp = Ops.get_integer(\n tm,\n [Ops.get_string(d, \"device\", \"xxx\"), \"max_primary\"],\n 0\n )\n if Ops.greater_than(mp, 0)\n Ops.set(\n d,\n \"partitions\",\n Builtins.maplist(Ops.get_list(d, \"partitions\", [])) do |pe|\n if Builtins.haskey(pe, \"partition_nr\") &&\n !Builtins.haskey(pe, \"partition_type\") &&\n Ops.less_or_equal(\n Ops.get_integer(pe, \"partition_nr\", -1),\n mp\n )\n Ops.set(pe, \"partition_type\", \"primary\")\n end\n deep_copy(pe)\n end\n )\n end\n end\n deep_copy(d)\n end\n Builtins.y2milestone(\"after setPartitionType = %1\", settings)\n deep_copy(settings)\n end", "def set_partition_table(device, partition_table)\n push_data = \"\\\"\" + partition_table.gsub(/\\/dev\\/(s|xv)d[a-z]/, \"#{device}\") + \"\\\"\"\n remote_execute(\"sfdisk -f #{device}\", push_data, nil)\n end", "def partition_device\n Souffle::Log.info \"#{@node.log_prefix} Partitioning the device...\"\n provider.partition(@node)\n end", "def partition(node, iteration=0)\n node.provisioner.partitioned_device\n end", "def set_partition_usage(host, partition, usage)\n self.client.set(\"gh.storage.server.usage.percent.#{host}.#{partition}\", usage.to_s)\n end", "def FSCKPartition(partition)\n if !Mode.test\n detected_fs = Storage.DetectFs(partition)\n if detected_fs == :ext2\n # label, %1 is partition\n out = Builtins.sformat(_(\"Checking partition %1\"), partition)\n UI.OpenDialog(Opt(:decorated), Label(out))\n\n Builtins.y2milestone(\"command: /sbin/e2fsck -y %1\", partition)\n SCR.Execute(\n path(\".target.bash\"),\n Ops.add(\"/sbin/e2fsck -y \", partition)\n )\n\n UI.CloseDialog\n end\n end\n\n nil\n end", "def create_partition\n super\n end", "def add_partition_to_node( tp, node )\n\n @nodes_lists_replicas[node][tp] = ''\n @partitions_lists[tp]['replicas'] ||= {}\n @partitions_lists[tp]['replicas'][node] = ''\n end", "def partition(dev, parts, verbose=false, ids=Array.new)\n if dev == nil or parts == nil then raise \"bad args\" end\n if verbose\n parts.each_index do |i|\n puts \"creating partition #{i} size #{parts[i]}MB\"\n end\n end\n input = create_sfdisk_input(parts, ids)\n\n #get the size of the drive\n cmd = \"{\\n #{input} } | sudo /sbin/sfdisk -uS --force #{dev}; sleep 5;\"\n puts cmd\n shell = SwrShell.new\n return shell.execute(cmd,verbose)\n end", "def SetPartitionFormat(device, format, fs)\n Builtins.y2milestone(\n \"SetPartitionFormat device:%1 format:%2 fs:%3\",\n device,\n format,\n fs\n )\n tmp = fromSymbol(FileSystems.conv_fs, fs)\n Builtins.y2milestone(\"SetPartitionFormat fs:%1\", tmp)\n ret = @sint.changeFormatVolume(device, format, tmp)\n if ret<0\n Builtins.y2error(\"SetPartitionFormat sint ret:%1\", ret)\n end\n UpdateTargetMapDev(device)\n ret == 0\n end", "def partition\n Partition.named(name)\n end", "def set_default_partition(opts)\n opts = check_params(opts,[:partition])\n super(opts)\n end", "def CreatePartition(disk, device, ptype, id, start, len, mby)\n Builtins.y2milestone(\n \"CreatePartition disk:%1 device:%2 ptype:%3 id:%4 start:%5 len:%6 mby:%7\",\n disk,\n device,\n ptype,\n id,\n start,\n len,\n mby\n )\n pt = fromSymbol(@conv_ptype, ptype)\n Builtins.y2milestone(\"CreatePartition type:%1 pt:%2\", ptype, pt)\n ret, cdev = @sint.createPartition(disk, pt, start, len)\n cdev = \"\" if ret<0\n if device != cdev\n Builtins.y2error(\"CreatePartition device:%1 cdev:%2\", device, cdev)\n end\n Builtins.y2error(\"CreatePartition ret %1\", ret) if ret<0\n ret = @sint.changePartitionId(device, id)\n Builtins.y2error(\"CreatePartition ret %1\", ret) if ret<0\n tmp = fromSymbol(@conv_mountby, mby)\n @sint.changeMountBy(device, tmp)\n Builtins.y2milestone(\"CreatePartition sint ret:%1\", ret)\n UpdateTargetMap()\n ret == 0\n end", "def set_active_partition(opts)\n opts = check_params(opts,[:active_partition])\n super(opts)\n end", "def partition_for(document)\n if options[:partition_strategy]\n options[:partition_strategy].call(document)\n else\n 'default'\n end\n end", "def release!(partition)\n zk.delete claim_path(partition), ignore: :no_node\n end", "def SetPartitionMount(device, mp)\n Builtins.y2milestone(\"SetPartitionMount device:%1 mp:%2\", device, mp)\n ret = @sint.changeMountPoint(device, mp)\n if ret<0\n Builtins.y2error(\"SetPartitionMount sint ret:%1\", ret)\n end\n UpdateTargetMapDev(device)\n ret == 0\n end", "def active_partition\n super\n end", "def partition_table(name, scheme)\n raise InvalidSchemeError, scheme if scheme.blank?\n execute(\"ALTER TABLE #{quote_table_name(name)} #{scheme}\")\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load partition file (code, web or configuration).
def loadpart(partname, filename) flashimage = Flashimage.new firmware = Flashimage.read(filename) size = firmware.size offset_signature = size - 10 signature = firmware[offset_signature .. -1] puts("signature: #{signature.inspect}") length, magic, crc32, offset = getblock(partname, firmware, offset_signature) partition = Partition.new(partname) partition.update(firmware[offset ... offset + length]) flashimage.update(partition) flashimage.write end
[ "def getPartition(driveId, partitionIdx)\n currentDrive = getDrive(driveId)\n Builtins.y2milestone(\"Loaded drive '%1'\", currentDrive)\n AutoinstDrive.getPartition(currentDrive, partitionIdx)\n end", "def load(path); end", "def preload_firmware(filename, board_class=Boards::Basys2)\n\n #Compute the relative path to the specified piece of firmware...\n path = File.expand_path(\"#{FirmwarePath}/#{filename}.bit\", __FILE__)\n\n #... read the bitstream file at that path...\n bitfile = DataFormats::Bitstream.from_file(path)\n\n #... and program the file to the connected board.\n board_class.open { |board| board.configure_fpga(bitfile) }\n\n end", "def load_path=(load_path); end", "def load\n @yaml_parts, @ruby_parts = lookup_parts\n @data.clear\n self.yaml_parts_in_loading_order.each do |yaml_part|\n yaml_data = YAML.load_file(yaml_part)\n part_sections = File.basename(yaml_part, '.yml').split('.')\n part_sections.delete_at 0 # delete the 'en' at the beginning\n if part_sections.empty?\n @data.merge! yaml_data\n else\n begin\n target_section = @data[*part_sections]\n raise EntryNotFound unless target_section.respond_to? :merge!\n target_section.merge! yaml_data\n rescue EntryNotFound\n @data[*part_sections] = yaml_data\n end\n end\n end\n \n @ruby_parts.each do |ruby_part|\n Kernel.load ruby_part\n end\n end", "def changepartition(partition, filename)\n\tbaseaddress = PARTITIONS['boot'][START]\t\n\tsize = partition[SIZE]\n\tpartdata = Flashimage.read(filename)\n\tlength = partdata.size\n\tlast = partition[SIZE]\n\traise('Input file too large.') if length + 12 > last\n\tcrc32 = Zlib.crc32(partdata)\n\tpartdata[length ... last - 12] = \"\\xff\" * (last - length - 12)\n\tpartdata[last - 12 ... last] = [length, 0x12345678, crc32].pack('V3')\n\tfilename = \"#{File.dirname(FLASHIMAGE)}/#{partition[FILE]}\"\n\tFlashimage.write(partdata, filename)\nend", "def load\n initialize(File.info(uuid).entity)\n end", "def load!\n return if running?\n @files = YAML.load_file(@persist) if @persist and test(?f, @persist)\n self\n end", "def create\n begin\n # Set the partition (/dev/sdb1), device (/dev/sdb) and alignment (optimal,minimal,none etc.) variables\n partition= resource[:name]\n device=partition[0,(partition.length-1)]\n alignment= resource[:alignment]\n\n # Now we can create the partition\n partitions = parted('-a', resource[:alignment],'--script',device,'mklabel',resource[:part_label],'mkpart', resource[:part_type],resource[:fs_type],resource[:p_begin],resource[:p_end])\n rescue Puppet::ExecutionFailure => e\n false\n end\n end", "def load_storage_system\n data = {\n credentials: { ip_hostname: @new_resource.storage_system },\n name: @new_resource.storage_system\n }\n @item.set_storage_system(load_resource(:StorageSystem, data))\n end", "def read_platform_from_file(path:)\n path.basename.to_s.split('.').first\n end", "def read_launchfile\n eval(File.read('Launchfile'))\nend", "def init(file)\n\t\tbegin\n\t\t\tload file\n\t\trescue => e\n\t\t\traise Disbatch::FailedLoadPluginError, file\n\t\tend\n\tend", "def load_from_filesystem(options)\n return if options[:skip_metadata]\n\n # Load localised data\n ignore_validation = options[:ignore_language_directory_validation]\n Loader.language_folders(options[:metadata_path], ignore_validation).each do |lang_folder|\n language = File.basename(lang_folder)\n (LOCALISED_VERSION_VALUES + LOCALISED_APP_VALUES).each do |key|\n path = File.join(lang_folder, \"#{key}.txt\")\n next unless File.exist?(path)\n\n UI.message(\"Loading '#{path}'...\")\n options[key] ||= {}\n options[key][language] ||= File.read(path)\n end\n end\n\n # Load non localised data\n (NON_LOCALISED_VERSION_VALUES + NON_LOCALISED_APP_VALUES).each do |key|\n path = File.join(options[:metadata_path], \"#{key}.txt\")\n next unless File.exist?(path)\n\n UI.message(\"Loading '#{path}'...\")\n options[key] ||= File.read(path)\n end\n\n # Load trade representative contact information\n options[:trade_representative_contact_information] ||= {}\n TRADE_REPRESENTATIVE_CONTACT_INFORMATION_VALUES.values.each do |option_name|\n path = File.join(options[:metadata_path], TRADE_REPRESENTATIVE_CONTACT_INFORMATION_DIR, \"#{option_name}.txt\")\n next unless File.exist?(path)\n next if options[:trade_representative_contact_information][option_name].to_s.length > 0\n\n UI.message(\"Loading '#{path}'...\")\n options[:trade_representative_contact_information][option_name] ||= File.read(path)\n end\n\n # Load review information\n options[:app_review_information] ||= {}\n REVIEW_INFORMATION_VALUES.values.each do |option_name|\n path = File.join(options[:metadata_path], REVIEW_INFORMATION_DIR, \"#{option_name}.txt\")\n next unless File.exist?(path)\n next if options[:app_review_information][option_name].to_s.length > 0\n\n UI.message(\"Loading '#{path}'...\")\n options[:app_review_information][option_name] ||= File.read(path)\n end\n end", "def get_part_file(p)\n \"#{@file}.part.#{p[:number]}\"\n end", "def load_rakefile(path); end", "def load( dirname )\n\t\t\t@filename= File.join( dirname, \"ticket.yaml\" )\n\t\t\t@idstring = File.basename( dirname )[0..7]\n\t\t\tif File.file?( @filename )\n\t\t\t\t@data = YAML.load_file( @filename ) \n\t\t\tend \n\t\t\tloadComments\n\t\t\tloadAttachments\n\t\tend", "def load_file\n process = Process.new(@processes.count + 1, :running) # Assuming we never remove halted processes from this array..\n @processes << process\n @current_process = process\n @translation[process.id] = []\n\n header_bytes = 3\n bytes = IO.read(file_path).bytes.map { |b| Integer(b) }\n segment_count = bytes.first\n\n puts \"bytes loaded: #{bytes}\"\n puts \"segment_count: #{segment_count}\"\n\n # each segment header is 3 byte, so we keep taking the first 3 bytes as many times as there are segments\n segment_count.times do |seg_num|\n puts \"------new segment---------\"\n header_start = 1 + seg_num * 3\n header = bytes.slice(header_start, header_start + 2)\n type = header[0] >> 7 # shift right by 7 so we get the first bit ... But what is the type used for?\n target_mem_addr = header[0] & 0b01111111 # apply bitwise AND operator because we want to get rid of the first bit\n length = header[1]\n payload_location = 1 + header_bytes * segment_count + header[2]\n payload = bytes.slice(payload_location, length)\n\n puts \"segment_header: #{header.map { |b| b.to_s(2) }}\"\n puts \"segment type: #{type}\"\n puts \"target_mem_addr = #{target_mem_addr.to_s(2)}\"\n puts \"length: #{length}\"\n puts \"payload: #{payload}\"\n\n load_segment_into_memory(process.id, seg_num, target_mem_addr, length, payload)\n puts \"translation: #{@translation}\"\n end\n end", "def storage_load(options)\n @storage[:device] = options['device']\n @storage[:partition] = options['partition']\n @storage[:dir] = options['dir']\n\n part_sub = { '$partition': @storage[:partition] }\n dev_sub = { '$device': @storage[:device] }\n\n storage_parse_cmd('mount', options['mount'], part_sub, mounted: false)\n storage_parse_cmd('unmount', options['unmount'], part_sub, unmount: true)\n storage_parse_cmd('sleep', options['sleep'], dev_sub, awake: false)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load firmware file (code and web).
def loadfw(filename) flashimage = Flashimage.new firmware = Flashimage.read(filename) size = firmware.size offset_signature = size - 10 signature = firmware[offset_signature .. -1] puts("signature: #{signature.inspect}") length, magic, crc32, offset_code = getblock('code', firmware, offset_signature) code = Partition.new('code') code.update(firmware[offset_code ... offset_code + length]) puts code.size length, magic, crc32, offset_web = getblock('web', firmware, offset_code) web = Partition.new('web') puts web.size web.update(firmware[offset_web ... offset_web + length]) flashimage.update(code) flashimage.update(web) flashimage.write end
[ "def preload_firmware(filename, board_class=Boards::Basys2)\n\n #Compute the relative path to the specified piece of firmware...\n path = File.expand_path(\"#{FirmwarePath}/#{filename}.bit\", __FILE__)\n\n #... read the bitstream file at that path...\n bitfile = DataFormats::Bitstream.from_file(path)\n\n #... and program the file to the connected board.\n board_class.open { |board| board.configure_fpga(bitfile) }\n\n end", "def get_firmware\n ensure_client && ensure_uri\n response = @client.rest_get(@data['uri'] + '/firmware')\n @client.response_handler(response)\n end", "def get_firmware\n ensure_client && ensure_uri\n response = @client.rest_get(@data['uri'] + '/firmware')\n @client.response_handler(response)\n end", "def sys_download_fw(url)\n send_to_plug(:system => {:downlod_firmware => {:url => url}})\n end", "def loadpart(partname, filename)\n\tflashimage = Flashimage.new\n\tfirmware = Flashimage.read(filename)\n\tsize = firmware.size\n\toffset_signature = size - 10\n\tsignature = firmware[offset_signature .. -1]\n\tputs(\"signature: #{signature.inspect}\")\n\tlength, magic, crc32, offset = getblock(partname, firmware, offset_signature)\n\tpartition = Partition.new(partname)\n\tpartition.update(firmware[offset ... offset + length])\n\tflashimage.update(partition)\n\tflashimage.write\nend", "def bootcode\n\t\t\t# /vl/bc.jsp?v=0.0.0.10&m=00:19:db:9e:92:91&l=00:00:00:00:00:00&p=00:00:00:00:00:00&h=4\n\t\t\t#\n\t\t\t# Firmware version, e.g.0.0.0.10\n\t\t\t@version = params[:v]\n\n\t\t\t# MAC address\n\t\t\t@serial = params[:m]\n\n\t\t\t# Hardware model 4 == V2 model\n\t\t\t@hardware = params[:h]\n\n\n\t\t\tsend_file Rails.public_path+'/'+'bc-nominal-segabor.bin',\n\t\t\t\t:type => 'application/octet-stream'\n\t\tend", "def pre_soft_load(mod); end", "def pre_hard_load(mod); end", "def load_program_from_file(path)\n data = Array.new\n\n File.open(path, \"rb\") do |f|\n until f.eof?\n data << f.read(2)\n end\n end\n\n @memory = Memory.new data\n @pc = 0\n @stack = Stack.new self\n end", "def load program_binary\n ram[code_start, program_binary.length] = program_binary\n self\n end", "def load(path); end", "def load_hardware_source_md(context, product_name)\n site = context.registers[:site]\n config = site.config\n src_dir = config[\"source\"]\n\n path = File.join(src_dir, 'documentation', 'hardware', product_name, 'index.md')\n File.read(path)\n end", "def load_file(file_path)\n\t\t\tprogram = File.open(file_path) { |f| f.read }\n\t\t\trun program\n\t\tend", "def read filepath\n\t\t\tbin = File.binread(filepath).unpack(\"C*\")\n\t\t\telf_ident = bin[0, ELF_IDENT_SIZE]\n\n\t\t\t# check magic number\n\t\t\tunless is_elf? elf_ident\n\t\t\t\tthrow \"This is not ELF Format File\"\n\t\t\tend\n\n\t\t\t# Check ELF class\n\t\t\tval = elf_ident[ELF_IDENT_OFFSET_CLASS].ord\n\t\t\tcase val\n\t\t\twhen ELF_CLASS_ELF32\n\t\t\t\t@elf_class = ELF_CLASS_ELF32\n\n\t\t\t\t# set Address and Offset size for ELF32\n\t\t\t\t@address_size = ELF_SIZE_ADDR_32\n\t\t\t\t@offset_size = ELF_SIZE_OFFSET_32\n\t\t\twhen ELF_CLASS_ELF64\n\t\t\t\t@elf_class = ELF_CLASS_ELF64\n\n\t\t\t\t# set Address and Offset size for ELF64\n\t\t\t\t@address_size = ELF_SIZE_ADDR_64\n\t\t\t\t@offset_size = ELF_SIZE_OFFSET_64\n\t\t\telse\n\t\t\t\tthrow \"Invalid ELF Class:#{val}\"\n\t\t\tend\n\n\t\t\t# Check Endian\n\t\t\tval = elf_ident[ELF_IDENT_OFFSET_ENDIAN].ord\n\t\t\tcase val\n\t\t\twhen ELF_LITTLE_ENDIAN, ELF_BIG_ENDIAN\n\t\t\t\t@elf_endian = val\n\t\t\telse\n\t\t\t\tthrow \"Invalid ELF Endian:#{val}\"\n\t\t\tend\n\n\t\t\t# Check ELF Format Version\n\t\t\tval = elf_ident[ELF_IDENT_OFFSET_FORMAT_VERSION].ord\n\t\t\tunless val == 1\n\t\t\t\tthrow \"Unsuppoted ELF Format Version:#{val}\"\n\t\t\tend\n\t\t\t@elf_version = val\n\n\t\t\t# Check OS ABI\n\t\t\tval = elf_ident[ELF_IDENT_OFFSET_OS_ABI].ord\n\t\t\tcase val\n\t\t\twhen OS_ABI_UNIX, OS_ABI_LINUX\n\t\t\t\t@os_abi = val\n\t\t\telse\n\t\t\t\tthrow \"Unsuppoted OS ABI Format:#{val}\"\n\t\t\tend\n\n\t\t\t# Check OS ABI Version\n\t\t\t@os_abi_version = elf_ident[ELF_IDENT_OFFSET_OS_ABI_VERSION]\n\n\t\t\t@bin = bin\n\t\t\t@ident = elf_ident\n\n\t\t\tis_little = @elf_endian == ELF_LITTLE_ENDIAN\n\t\t\tcase @elf_class\n\t\t\twhen ELF_CLASS_ELF32\n\t\t\t\t@elf_type = @bin[ELF32_OFFSET_TYPE, ELF_SIZE_HALF_WORD].to_i(is_little)\n\t\t\t\t@elf_machine = @bin[ELF32_OFFSET_MACHINE, ELF_SIZE_HALF_WORD].to_i(is_little)\n\t\t\t\t@elf_version = @bin[ELF32_OFFSET_VERSION, ELF_SIZE_HALF_WORD].to_i(is_little)\n\t\t\t\t@elf_entry = @bin[ELF32_OFFSET_ENTRY, ELF_SIZE_ADDR_32].to_i(is_little)\n\t\t\t\t@elf_program_h_offset = @bin[ELF32_OFFSET_PROGRAM_HEADER, ELF_SIZE_OFFSET_32].to_i(is_little)\n\t\t\t\t@elf_section_h_offset = @bin[ELF32_OFFSET_SECTION_HEADER, ELF_SIZE_OFFSET_32].to_i(is_little)\n\t\t\t\t@elf_flags = @bin[ELF32_OFFSET_FLAGS, ELF_SIZE_WORD].to_i(is_little)\n\t\t\t\t@elf_h_size \t\t= @bin[ELF32_OFFSET_ELF_HEADER_SIZE, ELF_SIZE_HALF_WORD].to_i(is_little)\n\t\t\t\t@elf_program_h_size = @bin[ELF32_OFFSET_PROGRAM_HEADER_SIZE, ELF_SIZE_HALF_WORD].to_i(is_little)\n\t\t\t\t@elf_program_h_num = @bin[ELF32_OFFSET_PROGRAM_HEADER_NUM, ELF_SIZE_HALF_WORD].to_i(is_little)\n\t\t\t\t@elf_section_h_size = @bin[ELF32_OFFSET_SECTION_HEADER_SIZE, ELF_SIZE_HALF_WORD].to_i(is_little)\n\t\t\t\t@elf_section_h_num = @bin[ELF32_OFFSET_SECTION_HEADER_NUM, ELF_SIZE_HALF_WORD].to_i(is_little)\n\t\t\t\t@elf_section_name_idx = @bin[ELF32_OFFSET_SECTION_NAME_IDX, ELF_SIZE_HALF_WORD].to_i(is_little)\n\t\t\twhen ELF_CLASS_ELF64\n\t\t\t\t@elf_type = @bin[ELF64_OFFSET_TYPE, ELF_SIZE_HALF_WORD].to_i(is_little)\n\t\t\t\t@elf_machine = @bin[ELF64_OFFSET_MACHINE, ELF_SIZE_HALF_WORD].to_i(is_little)\n\t\t\t\t@elf_version = @bin[ELF64_OFFSET_VERSION, ELF_SIZE_HALF_WORD].to_i(is_little)\n\t\t\t\t@elf_entry = @bin[ELF64_OFFSET_ENTRY, ELF_SIZE_ADDR_64].to_i(is_little)\n\t\t\t\t@elf_program_h_offset = @bin[ELF64_OFFSET_PROGRAM_HEADER, ELF_SIZE_OFFSET_64].to_i(is_little)\n\t\t\t\t@elf_section_h_offset = @bin[ELF64_OFFSET_SECTION_HEADER, ELF_SIZE_OFFSET_64].to_i(is_little)\n\t\t\t\t@elf_flags = @bin[ELF64_OFFSET_FLAGS, ELF_SIZE_WORD].to_i(is_little)\n\t\t\t\t@elf_h_size \t\t= @bin[ELF64_OFFSET_ELF_HEADER_SIZE, ELF_SIZE_HALF_WORD].to_i(is_little)\n\t\t\t\t@elf_program_h_size = @bin[ELF64_OFFSET_PROGRAM_HEADER_SIZE, ELF_SIZE_HALF_WORD].to_i(is_little)\n\t\t\t\t@elf_program_h_num = @bin[ELF64_OFFSET_PROGRAM_HEADER_NUM, ELF_SIZE_HALF_WORD].to_i(is_little)\n\t\t\t\t@elf_section_h_size = @bin[ELF64_OFFSET_SECTION_HEADER_SIZE, ELF_SIZE_HALF_WORD].to_i(is_little)\n\t\t\t\t@elf_section_h_num = @bin[ELF64_OFFSET_SECTION_HEADER_NUM, ELF_SIZE_HALF_WORD].to_i(is_little)\n\t\t\t\t@elf_section_name_idx = @bin[ELF64_OFFSET_SECTION_NAME_IDX, ELF_SIZE_HALF_WORD].to_i(is_little)\n\t\t\telse\n\t\t\t\tthrow \"Invalid ELF Class #{@elf_class}\"\n\t\t\tend\n\n\t\t\t# create section name - section index map.\n\t\t\tinitialize_section_h_map\n\n\t\t\t# DEBUG\n\t\t\t#show_elf_header\n\n\t\t\tget_program_header\n\t\tend", "def post_soft_load(mod); end", "def wifi_firmware(fetch: true)\n @wifi_firmware ||= begin\n send_message!(Protocol::Device::GetWifiFirmware.new,\n wait_for: Protocol::Device::StateWifiFirmware) do |payload|\n Firmware.new(payload)\n end if fetch\n end\n end", "def load_binary(filename=nil)\n load(filename,List::FORMAT_BINARY)\n end", "def load_file\n data = ''\n #@file = Pathname.new(Gem.loaded_specs['wmap'].full_gem_path).join('data', 'domains')\n @file = Rails.root.join('shared','data','domains')\n file = File.open(@file, 'r')\n file.each_line { |line| data += line }\n file.close\n render plain: data\n end", "def load \n return nil unless FileTest.readable? @filename\n File.open( @filename ) { |f| return Marshal.load(f) }\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /boots/1 GET /boots/1.json
def show @boot = Boot.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @boot } end end
[ "def show\n @boot_size = BootSize.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @boot_size }\n end\n end", "def index\n @boots = Boot.all\n end", "def new\n @boot = Boot.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @boot }\n end\n end", "def show\n @bootstrap = Bootstrap.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @bootstrap }\n end\n end", "def create\n @boot = Boot.new(boot_params)\n\n respond_to do |format|\n if @boot.save\n format.html { redirect_to @boot, notice: 'Boot was successfully created.' }\n format.json { render :show, status: :created, location: @boot }\n else\n format.html { render :new }\n format.json { render json: @boot.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @boot_size = BootSize.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @boot_size }\n end\n end", "def show\n @boot = Boot.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @boot }\n end\n end", "def index\n @testboots = Testboot.all\n end", "def first_boot_content\n first_boot = {}\n first_boot['run_list'] = config[:run_list]\n Chef::JSONCompat.to_json_pretty(first_boot)\n end", "def new\n @bootstrap = Bootstrap.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @bootstrap }\n end\n end", "def index\n @bootstraps = Bootstrap.all\n end", "def index\n @start_bootstraps = StartBootstrap.all\n end", "def get_brandings\n request :get,\n '/v3/brandings.json'\n end", "def update\n respond_to do |format|\n if @boot.update(boot_params)\n format.html { redirect_to @boot, notice: 'Boot was successfully updated.' }\n format.json { render :show, status: :ok, location: @boot }\n else\n format.html { render :edit }\n format.json { render json: @boot.errors, status: :unprocessable_entity }\n end\n end\n end", "def show\n @brakes_system = BrakesSystem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @brakes_system }\n end\n end", "def index\n @bootstraps = Bootstrap.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @bootstraps }\n end\n end", "def create\n @boot_size = BootSize.new(params[:boot_size])\n\n respond_to do |format|\n if @boot_size.save\n format.html { redirect_to @boot_size, notice: 'Boot size was successfully created.' }\n format.json { render json: @boot_size, status: :created, location: @boot_size }\n else\n format.html { render action: \"new\" }\n format.json { render json: @boot_size.errors, status: :unprocessable_entity }\n end\n end\n end", "def show\n render json: MangaBookshelf.find_shelves(params[:id])\n end", "def get_brandings\n request :get, \"/v3/brandings.json\"\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /boots/new GET /boots/new.json
def new @boot = Boot.new respond_to do |format| format.html # new.html.erb format.json { render json: @boot } end end
[ "def new\n @boot_size = BootSize.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @boot_size }\n end\n end", "def create\n @boot = Boot.new(boot_params)\n\n respond_to do |format|\n if @boot.save\n format.html { redirect_to @boot, notice: 'Boot was successfully created.' }\n format.json { render :show, status: :created, location: @boot }\n else\n format.html { render :new }\n format.json { render json: @boot.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @bootstrap = Bootstrap.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @bootstrap }\n end\n end", "def new\n @boot = Boot.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @boot }\n end\n end", "def new\n @newapp = Newapp.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @newapp }\n end\n end", "def new\n @breadcrumb = 'create'\n @app = App.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @app }\n end\n end", "def create\n @boot = Boot.new(params[:boot])\n\n respond_to do |format|\n if @boot.save\n flash[:notice] = 'Boot was successfully created.'\n format.html { redirect_to(@boot) }\n format.xml { render :xml => @boot, :status => :created, :location => @boot }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @boot.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @new_recipe = NewRecipe.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @new_recipe }\n end\n end", "def new\n @baton = Baton.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @baton }\n end\n end", "def new\n @launch = Launch.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @launch }\n end\n end", "def create\n @bootstrap = Bootstrap.new(params[:bootstrap])\n\n respond_to do |format|\n if @bootstrap.save\n format.html { redirect_to @bootstrap, notice: 'Bootstrap was successfully created.' }\n format.json { render json: @bootstrap, status: :created, location: @bootstrap }\n else\n format.html { render action: \"new\" }\n format.json { render json: @bootstrap.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @monkey = Monkey.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @monkey }\n end\n end", "def new\n @bread = Bread.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @bread }\n end\n end", "def create\n @boot_size = BootSize.new(params[:boot_size])\n\n respond_to do |format|\n if @boot_size.save\n format.html { redirect_to @boot_size, notice: 'Boot size was successfully created.' }\n format.json { render json: @boot_size, status: :created, location: @boot_size }\n else\n format.html { render action: \"new\" }\n format.json { render json: @boot_size.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @cook = Cook.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @cook }\n end\n end", "def new\n @lunch = Lunch.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @lunch }\n end\n end", "def new\n @startup = Startup.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @startup }\n end\n end", "def new\n @stalking = Stalking.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @stalking }\n end\n end", "def create\n @testboot = Testboot.new(testboot_params)\n\n respond_to do |format|\n if @testboot.save\n format.html { redirect_to @testboot, notice: 'Testboot was successfully created.' }\n format.json { render :show, status: :created, location: @testboot }\n else\n format.html { render :new }\n format.json { render json: @testboot.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PUT /boots/1 PUT /boots/1.json
def update @boot = Boot.find(params[:id]) respond_to do |format| if @boot.update_attributes(params[:boot]) flash[:success] = "Updated successfully " format.html { redirect_to boots_path, notice: 'Boot was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @boot.errors, status: :unprocessable_entity } end end end
[ "def update\n respond_to do |format|\n if @boot.update(boot_params)\n format.html { redirect_to @boot, notice: 'Boot was successfully updated.' }\n format.json { render :show, status: :ok, location: @boot }\n else\n format.html { render :edit }\n format.json { render json: @boot.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @boot = Boot.find(params[:id])\n\n respond_to do |format|\n if @boot.update_attributes(params[:boot])\n flash[:notice] = 'Boot was successfully updated.'\n format.html { redirect_to(@boot) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @boot.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @boot_size = BootSize.find(params[:id])\n\n respond_to do |format|\n if @boot_size.update_attributes(params[:boot_size])\n format.html { redirect_to @boot_size, notice: 'Boot size was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @boot_size.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @bootstrap = Bootstrap.find(params[:id])\n\n respond_to do |format|\n if @bootstrap.update_attributes(params[:bootstrap])\n format.html { redirect_to @bootstrap, notice: 'Bootstrap was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @bootstrap.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @start_bootstrap.update(start_bootstrap_params)\n format.html { redirect_to @start_bootstrap, notice: \"Start bootstrap was successfully updated.\" }\n format.json { render :show, status: :ok, location: @start_bootstrap }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @start_bootstrap.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @boot = Boot.new(boot_params)\n\n respond_to do |format|\n if @boot.save\n format.html { redirect_to @boot, notice: 'Boot was successfully created.' }\n format.json { render :show, status: :created, location: @boot }\n else\n format.html { render :new }\n format.json { render json: @boot.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @testboot.update(testboot_params)\n format.html { redirect_to @testboot, notice: 'Testboot was successfully updated.' }\n format.json { render :show, status: :ok, location: @testboot }\n else\n format.html { render :edit }\n format.json { render json: @testboot.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @bootstrap.update(bootstrap_params)\n format.html { redirect_to @bootstrap, notice: 'Bootstrap was successfully updated.' }\n format.json { render :show, status: :ok, location: @bootstrap }\n else\n format.html { render :edit }\n format.json { render json: @bootstrap.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @boot_test.update(boot_test_params)\n format.html { redirect_to @boot_test, notice: 'Boot test was successfully updated.' }\n format.json { render :show, status: :ok, location: @boot_test }\n else\n format.html { render :edit }\n format.json { render json: @boot_test.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @strap.update(strap_params)\n format.html { redirect_to @strap, notice: \"Strap was successfully updated.\" }\n format.json { render :show, status: :ok, location: @strap }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @strap.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @bootstrap = Bootstrap.find(params[:id])\n\n respond_to do |format|\n if @bootstrap.update_attributes(params[:bootstrap])\n @bootstrap.process\n flash[:notice] = 'Bootstrap was successfully updated.'\n format.html { redirect_to(@bootstrap) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @bootstrap.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @boot_size = BootSize.new(params[:boot_size])\n\n respond_to do |format|\n if @boot_size.save\n format.html { redirect_to @boot_size, notice: 'Boot size was successfully created.' }\n format.json { render json: @boot_size, status: :created, location: @boot_size }\n else\n format.html { render action: \"new\" }\n format.json { render json: @boot_size.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @zeilboot = Zeilboot.find(params[:id])\n\n respond_to do |format|\n if @zeilboot.update_attributes(params[:zeilboot])\n format.html { redirect_to(@zeilboot, :notice => 'Zeilboot was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @zeilboot.errors, :status => :unprocessable_entity }\n end\n end\n end", "def show\n @boot = Boot.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @boot }\n end\n end", "def destroy\n @boot = Boot.find(params[:id])\n @boot.destroy\n\n respond_to do |format|\n format.html { redirect_to(boots_url) }\n format.xml { head :ok }\n end\n end", "def mark_bootstrapped\n @container = current_node.containers.exists.find_by(\n hostname: params[:hostname],\n status: 'BOOTSTRAP_STARTED'\n )\n @container.update_status('BOOTSTRAPPED')\n render json: ::Api::V2::Node::ContainerSerializer.new(@container).to_h\n end", "def destroy\n @boot.destroy\n respond_to do |format|\n format.html { redirect_to boots_url, notice: 'Boot was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @boot = Boot.find(params[:id])\n @boot.destroy\n\n\n respond_to do |format|\n flash[:success] = \"Deleted successfully \"\n format.html { redirect_to boots_url }\n format.json { head :no_content }\n end\n end", "def create\n @boot = Boot.new(params[:boot])\n\n respond_to do |format|\n if @boot.save\n flash[:notice] = 'Boot was successfully created.'\n format.html { redirect_to(@boot) }\n format.xml { render :xml => @boot, :status => :created, :location => @boot }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @boot.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /boots/1 DELETE /boots/1.json
def destroy @boot = Boot.find(params[:id]) @boot.destroy respond_to do |format| flash[:success] = "Deleted successfully " format.html { redirect_to boots_url } format.json { head :no_content } end end
[ "def destroy\n @boot.destroy\n respond_to do |format|\n format.html { redirect_to boots_url, notice: 'Boot was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @boot = Boot.find(params[:id])\n @boot.destroy\n\n respond_to do |format|\n format.html { redirect_to(boots_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @bootstrap = Bootstrap.find(params[:id])\n @bootstrap.destroy\n\n respond_to do |format|\n format.html { redirect_to bootstraps_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @boot_size = BootSize.find(params[:id])\n @boot_size.destroy\n\n respond_to do |format|\n format.html { redirect_to boot_sizes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @testboot.destroy\n respond_to do |format|\n format.html { redirect_to testboots_url, notice: 'Testboot was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @zeilboot = Zeilboot.find(params[:id])\n @zeilboot.destroy\n\n respond_to do |format|\n format.html { redirect_to(zeilboots_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @boot_test.destroy\n respond_to do |format|\n format.html { redirect_to boot_tests_url, notice: 'Boot test was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @bootstrap.destroy\n respond_to do |format|\n format.html { redirect_to bootstraps_url, notice: 'Bootstrap was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @start_bootstrap.destroy\n respond_to do |format|\n format.html { redirect_to start_bootstraps_url, notice: \"Start bootstrap was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @bootstrap = Bootstrap.find(params[:id])\n @bootstrap.destroy\n\n respond_to do |format|\n format.html { redirect_to(bootstraps_url) }\n format.xml { head :ok }\n end\n end", "def delete\n Client.delete(\"/kits/#{@id}\")\n end", "def cmd_delete argv\n setup argv\n uuid = @hash['uuid']\n response = @api.delete(uuid)\n msg response\n return response\n end", "def delete_app name\n try_json delete(\"/app/#{name}\")\n end", "def destroy\n @beacon = Beacon.find(params[:id])\n @beacon.destroy\n\n respond_to do |format|\n format.html { redirect_to beacons_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @strap.destroy\n respond_to do |format|\n format.html { redirect_to straps_url, notice: \"Strap was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @latstraps1.destroy\n respond_to do |format|\n format.html { redirect_to latstraps1s_url, notice: 'Latstraps1 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete(id)\n request(:delete, \"/recipes/#{id}.json\")\n end", "def delete_aos_version(args = {}) \n delete(\"/aosversions.json/#{args[:aosVersionId]}\", args)\nend", "def delete_tenant_circle(args = {}) \n delete(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /daw_promos GET /daw_promos.json
def index @daw_promos = DawPromo.all end
[ "def show\n @promocion = Promocion.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @promocion }\n end\n end", "def show\n @promocion = Promocion.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n #format.json { render json: @promocion }\n end\n end", "def promos_sponsored\n url = URI.parse( @site + \"/1/promos/sponsored\")\n req = Net::HTTP::Get.new(url.path)\n @response = Net::HTTP.start(url.host, url.port) {|http|\n http.request(req)\n }\n @promos = JSON.parse(@response.body())[\"promos\"] \n end", "def index\n @daw_matricula_promos = DawMatriculaPromo.all\n end", "def promos_show(current_user, id)\n @access_token = prepare_access_token(current_user.token, current_user.secret)\n @response = @access_token.request(:post, @site + \"/1/promos/show\", :id => id)\n @promo = JSON.parse(@response.body())\n end", "def show\n @promo = Promo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @promo }\n end\n end", "def show\n @equipo_promocion = EquipoPromocion.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @equipo_promocion }\n end\n end", "def show\n @promotion_demotion = PromotionDemotion.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @promotion_demotion }\n end\n end", "def index\n @daw_curso_promos = DawCursoPromo.all\n end", "def show\n @promos = Promos.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @promos }\n end\n end", "def show\n @admin_promo = Admin::Promo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @admin_promo }\n end\n end", "def index\n @equipo_promocions = EquipoPromocion.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @equipo_promocions }\n end\n end", "def show\n @gymnasium = Gymnasium.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gymnasium }\n end\n end", "def show\n @moresmallweponinfo = Moresmallweponinfo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @moresmallweponinfo }\n end\n end", "def show\n @material_apoyo = MaterialApoyo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @material_apoyo }\n end\n end", "def index\n @memos = user_capabilities(Memo, {:manager => true})\n # puts @memos.to_yaml\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @memos }\n end\n end", "def show\n @rpm = Rpm.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @rpm }\n end\n end", "def show\n @presynaptic_terminal = PresynapticTerminal.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @presynaptic_terminal }\n end\n end", "def index\n @print_media = PrintMedium.order(\"updated_at DESC\").all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @print_media }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /daw_promos POST /daw_promos.json
def create @daw_promo = DawPromo.new(daw_promo_params) respond_to do |format| if @daw_promo.save format.html { redirect_to @daw_promo, notice: 'Daw promo was successfully created.' } format.json { render :show, status: :created, location: @daw_promo } else format.html { render :new } format.json { render json: @daw_promo.errors, status: :unprocessable_entity } end end end
[ "def create\n @daw_matricula_promo = DawMatriculaPromo.new(daw_matricula_promo_params)\n\n respond_to do |format|\n if @daw_matricula_promo.save\n format.html { redirect_to @daw_matricula_promo, notice: 'Daw matricula promo was successfully created.' }\n format.json { render :show, status: :created, location: @daw_matricula_promo }\n else\n format.html { render :new }\n format.json { render json: @daw_matricula_promo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @prom_env = PromEnv.new(prom_env_params)\n\n respond_to do |format|\n if @prom_env.save\n format.html { redirect_to @prom_env, notice: 'Prom env was successfully created.' }\n format.json { render :show, status: :created, location: @prom_env }\n else\n format.html { render :new }\n format.json { render json: @prom_env.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @promocion = Promocion.new(params[:promocion])\n\n respond_to do |format|\n if @promocion.save\n format.html { redirect_to @promocion, notice: 'Promocion was successfully created.' }\n format.json { render json: @promocion, status: :created, location: @promocion }\n else\n format.html { render action: \"new\" }\n format.json { render json: @promocion.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @promocion = Promocion.new(params[:promocion])\n\n respond_to do |format|\n if @promocion.save\n format.html { redirect_to @promocion, :notice => 'Promocion was successfully created.' }\n format.json { render json: @promocion, status: :created, location: @promocion }\n else\n format.html { render :action => \"new\" }\n format.json { render json: @promocion.errors }\n end\n end\n end", "def create\n @promos = Promos.new(params[:promos])\n\n respond_to do |format|\n if @promos.save\n flash[:notice] = 'Promos was successfully created.'\n format.html { redirect_to(@promos) }\n format.xml { render :xml => @promos, :status => :created, :location => @promos }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @promos.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @promocion = Promocion.new(params[:promocion])\n\n respond_to do |format|\n if @promocion.save\n format.html { redirect_to @promocion, notice: 'Promocion creada.' }\n format.json { render json: @promocion, status: :created, location: @promocion }\n else\n format.html { render action: \"new\" }\n format.json { render json: @promocion.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @equipo_promocion = EquipoPromocion.new(params[:equipo_promocion])\n\n respond_to do |format|\n if @equipo_promocion.save\n format.html { redirect_to @equipo_promocion, notice: 'Equipo promocion was successfully created.' }\n format.json { render json: @equipo_promocion, status: :created, location: @equipo_promocion }\n else\n format.html { render action: \"new\" }\n format.json { render json: @equipo_promocion.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @admin_promo = Admin::Promo.new(params[:admin_promo])\n\n respond_to do |format|\n if @admin_promo.save\n format.html { redirect_to @admin_promo, notice: 'Promo was successfully created.' }\n format.json { render json: @admin_promo, status: :created, location: @admin_promo }\n else\n format.html { render action: \"new\" }\n format.json { render json: @admin_promo.errors, status: :unprocessable_entity }\n end\n end\n end", "def scan_create(uuid, pid, name, targets)\n payload = {\n :uuid => uuid, \n :settings => {\n :policy_id => pid, \n :name => name,\n #:description => description, \n :use_dashboard => \"true\",\n :text_targets => targets,\n },\n :json => 1\n }.to_json\n http_post(:uri=>\"/scans\", :body=>payload, :fields=>x_cookie, :ctype=>'application/json')\n end", "def create\n @promocion_evento = PromocionEvento.new(promocion_evento_params)\n\n respond_to do |format|\n if @promocion_evento.save\n format.html { redirect_to @promocion_evento, notice: 'Promocion evento was successfully created.' }\n format.json { render :show, status: :created, location: @promocion_evento }\n else\n format.html { render :new }\n format.json { render json: @promocion_evento.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @power_order = PowerOrder.new(power_order_params)\n @power_order.save\n render json: @power_order\n end", "def create\n @daw_curso_promo = DawCursoPromo.new(daw_curso_promo_params)\n\n respond_to do |format|\n if @daw_curso_promo.save\n format.html { redirect_to @daw_curso_promo, notice: 'Daw curso promo was successfully created.' }\n format.json { render :show, status: :created, location: @daw_curso_promo }\n else\n format.html { render :new }\n format.json { render json: @daw_curso_promo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @wod = Wod.new(wod_params)\n\n if @wod.save\n render json: @wod, status: :created\n else\n render json: @wod.errors, status: :unprocessable_entity\n end\n end", "def index\n @daw_promos = DawPromo.all\n end", "def create\n @promocao = Promocao.new(params[:promocao])\n\n respond_to do |format|\n if @promocao.save\n format.html { redirect_to(@promocao, :notice => 'Promocção criada com sucesso!') }\n format.xml { render :xml => @promocao, :status => :created, :location => @promocao }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @promocao.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @gymnasium = Gymnasium.new(params[:gymnasium])\n\n respond_to do |format|\n if @gymnasium.save\n format.html { redirect_to @gymnasium, notice: 'Gymnasium was successfully created.' }\n format.json { render json: @gymnasium, status: :created, location: @gymnasium }\n else\n format.html { render action: \"new\" }\n format.json { render json: @gymnasium.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @admin_promo = Admin::Promo.new(admin_promo_params)\n\n respond_to do |format|\n if @admin_promo.save\n format.html { redirect_to session['previous_url'] || admin_promos_path, notice: 'Promozioni è stato creato con successo.' }\n format.json { render :show, status: :created, location: @admin_promo }\n else\n format.html { render :new }\n format.json { render json: @admin_promo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @promotion_demotion = PromotionDemotion.new(params[:promotion_demotion])\n\n respond_to do |format|\n if @promotion_demotion.save\n format.html { redirect_to :back, notice: 'Promotion demotion was successfully created.' }\n format.json { render json: @promotion_demotion, status: :created, location: @promotion_demotion }\n else\n format.html { render action: \"new\" }\n format.json { render json: @promotion_demotion.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @pagos_promocion = PagosPromocion.new(pagos_promocion_params)\n\n respond_to do |format|\n if @pagos_promocion.save\n format.html { redirect_to @pagos_promocion, notice: 'Pagos promocion was successfully created.' }\n format.json { render :show, status: :created, location: @pagos_promocion }\n else\n format.html { render :new }\n format.json { render json: @pagos_promocion.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove an attribute for the given key.
def delete(key) removeAttribute(key.to_s) end
[ "def delete_attribute(key)\n attr = @attributes.get_attribute(key)\n attr.remove unless attr.nil?\n end", "def unset_attribute (key)\n OpenWFE.unset_attribute(@attributes, key)\n end", "def removeAttribute(key)\n\t\tif hasAttribute(key)\n\t\t\t@attributes.delete(key)\n\t\t\treturn 1\n\t\telse\n\t\t\treturn 0\n\t\tend\n\tend", "def remove_attribute(name); end", "def remove_attr(attribute)\n attributes.delete(attribute)\n known_attributes.delete(attribute)\n end", "def destroy_key! attribute, key\n destroy_key(attribute, key).save\n end", "def remove_dependency_attributes(key)\n @dependency_attributes.delete(key)\n end", "def remove_attr(name); end", "def remove_property(key)\n end", "def remove_attribute(entities, path, attribute)\n entities.each{ |entity|\n dict = find_dictionary(entity, path)\n next warn(\"AttributeInspector: dictionary `#{path.inspect}` not found for entity #{entity}\") unless dict\n dict.delete_key(attribute)\n }\n end", "def delete(key)\n attribute = key.to_sym\n results.delete(attribute)\n end", "def remove_attribute(name)\n @attributes.delete(name)\n end", "def remove_attribute(name)\n @attributes.delete(name)\n end", "def remove_attribute(attribute)\n sa = standard_attribute(attribute)\n # if the attribute is local, then delete it, otherwise filter out the superclass attribute\n sp = @local_prop_hash.delete(sa)\n if sp then\n # clear the inverse, if any\n clear_inverse(sp)\n # remove from the mandatory attributes, if necessary\n @local_mndty_attrs.delete(sa)\n # remove from the attribute => metadata hash\n @local_std_prop_hash.delete_if { |aliaz, pa| pa == sa }\n else\n # Filter the superclass hashes.\n anc_prop_hash = @prop_hash.components[1]\n @prop_hash.components[1] = anc_prop_hash.filter_on_key { |pa| pa != attribute }\n anc_alias_hash = @alias_std_prop_map.components[1]\n @alias_std_prop_map.components[1] = anc_alias_hash.filter_on_key { |pa| pa != attribute }\n end\n logger.debug { \"Removed the #{qp} #{attribute} property.\" }\n end", "def remove(attribute)\n value = get(attribute)\n _error(Unisys.removexattr(@path, attribute, _follow_symlinks_option()))\n value\n end", "def remove(attribute)\n value = get(attribute)\n _error(Raw.removexattr(@path, attribute, _follow_symlinks_option()))\n value\n end", "def delete_attribute(attr_name)\n debug{\"Attributes#delete_attribute(#{attr_name.inspect})\"}\n set_attribute(attr_name, nil)\n end", "def remove_key(key)\n request(:remove_key, 'Key' => key)\n end", "def delete_override_attribute(key)\n delete_attribute(key, :override)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve all the attribute names (keys) from the servlet request. like Hashkeys
def keys getAttributeNames.to_a end
[ "def attribute_keys\n @attributes.keys\n end", "def attr_keys\n attributes.keys[0..-3]\n end", "def attribute_names\n result = attribute_declarations.keys.collect{|sym| sym.to_s}\n end", "def keys\n @attributes.keys\n end", "def allattrs\n raise NotImplementedError, \"allattrs() - return all attribute names in order - probably not used master side\"\n # key_attributes | (parameters & [:provider]) | properties.collect { |property| property.name } | parameters | metaparams\n end", "def attr_keys\n\t\treturn attr_keys_in @current_node\n\tend", "def attribute_names\n @attributes.keys.sort\n end", "def attribute_names\n @attributes.keys.sort\n end", "def get_array_of_symbolic_keys\n # getting array of keys (in symbol form)\n all_fields = self.attributes.keys.map do |key|\n key.to_sym;\n end\n return all_fields\n end", "def vendor_all_attribute_names\n return ATTRIBUTES.values\n end", "def instance_attribute_keys\n result = lookup_metadata \"instance\", \"attributes/\"\n result.nil? ? nil : result.split\n end", "def keys(model)\n model.attributes.keys\n end", "def attr_keys_in(node)\n\t\treturn is_valid(node) ? node.keys : nil\n\tend", "def defined_attribute_names\n (defined_attributes || {}).keys\n end", "def attribute_names; end", "def attribute_titles\n attribute_names.map {|f| f.to_s.capitalize.sub(/$/, \":\").gsub(/_/, \" \") }\n end", "def attributes_from_data\n data.first.keys\n end", "def namevar_attributes(context)\n context.type.attributes.select { |_attribute, properties| properties[:behaviour] == :namevar }.keys\n end", "def user_keys\n all_keys = params[:user].keys\n all_keys.collect do |key|\n next if key == \"addresses_attributes\"\n key\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterate over every attribute name/value pair from the servlet request. like Hasheach
def each getAttributeNames.each { |name| yield(name, getAttribute(name)) } end
[ "def each\n if block_given?\n attribute_names.each {|a|\n attr_name,values = a,self[a]\n yield attr_name, values\n }\n end\n end", "def each # :yields: attribute-name, data-values-array\n if block_given?\n attribute_names.each {|a|\n attr_name,values = a,self[a]\n yield attr_name, values\n }\n end\n end", "def each_attribute(&block)\n _attrs.each do |attr|\n block.call(attr, send(attr))\n end\n end", "def each_attribute(&block)\n attributes.each_attribute(&block)\n end", "def each_attribute_pair(&block)\n @attributes.each_pair do |name, value|\n block.call(name, value)\n end\n end", "def each\n attribute_nodes.each { |node|\n yield [node.node_name, node.value]\n }\n end", "def each\n attribute_nodes.each do |node|\n yield [node.node_name, node.value]\n end\n end", "def each_attr_value # :yields: attr_name, attr_value\n values = _dump_data\n self.class.shadow_attrs.each_with_index do |attr, i|\n yield attr.var.to_s, values[i]\n end\n instance_variables.each do |ivar|\n yield ivar[1..-1], instance_variable_get(ivar)\n end\n end", "def each_attribute(&block)\n return attributes_enumerator if block.nil?\n\n attributes_enumerator.each(&block)\n end", "def parse_attributes\n @xml.attributes.each do |key, value|\n self.send(key + '=', value) if self.respond_to? key\n end\n end", "def attributes\n attributes = Lib::Attributes::Parser.new\n yield attributes\n _form_attributes.deep_merge!(attributes.retrieve)\n define_attribute_read_and_write_methods\n end", "def each_attribute(global = true, &b)\n attrs = @node_attributes.to_h\n if global\n attrs = pg.node.to_h.merge attrs\n end\n attrs.each do |k,v|\n yield(k,v)\n end\n end", "def attributs()\n if block_given?\n rados_getxattrs.each { |key,value| \n yield key,value\n }\n else\n return rados_getxattrs\n end\n \n end", "def allattrs\n raise NotImplementedError, \"allattrs() - return all attribute names in order - probably not used master side\"\n # key_attributes | (parameters & [:provider]) | properties.collect { |property| property.name } | parameters | metaparams\n end", "def kwattr_values(attribute_name); end", "def attributes(*attrs)\n @safe_attributes ||= []\n\n attrs.each do |attr_name|\n name = underscore(attr_name.to_s).to_sym\n\n attr_accessor name\n @safe_attributes << name\n end\n end", "def attributes *attr_names\n @attribute_names ||= Set.new\n\n attr_names.each { |attr_name| @attribute_names << attr_name.intern }\n end", "def attributes=(value)\n return unless value.respond_to?(:keys)\n value.keys.each do |key|\n if respond_to?(assignment = \"#{key}=\".to_sym)\n send(assignment,value[key])\n end\n end\n end", "def attribute_filtering_params\n params[:attr] ? params[:attr].map(&:to_sym) : nil\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve all the attribute names (keys) from the session. like Hashkeys
def keys getAttributeNames.to_a end
[ "def keys\n @attributes.keys\n end", "def attribute_keys\n @attributes.keys\n end", "def attr_keys\n attributes.keys[0..-3]\n end", "def attribute_names\n result = attribute_declarations.keys.collect{|sym| sym.to_s}\n end", "def attr_keys\n\t\treturn attr_keys_in @current_node\n\tend", "def keys(model)\n model.attributes.keys\n end", "def get_array_of_symbolic_keys\n # getting array of keys (in symbol form)\n all_fields = self.attributes.keys.map do |key|\n key.to_sym;\n end\n return all_fields\n end", "def instance_attribute_keys\n result = lookup_metadata \"instance\", \"attributes/\"\n result.nil? ? nil : result.split\n end", "def attribute_names\n @attributes.keys.sort\n end", "def attribute_names\n @attributes.keys.sort\n end", "def attribute_names; end", "def vendor_all_attribute_names\n return ATTRIBUTES.values\n end", "def loaded_attributes\n loaded_attributes_hash.keys\n end", "def list_keys()\n # TODO\n end", "def keys\n list = []\n each_key{|key| list << key}\n list\n end", "def keys\n data.keys\n end", "def allattrs\n raise NotImplementedError, \"allattrs() - return all attribute names in order - probably not used master side\"\n # key_attributes | (parameters & [:provider]) | properties.collect { |property| property.name } | parameters | metaparams\n end", "def attributes_from_data\n data.first.keys\n end", "def keys\n dict.keys\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterate over every attribute name/value pair from the session. like Hasheach
def each getAttributeNames.each { |name| yield(name, getAttribute(name)) } end
[ "def each_attr_value # :yields: attr_name, attr_value\n values = _dump_data\n self.class.shadow_attrs.each_with_index do |attr, i|\n yield attr.var.to_s, values[i]\n end\n instance_variables.each do |ivar|\n yield ivar[1..-1], instance_variable_get(ivar)\n end\n end", "def each_persistent_attr_value # :yields: attr_name, attr_value\n values = _dump_data\n psa = self.class.shadow_attrs.select {|attr| attr.persists}\n psa.each_with_index do |attr, i|\n yield attr.var.to_s, values[i]\n end\n instance_variables.each do |ivar|\n yield ivar[1..-1], instance_variable_get(ivar)\n end\n end", "def session_attributes(attributes, merge)\n rewrite = true\n unless merge\n @resp[:sessionAttributes] = {}\n rewrite = false\n end\n attributes.each { |k, v| session_attribute(k, v, rewrite) }\n end", "def each\n if block_given?\n attribute_names.each {|a|\n attr_name,values = a,self[a]\n yield attr_name, values\n }\n end\n end", "def each_attribute(global = true, &b)\n attrs = @node_attributes.to_h\n if global\n attrs = pg.node.to_h.merge attrs\n end\n attrs.each do |k,v|\n yield(k,v)\n end\n end", "def each # :yields: attribute-name, data-values-array\n if block_given?\n attribute_names.each {|a|\n attr_name,values = a,self[a]\n yield attr_name, values\n }\n end\n end", "def kwattr_values(attribute_name); end", "def each\n attribute_nodes.each { |node|\n yield [node.node_name, node.value]\n }\n end", "def each\n attribute_nodes.each do |node|\n yield [node.node_name, node.value]\n end\n end", "def load_attributes\n\n # Set instance variable for each attribute.\n load_attributes_to_hash.each_pair do |key, value|\n instance_variable_set(\"@\" + key.to_s, value)\n end\n\n nil\n\n end", "def each_attribute(&block)\n attributes.each_attribute(&block)\n end", "def each_attribute(&block)\n return attributes_enumerator if block.nil?\n\n attributes_enumerator.each(&block)\n end", "def parse_attributes\n @xml.attributes.each do |key, value|\n self.send(key + '=', value) if self.respond_to? key\n end\n end", "def each_attribute_pair(&block)\n @attributes.each_pair do |name, value|\n block.call(name, value)\n end\n end", "def attributes\n @attributes ||= attribute_names.inject({}) do |hash, name|\n attribute_values = saml.xpath(\"//saml:Attribute[@Name='#{name}']/saml:AttributeValue/text()\")\n hash[name] = attribute_values.length > 1 ? attribute_values.collect(&:to_s) : attribute_values.to_s\n hash\n end\n end", "def attr_values\n @attr_values ||= {}\n end", "def get_attributes\n SpaceMissions::Mission.all.each do |mission|\n doc = Nokogiri::HTML(open(mission.url))\n mission.name = doc.css('.media_feature_title').text.strip\n #from fast_facts box\n attributes = doc.css('ul.fast_facts li')\n attributes.each do |el|\n @el = el\n @kv = el.children.children.text.split(\":\")\n @key = @kv[0].downcase.gsub(\" \", \"_\")\n format_keys_and_values\n mission.send(\"#{@key}=\", @value)\n end #second do\n end #first do\n end", "def allattrs\n raise NotImplementedError, \"allattrs() - return all attribute names in order - probably not used master side\"\n # key_attributes | (parameters & [:provider]) | properties.collect { |property| property.name } | parameters | metaparams\n end", "def attributes=(value)\n return unless value.respond_to?(:keys)\n value.keys.each do |key|\n if respond_to?(assignment = \"#{key}=\".to_sym)\n send(assignment,value[key])\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
codewars kata: colour association
def colour_association(array) array.map{|pair| Hash[pair.first, pair.last]} end
[ "def vary_colors; end", "def scan_for_colors; end", "def colour_changer(key)\n @@colours = [key]\n end", "def color_id; end", "def insert_color_flip\n if @left.red? and @right.red?\n color_flip\n else\n self\n end\n end", "def colour_graoh(colors, graph)\n graph.nodes.each do |node|\n \n all_neighbouring_colors = []\n \n node.neighbours.each do |neighbour|\n all_neighbouring_colors << neighbour.color if !all_neighbouring_colors.include?(neighbour.color)\n end\n \n colors.each do |color|\n node.color = color if !all_neighbouring_colors.include?(color)\n break\n end\nend", "def hue_and_chroma(color); end", "def force_colors=(_arg0); end", "def c_color_pairs\n @@c_pairs ||= { [nil, nil] => 0 }\n end", "def add_color\n if !color\n self.color = %w(\n #000000 #0000FF #00FF00 #FF0000 #FFFF00 #9900CC\n #CC0066 #00FFFF #FF00FF #C0C0C0 #00008B #FFD700\n #FFA500 #FF1493 #FF00FF #F0FFFF #EE82EE #D2691E\n #C0C0C0 #A52A2A #9ACD32 #9400D3 #8B008B #8B0000\n #87CEEB #808080 #800080 #008B8B #006400\n ).sample\n end\n end", "def vary_colors=(v); end", "def guess_color(r,g,b)\n my_color = \"unknown\"\n hue = self.color_intensity(r,g,b)\n percent=hue\n \n return my_color =\"red\" if ( r > 200 and g < 50 and b <50 ) #red\n \n return my_color =\"jtarget_yellow\" if ( \n ( r > 117 and g > 117 and b < 50 ) and\n ( (r == g) or ( ( (g - 50) > b) and ( ( r - 50) > b ) )) \n ) #yellow\n \n return my_color =\"blue\" if ( r < 120 and b > 198) #blue\n \n return my_color =\"white_icon\" if ( r>160 and g> 100 and b > 150 ) #white\n \n return my_color =\"black\" if ( r < 40 and g < 40 and b < 40 ) #black\n \n return my_color =\"blue_speed\" if ( \n ( r> 65 and r<145) and ( g > 124 and g < 155) and ( b > 155 and b < 200 )\n ) \n return my_color =\"grey_speed\" if ( \n ( r> 65 and r<190) and ( g > 65 and g < 190) and ( b > 65 and b < 190 ) and \n ( \n ( hue > (r - 5)) and ( hue > (g - 5)) and (hue > (b - 5 )) \n ) \n )\n #my_color = \"#{my_color}:#{hue}\"\n return my_color\n end", "def test c1,c2\n puts \"#{c1.contraste(c2)} entre Color1: (#{c1.r}, #{c1.g}, #{c1.b}) y Color2: (#{c2.r}, #{c2.g}, #{c2.b})\"\nend", "def correct_color?(array)\n @correct_colors = array & $code_strings\n end", "def colorize(key, color)\n op = {:operation => :colorize, :key => key, :color => color}\n add_operation op\n end", "def purple\n colorize(35)\n end", "def nc\n Ncurses::COLOR_PAIR(@id)\n end", "def dark_green; colorize(self, \"\\e[0;32m\"); end", "def color\n @color ||= COLORS[label.length%COLORS.length].to_sym\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
codewars kata: matrix addition
def matrixAddition(a, b) c = [] << a << b c.transpose.map{ |i| i.transpose }.map{ |s| s.map{ |p| p.reduce(&:+)}} end
[ "def matrix_addition(m1, m2)\n height = m1.length\n width = m1[0].length\n result = Array.new(height) { [0] * width }\n\n (0...height).each do |row|\n (0...width).each do |col|\n result[row][col] = m1[row][col] + m2[row][col]\n end\n end\n\n result\nend", "def matrix_addition(matrx_1, matrx_2)\n height = matrx_1.length\n width = matrx_1[0].length\n\n result = Array.new(height) { [0] * height }\n\n (0...height).each do |row|\n (0...width).each do |col|\n result[row][col] = matrx_1[row][col] + matrx_2[row][col]\n end\n end\n\n result\nend", "def matrixAddition(a, b)\n\n final_array = []\n\n a.each.with_index do |arr1, i1|\n matrix_row = []\n arr1.each_with_index do |n1, i2|\n sum = n1 + b[i1][i2]\n matrix_row.push(sum)\n end\n final_array.push(matrix_row)\n end\n\n final_array\nend", "def sum_matrix(m)\n sum = 0\n m.each { |row|\n row.each { |element|\n sum += element\n }\n }\n\n sum\nend", "def +(other)\n raise ArgumentError, \"La longitud de las matrices no coincide.\" unless @filas == other.filas && @columnas == other.columnas \n sum = Matriz.new(matriz) #inicializas el vector sum con el primer con el primer\n dev_filas.times do |i| \n dev_columnas.times do |j|\n sum.matriz[i][j] = self.matriz[i][j] + other.matriz[i][j] \n end\n end\n return sum #devuelve un tipo array modificando el objeto m1 si se hace m3=m1+m2 -> Se necesita q sea tipo Matriz\n end", "def add!(matrix)\n to_sparse!(to_matrix + matrix)\n end", "def __add(other)\n\t\tm = Memory.new(@row_count) { |i|\n\t\t\tMemory.new(@column_count) { |j|\n\t\t\t\t@m[i][j] + other.__get(i, j)\n\t\t\t}\n\t\t}\n\t\treturn Matrix.__new__(m, @row_count, @column_count)\n\tend", "def mat_add_or_subtract(mat1, mat2, operation='+')\n n = mat1.size\n result = n.times.map{ |x| [] }\n (0..n-1).each do |i|\n (0..n-1).each do |j|\n result[i] << (operation == '+' ? (mat1[i][j] + mat2[i][j]) : (mat1[i][j] - mat2[i][j]))\n end\n end\n result\nend", "def add_rows ( r1, r2 )\r\n new_matrix = [] \r\n @matrix.each do |row| \r\n if row == row(r2)\r\n new_row = [] \r\n row(r2).each_index do |i|\r\n c = i + 1\r\n new_row << ele( r2, c ) + ele( r1, c )\r\n end\r\n new_matrix << new_row\r\n else\r\n new_matrix << row\r\n end\r\n end \r\n Matrix.new( new_matrix )\r\n end", "def +(m)\n case m\n when Numeric\n Matrix.Raise ErrOperationNotDefined, \"+\"\n when Vector\n m = Matrix.column_vector(m)\n when Matrix\n else\n x, y = m.coerce(self)\n return x + y\n end\n \n Matrix.Raise ErrDimensionMismatch unless row_size == m.row_size and column_size == m.column_size\n \n rows = (0 .. row_size - 1).collect {\n |i|\n (0 .. column_size - 1).collect {\n |j|\n self[i, j] + m[i, j]\n }\n }\n Matrix.rows(rows, false)\n end", "def matrixElementsSum(matrix)\r\n(0..matrix.length-2).each do |floor_number|\r\n\r\n (0..matrix[floor_number].length-1).each do |column_number|\r\n if matrix[floor_number][column_number] == 0\r\n matrix[floor_number+1].delete_at(column_number)\r\n matrix[floor_number+1].insert(column_number, 0)\r\n end\r\n end\r\n \r\nend\r\n\r\nreturn matrix.flatten.inject(:+)\r\n\r\nend", "def +(m)\n if m.is_a? Matrix then\n if m.similar_to? self then\n return Matrix.new(@MyRws, @MyCls){ |i,j| self[i,j] + m[i,j]}\n else\n raise MyArgError, \" Argument Error: invalid matrix for + operation\"\n end\n else\n raise MyArgError, \" Argument Error: can't sum #{m.class} to Matrix\"\n end\n end", "def +(matrix)\n sum_validation(self, matrix)\n values = self.diagonal_values.zip(matrix.diagonal_values).map{ |i| i.inject(:+) }\n Mat::Diagonal.new self.m, self.n, *(values)\n end", "def mat_add_or_subtract(mat1, mat2, operation='+')\n n = mat1.size\n result = n.times.map{ |x| [] }\n (0..n-1).each do |i|\n (0..n-1).each do |j|\n result[i] << (operation == '+' ? (mat1[i][j] + mat2[i][j]) : (mat1[i][j] - mat2[i][j]))\n end\n end\n result\n end", "def matrix_addition_reloaded(*matrices)\n matrix = matrices.first\n height = matrix.length\n width = matrix[0].length\n\n empty_matrix = Array.new(height) { [0] * width }\n matrices.inject(empty_matrix) do |m1, m2|\n return nil if m2.length != height or m2[0].length != width\n matrix_addition(m1, m2)\n end\nend", "def add_rows! *rows\r\n matrix_new = add_rows *rows\r\n @rows = matrix_new.to_a\r\n end", "def diagonalSum(matrix)\ntotal = 0\n (0...matrix.length).each {|sub| total += matrix[sub][sub]}\nreturn total\nend", "def rec_matrix_multiplication(a, b)\n return a[0] * b[0] if a.length == 1\n\n a_splited = split_matrix(a, a.length)\n b_splited = split_matrix(b, a.length)\n\n a_b_1 = [matrix_sum(rec_matrix_multiplication(a_splited[0], b_splited[0]), rec_matrix_multiplication(a_splited[1], b_splited[2]))].flatten\n a_b_2 = [matrix_sum(rec_matrix_multiplication(a_splited[0], b_splited[1]), rec_matrix_multiplication(a_splited[1], b_splited[3]))].flatten\n a_b_3 = [matrix_sum(rec_matrix_multiplication(a_splited[2], b_splited[0]), rec_matrix_multiplication(a_splited[3], b_splited[2]))].flatten\n a_b_4 = [matrix_sum(rec_matrix_multiplication(a_splited[2], b_splited[1]), rec_matrix_multiplication(a_splited[3], b_splited[3]))].flatten\n\n row_length = a_b_1.count\n\n if row_length == 1\n result = [[a_b_1[0], a_b_2[0], a_b_3[0] , a_b_4[0]]]\n else\n result = \n [\n a_b_1[0..(row_length / 2) - 1] + a_b_2[0..(row_length / 2) - 1] +\n a_b_1[(row_length / 2).. - 1] + a_b_2[(row_length / 2).. - 1] +\n a_b_3[0..(row_length / 2) - 1] + a_b_4[0..(row_length / 2) - 1] +\n a_b_3[(row_length / 2).. - 1] + a_b_4[(row_length / 2).. - 1]\n ]\n end\n\n build(result[0], result[0].length)\nend", "def concatenate_matrix(a, b, c, d, e, f)\n transform = Matrix[\n [a, b, 0],\n [c, d, 0],\n [e, f, 1]\n ]\n if state[:ctm]\n state[:ctm] = transform * state[:ctm]\n else\n state[:ctm] = transform\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Insert a set into the search dictionary
def add_search_set( search_set, number_to_transpose = 0 ) @search_sets << Set.new( MiltonsMachine::Core::ForteSet.new(search_set).transpose_mod12(number_to_transpose) ) end
[ "def add_to_sets\n self[\"$addToSet\"] ||= {}\n end", "def insert(val)\n return false if includes?(val)\n set[val] = true\n true\n end", "def addSet(synset_id, nouns)\n\t\n\tif (synset_id > -1) && (!nouns.empty?) && (!@hash.has_key? synset_id) \n\t\t@hash[synset_id] = nouns\n\t\treturn true\n\telse\n\t\treturn false\t\n\tend\n end", "def insert(val)\n hash[val] = Set.new unless hash[val]\n hash[val].add(values.size)\n values.push(val)\n hash[val].size == 1\n end", "def add_set(key1, key2, value)\n\t\t@corpus.has_key?([key1,key2]) ? @corpus[[key1,key2]] << value : @corpus[[key1,key2]] = [value]\n\tend", "def add_sorted_set(key, member, score)\n @kvs_instance.zadd(safe_key(key), score, member)\n end", "def add_entry_to_set(entry, ret, seen, entries, all_entries)\n return if seen.include?(entry)\n\n seen << entry\n req = required_entries(entry[:required], entries, entry, all_entries)\n req.each do |required|\n add_entry_to_set(required, ret, seen, entries, all_entries)\n end\n ret << entry\n end", "def add(x) Set.new().add(x) end", "def process_set(tree, objects)\n # @TODO Error handling\n tree.each do |thing|\n set.push(objects[thing.to_s])\n end\n set\n end", "def create_set(set_id,search_str)\n\t\t\targs = search_str.split(\" \")\n\t\t\tself.dbsearch(args)\n\t\t\tself.cmd_db_set_create(set_id)\n\t\tend", "def create\n @search_set = SearchSet.new(params[:search_set].slice(:title, :description))\n\n searches = params[:search_set][:searches].select(&:present?).collect { |search_id| Search.find(search_id)}\n @search_set.searches << searches\n\n respond_to do |format|\n if @search_set.save\n format.html { redirect_to @search_set, notice: 'Search set was successfully created.' }\n format.json { render json: @search_set, status: :created, location: @search_set }\n else\n format.html { render action: \"new\" }\n format.json { render json: @search_set.errors, status: :unprocessable_entity }\n end\n end\n end", "def add_all(set)\n raise NotImplementedError\n end", "def add_to_set(set, word)\n\tif !(set.key?(word))\n\t\tset.merge!(word => 1)\n\telse\n\t\tset[word] += 1\n\tend\nend", "def parse_set\n @current_set = Set.new\n @current_match.add_set @current_set\n end", "def search_builder(*args)\n super.tap do |builder|\n if @set\n builder.set = @set\n end\n end\n end", "def find_sets_and_rules\n @item_sets << find_singletons\n find_frequent_item_sets\n @rules = find_rules\n end", "def add(tree)\n @set[tree] = true\n end", "def add_sorted_set(key, member, score)\n raise NoMethodError\n end", "def +(set)\n elements2 = set.is_a?(Set) ? set.elements : set\n Set.new(*self.elements, *elements2)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run the rotation_analysis and print out the results
def run_rotation_analysis initialize_run rotate_group print_summary end
[ "def print_rotation_count\n @rotation_count += 1\n print \"\\r\\e#{@rotation_count} of #{@maximum_rotations} processed...\"\n $stdout.flush\n end", "def test_correct_rotation\r\n actual_test([\"PLACE 0,0,SOUTH\",\r\n \"LEFT\",\r\n \"REPORT\"],\"0,0,EAST\")\r\n $stdout.clear\r\n actual_test([\"PLACE 0,0,SOUTH\",\r\n \"RIGHT\",\r\n \"REPORT\"],\"0,0,WEST\")\r\n end", "def runAnalyzer(num_samples,inhash)\n # select profile for run\n show do \n title \"Select #{QIAXCEL_TEMPLATE[inhash[:sampleTypes]]}\" # this is just a profile name, should be ok for other polymerases\n note \"Click <b>Back to Wizard</b> if previous data is displayed.\"\n check \"Under <b>Process -> Process Profile</b>, make sure <b>#{QIAXCEL_TEMPLATE[inhash[:sampleTypes]]}</b> is selected.\"\n end\n \n # select alignment marker\n ref_marker = (inhash[:sampleTypes] == 'DNA') ? REF_MARKERS[inhash[:type_ind]][inhash[:cutoff_ind]] : REF_MARKERS[inhash[:type_ind] ]\n show do \n title \"Select alignment marker\"\n check \"Under <b>Marker</b>, in the <b>Reference Marker </b> drop-down, select <b>#{ref_marker}</b>. A green dot should appear to the right of the drop-down.\"\n end\n \n # empty rows\n if inhash[:sampleTypes] == 'RNA'\n num_samples = num_samples + 1 # Include the ladder in the first well of the first stripwell\n nonempty_rows = (num_samples/WELLS_PER_STRIPWELL.to_f).ceil\n (num_samples % WELLS_PER_STRIPWELL) > 0 ? nonempty_rows + 1 : nonempty_rows\n else\n nonempty_rows = (num_samples/WELLS_PER_STRIPWELL.to_f).ceil\n end\n show do \n title \"Deselect empty rows\"\n check \"Under <b>Sample selection</b>, deselect all rows but the first #{nonempty_rows}.\"\n end\n \n # check \n show do \n title \"Perform final check before running analysis\"\n note \"Under <b>Run Check</b>, manually confirm the following:\"\n check \"Selected rows contain samples.\"\n check \"Alignment marker is loaded (changed every few weeks).\"\n end\n \n # run and ask tech for remaining number of runs\n run_data = show do \n title \"Run analysis\"\n note \"If you can't click <b>Run</b>, and there is an error that reads <b>The pressure is too low. Replace the nitrogen cylinder or check the external nitrogen source</b>, close the software, and reopen it. Then restart at title - <b>Select #{QIAXCEL_TEMPLATE[inhash[:sampleTypes]]} </b>\"\n check \"Otherwise, click <b>Run</b>\"\n note \"Estimated time of experiment is given at the bottom of the screen\"\n get \"number\", var: \"runs_left\", label: \"Enter the number of <b>Remaining Runs</b> left in this cartridge\", default: 0\n #image \"frag_an_run\"\n end\n \n # return\n run_data[:runs_left]\n \n end", "def analyze\n algorithm = select_algorithm\n space_invaders, radar_images = read_files\n validate_measurements(space_invaders, radar_images.first)\n call_algorithm(algorithm, space_invaders, radar_images.first)\n end", "def displaygameanalysis\n\t\t\t@output.puts \"Analysis of game.\"\n\t\tend", "def rotate \n#--{{{\n init_logging\n rotater = Rotater::new self\n rotater.rotate\n#--}}}\n end", "def output(results)\n puts \"File checked: #{results[:file]}\"\n puts \"Range: #{results[:range]}\"\n puts \"Palindromes: #{results[:count]}\"\n puts '========================'\n puts\n end", "def zrotation\n end", "def setup_rotation\n return TSBS.error(@acts[0], 3, @used_sequence) if @acts.size < 4\n @angle = @acts[1]\n change_angle(@acts[2], @acts[3])\n end", "def start\n array = []\n $rover_orientation = \"\"\n cardinal_compass_points = []\n index = params[:pass_rover].to_i\n\n if $rover[index][:facing] == \"N\"\n $rotation = 0\n $rover[index][:degrees] = array << $rotation\n cardinal_compass_points << \"North\"\n elsif $rover[index][:facing] == \"E\"\n $rotation = 90\n $rover[index][:degrees] = array << $rotation\n cardinal_compass_points << \"East\"\n elsif $rover[index][:facing] == \"S\"\n $rotation = 180\n $rover[index][:degrees] = array << $rotation\n cardinal_compass_points << \"South\"\n elsif $rover[index][:facing] == \"W\"\n $rotation = 270\n $rover[index][:degrees] = array << $rotation\n cardinal_compass_points << \"West\"\n end\n\n $rover[index][:directions].each do |directions|\n \n if directions == \"L\"\n $rotation -= 90\n $rover[index][:degrees] = array << $rotation\n elsif directions == \"R\"\n $rotation += 90\n $rover[index][:degrees] = array << $rotation\n end\n \n if $rotation / 90 % 4 == 0\n $rover_orientation = \"N\"\n cardinal_compass_points << \"North\"\n elsif $rotation / 90 % 4 == 1\n $rover_orientation = \"E\"\n cardinal_compass_points << \"East\"\n elsif $rotation / 90 % 4 == 2 \n $rover_orientation = \"S\"\n cardinal_compass_points << \"South\"\n elsif $rotation / 90 % 4 == 3\n $rover_orientation = \"W\"\n cardinal_compass_points << \"West\"\n elsif $rotation / 90 % 4 == -1\n $rover_orientation = \"W\"\n cardinal_compass_points << \"West\"\n elsif $rotation / 90 % 4 == -2\n $rover_orientation = \"S\"\n cardinal_compass_points << \"South\"\n elsif $rotation / 90 % 4 == -3\n $rover_orientation = \"E\"\n cardinal_compass_points << \"East\"\n end\n\n if directions == \"M\" && $rover_orientation == \"N\"\n # just increases the value on the y-axis\n $rover[index][:degrees] = array << \"M\"\n $rover[index][:path] << \"#{$rover[index][:path].last.split(\"_\")[0].to_i}_#{$rover[index][:path].last.split(\"_\")[1].to_i + 1}\"\n elsif directions == \"M\" && $rover_orientation == \"E\"\n # just increases the value on the x-axis\n $rover[index][:degrees] = array << \"M\"\n $rover[index][:path] << \"#{$rover[index][:path].last.split(\"_\")[0].to_i + 1}_#{$rover[index][:path].last.split(\"_\")[1].to_i}\"\n elsif directions == \"M\" && $rover_orientation == \"S\"\n # just decreases the value on the y-axis\n $rover[index][:degrees] = array << \"M\"\n $rover[index][:path] << \"#{$rover[index][:path].last.split(\"_\")[0].to_i}_#{$rover[index][:path].last.split(\"_\")[1].to_i - 1}\"\n elsif directions == \"M\" && $rover_orientation == \"W\" \n # just decreases the value on the x-axis\n $rover[index][:degrees] = array << \"M\"\n $rover[index][:path] << \"#{$rover[index][:path].last.split(\"_\")[0].to_i - 1}_#{$rover[index][:path].last.split(\"_\")[1].to_i}\"\n end\n \n end\n \n $rover[index][:cardinal_compass_points] = cardinal_compass_points\n \n @rover_array_of_hashes = $rover\n respond_to do |format|\n format.json {render json: @rover_array_of_hashes[params[:pass_rover].to_i]}\n end\n end", "def test_it_can_find_rotation_numbers\n enigma = Enigma.new\n assert_equal [31, 37, -17, -17, -8, 37, 22], enigma.find_rotation_numbers(\"gav4lap\")\n end", "def test_complete_rotation\n rover = MarsRover.new\n rover.command('LLLL')\n assert_equal([0,0,'N'], rover.position)\n end", "def create_analysis_views\n puts \"====================\"\n puts \"creating analysis views for #{self.name}\"\n puts \"====================\"\n\n run_analysis_views\n\n puts \"> done\"\n puts \"====================\"\n end", "def index\n @rotations = Rotation.all\n end", "def rotCheck\n # check if exporting for Daysim v3.0; if so, rotating points not necessary, so return false\n if $DS_VERSION == '3.0'\n return false\n end\n \n # get path of rotated geometry file, from which rotation angle will be read\n rotRadName = \"#{File.basename(@path).split(/\\./)[0]}.rad.rotated.rad\"\n rotRadPath = \"#{File.expand_path(\"./..\", File.dirname(@path))}/#{rotRadName}\"\n \n # read rotation angle\n if File.exists?(rotRadPath)\n f = File.new(rotRadPath)\n lines = f.readlines\n f.close\n @rotation = lines[0].split[-1].strip.to_f\n return true\n else\n return false\n end\n end", "def create_analysis_tables_and_views\n puts \"====================\"\n puts \"creating analysis tables and views for #{self.name}\"\n puts \"====================\"\n\n run_analysis_tables\n run_analysis_views\n\n puts \"> done\"\n puts \"====================\"\n end", "def matrixRotation(matrix, r)\n resultMatrix = Array.new($m) { |_| Array.new($n) }\n\n (0..$m-1).each do |row|\n (0..$n-1).each do |col|\n x,y = computeOffset col, row, r\n puts [matrix[row][col], row, col, y, x].inspect\n resultMatrix[y][x] = matrix[row][col]\n end\n end\n\n printMatrix resultMatrix\nend", "def analyze_samples\n run_data = show do \n title \"Run analysis\"\n note \"If you can't click \\\"run\\\", and there is an error that reads, \\\"The pressure is too low. Replace the nitrogen cylinder or check the external nitrogen source,\\\" \n close the software, and reopen it. Then repeat steps 9-13.\"\n check \"Otherwise, click run\"\n note \"Estimated time is given at the bottom of the screen\"\n get \"number\", var: \"runs_left\", label: \"Enter the number of \\\"Remaining Runs\\\" left in this cartridge.\", default: 0\n image \"Actions/Fragment Analyzer/frag_an_run.jpg\"\n end\n\n while run_data[:runs_left].nil? && !debug\n run_data = show do \n title \"Enter remaining runs\"\n warning \"Please enter the number of remaining runs left in this cartridge.\"\n get \"number\", var: \"runs_left\", label: \"Enter the number of \\\"Remaining Runs\\\" left in this cartridge.\", default: 0\n end\n end\n run_data\n end", "def run\n create_log_folder\n \n in_tmp_dir do\n start_frame = tmp_path START_FRAME\n extract_start_transition_frame(start_frame) # 1.\n \n end_frame = tmp_path END_FRAME\n extract_end_transition_frame(end_frame) # 2.\n \n transitions = tmp_path TRANSITIONS\n Cmd::GenerateTransitionFrames.new(start_frame, end_frame, transitions, INNER_FRAMES_AMOUNT).run! *logs('3_generate_transition_frames') # 3.\n \n Queue.run *FORMATS.map{ |format| proc{ transition(format) } }, close_connection_before_execution: true # 4.\n end\n \n outputs\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A recursive routine that rotates a group of voices in the horizontal matrix. If it is at depth, performs the final vertical analysis for the current rotations; otherwise, just calls itself to process the next group in the hierarchy.
def rotate_group( level = -1 ) level += 1 if level == 0 # First group always remains static rotate_group(level) # Recursive call to process next group of rows else # Rotate each pitch to the right for each row in this group. If its the last group then analyze the verticals # in each column across all groups; otherwise recursively call to process next group of rows. 0.upto(@max_column_index) do @groups[level].each { |row| row.rotate!(-1) } level == @max_group_index ? analyze_sonorities : rotate_group(level) end end end
[ "def run_rotation_analysis\n initialize_run\n rotate_group\n print_summary\n end", "def rotate\n # Rotated room\n @rotated = Array.new(@height) do |l|\n Array.new(@width) do |c|\n nil\n end\n end\n \n @squares.each do |line|\n line.each do |sq|\n @rotated[sq.x][@height -1 - sq.y] = sq\n sq.rotate\n end\n end\n \n @squares = @rotated\n end", "def _rotate_face(v,face)\n ents = Sketchup.active_model.entities\n l = []\n limit = 0\n if face == 1\n limit = @outter_limit\n else\n limit = @inner_limit\n end\n index = 0\n while index < v.length\n if v[index] != 0;break;end\n index=index +1\n end\n ents.each{|g| \n if face == 1\n if g.bounds.center.to_a[index] > limit;l.insert(-1,g)\n end\n else\n if g.bounds.center.to_a[index] < limit;l.insert(-1,g)\n end\n end\n }\n group = ents.add_group l\n _rotate(group,group.bounds.center,v)\n end", "def fourTypeRotate(direction)\n old_blocks = DeepClone.clone(@blocks)\n old_index = @orientation_index\n center_block = @blocks.first()\n ref_row = center_block.getRow()\n ref_col = center_block.getColumn()\n \n if (direction == CLOCKWISE)\n @orientation_index = (@orientation_index + 1) % 4\n else\n @orientation_index = ((@orientation_index - 1) + 4) % 4\n end\n @blocks = getOrientation(ref_row, ref_col)\n \n @blocks.each do |block|\n row = block.getRow()\n col = block.getColumn()\n if (row < 0 or col < 0 or \n row >= Board::ROWS or\n col >= Board::COLUMNS)\n @blocks = old_blocks\n @orientation_index = old_index\n break\n end\n end\n end", "def performRotation(x, y, rotationDistance, coordinates)\n puts [x,y,rotationDistance].inspect\n # top row\n if y == coordinates[:ul][:y]\n distanceFromUpperLeft = x - coordinates[:ul][:x]\n distanceToMove = distanceFromUpperLeft >= rotationDistance ? rotationDistance : (rotationDistance - distanceFromUpperLeft)\n\n # Move to the next edge\n if distanceToMove > distanceFromUpperLeft # if its greater, rotate through\n performRotation coordinates[:ul][:x], (y+1), (distanceToMove -1), coordinates\n elsif distanceToMove < distanceFromUpperLeft\n return [x - distanceToMove, y]\n else # make it the corner\n performRotation coordinates[:ul][:x], y, distanceToMove, coordinates\n end\n # bottom\n elsif y == coordinates[:ll][:y]\n distanceFromLowerRight = coordinates[:lr][:x] - x\n distanceToMove = distanceFromLowerRight >= rotationDistance ? rotationDistance : (rotationDistance - distanceFromLowerRight)\n\n if distanceToMove > distanceFromLowerRight # if its greater, rotate through\n performRotation coordinates[:lr][:x], (y-1), (distanceToMove -1), coordinates\n elsif distanceToMove < distanceFromLowerRight # if its less, rotate less\n return [x + distanceToMove, y]\n else # otherwise, make it the corner\n performRotation coordinates[:lr][:x], y, distanceToMove, coordinates\n end\n # left side\n elsif x == coordinates[:ll][:x] && y != coordinates[:ul][:y] && y != coordinates[:ll][:y]\n distanceFromLowerLeft = coordinates[:ll][:y] - y\n distanceToMove = distanceFromLowerLeft >= rotationDistance ? rotationDistance : (rotationDistance - distanceFromLowerLeft)\n\n if distanceToMove > distanceFromLowerLeft\n performRotation (x+1), coordinates[:ll][:y], (distanceToMove -1), coordinates\n elsif distanceToMove == distanceFromLowerLeft\n performRotation x, coordinates[:ll][:y], distanceToMove, coordinates\n else\n return [x, y + distanceToMove]\n end\n # right side\n elsif x == coordinates[:ur][:x] && y != coordinates[:lr][:y] && y != coordinates[:ur][:y]\n distanceFromUpperRight = y - coordinates[:ur][:y]\n distanceToMove = distanceFromUpperRight >= rotationDistance ? rotationDistance : (rotationDistance - distanceFromUpperRight)\n\n if distanceToMove > distanceFromUpperRight\n performRotation (x-1), coordinates[:ur][:y], (distanceToMove -1), coordinates\n elsif distanceToMove < distanceFromUpperRight\n performRotation x, coordinates[:ur][:y], distanceToMove, coordinates\n else\n return [x, y - distanceToMove]\n end\n else\n puts \"Failure\"\n end\nend", "def rotate\n case left.height - right.height\n when 2\n if left.left.height < left.right.height # case b\n @left = left.rotate_left\n end\n root = rotate_right # case a\n when -2\n if right.right.height < right.left.height # case d\n @right = right.rotate_right\n end\n root = rotate_left # case c\n else\n root = self\n end\n\n root.update_height\n root\n end", "def move dir, increment = false, board = @board\n newScore = 0 if increment\n newBoard = Array.new(4){ |x|\n Array.new(board[x])\n }\n if increment\n @moveFactor = Array.new(4){ |x|\n Array.new(4, 0) \n }\n end\n if dir == Dir::Up\n for column in 0...4\n isNew = -1 #only declared here for scope reasons TODO check to see if this is necesary\n for row in 0...4\n slid = false\n if newBoard[column][row] > 0\n for checker in (row+1)...4#this for loop only deals with the combining of similar tiles\n if newBoard[column][checker] == newBoard[column][row] and isNew != row\n newScore += newBoard[column][row] if increment\n newBoard[column][row] *= 2\n isNew = row #that should work... right?\n #puts newBoard\n newBoard[column][checker] = 0\n @moveFactor[column][checker] = checker - row if increment\n elsif newBoard[column][checker] > 0\n break\n end\n end#end for checker\n else#i.e newBoard[column][row] not greater than 0\n for mover in (row+1)...4#this for loop deals with sliding tiles without combining\n if newBoard[column][mover] > 0\n newBoard[column][row] = newBoard[column][mover]\n newBoard[column][mover] = 0\n @moveFactor[column][mover] = mover - row if increment\n slid = true\n break\n end\n end#end for mover\n end#end if newBoard[column][row] > 0\n redo if slid\n end#end for row\n end#end for column\n @score += newScore if increment\n elsif dir == Dir::Right\n newBoard = move Dir::Up, increment, rotate(newBoard)\n 3.times{\n newBoard = rotate newBoard\n @moveFactor = rotate @moveFactor\n }\n elsif dir == Dir::Left\n newBoard = move Dir::Down, increment, rotate(newBoard)\n 3.times{\n newBoard = rotate newBoard\n @moveFactor = rotate @moveFactor\n }\n elsif dir == Dir::Down\n newBoard = move Dir::Right, increment, rotate(newBoard)\n 3.times{\n newBoard = rotate newBoard\n @moveFactor = rotate @moveFactor\n }\n end\n newBoard\n end", "def rotate_vertical\n @original_columns = columns_size\n @original_rows = rows_size\n @rows = orientation.slice(self)\n @header = [] if header\n @rotated = true\n end", "def rec(a, level)\n swap_interleaved a\n swap(a)\n if (level>0)\n a[0..a.size/2-1] = rec(a[0..a.size/2-1], level-1)\n a[a.size/2..-1] = rec(a[a.size/2..-1], level-1)\n end\n a\nend", "def rotate_matrix matrix, direction\n return clockwise(matrix) if direction == \"clockwise\"\n return counter_clockwise(matrix) if direction == \"counter-clockwise\"\nend", "def rotate_matrix_in_place\n # We only need to loop over 1/4th of the numbers because rotate_position rotates all four numbers.\n\n # Because the matrix is rotating in place, only go over the first half of the rows.\n # The second half will be rotated by rotate_position as we rotate the first half. \n (@matrix.length / 2).floor.times do |row|\n # The number of columns to rotate per row number is equal to N - 1 - (2 * row_number).\n # Each column gets offset by how many row's we've seen because the numbers in the left most columns\n # have already been rotated by previous iterations\n (@matrix.length - 1 - 2 * row).times do |num_cols|\n offset = row\n rotate_position(row, offset + num_cols)\n end\n end\n self\n end", "def rotate \n#--{{{\n init_logging\n rotater = Rotater::new self\n rotater.rotate\n#--}}}\n end", "def rotate dir = \"LR\"\n orient dir\n end", "def zrotation\n end", "def setup_rotation\n return TSBS.error(@acts[0], 3, @used_sequence) if @acts.size < 4\n @angle = @acts[1]\n change_angle(@acts[2], @acts[3])\n end", "def rotate_horizontal\n return unless rotated?\n head, body = orientation.slice(self)\n if header && header.empty?\n @header = head[0]\n @rows = body.map { |row| to_row(row, @header) }\n else\n @rows = body.map { |row| to_row(row) }\n end\n end", "def rotate_degrees(matrix, degrees)\n return puts\"Not a valid degree: #{degrees}\" unless degrees % 90 == 0\n n = degrees / 90\n return matrrix if n == 4 || n == 0\n temp = matrix\n result = nil\n n.times do |_|\n result = rotate90(temp)\n temp = result\n end\n result\nend", "def rotate_view!(amount_x, amount_y, amount_z = 0)\n amount_y = -amount_y # because the user is expecting positive amount to rotate right, not left\n\n if amount_x != 0 # effectively \"looking up/down\"\n view.rotate! amount_x, right\n unless lock_up_vector?\n @up = right.cross(view).normalize!\n end\n end\n\n if amount_y != 0 # effectively \"looking left/right\"\n view.rotate! amount_y, up\n @right = view.cross(up).normalize!\n end\n\n if amount_z != 0 # effectively rotating clockwise/counterclockwise\n up.rotate! amount_z, view\n @right = view.cross(up).normalize!\n end\n\n view.normalize!\n\n if lock_up_vector?\n # prevent view from rotating too far\n #angle = asin(view.dot(@up))#acos(view.dot(@up))\n # FIXME: I really hate these hard numbers -- and it may be because I'm really tired right now - but I can't figure\n # out a better way to detect this. Seems to work, in any case, but it may fail if amount_x is too high.\n angle = acos(view.dot(@up)) - 0.05\n if angle != 0\n angle = -angle if angle >= 3 - 0.05\n angle /= angle.abs # we want 1 or -1\n @last_angle = angle if @last_angle.nil?\n if angle != @last_angle and amount_x != 0\n rotate_view! -amount_x, 0, 0\n else\n @last_angle = angle\n end\n end\n end\n matrix.look_at! position, view, up\n self\n end", "def rotate matrix, direction\n direction == 'clockwise' ? matrix.reverse.transpose : matrix.transpose.reverse\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Accumulate current permutation search result counts into the reports summary totals. For example: if the total column score was 9 for the current rotation of the rows, summary_totals[9] would be incremented to reflect that a matrix solution was found with score = 9
def accumulate_summary_totals( score ) @summary_totals[score] ||= 0 @summary_totals[score] += 1 end
[ "def total_search_results(summary_details)\n total_count = 0\n\n summary_details.map do |sequence|\n total_count += sequence.matches.count\n end\n\n total_count\n end", "def comp_add_total(view)\n row = {\n :col0 => \"<span class='cell-effort-driven cell-plain'>\" + _(\"Total Matches\") + \"</span>\",\n :id => \"id_#{@rows.length}\",\n :total => true\n }\n view.ids.each_with_index do |_id, idx|\n if idx.zero?\n row.merge!(compare_add_txt_col(idx, @compressed ? \"%:\" : _(\"% Matched:\")))\n else\n key = @exists_mode ? :_match_exists_ : :_match_\n pct_match = view.results[view.ids[idx]][key]\n image = calculate_match_img(pct_match)\n row.merge!(compare_add_piechart_image(idx, \"#{pct_match}% matched\", image))\n end\n end\n @rows << row\n end", "def total\n sum = 0\n\n @four_result.each do |result|\n sum += result\n end\n @six_result.each do |result|\n sum += result\n end\n @eight_result.each do |result|\n sum += result\n end\n @ten_result.each do |result|\n sum += result\n end\n @twelve_result.each do |result|\n sum += result\n end\n @twenty_result.each do |result|\n sum += result\n end\n @percentile_result.each do |result|\n sum += result\n end\n\n sum\n end", "def aggregate_results\n total_info = 0\n total_warnings = 0\n total_errors = 0\n @results[:by_measure].each_pair do |k, v|\n total_info += v[:measure_info]\n total_warnings += v[:measure_warnings]\n total_errors += v[:measure_errors]\n end\n @results[:total_info] = total_info\n @results[:total_warnings] = total_warnings\n @results[:total_errors] = total_errors\n end", "def summary\n return \"\\nNo results identified.\\n\" if tally.keys.empty?\n result = [ \"\\nSummary of identified results:\\n\" ]\n sum = 0\n tally.keys.sort_by {|k| -1*tally[k] }.each do |k|\n sum += tally[k]\n result << \"%30s: %6d\" % [k, tally[k]]\n end\n result << \"%30s: %6d\" % ['TOTAL', sum]\n result.join \"\\n\"\n end", "def opc_total()\n opx_err(\"Command \\\"total\\\" ignored, Tabulator state: EMPTY\") if opx_empty_state?()\n tab = opx_instantiate_tabulator()\n state = opc_state(tab, true)\n if ([\"ACCUMULATING\", \"DONE\"].include?(state))\n if (state == \"DONE\")\n opx_print(\"Writing Tabulator Spreadsheet: \" +\n \"#{TABULATOR_SPREADSHEET_FILE}\\n\")\n lines = opx_file_write_spreadsheet(tab, true)\n #opx_print(\"\\nFinal Vote Count Data (CSV Spreadsheet Format):\\n\\n\")\n #opx_print(lines)\n else\n lines = opx_file_write_spreadsheet(tab, false)\n #opx_print(\"\\nPartial Vote Count Data (CSV Spreadsheet Format):\\n\\n\")\n #opx_print(lines)\n opx_print(\"\\n\")\n opx_err(\"Command \\\"total\\\" REJECTED, Counts MISSING (See Above)\")\n end\n end\n end", "def set_total_hits\n return set_top_hits + set_all_hits\n end", "def print_summary\n puts \"\\n\\nScore : # Instances\\n\" << (\"=\" * 19)\n @summary_totals.each_with_index { |value, index| puts \" %5d:%8d\\n\" % [index, value] unless value.nil? }\n puts \"\\n** End of Report\"\n end", "def summarize_suite(suite, tests)\n summary = Hash.new(0)\n summary[:name] = suite.to_s\n tests.each do |test|\n summary[:\"#{result(test)}_count\"] += 1\n summary[:assertion_count] += test.assertions\n summary[:test_count] += 1\n summary[:time] += test.time\n end\n summary[:has_errors_or_failures] = (summary[:fail_count] + summary[:error_count]) > 0\n summary[:has_skipps] = summary[:skip_count] > 0\n summary\n end", "def summary\n unless @summary\n @summary = Hash.new{ |h, k| h[k] = 0 }\n @diffs.each{ |k, v| @summary[v[:action]] += 1 }\n @summary['Warning'] = warnings.size if warnings.size > 0\n end\n @summary\n end", "def drift_add_total(view)\n row = {\n :col0 => \"<span class='cell-effort-driven cell-plain'>\" + _(\"All Sections\") + \"</span>\",\n :id => \"id_#{@rows.length}\",\n :total => true\n }\n view.ids.each_with_index do |_id, idx|\n if idx.zero?\n row.merge!(drift_add_same_image(idx, _(\"Same as previous\")))\n elsif view.results[view.ids[idx]][:_match_] == 100\n row.merge!(drift_add_same_image(idx, _(\"Same as previous\")))\n else\n row.merge!(drift_add_diff_image(idx, _(\"Changed from previous\")))\n end\n end\n @rows << row\n end", "def computeResults\n self.wins = 0\n self.loss = 0\n self.ties = 0\n self.goals_for = 0\n self.goals_against = 0\n self.points = 0\n\n self.matchups.each do |match|\n if match.final\n updateResults(match)\n end\n end\n \n # TODO: Handle error\n self.save\n end", "def total_summary\n\n products = {}\n products.store(:item_cost, item_cost)\n products.store(:extras_cost, extras_cost)\n\n supplements = {}\n supplements.store(:pick_up_place, pickup_place_cost)\n supplements.store(:return_place, return_place_cost)\n supplements.store(:time_from_cost, time_from_cost)\n supplements.store(:time_to_cost, time_to_cost)\n supplements.store(:driver_age_cost, driver_age_cost)\n supplements.store(:category_supplement_1, category_supplement_1_cost)\n supplements.store(:category_supplement_2, category_supplement_2_cost)\n supplements.store(:category_supplement_3, category_supplement_3_cost)\n supplements.store(:supplement_1, supplement_1_cost)\n supplements.store(:supplement_2, supplement_2_cost)\n supplements.store(:supplement_3, supplement_3_cost)\n\n deposit = {}\n deposit.store(:product_deposit_cost, product_deposit_cost)\n\n totals = {}\n totals.store(:total_cost, total_cost)\n totals.store(:total_paid, total_paid)\n totals.store(:total_pending, total_pending)\n\n summary = {products: products,\n supplements: supplements,\n deposit: deposit,\n totals: totals }\n\n end", "def total_tests\n Stats.test_results.values.reduce(0) { |memo, obj| memo += obj.length }\n end", "def summarize_results(results)\n text = super\n return text unless $stdout.tty?\n sums = sum_up_results(results)\n color =\n if sums['failure'] > 0\n 31 # red\n elsif sums['pending'] > 0\n 33 # yellow\n else\n 32 # green\n end\n \"\\e[#{color}m#{text}\\e[0m\"\n end", "def compute_score(results)\n # results is a hash of months and the results for each month\n # month => type => id => detail\n\n totals = { }\n prev_month_result = { }\n prev_month_totals = { }\n \n # iterate through each month\n results.sort.each do | month, result | \n month_total = compute_month_totals(result)\n totals[month] = month_total\n # total is already given by month_total[\"total\"]\n intersection = compute_intersection(prev_month_result, result)\n \n totals[month][\"existing\"] = intersection['existing']\n totals[month][\"new\"] = intersection['new']\n totals[month][\"closed\"] = intersection['closed']\n\n prev_month_totals = totals[month]\n prev_month_result = result\n end\n\n return totals\n \n end", "def summarizeMain(subKeys = nil)\n counts = Hash.new\n total = 0\n @role.keys.each {|name|\n if (subKeys.nil? || subKeys.include?(name))\n category = @role[name].first\n if (counts[category].nil?)\n counts[category] = [name]\n else\n counts[category].push(name)\n end\n total += 1.0\n end\n }\n return counts, total\n end", "def total_hits_count\n return top_hits_count + all_hits_count\n end", "def calcular_total hash\n p hash.inject(0) { |sum, tuple| sum += tuple[1] }\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print out a progress indicator of how many rotations / permutations have been processed and how many are remaining.
def print_rotation_count @rotation_count += 1 print "\r\e#{@rotation_count} of #{@maximum_rotations} processed..." $stdout.flush end
[ "def print_progress_bar_finish\n puts(NL) unless amount_mutation_results.zero?\n end", "def show_progress\n\t\t\t# bar_size is between 0 and 30\n finish_size = (((@top_card-12).to_f / (@deck.length-11).to_f) * 30).to_i\n\t\t\tremain_size = 30 - finish_size\n\t\t\tprint \"\\nProgress: \"\n\t\t\tfinish_size.times {print '▓'}\n\t\t\tremain_size.times {print '░'}\n\t\t\tputs\n\t\t\tputs\n end", "def print_progress \n puts @result\n puts \"You have #{@attemps} of #{@total_attempts} \"\n end", "def print_progress\n @progress_tracker ||= 0\n @progress_tracker += 1\n puts \"Total progress: #{@progress_tracker}\" if @progress_tracker % 500 == 0\n end", "def print_game_progress(count)\n puts \"#{\".\" * 50}\"\n puts \"\\nWord : #{@incomplete_word}\"\n puts \"Attempts Left: #{@limit - count}\"\n unless @incorrect_guesses.empty?\n puts \"Incorrect inputs: #{@incorrect_guesses.join(\", \")}\"\n end\n puts \"#{\".\" * 50}\"\n end", "def print_progress_bar_at i\n if (i%PROGRESSOR_SAMPLE_PERIOD == 0)\n print '.'\n $stdout.flush\n end\nend", "def synchronous_printout\n elapsed_time = Time.now - @threads_finished_at\n @synchronous_remaining = self.synchronous_items.count\n @synchronous_start_count ||= @synchronous_remaining\n @synchronous_completed_after_start = @synchronous_start_count - @synchronous_remaining\n if @synchronous_completed_after_start > 0\n @synchronous_rate_per_second = @synchronous_completed_after_start.to_f / elapsed_time\n seconds_remaining = @synchronous_remaining.to_f / @synchronous_rate_per_second\n @synchronous_nice_time = Time.at(seconds_remaining).utc.strftime(\"%H:%M:%S\")\n end\n print \"\\r#{\"Synchronous\".purple} -> Remaining: #{\"#{@synchronous_remaining}\".light_yellow} :: Completed: #{\"#{self.synchronous_completed}\".light_green} :: Rate: #{\"#{'%.2f' % ((@synchronous_rate_per_second || 0) * 60.0)}\".light_cyan} :: #{\"#{@synchronous_nice_time}\".light_green} \"\n end", "def print_progress(current, total, started_at)\n if total.nil?\n print_progress_nosize(current, started_at)\n return\n end\n ratio = [current.to_f / total, 1.0].min\n percent = (ratio * 100.0).round(1)\n arrow = (ratio * 20.0).floor\n time_spent = Time.now.to_i - started_at\n print(\"\\r[\")\n print('=' * [arrow - 1, 0].max)\n print('>')\n print('.' * (20 - arrow))\n print(\"] #{pretty_filesize(current)}/#{pretty_filesize(total)} (#{percent}% at #{pretty_filesize(current.to_f / time_spent)}/s) \")\n end", "def dump_progress\n title = \" #{current.to_s.rjust max_count_width}/#{example_count.to_s.rjust max_count_width}:\"\n max_width = 30\n self.color_index -= [bar_length - max_title_width - 18, current].min - 1\n examples = example_results.last(bar_length - max_title_width - 18)\n rainbow = examples.map {|r| highlight r}.join\n output.print (' ' * title.size) + rainbow + nyan_cat_back + \"\\n\"\n output.print (' ' * title.size) + rainbow + nyan_cat_ears + \"\\n\"\n output.print title + rainbow + nyan_cat_face + \"\\n\"\n output.print (' ' * title.size) + rainbow + nyan_cat_feet + \"\\r\\e[3A\"\n end", "def indicate_progress\n @iteration_counter += 1\n\n if iteration_rate.nil?\n if ((Time.now - started_at) % 3600).round >= 1\n @iteration_rate = iteration_counter\n end\n else\n if ((iteration_counter % iteration_rate) == 0)\n Bundler.ui.info \".\", false\n end\n end\n end", "def print_status\n next_run = ((@@next_task-Time.now)/60.0).round(2)\n\n print \"\\r\"\n print \"#{Time.now} #{[@chains.count,@steps_done].min}/#{@chain_count} chains active - #{@chains.sum(&:remaining_task_count)}/#{@task_count} Tasks remaining - Next task will run in #{next_run} minutes\"\n\n EM.add_timer 1, proc {\n print_status\n }\n end", "def progress_output\n arr = @progress.map do |key, value|\n \"#{key}: #{value}\\n\"\n end\n arr.join('')\n end", "def step(step_increment = 1)\n @current_steps+= step_increment\n new_markers = @max_steps != 0 ? (@current_steps / @steps_per_marker).to_i : max_markers\n\n new_percentage = @max_steps != 0 ? @current_steps * 100 / @max_steps : 100\n if @use_ansi and new_percentage != @current_percentage\n # This part uses ANSI escape sequences to show a running percentage\n # to the left of the progress bar\n print \"\\e[1D\" * (@current_markers + 5) if @current_percentage != 0 # go left\n print \"#{new_percentage}%\".rjust(4) << \" \"\n print \"\\e[1C\" * @current_markers if @current_markers != 0 # go back right\n $stdout.flush rescue nil\n @current_percentage = new_percentage\n end\n\n if new_markers > @current_markers\n print '.' * (new_markers - @current_markers)\n @current_markers = new_markers\n $stdout.flush rescue nil\n end\n if @current_steps == @max_steps\n print '.' * (max_markers - @current_markers) + ' '\n $stdout.flush rescue nil\n end\n end", "def complete_progress\n # Just clear the line back out\n print \"#{cl_reset}\"\n end", "def show_progress(collection, say=\"Progress\", &block)\n progress_bar = ProgressBar.new say, collection.count\n\n collection.each do |thing|\n block.call thing\n progress_bar.increment\n end\n\n puts # distinguish progress_bar output from other output\nend", "def progress; @progress; end", "def pryrc_progress_bar(len=1, done=false)\n last = \"\\r\"\n last = \" Load Completed!\\n\" if done\n \"|#{'====' * len}>#{last}\"\n end", "def overview\n \"#{progress.files_completed}/#{progress.file_count} files | #{progress.test_count} tests, #{progress.failure_count} failures\"\n end", "def increment_progress\n @progress += 1\n update_progress\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints a summary section for the entire report
def print_summary puts "\n\nScore : # Instances\n" << ("=" * 19) @summary_totals.each_with_index { |value, index| puts " %5d:%8d\n" % [index, value] unless value.nil? } puts "\n** End of Report" end
[ "def generate_summary_report\n Formatter.info 'Spec coverage summary:'\n\n puts ''\n\n `#{coverage_bin} report --root #{ coverage_root } text-summary #{ coverage_file }`.each_line do |line|\n puts line.sub(/\\n$/, '') if line =~ /\\)$/\n end\n\n puts ''\n end", "def print_summary(report)\n return unless log.summary_enabled\n\n log.log('')\n print_summary_files(report)\n\n print_summary_lints(report, is_append: true)\n\n log.log ' detected', false\n\n print_summary_corrected_lints(report, is_append: true)\n log.log ''\n end", "def summary; end", "def build_summary(global_coverage, class_coverage, module_coverage, method_coverage)\n output = Utils.heading_for_builder(\"Global coverage percentage : #{global_coverage.to_i}%\", global_coverage.to_i)\n output << \"<h3>Summary</h3><p>\\n<table class='bodyTable' style='width: 200px;'><tr><th>Type</th><th>Coverage</th></tr><tr class='a'><td><b>Class</b></td><td style='text-align: right;'>#{class_coverage}%</td></tr>\\n<tr class='b'><td><b>Module</b></td><td style='text-align: right;'>#{module_coverage}%</td></tr>\\n<tr class='a'><td><b>Method</b></td><td style='text-align: right;'>#{method_coverage}%</td></tr></table>\\n</p>\\n\\n\"\n end", "def summary\n #render unless @output\n @summary\n end", "def print_summary(ui)\n # Print whether it passed/failed at the top\n if failed?\n ui.puts \"\\n[!] Failed\\n\".red\n else\n ui.notice \"Passed\"\n end\n\n # A generic proc to handle the similarities between\n # errors and warnings.\n do_rules = proc do |name, rules|\n unless rules.empty?\n ui.puts \"\"\n ui.section(name.bold) do\n rules.each do |rule|\n title = rule.title.bold + \" - #{rule.object_applied_to}\"\n subtitles = [rule.description, link(rule.ref)]\n subtitles += [rule.metadata[:files].join(\":\")] if rule.metadata[:files]\n ui.labeled(title, subtitles)\n ui.puts \"\"\n end\n end\n end\n end\n\n # Run the rules\n do_rules.call(\"Errors\".red, errors)\n do_rules.call(\"Warnings\".yellow, warnings)\n end", "def print_summary\r\n traverse do |node|\r\n print node.effectively_skipped? ? '-' : '+'\r\n case\r\n when node.test? then print 'T'\r\n when node.suite? then print 'S'\r\n when node.static? then print 'X'\r\n else print '?'\r\n end\r\n print node.indented_name(' ')\r\n tags = node.effective_tags.to_a\r\n unless tags.empty?\r\n # highlight the tags that are explicit on this node\r\n tags = tags.map {|tag| node.explicit_tags.include?(tag) ? \"*#{tag}\" : tag }\r\n print \" [#{tags.join(',')}]\"\r\n end\r\n print \"\\n\"\r\n end\r\n end", "def print_summary\n stats = [statistics[:total_code_loc], statistics[:total_spec_loc]]\n stats.push(stats[1].to_f / stats[0].to_f)\n \n puts \" Code LOC: %s Test LOC: %s Code to Test Ratio: 1:%1.1f\" % stats\n puts\n end", "def summary\n definition \"Summary\"\n end", "def summary\n @summary\n end", "def summary_report\n s = StringIO.new\n s.puts \"Files analyzed : #{\"%12d\" % @time_metric.count}\"\n s.puts \"Elapsed time : #{\"%12d\" % @time_metric.duration} seconds\"\n s.puts \"Collection Rate : #{\"%16.3f\" % @time_metric.rate} files/sec\"\n s.puts \"Good files : #{\"%12d\" % @good_data_count}\"\n s.puts \" average size : #{\"%16.3f\" % @size_metric.mean} bytes\"\n s.puts \" minimum size : #{\"%16.3f\" % @size_metric.min} bytes\"\n s.puts \" maximum size : #{\"%16.3f\" % @size_metric.max} bytes\"\n s.puts \" sum of sizes : #{\"%12d\" % @size_metric.sum} bytes\"\n s.puts \"Bad files : #{\"%12d\" % @bad_data_count}\"\n return s.string\n end", "def summary_dl; @summary; end", "def dump\n puts \"*************************************************************************************\"\n puts \" Summary Results\"\n puts \"\\n\\n\"\n puts \" No of Soap Services found : #{@counts[:soap_services]}\"\n puts \" No of Rest Services found : #{@counts[:rest_services]}\"\n puts \" No of successful script imports : #{@counts[:success_script_imports]}\"\n puts \" No of failed script imports : #{@counts[:failed_script_imports]}\"\n puts \" No of scripts from services not found : #{@counts[:services_not_found_scripts]}\"\n puts \" No of script that were already imported : #{@counts[:existing]}\"\n puts \"*************************************************************************************\"\n end", "def summary(method = :to_text)\n ReportBuilder.new(no_title: true).add(self).send(method)\n end", "def summary\n puts \"HEAD count = #{@header_record.length}\"\n puts \"SUBM count = #{@submission_record.length}\"\n puts \"SUBN count = #{@submitter_record.length}\"\n puts \"INDI count = #{@individual_record.length}\"\n puts \"FAM count = #{@family_record.length}\"\n puts \"SOUR count = #{@source_record.length}\"\n puts \"REPO count = #{@repository_record.length}\"\n puts \"OBJE count = #{@multimedia_record.length}\"\n puts \"NOTE count = #{@note_record.length}\"\n puts \"TRLR count = #{@trailer_record.length}\"\n \n #p ClassTracker #Debugging line.\n #pp @indexes[:individual][\"IPB4\"] #debugging test to find and print an indivual's record with xref @IPB4@\n #pp @indexes[:family][\"F1\"] #debugging test to find and print a family record with the xref @F1@\n #pp @indexes[:note] #debugging test to print all NOTE records\n #p find(:individual,\"IB1024\").to_gedcom #debugging test to find an individual record with xref @IB1024@ and print the record and its sub-records.\n end", "def print_report(total_contacts, duplicate_contacts, invalid_contacts)\n print \"Summary:\\n\"\n print \"Total Valid Contacts: #{total_contacts}\\nDuplicate Contacts: #{duplicate_contacts}\\nInvalid Contacts: #{invalid_contacts}\\n\\n\"\n end", "def summary\n return \"\\nNo results identified.\\n\" if tally.keys.empty?\n result = [ \"\\nSummary of identified results:\\n\" ]\n sum = 0\n tally.keys.sort_by {|k| -1*tally[k] }.each do |k|\n sum += tally[k]\n result << \"%30s: %6d\" % [k, tally[k]]\n end\n result << \"%30s: %6d\" % ['TOTAL', sum]\n result.join \"\\n\"\n end", "def print_summary(dsobj)\n dshash = get_dshash(dsobj)\n ds_pollint_m = dshash['pollint_s'].to_i / 60\n dp_alert_count = 0.to_i\n\n # iterate over each datapoint\n dshash['datapoints'].each { |datapoint|\n dphash = get_dphash(datapoint)\n\n # is the alert trigger set on this datapoint\n if ( dphash['alert_trigger'].size > 0 )\n # yes, increment the alert count var\n dp_alert_count += 1\n end\n\n }\n\n puts \"Summary:\\n\"\n\n puts \" - datasource name:\\t\" + dshash['name'] + \"\\n\"\n puts \" - display name:\\t\" + dshash['dname'] + \"\\n\"\n puts \" - applies to:\\t\\t\" + dshash['applies'] + \"\\n\"\n puts \" - search keywords:\\t\" + dshash['tags'] + \"\\n\"\n puts \" - polling interval:\\t\" + ds_pollint_m.to_s + \"m\\n\"\n puts \" - multi instance:\\t\" + dshash['multi'] + \"\\n\"\n puts \" - datapoints:\\t\\t\" + dshash['datapoints'].size.to_s + \"\\n\"\n puts \" - datapoint alerts:\\t\" + dp_alert_count.to_s + \"\\n\"\n puts \" - graphs:\\t\\t\" + dshash['graphs'].size.to_s + \"\\n\"\n puts \" - overview graphs:\\t\" + dshash['ographs'].size.to_s + \"\\n\"\n puts \"=====================\\n\"\n end", "def summary\n api.get('summary')\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a chromosome object
def chromosome(id=nil) return if id.nil? begin self.chromosomes[id.intern] rescue end end
[ "def get_chromosome\n self\n end", "def copy\n Chromosome.new(map(&:copy))\n end", "def find_chromosome(id)\n @chromosomes.select { |ch| ch.id == id }.first\n end", "def chromosomes\n # Cache for performance\n if @chromosomes.nil?\n index() if not indexed?\n @chromosomes = Array.new\n Utils::SAMTools.idxstats(@data_file).each_line do |line| \n entry = line.chomp.split(\"\\t\")\n chr = entry[0]\n bases = entry[1].to_i\n mapped = entry[2].to_i\n unmapped = entry[3].to_i\n @chromosomes << chr if (mapped+unmapped) > 0\n end\n end\n \n return @chromosomes\n end", "def chromosomes\n # Cache for performance\n if @chromosomes.nil?\n s = Set.new\n self.each { |entry| s << entry.chr }\n @chromosomes = s.to_a\n end\n \n return @chromosomes\n end", "def copy\n c = Chromosome.new(0.0, @fitness_alg)\n genes.each do |gene|\n c << gene #push_back arreglo\n end\n c\n end", "def chromosomes\n @index.collect { |contig_info| contig_info.chr }.uniq\n end", "def random_chrom\n position_from_total 1+rand(genome_size),true\n end", "def copy\n karyotype = Karyotype.new(@genome, @chromosomes_description)\n karyotype.chromosomes = chromosomes.map(&:copy)\n karyotype\n end", "def mutate()\n Chromosome.new(@value + RNG::rand(-1.0 .. 1.0))\n end", "def best_chromosome\n return @population.min_by(&:fitness)\n end", "def add chromosome\n\t\t@arrayChromosomes << chromosome\n\tend", "def to_s\n \"<Chromosome> #{@chromosome.to_s} #{@fitness}\"\n end", "def best_chromosome()\n the_best = @population[0]\n @population.each do |chromosome|\n the_best = chromosome if chromosome.fitness > the_best.fitness\n end\n return the_best\n end", "def best_chromosome\n the_best = @population[0]\n @population.each do |chromosome|\n the_best = chromosome if chromosome.fitness > the_best.fitness\n end\n return the_best\n end", "def best_chromosome\n the_best = @population[0]\n @population.each do |chromosome|\n the_best = chromosome if chromosome.fitness > the_best.fitness\n end\n return the_best\n end", "def init_chromosomes(pop_size, macro_cromosomes)\n (0...pop_size).each do |j|\n chromo = Chromosome.new\n each do |gene|\n chromo << macro_cromosomes[j][gene]\n end\n @chromosomes << chromo\n end\n @best_chromosomes_experiences = @chromosomes.clone\n end", "def mutate(chromosome)\n gene_pos = (0...@num_genes).to_a.sample\n gene = chromosome[gene_pos]\n gene = gene.zero? ? 1 : 0\n chromosome[gene_pos] = gene\n chromosome\n end", "def hit_from; @genomic.from; end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if a user is defined.
def user_defined? !@user.nil? || !@user['userId'].nil? end
[ "def user_in_system\n\t\t# seems risky, but will be caught by numericality validations and if this isn't here it blows up\n\t\t# my shoulda matchers in attendance_test.rb\n\t\treturn true if self.user_id.nil?\n\t\tuser_ids = User.all.map { |user| user.id }\n\t\tunless user_ids.include?(self.user_id)\n\t\t\terrors.add(:user, 'is not recognized by the system')\n\t\t\treturn false\n\t\tend\n\t\ttrue\n\tend", "def user?\n get_mode == :user\n end", "def built_in?\n id == User::SYSTEM_USER_ID || id == User::DELETED_USER_ID\n end", "def user?\n type == :user_id\n end", "def exist?\n userinfo.exist?\n end", "def drc_user_has_local_user?\n return !get_local_user_id.nil?\n end", "def type_user?\n type&.downcase == 'user'\n end", "def is_user?\n usertype == 'user'\n end", "def may_launch? (definition)\n\t\treturn false if definition.is_special?\n\t\t#puts \"User.may_launch? #{definition} user.groups=#{self.groups} def.groups=#{definition.groups}:#{(self.groups & definition.groups).size}\"\n\t\tis_admin? or (self.roles & definition.roles).size > 0\n\tend", "def personal?\n @target.is_a?(Model::User) ? true : false\n end", "def user?\n is_a?(Merit::User)\n end", "def user_has? name\n\t\tuid = Sdb[:user_info].filter(:name => name).get(:uid)\n\t\tuid ? uid : nil\n\tend", "def current_user_exists?\n return false if config.current_user.nil?\n return true\n end", "def user_exists?(username)\n #TODO\n end", "def user_not_yet_created?\n return @user_not_yet_created if defined?(@user_not_yet_created)\n @user_not_yet_created = `getent passwd #{resource.name}` == \"\"\n end", "def user_exists?\n return (session[:user_id] && User.find(session[:user_id])) ? true : false\n end", "def user_params_set?\n return false if params[:user].nil?\n !params[:user][:username].blank? && !params[:user][:password].blank?\n end", "def user?\n role?(:user)\n end", "def user_exists?\n \t# User.find_by_email(@email) != nil\n \tuser_object != nil\n \tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /favorite_tweets POST /favorite_tweets.json
def create @favorite_tweet = FavoriteTweet.new(favorite_tweet_params) respond_to do |format| if @favorite_tweet.save format.html { redirect_to @favorite_tweet, notice: 'Favorite tweet was successfully created.' } format.json { render action: 'show', status: :created, location: @favorite_tweet } else format.html { render action: 'new' } format.json { render json: @favorite_tweet.errors, status: :unprocessable_entity } end end end
[ "def create_favorite_tweet tweet\n response = client.favorite tweet.id\n if response.first.is_a? Twitter::Tweet\n FavoriteTweet.create tweet_id: tweet.id,\n tweeted_by_username: tweet.user.screen_name,\n tweeted_by_user_picture: tweet.user.profile_image_url.to_s,\n tweeted_by_user_id: tweet.user.id,\n body: tweet.text\n end\n end", "def create\n user = user_from_token\n @tweet = user.tweets.new()\n @tweet.tweet = params[:tweet]\n if @tweet.save\n render :json => @tweet, :status => :created\n else\n render :json => @tweet.errors, :status => :unprocessable_entity\n end\n end", "def create\n @favtweet = Favtweet.new(params[:favtweet])\n\n respond_to do |format|\n if @favtweet.save\n format.html { redirect_to @favtweet, notice: 'Favtweet was successfully created.' }\n format.json { render json: @favtweet, status: :created, location: @favtweet }\n else\n format.html { render action: \"new\" }\n format.json { render json: @favtweet.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @favoriting_tweet = FavoritingTweet.new(favoriting_tweet_params)\n\n respond_to do |format|\n if @favoriting_tweet.save\n format.html { redirect_to @favoriting_tweet, notice: \"Favoriting tweet was successfully created.\" }\n format.json { render :show, status: :created, location: @favoriting_tweet }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @favoriting_tweet.errors, status: :unprocessable_entity }\n end\n end\n end", "def favorite_tweets\n logger.debug { \"#{__method__} is called twitter_user_id=#{id}\" }\n tweets = []\n tweets = InMemory::FavoriteTweet.find_by(uid) if InMemory.enabled? && InMemory.cache_alive?(created_at)\n tweets = Efs::FavoriteTweet.where(uid: uid) if tweets.blank? && Efs::Tweet.cache_alive?(created_at)\n tweets = ::S3::FavoriteTweet.where(uid: uid) if tweets.blank?\n tweets.map { |tweet| ::TwitterDB::Favorite.new(uid: uid, screen_name: screen_name, raw_attrs_text: tweet.raw_attrs_text) }\n end", "def favorite(tweet)\n Favorite.create(user: self, tweet: tweet, author: tweet.user)\n end", "def addTweets (tweets)\n\t\ttweets.each do |jsonTweet|\n\t\t\taddTweet jsonTweet\n\t\tend\n\tend", "def create\n @save_tweet = SaveTweet.new(save_tweet_params)\n @save_tweet.user_id = @user.id\n\n if @save_tweet.save\n render json: @save_tweet, status: :created, location: @save_tweet\n else\n render json: @save_tweet.errors, status: :unprocessable_entity\n end\n end", "def create\n params = tweet_params\n name = params[:name]\n user_id = params[:user_id]\n content = params[:content]\n @tweet = Tweet.new({user_id: user_id, content: content })\n\n if @tweet.save\n tweets = get_tweets(name)\n render json: { data: tweets }\n else\n render json: @tweet.errors, status: :unprocessable_entity\n end\n end", "def send_favorite(tweet)\n FastProwl.add(\n :application => PreyFetcher::config(:app_prowl_appname),\n :providerkey => PreyFetcher::config(:app_prowl_provider_key),\n :apikey => prowl_api_key,\n :priority => favorite_priority,\n :event => \"Favorited by @#{tweet[:from]}\",\n :description => tweet[:text].unescaped,\n :url => (custom_url.blank?) ? nil : custom_url\n )\n Notification.create(:twitter_user_id => twitter_user_id, :type => Notification::TYPE_FAVORITE)\n end", "def favorite(id)\n post(\"/favorites/create/#{id}.json\")\n end", "def create_favorite(favorite_params)\n handle_error { sendsecure_connection.post(\"api/v2/enterprises/#{@enterprise_account}/users/#{@user_id}/favorites.json\", favorite_params) }\n end", "def favorite_tweet(tweet)\n # Ternary to prevent duplicates\n favorited_tweet?(tweet) ? favorite_tweets : favorite_tweets << tweet\n end", "def post_tweet(user_id, tweet_id)\n @alltweets << [user_id, tweet_id]\n end", "def post_tweet(user_id, tweet_id)\n \n end", "def favorited_tweet?(tweet)\n favorite_tweets.include? tweet\n end", "def create\n @saved_tweet = SavedTweet.new(saved_tweet_params)\n\n respond_to do |format|\n if @saved_tweet.save\n format.html { redirect_to @saved_tweet, notice: 'Saved tweet was successfully created.' }\n format.json { render action: 'show', status: :created, location: @saved_tweet }\n else\n format.html { render action: 'new' }\n format.json { render json: @saved_tweet.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @favoritetweet = Favoritetweet.new(params[:favoritetweet])\n\n respond_to do |format|\n if @favoritetweet.save\n format.html { redirect_to(@favoritetweet, :notice => 'Favoritetweet was successfully created.') }\n format.xml { render :xml => @favoritetweet, :status => :created, :location => @favoritetweet }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @favoritetweet.errors, :status => :unprocessable_entity }\n end\n end\n end", "def add_to_favorite\n @favorite = @user.likes.new(movie_id: @movie.id, favorite: true)\n\n if @favorite.save\n render json: @movie, status: :created\n else\n render json: @favorite.errors, status: :unprocessable_entity\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /favorite_tweets/1 PATCH/PUT /favorite_tweets/1.json
def update respond_to do |format| if @favorite_tweet.update(favorite_tweet_params) format.html { redirect_to @favorite_tweet, notice: 'Favorite tweet was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @favorite_tweet.errors, status: :unprocessable_entity } end end end
[ "def update\n @favtweet = Favtweet.find(params[:id])\n\n respond_to do |format|\n if @favtweet.update_attributes(params[:favtweet])\n format.html { redirect_to @favtweet, notice: 'Favtweet was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @favtweet.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @tweet = Tweet.find(params[:id])\n\n if @tweet.update(tweet_params)\n head :no_content\n else\n render json: @tweet.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @favoriting_tweet.update(favoriting_tweet_params)\n format.html { redirect_to @favoriting_tweet, notice: \"Favoriting tweet was successfully updated.\" }\n format.json { render :show, status: :ok, location: @favoriting_tweet }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @favoriting_tweet.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @favorite.update(favorite_params)\n render json: @favorite, status: :ok\n else\n render json: @favorite.errors, status: :unprocessable_entity\n end\n end", "def update\n @custom_tweet = CustomTweet.find(params[:id])\n\n respond_to do |format|\n if @custom_tweet.update_attributes(params[:custom_tweet])\n format.html { redirect_to @custom_tweet, notice: 'Custom tweet was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @custom_tweet.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @favorite = Favorite.find(params[:id])\n @favorite.user_id = params[:user_id]\n @favorite.announcement_id = params[:announcement_id]\n @favorite.save\n render json:@favorite\n end", "def update\n @tweet = Tweet.find(params[:id])\n\n respond_to do |format|\n if @tweet.update_attributes(params[:tweet])\n format.html { redirect_to(@tweet, :notice => 'Tweet was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @tweet.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @new_tweet.update(new_tweet_params)\n format.html { redirect_to @new_tweet, notice: 'New tweet was successfully updated.' }\n format.json { render :show, status: :ok, location: @new_tweet }\n else\n format.html { render :edit }\n format.json { render json: @new_tweet.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @favoritetweet = Favoritetweet.find(params[:id])\n\n respond_to do |format|\n if @favoritetweet.update_attributes(params[:favoritetweet])\n format.html { redirect_to(@favoritetweet, :notice => 'Favoritetweet was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @favoritetweet.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @saved_tweet.update(saved_tweet_params)\n format.html { redirect_to @saved_tweet, notice: 'Saved tweet was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @saved_tweet.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @quick_tweet = QuickTweet.find(params[:id])\n\n respond_to do |format|\n if @quick_tweet.update_attributes(params[:quick_tweet])\n format.html { redirect_to @quick_tweet, notice: 'Quick tweet was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @quick_tweet.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @retweet.update(tweet_params)\n format.html { redirect_to retweets_path, notice: 'Retweet was successfully updated.' }\n format.json { render :show, status: :ok, location: @retweet }\n else\n format.html { render :edit }\n format.json { render json: @retweet.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @hashtags_tweet = HashtagsTweet.find(params[:id])\n\n respond_to do |format|\n if @hashtags_tweet.update_attributes(params[:hashtags_tweet])\n format.html { redirect_to @hashtags_tweet, notice: 'Hashtags tweet was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @hashtags_tweet.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @favorite_toy.update(favorite_toy_params)\n format.html { redirect_to @favorite_toy, notice: 'Favorite toy was successfully updated.' }\n format.json { render :show, status: :ok, location: @favorite_toy }\n else\n format.html { render :edit }\n format.json { render json: @favorite_toy.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @trash_tweet.update(trash_tweet_params)\n format.html { redirect_to @trash_tweet, notice: 'Trash tweet was successfully updated.' }\n format.json { render :show, status: :ok, location: @trash_tweet }\n else\n format.html { render :edit }\n format.json { render json: @trash_tweet.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @favorite_template.update(favorite_template_params)\n render json: @favorite_template\n end", "def update\n respond_to do |format|\n if @create_tweet.update(create_tweet_params)\n format.html { redirect_to @create_tweet, notice: 'Create tweet was successfully updated.' }\n format.json { render :show, status: :ok, location: @create_tweet }\n else\n format.html { render :edit }\n format.json { render json: @create_tweet.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @fake_twitter = FakeTwitter.find(params[:id])\n\n respond_to do |format|\n if @fake_twitter.update_attributes(params[:fake_twitter])\n format.html { redirect_to @fake_twitter, notice: 'Fake twitter was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @fake_twitter.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @tweet_file.update(tweet_file_params)\n format.html { redirect_to @tweet_file, notice: 'Tweet file was successfully updated.' }\n format.json { render :show, status: :ok, location: @tweet_file }\n else\n format.html { render :edit }\n format.json { render json: @tweet_file.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /favorite_tweets/1 DELETE /favorite_tweets/1.json
def destroy TwitterSyncWorker.new.delete(session[:user_id], @favorite_tweet.id) @favorite_tweet.destroy respond_to do |format| format.html { redirect_to request.referer } format.json { head :no_content } end end
[ "def destroy\n @favtweet = Favtweet.find(params[:id])\n @favtweet.destroy\n\n respond_to do |format|\n format.html { redirect_to favtweets_url }\n format.json { head :no_content }\n end\n end", "def destroy\n user = user_from_token\n user.tweets.destroy(params[:id])\n head :no_content\n end", "def destroy\n @interesting_tweet.destroy\n respond_to do |format|\n format.html { redirect_to interesting_tweets_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @favoritetweet = Favoritetweet.find(params[:id])\n @favoritetweet.destroy\n\n respond_to do |format|\n format.html { redirect_to(favoritetweets_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @tweet = Tweet.find(params[:id])\n @tweet.destroy\n\n respond_to do |format|\n format.html { redirect_to tweets_url }\n format.json { head :ok }\n end\n end", "def destroy\n @favoriting_tweet.destroy\n respond_to do |format|\n format.html { redirect_to favoriting_tweets_url, notice: \"Favoriting tweet was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @tweet = Tweet.find(params[:id])\n @tweet.destroy\n\n respond_to do |format|\n format.html { redirect_to tweets_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @saved_tweet.destroy\n respond_to do |format|\n format.html { redirect_to saved_tweets_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @gettweet = Gettweet.find(params[:id])\n @gettweet.destroy\n\n respond_to do |format|\n format.html { redirect_to gettweets_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @tweet = @site.tweets.find(params[:id])\n @tweet.destroy\n\n respond_to do |format|\n format.html { redirect_to(tweets_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @hashtags_tweet = HashtagsTweet.find(params[:id])\n @hashtags_tweet.destroy\n\n respond_to do |format|\n format.html { redirect_to hashtags_tweets_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @custom_tweet = CustomTweet.find(params[:id])\n @custom_tweet.destroy\n\n respond_to do |format|\n format.html { redirect_to custom_tweets_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @activity_tweet = ActivityTweet.find(params[:id])\n @activity_tweet.destroy\n\n respond_to do |format|\n format.html { redirect_to activity_tweets_url }\n format.json { head :ok }\n end\n end", "def destroy\n @l_tweet = LTweet.find(params[:id])\n @l_tweet.destroy\n\n respond_to do |format|\n format.html { redirect_to l_tweets_url }\n format.json { head :ok }\n end\n end", "def destroy\n @favorite = Favorite.find(params[:id])\n @favorite.destroy\n\n respond_to do |format|\n format.html { redirect_to favorites_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @tweet = Tweet.find(params[:id])\n @tweet.destroy\n\n respond_to do |format|\n format.html { redirect_to(tweets_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @retweet = Retweet.find(params[:id])\n @retweet.destroy\n\n respond_to do |format|\n format.html { redirect_to retweets_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @quick_tweet = QuickTweet.find(params[:id])\n @quick_tweet.destroy\n\n respond_to do |format|\n format.html { redirect_to quick_tweets_url }\n format.json { head :no_content }\n end\n end", "def delete_tweet(db_file, twitter_client, tweet_id)\n db = SQLite3::Database.new db_file\n $logger.info(\"Deleting tweet id #{tweet_id}\")\n destroy_output = twitter_client.destroy_status(tweet_id)\n $logger.debug(\"Deleted tweet id #{tweet_id}, updating DB\")\n delete_id = destroy_output[0].id\n delete_timestamp = Time.now.strftime('%s')\n update_sql = <<-SQL\n UPDATE tweets SET\n delete_id = ?,\n delete_timestamp = ?\n WHERE id = ?\n SQL\n db.execute(update_sql, [delete_id, delete_timestamp, tweet_id])\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
jobs:stop JOB_ID Stop a running job.
def stop job_id = shift_argument unless job_id error("Usage: mortar jobs:stop JOB_ID\nMust specify JOB_ID.") end response = api.stop_job(job_id).body #TODO: jkarn - Once all servers have the additional message field we can remove this check. if response['message'].nil? display("Stopping job #{job_id}.") else display(response['message']) end end
[ "def stop\n job_id = shift_argument\n unless job_id\n error(\"Usage: mortar jobs:stop JOB_ID\\nMust specify JOB_ID.\")\n end\n validate_arguments!\n\n response = api.stop_job(job_id).body \n\n #TODO: jkarn - Once all servers have the additional message field we can remove this check.\n if response['message'].nil?\n display(\"Stopping job #{job_id}.\")\n else\n display(response['message'])\n end\n end", "def job_stop(args = { })\n identifier = args[:identifier]\n query = { 'identifier' => identifier }\n do_post('StopJob', { }, :query => query)\n end", "def kill\n interface.client.kill_job(job_id)\n end", "def stop\n @job = Job.find(params[:id])\n\n result = StopJob.new(@job).call\n respond_to do |format|\n if result.success?\n format.html { redirect_to jobs_url, notice: \"Job was successfully stopped.\" }\n format.json { head :no_content }\n else\n format.html { redirect_to jobs_url, alert: result.error }\n format.json { render json: { error: result.error }, status: :unprocessable_entity }\n end\n end\n end", "def kill_job(job_id)\n __push([], :kill_job, job_id)\n end", "def stop\n # TODO: can this be elsewhere?\n puts \"Stopping job #{@sandbox.job.id}\"\n\n @thread.kill\n ActiveRecord::Base.clear_active_connections!\n @mutex.synchronize { @thread_status.running = false }\n end", "def stop\n\t\tif (self.job_thread)\n\t\t\tself.job_thread.kill\n\t\t\tself.job_thread = nil\n\t\tend\n\n\t\tclean_proc.call(ctx) if (clean_proc)\n\tend", "def stop\n interface.remove_job_monitor(self)\n end", "def stop\n interface.remove_new_job_listener(self)\n end", "def cancel(job_id)\n driver.cancel(job_id)\n end", "def kill(job_id, user=@user)\n execute('job', user, {\n oozie: @oozie,\n kill: job_id\n })\n end", "def cancel(envid)\n @jobList.each { |job|\n if job.envid == envid && job.status == \"RUNNING\"\n begin\n Process.kill('TERM', job.pid.to_i)\n rescue Errno::ESRCH\n reportDone(job.pid, -1)\n end\n end\n }\n end", "def stop\n stop_erequest = self.environment.erequests.create(:command => 'stop')\n # sql = \"select * from jobs where erequest_id = #{self.id} and stop_erequest_id IS NULL and finished_at IS null;\"\n jobs = Job.find_all_by_erequest_id_and_stop_erequest_id_and_finished_at(self.id,nil,nil)\n stop_erequest.stop_jobs jobs\n end", "def stop\n jobs_active_record_relation.to_a.each(&:stop)\n\n true\n rescue PBS::Error => e\n msg = \"A PBS::Error occurred when trying to stop jobs for simulation #{id}: #{e.message}\"\n errors[:base] << msg\n Rails.logger.error(msg)\n\n false\n end", "def kill\n self.class.kill_jobs self.id\n end", "def stop\n jobs_active_record_relation.to_a.each(&:stop)\n\n true\n rescue PBS::Error => e\n msg = \"An error occurred when trying to stop jobs for simulation #{id}: #{e.message}\"\n errors[:base] << msg\n Rails.logger.error(msg)\n\n false\n end", "def kill_job\n raise UnableToKillJobNotRunningError unless self.status == RUNNING\n begin\n JobScheduler.find.try(:kill_job, self)\n raise KilledJobError.new 'Job Killed'\n rescue => err\n job_error_handler(err)\n ensure\n close_job \n end\n end", "def terminate\n find_job\n if @job.nil?\n type = :error\n text = \"Sorry, this job does not exist or is not accessible by you\"\n path = api_jobs_path\n\n render json: { path: path, message: { type: type, text: text } }, adapter: :json\n return\n end\n if !@job.terminal?\n DNAnexusAPI.new(@context.token).call(@job.dxid, \"terminate\")\n type = :success\n text = \"Job was successfully terminated\"\n else\n type = :warning\n text = \"Job is in terminal state and can not be terminated\"\n end\n path = api_job_path(@job)\n\n render json: { path: path, message: { type: type, text: text } }, adapter: :json\n end", "def stop (bundleId)\n execute(:stop, bundleId)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /favourite_foods/1 GET /favourite_foods/1.json
def show @favourite_food = FavouriteFood.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @favourite_food } end end
[ "def favorite_foods\n get(\"/user/#{@user_id}/foods/log/favorite.json\")\n end", "def index\n @favourites = Favourite.all\n render json: @favourites\n end", "def index\n @favourite_foods = FavouriteFood.all\n end", "def show\n render json: @favourites\n end", "def show\n @favourite_listing = get_favourite_listing(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @favourite_listing }\n end\n end", "def get_favourite_restaurants\n @profile = Profile.find(params[:id])\n @restaurants = @profile.favourites\n\n render status: 200, json: @restaurants\n end", "def show\n @fav = Fav.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fav }\n end\n end", "def food_info(food_id)\n get(\"/foods/#{food_id}.json\")\n end", "def index\n @foods = Food.all\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @foods }\n end\n end", "def frequent_foods\n get(\"/user/#{@user_id}/foods/log/frequent.json\")\n end", "def favorite_activities\n get(\"/user/#{@user_id}/activities/favorite.json\")\n end", "def favorite_foods\n @favorite_foods\n end", "def show\n @favorite_resource = FavoriteResource.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @favorite_resource }\n end\n end", "def show\n @fav ||= Fav.find(params[:id])\n render json: FavSerializer.new(@fav)\n end", "def favorite_activities()\n get(\"/user/#{@user_id}/activities/favorite.json\")\n end", "def get_favs\n beers = @user_beer.get_favs(@current_user)\n\n render json: {\n status: 200,\n beers: beers,\n errors: nil\n }\n end", "def favorites\n artworks = Artwork.where(favorite: true)\n shares = ArtworkShare.where(favorite: true)\n render json: artworks + shares\n end", "def favorite_activities\n get(\"user/#{user_id}/activities/favorite.json\")\n end", "def show\n\n @food = Food.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @food }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /favourite_foods/new GET /favourite_foods/new.json
def new @favourite_food = FavouriteFood.new respond_to do |format| format.html # new.html.erb format.json { render json: @favourite_food } end end
[ "def new\n @favourite = Favourite.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @favourite }\n end\n end", "def new\n @fav = Fav.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @fav }\n end\n end", "def new\n @favorite = Favorite.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @favorite }\n end\n end", "def new\n @favorite = Favorite.new\n\n respond_to do |format|\n format.html # new.html.erb\n #format.json { render json: @favorite }\n end\n end", "def new\n @favorite_resource = FavoriteResource.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @favorite_resource }\n end\n end", "def new\n @favourite_listing = FavouriteListing.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @favourite_listing }\n end\n end", "def new\n @food = Food.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @food }\n end\n end", "def create\n @favourite_food = FavouriteFood.new(favourite_food_params)\n\n respond_to do |format|\n if @favourite_food.save\n format.html { redirect_to @favourite_food, notice: 'Favourite food was successfully created.' }\n format.json { render :show, status: :created, location: @favourite_food }\n else\n format.html { render :new }\n format.json { render json: @favourite_food.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @fav_line_item = FavLineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @fav_line_item }\n end\n end", "def new\n @favtweet = Favtweet.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @favtweet }\n end\n end", "def new\n @food = Food.new\n @food.user = current_user\n @series = get_series('foods')\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @food }\n end\n end", "def new\n @food_item = FoodItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @food_item }\n end\n end", "def new\n @favorite_flyer = FavoriteFlyer.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @favorite_flyer }\n end\n end", "def new\n @favorito = Favorito.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @favorito }\n end\n end", "def new\n @fish = Fish.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @fish }\n end\n end", "def new\n @fooditem = Fooditem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @fooditem }\n end\n end", "def create\n @fav_recipe = FavRecipe.new(fav_recipe_params)\n\n respond_to do |format|\n if @fav_recipe.save\n format.html { redirect_to @fav_recipe, notice: 'Fav recipe was successfully created.' }\n format.json { render action: 'show', status: :created, location: @fav_recipe }\n else\n format.html { render action: 'new' }\n format.json { render json: @fav_recipe.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @line_food = LineFood.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_food }\n end\n end", "def create\n @fav = Fav.new(fav_params)\n @fav.id = @fav.collectionId\n if @fav.save\n render json: @fav, status: :created, location: api_fav_path(@fav)\n else\n render json: @fav.errors, status: :unprocessable_entity\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PUT /favourite_foods/1 PUT /favourite_foods/1.json
def update @favourite_food = FavouriteFood.find(params[:id]) respond_to do |format| if @favourite_food.update_attributes(params[:favourite_food]) format.html { redirect_to @favourite_food, notice: 'Favourite food was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @favourite_food.errors, status: :unprocessable_entity } end end end
[ "def update\r\n @fav = Fav.find(params[:id])\r\n\r\n if @fav.update(fav_params)\r\n render json: @fav\r\n else\r\n render json: { error: \"Fav updating error\" }, status: :unprocessable_entity\r\n end\r\n end", "def favorite_foods\n get(\"/user/#{@user_id}/foods/log/favorite.json\")\n end", "def update\n respond_to do |format|\n if @favourite_food.update(favourite_food_params)\n format.html { redirect_to @favourite_food, notice: 'Favourite food was successfully updated.' }\n format.json { render :show, status: :ok, location: @favourite_food }\n else\n format.html { render :edit }\n format.json { render json: @favourite_food.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @favorite.update(favorite_params)\n render json: @favorite, status: :ok\n else\n render json: @favorite.errors, status: :unprocessable_entity\n end\n end", "def update\n @fav = Fav.find(params[:id])\n\n if @fav.update(fav_params)\n head :no_content\n else\n render json: @fav.errors, status: :unprocessable_entity\n end\n end", "def update\n @favorite = Favorite.find(params[:id])\n @favorite.user_id = params[:user_id]\n @favorite.announcement_id = params[:announcement_id]\n @favorite.save\n render json:@favorite\n end", "def update\n json_response(@food_item.update!(food_item_params))\n end", "def update\n respond_to do |format|\n if @favory.update(favory_params)\n format.html { redirect_to @favory, notice: \"Favory was successfully updated.\" }\n format.json { render :show, status: :ok, location: @favory }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @favory.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @favo.update(favo_params)\n format.html { redirect_to @favo, notice: 'Favo was successfully updated.' }\n format.json { render :show, status: :ok, location: @favo }\n else\n format.html { render :edit }\n format.json { render json: @favo.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @fav = Fav.find(params[:id])\n\n respond_to do |format|\n if @fav.update_attributes(params[:fav])\n format.html { redirect_to @fav, notice: 'Fav was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @fav.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n user = User.find_by(id: params[:user_id])\n recipe_id = params[:id]\n user_recipe_favorite = UserRecipeFavorite.new(user_id: user.id, recipe_id: recipe_id)\n authorize user_recipe_favorite\n if params[:favorite] == 'false' # if favorite is not checked\n user.user_recipe_favorites.where(recipe_id: recipe_id).first.destroy # remove recipe from favorites.\n elsif !user.user_recipe_favorites.exists?(recipe_id: recipe_id) # if favorite is checked but recipe doesn't exist in favaorites yet\n user.user_recipe_favorites.create(user_id: user.id, recipe_id: recipe_id) # add to recipe favorites\n end\n render json: {}\n end", "def add_favorite_food(food_id)\n post(\"user/#{user_id}/foods/log/favorite/#{food_id}.json\")\n end", "def update\n respond_with Favor.update(params[:id], params[:favor])\n end", "def update\n respond_to do |format|\n if @fav_item.update(fav_item_params)\n format.html { redirect_to @fav_item, notice: \"Fav item was successfully updated.\" }\n format.json { render :show, status: :ok, location: @fav_item }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @fav_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @fav_recipe.update(fav_recipe_params)\n format.html { redirect_to @fav_recipe, notice: 'Fav recipe was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @fav_recipe.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @favorite_toy.update(favorite_toy_params)\n format.html { redirect_to @favorite_toy, notice: 'Favorite toy was successfully updated.' }\n format.json { render :show, status: :ok, location: @favorite_toy }\n else\n format.html { render :edit }\n format.json { render json: @favorite_toy.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @user_favourite_recipe.update(user_favourite_recipe_params)\n format.html { redirect_to @user_favourite_recipe, notice: 'User favourite recipe was successfully updated.' }\n format.json { render :show, status: :ok, location: @user_favourite_recipe }\n else\n format.html { render :edit }\n format.json { render json: @user_favourite_recipe.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @favourite = Favourite.find(params[:id])\n\n respond_to do |format|\n if @favourite.update_attributes(params[:favourite])\n flash[:notice] = 'Favourite was successfully updated.'\n format.html { redirect_to(@favourite) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @favourite.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @favourites = Favourite.find(params[:id])\n\n respond_to do |format|\n if @favourites.update_attributes(params[:favourites])\n flash[:notice] = 'Favourites was successfully updated.'\n format.html { redirect_to(@favourites) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @favourites.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /favourite_foods/1 DELETE /favourite_foods/1.json
def destroy @favourite_food = FavouriteFood.find(params[:id]) @favourite_food.destroy respond_to do |format| format.html { redirect_to favourite_foods_url } format.json { head :no_content } end end
[ "def delete_food(food_id)\n delete(\"user/#{user_id}/foods/#{food_id}.json\")\n end", "def delete_favorite_food(food_id)\n delete(\"user/#{user_id}/foods/log/favorite/#{food_id}.json\")\n end", "def destroy\n @dish_food.destroy\n respond_to do |format|\n format.html { redirect_to dish_foods_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @food = Food.find(params[:id])\n @food.destroy\n\n respond_to do |format|\n format.html { redirect_to foods_url }\n format.json { head :ok }\n end\n end", "def destroy\n @line_food = LineFood.find(params[:id])\n @line_food.destroy\n\n respond_to do |format|\n format.html { redirect_to line_foods_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @favourite = Favourite.find(params[:id])\n @favourite.destroy\n\n respond_to do |format|\n format.html { redirect_to favourites_url }\n format.json { head :no_content }\n end\n end", "def destroy\n food = Food.find(params[:id])\n food.destroy\n head :no_content\n end", "def destroy\n @food_item = FoodItem.find(params[:id])\n @food_item.destroy\n\n respond_to do |format|\n format.html { redirect_to food_items_url }\n format.json { head :ok }\n end\n end", "def destroy\n @fooditem = Fooditem.find(params[:id])\n @fooditem.destroy\n\n respond_to do |format|\n format.html { redirect_to fooditems_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @fav_recipe.destroy\n respond_to do |format|\n format.html { redirect_to fav_recipes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @food_visit = FoodVisit.find(params[:id])\n @food_visit.destroy\n\n respond_to do |format|\n format.html { redirect_to pending_food_visits_path }\n format.json { head :no_content }\n end\n end", "def destroy\n @saved_food = SavedFood.find(params[:id])\n @saved_food.destroy\n\n respond_to do |format|\n format.html { redirect_to(saved_foods_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @food_stuff = FoodStuff.find(params[:id])\n @food_stuff.destroy\n\n respond_to do |format|\n format.html { redirect_to food_stuffs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @my_food = MyFood.find(params[:id])\n @my_food.destroy\n\n respond_to do |format|\n format.html { redirect_to(my_foods_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @fridge_food = FridgeFood.find(params[:id])\n @fridge_food.destroy\n\n respond_to do |format|\n format.html { redirect_to(fridge_foods_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @fav = Fav.find(params[:id])\n @fav.destroy\n\n respond_to do |format|\n format.html { redirect_to favs_url }\n format.json { head :ok }\n end\n end", "def destroy\n @food.destroy\n\n respond_to do |format|\n format.html { redirect_to(foods_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @fav_line_item = FavLineItem.find(params[:id])\n @fav_line_item.destroy\n\n respond_to do |format|\n format.html { redirect_to fav_line_items_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @line_favourite.destroy\n respond_to do |format|\n format.html { redirect_to line_favourites_url }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /shops/1 DELETE /shops/1.xml
def destroy @shop = Shop.find(params[:id]) @shop.destroy respond_to do |format| format.html { redirect_to(admin_shops_url) } format.xml { head :ok } end end
[ "def destroy\n @shop = Shop.find(params[:id])\n @shop.destroy\n\n respond_to do |format|\n format.html { redirect_to(shops_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @shops_visit = ShopsVisit.find(params[:id])\n @shops_visit.destroy\n\n respond_to do |format|\n format.html { redirect_to(shops_visits_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @shops_request = ShopsRequest.find(params[:id])\n @shops_request.destroy\n\n respond_to do |format|\n format.html { redirect_to(shops_requests_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @client_shop = ClientShop.find(params[:id])\n @client_shop.destroy\n\n respond_to do |format|\n format.html { redirect_to(client_shops_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @scrap_xml = ScrapXml.find(params[:id])\n @scrap_xml.destroy\n\n respond_to do |format|\n format.html { redirect_to(scrap_xmls_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @workshop = Workshop.find(params[:id])\n @workshop.destroy\n\n respond_to do |format|\n format.html { redirect_to(workshops_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @repairshop = Repairshop.find(params[:id])\n @repairshop.destroy\n\n respond_to do |format|\n format.html { redirect_to(repairshops_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @hops_addition = HopsAddition.find(params[:id])\n @hops_addition.destroy\n\n respond_to do |format|\n format.html { redirect_to(hops_additions_url) }\n format.xml { head :ok }\n end\n end", "def demolish\n @shop = Shop.find(params[:id])\n @shop.destroy\n\n respond_to do |format|\n format.html { redirect_to(shops_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @user_shop = UserShop.find(params[:id])\n @user_shop.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_user_shops_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @user.shops.delete(@shop)\n @shop.destroy\n respond_to do |format|\n format.html { redirect_to shops_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @yoga_workshop = YogaWorkshop.find(params[:id])\n @yoga_workshop.destroy\n\n respond_to do |format|\n format.html { redirect_to workshops_url }\n format.xml { head :ok }\n end\n end", "def destroy\n @home_indices_shop = Home::Indices::Shop.find(params[:id])\n @home_indices_shop.destroy\n\n respond_to do |format|\n format.html { redirect_to home_indices_shops_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @sop = Sop.find(params[:id])\n @sop.destroy\n\n respond_to do |format|\n format.html { redirect_to sops_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @shopcat = Shopcat.find(params[:id])\n @shopcat.destroy\n\n respond_to do |format|\n format.html { redirect_to(shopcats_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @favorite_shop = FavoriteShop.find(params[:id])\n @favorite_shop.destroy\n\n respond_to do |format|\n format.html { redirect_to(favorite_shops_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @title = \"Destroy Operations\"\n @operation = Operation.find(params[:id])\n @operation.destroy\n\n respond_to do |format|\n format.html { redirect_to(operations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @shelf = Shelf.find(params[:id])\n @shelf.destroy\n\n respond_to do |format|\n format.html { redirect_to(shelves_url) }\n format.xml { head :ok }\n end\n end", "def del\n @office1 = Office1.find(params[:id])\n @office1.destroy\n\n respond_to do |format|\n format.html { redirect_to(office1s_url) }\n format.xml { head :ok }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compiles all routes into regexps.
def compile! return if compiled? @routes.each_with_index do |route, index| route.index = index route.regexp = /(?<_#{index}>#{route.matcher.to_regexp})/ end @compiled = true end
[ "def compile!\n return if compiled?\n @regexps = @routes.map.with_index do |route, index|\n route.index = index\n /(?<_#{index}>#{route.matcher.to_regexp})/\n end\n @regexps = recursive_compile(@regexps)\n @compiled = true\n end", "def precompile_all_routes!\n mounted_apps.each do |app|\n app_obj = app.app_obj\n next unless app_obj.respond_to?(:precompile_routes?) && app_obj.precompile_routes?\n app_obj.setup_application!\n logger.devel \"Precompiled routes of #{app_obj} (routes size #{app_obj.compiled_router.routes.size})\"\n end\n end", "def regify\n if (@path.index('/'))\n grouping = []\n url = @path.split('/')\n for part in url\n if /^:/.match(part) \n token = part.gsub(/:/,'')\n # part = '(?P<'+token+'>.)'\n # part = '(\\.*)'\n # part = '(\\w*)'\n part = '([a-zA-Z0-9,-.%_~;]*)' # this picks up all allowable route tokens (a-zA-Z0-9,-.%)\n @tokens.push(token)\n end\n grouping.push(part)\n end\n out = \"^#{grouping.join('/')}\"\n out += \".#{@format.to_s}\" if @format != :html # we need to include the \n @grouping = Regexp.compile(out)\n else\n #handle default index route\n @grouping = Regexp.compile(\"/\")\n end\n end", "def compile\n if @paths.nil?\n router.named_routes[@name] = self if @name\n @paths = compile_paths\n @paths.each_with_index do |p1, i|\n @paths[i+1, @paths.size].each do |p2|\n raise AmbiguousRouteException.new if p1 === p2\n end\n end\n @paths.each do |path|\n current_node = router.root.add_path(path)\n working_set = current_node.add_request_methods(@conditions)\n working_set.map!{|node| node.add_arbitrary(@arbitrary)}\n working_set.each do |current_node|\n current_node.value = path\n end\n end\n end\n self\n end", "def initialize_routes\n @routes = Dio::Router.new\n self.class.rules ||= [] # routes { ... } block is optional and if it's missing the rules are nil.\n self.class.rules.each do |rule|\n @routes.__send__(*rule)\n end\n @routes.any \"/\", :index\n @routes.any \"/:action/?:id?.?:format?\", lambda { |params| params[:action] }\n # ap @routes\n end", "def initialize_routes\n @extended_routes.each do |verb, matches|\n matches.each do |match, data|\n register_route(verb, match, data[:args], data[:block])\n end\n end\n end", "def initialize(routes)\n @routes = routes.map { |r| '/' + r }\n @captures = Match.new []\n end", "def all_routes\n matching_routes\n end", "def generate_routes!\n Router.new(self).generate(@app)\n end", "def walk_the_routes\n routes.each do |route|\n if route[:route] === request.path_info\n instance_eval &route[:block] unless route[:block].nil?\n @nirb = route[:class].new(@nirb).call unless route[:class].nil?\n end\n \n route_frags = route[:route].split('/')\n path_frags = request.path_info.split('/')\n \n if route_frags.length === path_frags.length\n route_frags.each_with_index do |frag, index|\n if frag[0,1] === ':'\n request.params[frag[1..-1].to_sym] = path_frags[index]\n elsif frag[0,1] === '@'\n request.params[:method] = path_frags[index]\n elsif path_frags[index] != frag\n break\n end\n\n if index === route_frags.length - 1\n instance_eval &route[:block] unless route[:block].nil?\n @nirb = route[:class].new(@nirb).call unless route[:class].nil?\n end\n end\n end\n end\n end", "def add_routes(*lines)\n text = (lines.flatten.map do |line|\n line.strip!\n logger.route line\n \" #{line}\\n\"\n end).join\n\n sentinel = 'ActionController::Routing::Routes.draw do |map|'\n unless options[:pretend]\n gsub_file('config/routes.rb', /(#{Regexp.escape(sentinel)})/mi) {|match| \"#{match}\\n#{text}\" }\n end\n end", "def init_routes\n puts \"Adding the caboose routes...\"\n \n filename = File.join(@app_path,'config','routes.rb')\n return if !File.exists?(filename)\n return if !@force\n \n str = \"\" \n str << \"\\t# Catch everything with caboose\\n\" \n str << \"\\tmount Caboose::Engine => '/'\\n\"\n str << \"\\tmatch '*path' => 'caboose/pages#show'\\n\"\n str << \"\\troot :to => 'caboose/pages#show'\\n\" \n file = File.open(filename, 'rb')\n contents = file.read\n file.close \n if (contents.index(str).nil?)\n arr = contents.split('end', -1)\n str2 = arr[0] + \"\\n\" + str + \"\\nend\" + arr[1]\n File.open(filename, 'w') {|file| file.write(str2) }\n end \n end", "def make_r\n return @path_full if @path_full.is_a? Regexp\n return @path_regex if @path_regex.is_a? Regexp\n @path_regex = Route.make_r(@path_full)\n end", "def recursive_compile(regexps, paths = [])\n return paths if regexps.length.zero?\n paths << Regexp.union(regexps)\n regexps.shift\n recursive_compile(regexps, paths)\n end", "def process_routes\n if File.exists? \"#@path/config/routes.rb\"\n @processor.process_routes RubyParser.new.parse(File.read(\"#@path/config/routes.rb\"))\n end\n end", "def alter_regex_for_custom_routes(node); end", "def define_routes; end", "def rewrite_routes_trailing_slash\n trailing_slash = Regexp.new(/.*\\/\\?\\\\z/)\n no_trailing_slash = Regexp.new(/(.*)\\\\z\\//)\n Sinatra::Application.routes.each do |method, routes|\n routes.each do |r|\n route_regexp_str = r[0].inspect\n if trailing_slash.match(route_regexp_str)\n next\n else\n new_route = route_regexp_str.gsub(no_trailing_slash, \"\\\\1\\\\/?\\\\z/\")\n r[0] = eval(new_route)\n end\n end\n end\nend", "def generate_routes(urls, prefix = nil)\n urls.map do |url|\n prefix = prefix ? Regexp.escape(prefix) : ''\n url = url == \"/\" ? '' : Regexp.escape(url)\n if @keylen\n /^#{prefix}(#{url}\\/.+)#{RE_TH_BASE}-([0-9a-f]{#{@keylen}})#{RE_TH_EXT}$/\n else\n /^#{prefix}(#{url}\\/.+)#{RE_TH_BASE}#{RE_TH_EXT}$/\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds routes by using request or env.
def find_by(request_or_env) request = request_or_env.is_a?(Hash) ? Sinatra::Request.new(request_or_env) : request_or_env pattern = decode_pattern(request.path_info) verb = request.request_method rotation { |offset| match?(offset, pattern) }.select { |route| route.verb == verb } end
[ "def find_by(request_or_env)\n request = request_or_env.is_a?(Hash) ? Sinatra::Request.new(request_or_env) : request_or_env\n pattern = encode_default_external(request.path_info)\n verb = request.request_method\n rotation { |offset| match?(offset, pattern) }.select { |route| route.verb == verb }\n end", "def route_for env\n path = env[\"PATH_INFO\"]\n method = env[\"REQUEST_METHOD\"].downcase.to_sym\n route_array = routes[method].detect do |route|\n case route.first\n when String\n path == route.first\n when Regexp\n path =~ route.first\n end\n end\n return Route.new(route_array) if route_array\n return nil #No route matched\n end", "def find_route(request)\n @routes.find {|r| r.match?(request) }\n end", "def find_route(routes, request)\n transport = request.websocket? ? 'WS' : 'HTTP'\n routes.match(request.request_method, transport, request.path)\n end", "def route_for(request)\n index, params = if @around_match\n send(@around_match, request) { match(request) }\n else\n match(request)\n end\n route = routes[index] if index\n if !route\n raise ControllerExceptions::NotFound, \n \"No routes match the request: #{request.uri}\"\n end\n [route, params]\n end", "def route_for(request) #:nodoc:\n index, params = match(request)\n route = routes[index] if index\n if !route\n raise ControllerExceptions::NotFound, \n \"No routes match the request: #{request.uri}\"\n end\n [route, params]\n end", "def call(env)\n req = Rack::Request.new(env)\n routes = self.routes.select { |route| route.matches_filters?(req) }\n case routes.count\n when 1\n routes.first.call(env)\n when 0\n raise Sly::NotFoundError.new(\"No matching routes.\")\n else\n # sort by how many captures are in the regex and take the lowest\n # if there are two routes with the lowest number of captures then\n # return the `TooMany` response\n routes = sort_by_path_params(routes)\n routes.first.call(env)\n end\n end", "def match(request)\n path = String.normalize_path(request.path)\n method = request.method\n\n match, data = nil\n @sets.each { |set|\n match, data = set[1].match(path, method)\n break if match\n }\n\n fns = []\n if match\n fns = match[3]\n\n # handle route params\n #TODO where to do this?\n request.params.merge!(Hash.strhash(self.data_from_path(path, data, match[1])))\n\n #TODO where to do this?\n request.route_path = match[4]\n end\n\n fns\n end", "def find_match(env)\n path = env['REQ_PATH']\n @serve.each do |pattern, block|\n case pattern\n when FalseClass\n when TrueClass\n return Match.new(self, path, block)\n when String\n if pattern=='*'\n return Match.new(self, path, block)\n elsif /^\\*?\\.[a-z]+$/ =~ pattern\n return Match.new(self, path, block) if File.extname(realpath(path))==pattern\n else\n return Match.new(self, path, block) if File.basename(realpath(path))==pattern\n end\n when Regexp\n if matchdata = pattern.match(path)\n return Match.new(self, path, block, *matchdata.to_a)\n end\n when Waw::Validation::Validator\n if pattern.validate(matching_file(path))\n return Match.new(self, path, block) \n end\n when StaticController::AbstractMatcher\n if pattern.matches?(env)\n return Match.new(self, path, block)\n end\n else\n raise WawError, \"Unrecognized wawaccess pattern #{pattern}\"\n end\n end\n nil\n end", "def get_requested_route(env)\n request = Rack::Request.new(env)\n \n http_method = request.request_method.downcase\n path = request.path_info\n\n [http_method, path]\n end", "def route\n @route ||= Role.available_routes.find {|r| r.conditions[:path_info].to_s == path_info && r.conditions[:request_method].to_s == request_method}\n end", "def routeprovider_routes\n inspected_routes.select { |r| r[:verb] == \"GET\" || r[:name] == \"root\" }\n end", "def routes_for(token)\n all_routes = {}\n count = 0\n Sinatra::Application.routes.each do |verb_routes|\n verb, routes = verb_routes[0], verb_routes[1]\n all_routes[verb] ||= []\n routes.each_with_index do |route, i|\n route_regex = route.first.source\n if route_regex.to_s.include?(token)\n all_routes[verb] << route\n count += 1\n\n puts \"Route located: #{verb} -> #{route_regex.to_s}\"\n end\n end\n all_routes[verb].uniq!\n end\n [ all_routes, count ]\n end", "def find_named_routes\n routes = []\n\n Rails.application.routes.named_routes.each do |name, route|\n req = route.requirements\n if req[:controller] == params[:controller] && req[:action] == params[:action]\n routes << name\n end\n end\n\n routes\n end", "def find_router_for(request)\n match = Application.routers.find { |router| router.matches?(request) }\n match || DefaultRouter.new(:application => self)\n end", "def walk_the_routes\n routes.each do |route|\n if route[:route] === request.path_info\n instance_eval &route[:block] unless route[:block].nil?\n @nirb = route[:class].new(@nirb).call unless route[:class].nil?\n end\n \n route_frags = route[:route].split('/')\n path_frags = request.path_info.split('/')\n \n if route_frags.length === path_frags.length\n route_frags.each_with_index do |frag, index|\n if frag[0,1] === ':'\n request.params[frag[1..-1].to_sym] = path_frags[index]\n elsif frag[0,1] === '@'\n request.params[:method] = path_frags[index]\n elsif path_frags[index] != frag\n break\n end\n\n if index === route_frags.length - 1\n instance_eval &route[:block] unless route[:block].nil?\n @nirb = route[:class].new(@nirb).call unless route[:class].nil?\n end\n end\n end\n end\n end", "def process_request\n walk_the_routes\n end", "def route_for(**url_details)\n @routes.select { |rt| url_details <= rt.url_details }.first\n end", "def route! env\n http_route = \"#{env[REQ_METHOD]} #{env[PATH_INFO]}\"\n return true if env[GIN_ROUTE] == http_route\n\n env[GIN_TARGET], env[GIN_PATH_PARAMS] =\n router.resources_for env[REQ_METHOD], env[PATH_INFO]\n\n env[GIN_ROUTE] = http_route\n\n !!env[GIN_TARGET]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Encode string with Encoding.default_external
def encode_default_external(string) string.encode(Encoding.default_external) end
[ "def encode(string); end", "def encode_string_ex; end", "def force_encoding(str)\n encoding = ::Rails.application.config.encoding if defined? ::Rails\n encoding ||= DEFAULT_ENCODING\n str.force_encoding(encoding).encode(encoding)\n end", "def encode_utf8 string\n (string.respond_to?(:force_encoding) and string.respond_to?(:encoding)) ?\n string.force_encoding(Encoding::UTF_8) : string\n end", "def encode(string)\n Base32.encode(string).downcase.sub(/=+$/, '')\n end", "def encode(string)\n Base32.encode(string).downcase.sub(/=+$/, \"\")\n end", "def charset_encoder; end", "def ensure_ascii_compatible_encoding(string, options = nil)\n if string.encoding.ascii_compatible?\n string\n else\n string.encode(Encoding::UTF_8, options || { invalid: :replace, undef: :replace })\n end\n end", "def encode(text = nil)\n _text = text\n _encoding = \"\"\n if _text == nil\n _text = @text\n end\n\n _text.split(\"\").each do |ch|\n if @table[ch] != nil\n _encoding += @table[ch]\n end\n end\n\n return _encoding\n end", "def force_default_encoding; end", "def encode( string, coding )\n return string.encode(coding)\n rescue\n raise Error, \"Error when encoding from 'UTF-8' into '#{coding}'.\"\n end", "def with_external_encoding(encoding)\n old_encoding = Encoding.default_external\n silence_warnings {Encoding.default_external = \"iso-8859-1\"}\n ensure\n silence_warnings {Encoding.default_external = old_encoding if old_encoding}\n end", "def set_encoding\n Encoding.default_external = Encoding::UTF_8\n Encoding.default_internal = Encoding::UTF_8\n nil\n end", "def encode\n ::Base64.encode64(@string)\n end", "def transcode(string)\n return string.encode(\"iso-8859-1\").force_encoding(\"utf-8\")\nend", "def standard_encode\n encode_entities(:basic).gsub(/&apos;/, '&#39;')\n end", "def encode(binary_string)\n return binary_string if binary_string.nil? || (binary_string == \"\")\n\n encoder.encode(binary_string)\n end", "def encode text\n Base64.encode64(text).gsub /\\n/, ''\nend", "def url_encode(string) \r\n encoded_string = ''\r\n string.each_char do |char|\r\n char = (\"%%%02X\" % char.ord) if char.match(/[A-Za-z0-9]/) == nil\r\n encoded_string << char\r\n end\r\n return encoded_string\r\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds an emoji by its name.
def find_emoji(name) LOGGER.out("Resolving emoji #{name}") emoji.find { |element| element.name == name } end
[ "def find(symbol)\n return symbol if (symbol.is_a?(Emoji::Character))\n symbol = emoticons[symbol].to_s if emoticons.has_key?(symbol)\n Emoji.find_by_alias(symbol) || Emoji.find_by_unicode(symbol) || nil\n end", "def valid_emoji?(emoji)\n Emoji.find_by_name emoji\n end", "def find_character_by_name(name)\n InitTrackerLogger.log.debug {\"Find by name: #{name}\"}\n characters.select{|char| char[:name].strip.downcase.eql?(name.strip.downcase)}.first\n end", "def find_emoji(key, server = nil)\n server = server || $bot.servers[SERVER_ID] || $bot.servers.first\n return if server.nil?\n if key.is_a?(Integer)\n server.emojis[key]\n elsif key.is_a?(String)\n server.emojis.find{ |id, e| e.name.downcase.include?(key.downcase) }[1]\n else\n nil\n end\nrescue\n nil\nend", "def emoji\n if failure?\n FAILURE_EMOJI\n else\n ERROR_EMOJI\n end\n end", "def find_by_mention_name(mention_name)\n id = redis.get(\"mention_name:#{mention_name}\")\n find_by_id(id) if id\n end", "def replace_emoji(text)\n emojis = Mumuki::Emojis::EMOJIS\n text.gsub(/:([^\\s:])+:/) do |short_name|\n short_code = short_name.gsub(':', '')\n emoji = emojis[short_code]\n if emoji\n %{<i class=\"mu-emoji #{emoji['ca']} _#{emoji['co']}\" title=\"#{short_name}\"></i>}\n else\n short_name\n end\n end\n end", "def emoji_for_species(string)\n case string.downcase.strip\n when 'wolf', /\\swolf/\n '🐺'\n when 'gorilla', /\\sgorilla/\n '🦍'\n when 'rhino', 'rhinoceros', /\\srhino/, /\\srhinoceros/\n '🦏'\n when 'owl', /\\sowl/\n '🦉'\n when 'lion', /\\slion/\n '🦁'\n when 'tiger', /\\stiger/\n '🐯'\n when 'octopus', /\\soctopus/\n '🐙'\n when 'chicken', /\\schicken/\n '🐓'\n when 'dog', /\\sdog/\n '🐶'\n when 'human', /\\shuman/\n '👮‍'\n when 'eagle', /\\seagle/\n '🦅'\n when 'fish', /\\sfish/\n '🐟'\n when 'unicorn', /\\sunicorn/\n '🦄'\n else\n '❓'\n end\nend", "def find_jid_by_name(name)\n name = name.downcase\n connection.roster.items.detect {|jid, item| item.iname.downcase == name}.first\n end", "def emoji\n @attributes[:emoji]\n end", "def create(name)\n emoji = Emoji::Character.new(name)\n self.all << edit_emoji(emoji) { yield emoji if block_given? }\n emoji\n end", "def find_cellar_by_name(name)\n cellars.find{|cellar|\n cellar.name == name\n }\n end", "def emoji\n if success?\n SUCCESS_EMOJI\n elsif warning?\n WARNING_EMOJI\n else\n INFO_EMOJI\n end\n end", "def include_emoji?(text)\n text && text[/:\\S+:/]\n end", "def find(name)\n name = /^#{name.to_s.gsub('_', ' ')}/i\n\n results = @countries.select do |country|\n country.name =~ name\n end\n\n if results.size == 1\n return results.first\n elsif results.size > 1\n raise AmbiguousNameError, \"#{name.inspect} is ambiguous\"\n else\n raise CountryNotFoundError, \"No country found for #{name.inspect}\"\n end\n end", "def fetch_character_by_name(name)\n uri = URI(BASE_URI + \"?name=#{name}\")\n characters = make_request(uri)\n if characters[0]\n Character.new(characters[0])\n else\n \"Couldn't find a character with that name...\"\n end\n end", "def find_by_name(name)\n find { |llama| llama.name == name }\n end", "def emoji?\n emoji = scan_for_emoji\n return true unless emoji.empty?\n end", "def get_emoji\n begin\n rand_emoji = EmojiURL::get_online_emoji(Emojis::APPLE_FACES[rand(0...(Emojis::APPLE_FACES.length))]) # Downloads a random emoji\n return [Imgcodecs.imread(\"#{EXE_DIR}/assets/temp/#{rand_emoji}.png\"), # Emoji as OpenCV matrix\n ChunkyPNG::Image.from_file(\"#{EXE_DIR}/assets/temp/#{rand_emoji}.png\")] # Emoji as ChunkyPNG matrix\n rescue ChunkyPNG::SignatureMismatch => e\n $logger.debug \"Emoji Signature Mismatch, likely network error:\"\n $logger.error \"Full error message: #{e.message}\"\n puts \"Emoji unable to be found! This is most likely and error with the network, so try again later.\"\n exit\n end\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The bot's OAuth application.
def bot_application return unless @type == :bot response = API.oauth_application(token) Application.new(JSON.parse(response), self) end
[ "def oauth_application(auth)\n request(\n :oauth2_applications_me,\n nil,\n :get,\n \"#{APIBASE_URL}/oauth2/applications/@me\",\n Authorization: auth\n )\n end", "def oauth_application(token)\n request(\n __method__,\n :get,\n \"#{api_base}/oauth2/applications/@me\",\n Authorization: token\n )\n end", "def oauth_application(token)\n request(\n :oauth2_applications_me,\n nil,\n :get,\n \"#{api_base}/oauth2/applications/@me\",\n Authorization: token\n )\n end", "def oauth_flow\n Google::APIClient::InstalledAppFlow.new(\n client_id: client_secrets.client_id,\n client_secret: client_secrets.client_secret,\n scope: configuration.api_scope\n )\n end", "def oauth2_client(id)\n raise 'Add a method #oauth2_client to your ApplicationController that returns the OAuth client application for given id.'\n end", "def o_auth\n @o_auth ||= OAuthApi.new config\n end", "def oauth_client\n @oauth_client ||= OAuth2::Client.new @app_key, @app_secret, site: @workxp_site do |stack|\n stack.request :multipart\n stack.request :url_encoded\n stack.adapter :net_http\n end\n end", "def oauth\n self.class.oauth\n end", "def oauth_client\n @oauth_client ||= OAuth2::Client.new(api_key, api_secret,\n site: \"https://openapi.baidu.com\",\n authorize_url: \"/oauth/2.0/authorize\",\n token_url: \"/oauth/2.0/token\")\n\n end", "def app\n BatchConnect::App.from_token(self.token)\n end", "def oauth\n request_token = @oauth_consumer.get_request_token\n authorize_url = request_token.authorize_url(:oauth_consumer_key => \n Netflix::Client.consumer_key)\n Launchy.open(authorize_url)\n puts \"Go to browser, a page has been opened to establish oauth\"\n printf \"Pin from Netflix:\"\n pin = gets.chomp\n access_token = request_token.get_access_token(:oauth_verifier => pin)\n end", "def facebook_oauth\n # Insert your own Facebook client ID and secret here\n @facebook_oauth ||= Koala::Facebook::OAuth.new(Setting.facebook_auth_key.app_id, Setting.facebook_auth_key.app_secret)\n end", "def oauth_instance name = nil\n oauth = Rack::OAuth.get(oauth_request_env, nil)\n raise \"Couldn't find Rack::OAuth instance with name #{ name }\" unless oauth\n oauth\n end", "def application_token\n oauth_client.\n client_credentials.\n get_token(scope: config[:application_permissions].join(' ')).\n token\n end", "def oauth_instance name = nil\n oauth = Rack::OAuth.get(oauth_request_env, nil)\n raise \"Couldn't find Rack::OAuth instance with name #{ name }\" unless oauth\n oauth\n end", "def access_token\n oauth_config = YAML.load_file('config/oauth.yml')[Rails.env]\n oauth_consumer = OAuth::Consumer.new oauth_config['consumer_key'],\n oauth_config['consumer_secret'], { :site => oauth_config['site'] }\n OAuth::AccessToken.new(oauth_consumer, oauth_token, oauth_secret)\n end", "def config\n Simple::OAuth2.config\n end", "def oauth2_client\n OAuth2::Client.new(\n $config['client_id'],\n $config['client_secret'], \n :site => $config['oauth_server'], \n :authorize_url =>'/oauth2/authorize', \n :token_url => '/oauth2/token',\n :raise_errors => false\n )\nend", "def get_consumer\n OAuth::Consumer.new(ENV[\"EVERNOTE_CONSUMER_KEY\"], ENV[\"EVERNOTE_SECRET\"], {\n :site => ENV[\"EVERNOTE_URL\"],\n :request_token_path => \"/oauth\",\n :access_token_path => \"/oauth\",\n :authorize_path => \"/OAuth.action\"\n })\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an OAuth invite URL that can be used to invite this bot to a particular server.
def invite_url(server: nil, permission_bits: nil) @client_id ||= bot_application.id server_id_str = server ? "&guild_id=#{server.id}" : '' permission_bits_str = permission_bits ? "&permissions=#{permission_bits}" : '' "https://discord.com/oauth2/authorize?&client_id=#{@client_id}#{server_id_str}#{permission_bits_str}&scope=bot" end
[ "def invite_url(server = nil)\n raise 'No application ID has been set during initialization! Add one as the `application_id` named parameter while creating your bot.' unless @application_id\n\n guild_id_str = server ? \"&guild_id=#{server.id}\" : ''\n \"https://discordapp.com/oauth2/authorize?&client_id=#{@application_id}#{guild_id_str}&scope=bot\"\n end", "def guest_url\n \"#{@connection.uri}/#{guest_invite_code}\" if guest_access_enabled?\n end", "def invite_path\n \"#{Rails.configuration.relative_url_root}/#{uid}\"\n end", "def join_server(token, invite_code)\n request(\n __method__,\n :post,\n \"#{api_base}/invite/#{invite_code}\",\n nil,\n Authorization: token\n )\n end", "def invite_path\n \"#{Rails.configuration.relative_url_root}/#{CGI.escape(uid)}\"\n end", "def create_server_url(ip)\n return REMOTE_SERVER_LINK_PREFIX + ip + REMOTE_SERVER_LINK_PORT\n end", "def invitations_url\n \"https://github.com/#{context.repo}/invitations\"\n end", "def guest_url\n if guest_access_enabled?\n \"http://#{@campfire.subdomain}.campfirenow.com/#{guest_invite_code}\"\n else\n nil\n end\n end", "def invite_redirect_url\n return @invite_redirect_url\n end", "def build_sso_url(link_authn_context)\n new_url_settings = url_settings\n new_url_settings.authn_context = link_authn_context\n saml_auth_request = OneLogin::RubySaml::Authrequest.new\n\n saml_auth_request.create(new_url_settings, RelayState: relay_state_params)\n end", "def get_invitation_link\n\t\tscope = self.scope\n\t\trace_id = self.race_id\n\t\t\n\t\tbase_url = InvitationEmailTarget.get_base_url(race_id, scope)\n\t\t\n\t\tbase_url += case self.scope\n\t\twhen (COMPETITION_SCOPE[:SITE])\n\t\t\t'competitions/' + self.id.to_s + '?code=' + self.invitation_code\n\t\twhen (COMPETITION_SCOPE[:CYCLINGTIPS])\n\t\t\t'?competition_id=' + self.id.to_s + '&code=' + self.invitation_code\n\t\tend\n\t\t\n\t\treturn base_url\n\tend", "def create_site_uri\n @create_site_uri ||= \"#{base_uri}/api/2/users/me/sites\"\n end", "def join_url(username, role, key=nil, options={})\n server = BigbluebuttonRails.configuration.select_server.call(self, :join_meeting_url)\n\n pass = case role\n when :moderator\n self.moderator_api_password\n when :attendee\n self.attendee_api_password\n when :guest\n if BigbluebuttonRails.configuration.guest_support\n options = { guest: true }.merge(options)\n end\n self.attendee_api_password\n else\n map_key_to_internal_password(key)\n end\n\n r = server.api.join_meeting_url(self.meetingid, username, pass, options)\n r.strip! unless r.nil?\n r\n end", "def build_endpoint\n endpoint = ssl || self.api_token.nil? ? \"https://\" : \"http://\"\n endpoint << \"#{self.username}:#{self.password}@\" unless self.authenticated?\n endpoint << \"www.pivotaltracker.com/services/v3/\"\n self.api_endpoint = endpoint\n end", "def url_after_invite(invite)\n invite.invitable\n end", "def invite_bot\n SlackUtils::SingletonClient.instance.invite_channel(@bot.channel_id, Bot.slack_bot_id, session[:token])\n end", "def get_base_uri(server = Server::DEFAULT)\n parameters = {\n 'port' => { 'value' => port, 'encode' => false },\n 'suites' => { 'value' => suites, 'encode' => false }\n }\n APIHelper.append_url_with_template_parameters(\n ENVIRONMENTS[environment][server], parameters\n )\n end", "def invitation_url(type, employee)\n if type == :invite\n new_account_organization_invitation_path(current_account, current_organization, invitation: { employee_id: employee.id })\n else\n edit_account_organization_invitation_path(current_account, current_organization, employee.invitation)\n end\n end", "def build_sso_auth_url\n # Get the base URL:\n sso_url = @url.to_s[0..@url.to_s.rindex('/')]\n\n # The SSO access scope:\n scope = 'ovirt-app-api'\n\n # Set the grant type and entry point to request from SSO:\n if @kerberos\n grant_type = 'urn:ovirt:params:oauth:grant-type:http'\n entry_point = 'token-http-auth'\n else\n grant_type = 'password'\n entry_point = 'token'\n end\n\n # Build and return the SSO URL:\n return \"#{sso_url}sso/oauth/#{entry_point}?grant_type=#{grant_type}&scope=#{scope}\"\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a text message to a channel given its ID and the message's content, then deletes it after the specified timeout in seconds.
def send_temporary_message(channel, content, timeout, tts = false, embed = nil, attachments = nil, allowed_mentions = nil, message_reference = nil, components = nil) Thread.new do Thread.current[:discordrb_name] = "#{@current_thread}-temp-msg" message = send_message(channel, content, tts, embed, attachments, allowed_mentions, message_reference, components) sleep(timeout) message.delete end nil end
[ "def send_temporary_message(channel_id, content, timeout, tts = false, server_id = nil)\n Thread.new do\n message = send_message(channel_id, content, tts, server_id)\n\n sleep(timeout)\n\n message.delete\n end\n\n nil\n end", "def send_temporary_message(content, timeout, tts = false, embed = nil)\n @bot.send_temporary_message(@id, content, timeout, tts, embed)\n end", "def send_temporary_message(content, timeout, tts = false, embed = nil, attachments = nil, allowed_mentions = nil, components = nil)\n channel.send_temporary_message(content, timeout, tts, embed, attachments, allowed_mentions, components)\n end", "def delete_message(id)\n @client.raw('delete', \"/content/messages/#{id}\")\n end", "def edit_osd_message(id, text, timeout: nil)\n @osd_messages[id] = Ass::Text.new(text)\n delete_osd_message(id, delay: timeout) if timeout.to_f.positive?\n render_osd_messages\n end", "def delete\n API.delete_channel(@bot.token, @id)\n end", "def send_message(channel_id, content, tts = false, server_id = nil)\n channel_id = channel_id.resolve_id\n debug(\"Sending message to #{channel_id} with content '#{content}'\")\n\n response = API.send_message(token, channel_id, content, [], tts, server_id)\n Message.new(JSON.parse(response), self)\n end", "def send_text_message(msg, opts={})\n # observe Slack's message limit and truncate, if necessary\n msg = msg[0...MAX_SEND_CHARS-16]+\"...truncating...\" if msg.size >= MAX_SEND_CHARS\n msg = \":exclamation: \" << msg if opts[:bang]\n\n @pending << { type: :text, text: msg }\n @pending << { type: :text, text: \"<!channel> (see above)\" } if opts[:poke_channel]\n end", "def chat_deleteScheduledMessage(options = {})\n raise ArgumentError, 'Required arguments :channel missing' if options[:channel].nil?\n raise ArgumentError, 'Required arguments :scheduled_message_id missing' if options[:scheduled_message_id].nil?\n options = options.merge(channel: conversations_id(options)['channel']['id']) if options[:channel]\n post('chat.deleteScheduledMessage', options)\n end", "def delete(text_id)\n run do\n db = Translatomatic::Database.new(options)\n text = db.text.find(text_id)\n raise t('cli.database.text_not_found', id: text_id) unless text\n text.destroy\n end\n end", "def delete(channel_id)\n\t\t\tkparams = {}\n\t\t\tclient.add_param(kparams, 'channelId', channel_id)\n\t\t\tclient.queue_service_action_call('channel', 'delete', 'bool', kparams)\n\t\t\tif (client.is_multirequest)\n\t\t\t\treturn nil\n\t\t\tend\n\t\t\treturn client.do_queue()\n\t\tend", "def send_message(channel_id, params)\n cleaned = params.permit(:author_id,\n :sender_name,\n :subject,\n :body,\n :text,\n :attachments,\n { options: [:tags, :archive] },\n :to,\n :cc,\n :bcc)\n create(\"channels/#{channel_id}/messages\", cleaned)\n end", "def delete_message(display_id, message_id)\n delete \"commandcenter/displays/#{display_id}/messages/#{message_id}\"\n end", "def reply(message, text)\n send_in_channel(message[\"channel\"], text)\nend", "def delete(id)\n\t\t\tkparams = {}\n\t\t\t# Live channel id to delete\n\t\t\tclient.add_param(kparams, 'id', id);\n\t\t\tclient.queue_service_action_call('livechannel', 'delete', kparams);\n\t\t\tif (client.is_multirequest)\n\t\t\t\treturn nil;\n\t\t\tend\n\t\t\treturn client.do_queue();\n\t\tend", "def delete_message(channel_id, message_id, reason: nil)\n request(\n :channels_cid_messages_mid, channel_id,\n :delete,\n \"channels/#{channel_id}/messages/#{message_id}\",\n nil,\n 'X-Audit-Log-Reason': reason,\n )\n end", "def send(message, timeout = 30)\n client do |sock|\n sock.write \"#{message}\\r\\n\"\n ready = IO.select([sock], nil, nil, timeout)\n raise ServiceError, \"timed out waiting for server response\" unless ready\n sock.recv(256)\n end\n rescue Errno::ECONNREFUSED, Errno::ENOENT\n raise ServiceError, \"#{name} process not running\" unless daemon_running?\n raise ServiceError, \"unable to establish connection\"\n end", "def test_timeout\n @client.queue_name = \"test_timeout\"\n clear_queue\n\n res = @client.messages.post(\"hello world timeout!\")\n p res\n\n msg = @client.messages.get()\n p msg\n assert msg\n\n msg4 = @client.messages.get()\n p msg4\n assert msg4.nil?\n\n puts 'sleeping 45 seconds...'\n sleep 45\n\n msg3 = @client.messages.get()\n p msg3\n assert msg3.nil?\n\n puts 'sleeping another 45 seconds...'\n sleep 45\n\n msg2 = @client.messages.get()\n assert msg2\n assert msg.id == msg2.id\n\n msg2.delete\n\n # now try explicit timeout\n res = @client.messages.post(\"hello world timeout2!\", :timeout=>10)\n p res\n msg = @client.messages.get()\n p msg\n assert msg\n msg4 = @client.messages.get()\n p msg4\n assert msg4.nil?\n puts 'sleeping 15 seconds...'\n sleep 15\n msg2 = @client.messages.get()\n assert msg2\n assert msg.id == msg2.id\n\n end", "def send_text(params = {})\n fail InitWithoutBot unless @bot\n\n params[:chat] = id\n @bot.send_text params\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a file to a channel. If it is an image, it will automatically be embedded.
def send_file(channel, file, caption: nil, tts: false, filename: nil, spoiler: nil) if file.respond_to?(:read) if spoiler filename ||= File.basename(file.path) filename = "SPOILER_#{filename}" unless filename.start_with? 'SPOILER_' end # https://github.com/rest-client/rest-client/blob/v2.0.2/lib/restclient/payload.rb#L160 file.define_singleton_method(:original_filename) { filename } if filename file.define_singleton_method(:path) { filename } if filename end channel = channel.resolve_id response = API::Channel.upload_file(token, channel, file, caption: caption, tts: tts) Message.new(JSON.parse(response), self) end
[ "def send_file(channel_id, file)\n response = API.send_file(token, channel_id, file)\n Message.new(JSON.parse(response), self)\n end", "def send_file(token, channel_id, file, caption: nil, tts: false)\n request(\n __method__,\n :post,\n \"#{api_base}/channels/#{channel_id}/messages\",\n { file: file, content: caption, tts: tts },\n Authorization: token\n )\n end", "def send_file(file)\n @bot.send_file(@id, file)\n end", "def send_file(file_path, receiver_uuid, file_uuid)\n @networking.send_file(file_path, receiver_uuid, file_uuid)\n end", "def send_file(path)\n\n @buffer = File.read(path)\n send\n end", "def send_file(controller)\n ext = File.extname(filename)[1..-1]\n mime_type = Mime::Type.lookup_by_extension(ext)\n content_type = mime_type.to_s unless mime_type.nil?\n content_type ||= 'text/plain'\n \n controller.send_file(filename,\n :x_sendfile => true,\n :type => content_type)\n end", "def send_file(path)\n commit!\n @stream = FileBody.new(path)\n end", "def ssh_send_file_ruby(host, username, command, filename)\n filename = File.expand_path(filename)\n ssh_ruby(host, username, command) do |channel|\n File.open(filename, 'rb') do |file|\n file.chunk(1024) do |chunk|\n channel.send_data chunk\n end\n end\n end\n end", "def upload_file_to_slack(channels: ,file: ,options: {})\n upload_file = nil\n ActiveSupport::Notifications.instrument('upload_file_to_slack.action_messenger', channels: channels) do\n upload_file = slack_client.upload_file(channels, file, options)\n end\n upload_file\n ensure\n self.deliveries << DeliveryLog.new(__method__, channels, upload_file)\n end", "def send_file(path, response)\n input = java.io.FileInputStream.new(path.to_s)\n channel = input.getChannel\n begin\n transfer_channel channel, response.getOutputStream\n ensure\n channel.close\n input.close rescue nil\n end\n end", "def send_file(file_path, receiver_uuid, file_uuid)\n Pantry.logger.debug(\"[FileService] Sending file #{file_path} to #{receiver_uuid}\")\n @sender.send_file(file_path, receiver_uuid, file_uuid)\n end", "def send_file(path, options = {}) #:doc:\n raise MissingFile, \"Cannot read file #{path}\" unless File.file?(path) and File.readable?(path)\n\n options[:length] ||= File.size(path)\n options[:filename] ||= File.basename(path)\n send_file_headers! options\n\n if options[:stream]\n render_text do\n logger.info \"Streaming file #{path}\" unless logger.nil?\n len = options[:buffer_size] || 4096\n File.open(path, 'rb') do |file|\n if $stdout.respond_to?(:syswrite)\n begin\n while true\n $stdout.syswrite file.sysread(len)\n end\n rescue EOFError\n end\n else\n while buf = file.read(len)\n $stdout.write buf\n end\n end\n end\n end\n else\n logger.info \"Sending file #{path}\" unless logger.nil?\n File.open(path, 'rb') { |file| render_text file.read }\n end\n end", "def response_send_file(info)\n send_file(info[:file_path], response_binary_metadata(info))\n end", "def send_file(path, options = {}) #:doc:\n raise MissingFile, \"Cannot read file #{path}\" unless File.file?(path) and File.readable?(path)\n\n options[:length] ||= File.size(path)\n options[:filename] ||= File.basename(path)\n options[:type] ||= Rack::File::MIME_TYPES[File.extname(options[:filename])[1..-1]] || 'text/plain'\n options[:last_modified] ||= File.mtime(path).httpdate\n options[:stream] = true unless options.key?(:stream)\n options[:buffer_size] ||= DEFAULT_SEND_FILE_OPTIONS[:buffer_size]\n send_file_headers! options\n\n if options[:stream]\n throw :halt, [options[:status] || 200, FileStreamer.new(path, options)]\n else\n File.open(path, 'rb') { |file| throw :halt, [options[:status] || 200, [file.read]] }\n end\n end", "def send_bytes(file)\n until file.eof?\n buffer = file.read(1024)\n @socket.write(buffer)\n end\n end", "def file(value = nil)\n if value.is_a?(String)\n ActiveSupport::Deprecation.warn('Use sendfile or stream to send files.')\n sendfile(value)\n elsif !value.is_a?(NilClass)\n ActiveSupport::Deprecation.warn('Use stream to use a Stream object.')\n stream(value)\n else\n ActiveSupport::Deprecation.warn('Use sendfile or stream to send files.')\n sendfile\n end\n end", "def send_file(file, opts={})\n opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts))\n disposition = opts[:disposition].dup || 'attachment'\n disposition << %(; filename=\"#{opts[:filename] ? opts[:filename] : File.basename(file)}\")\n headers.update(\n 'Content-Type' => opts[:type].strip, # fixes a problem with extra '\\r' with some browsers\n 'Content-Disposition' => disposition,\n 'Content-Transfer-Encoding' => 'binary'\n )\n Proc.new do |response|\n file = File.open(file, 'rb')\n while chunk = file.read(16384)\n response.write chunk\n end\n file.close\n end\n end", "def send_file(path, options = {}) #:doc:\n raise MissingFile, \"Cannot read file #{path}\" unless File.file?(path) and File.readable?(path)\n\n options[:length] ||= File.size(path)\n options[:filename] ||= File.basename(path) unless options[:url_based_filename]\n send_file_headers! options\n\n @performed_render = false\n\n if options[:x_sendfile]\n logger.info \"Sending #{X_SENDFILE_HEADER} header #{path}\" if logger\n head options[:status], X_SENDFILE_HEADER => path\n else\n if options[:stream]\n render :status => options[:status], :text => Proc.new { |response, output|\n logger.info \"Streaming file #{path}\" unless logger.nil?\n len = options[:buffer_size] || 4096\n File.open(path, 'rb') do |file|\n while buf = file.read(len)\n output.write(buf)\n end\n end\n }\n else\n logger.info \"Sending file #{path}\" unless logger.nil?\n File.open(path, 'rb') { |file| render :status => options[:status], :text => file.read }\n end\n end\n end", "def transfer file\n stop_timeout\n\n @number += 1\n\n @type = :sending\n @file = file\n\n\t @file.seek 0, IO::SEEK_END\n @filesize = file.tell\n\t @file.seek 0, IO::SEEK_SET\n @total_frames = (@filesize.to_f / @options[:frame_size].to_f).ceil\n\n puts \"Sending file (#{@filesize} bytes)\"\n\n # Set up how much do we currently have (outside of the window)\n @delivered = 0\n\n # window number\n @window = 0\n @current_frame = 0\n @next_frame = 0\n @sum_buffer_len = 0\n @max_buffer_len = 0\n @buffer_len = 0\n\n @buffer = Array.new(@options[:window_size] * 2) { nil }\n @sent = Array.new(@options[:window_size] * 2) { 0 }\n\n start_timeout\n\n send_window\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a server on Discord with a specified name and a region.
def create_server(name, region = :'eu-central') response = API::Server.create(token, name, region) id = JSON.parse(response)['id'].to_i sleep 0.1 until (server = @servers[id]) debug "Successfully created server #{server.id} with name #{server.name}" server end
[ "def create_server(name, region = :london)\n response = API.create_server(token, name, region)\n id = JSON.parse(response)['id'].to_i\n sleep 0.1 until @servers[id]\n server = @servers[id]\n debug \"Successfully created server #{server.id} with name #{server.name}\"\n server\n end", "def create_in_world(client, world: required(\"world\"), options: {}, **data)\n\n self.new(parse(client.post(\"/worlds/#{world}/unicorns\", body: data, options: options)).first, client: client)\n end", "def create(name, type)\n configure [\"aaa group server #{type} #{name}\", 'exit']\n end", "def server(name, args)\n @servers ||= {}\n raise(ArgumentError, \"Server name must be a symbol\") unless name.kind_of?(Symbol)\n @servers[name.to_sym] = Deployr::Server.new(name, args, @config)\n end", "def server_create(attributes = {}, &block)\n register_event(ServerCreateEvent, attributes, block)\n end", "def create(client, world: required(\"world\"), options: {}, **data)\n with_params = data.merge(world: world).reject { |_,v| v.nil? || Array(v).empty? }\n self.new(parse(client.post(\"/unicorns\", body: with_params, options: options)).first, client: client)\n end", "def create_server(args = {})\n params = {'command' => 'deployVirtualMachine'}\n params['keypair'] = args[:keypair] if args[:keypair]\n params['size'] = args[:disk_size] if args[:disk_size]\n params['group'] = args[:group] if args[:group]\n params['displayname'] = args[:displayname] if args[:displayname]\n\n if args[:account]\n account = list_accounts({name: args[:account]}).first\n unless account\n puts \"Error: Account #{args[:account]} not found.\"\n exit 1\n end\n params['domainid'] = account[\"domainid\"]\n params['account'] = args[:account]\n end\n\n if args[:project]\n project = get_project(args[:project])\n if !project\n msg = \"Project '#{args[:project]}' is invalid\"\n puts \"Error: #{msg}\"\n exit 1\n end\n params['projectid'] = project['id']\n elsif args[:project_id]\n params['projectid'] = args[:project_id]\n end\n params['name'] = args[:name] if args[:name]\n\n if args[:name]\n server = get_server(args[:name], project_id: params['projectid'])\n if server \n puts \"Error: Server '#{args[:name]}' already exists.\"\n exit 1\n end\n end\n\n networks = []\n if args[:networks]\n args[:networks].each do |name|\n network = get_network(name, params['projectid'])\n if !network\n puts \"Error: Network '#{name}' not found\"\n exit 1\n end\n networks << network\n end\n end\n if networks.empty?\n unless default_network = get_default_network\n puts \"Error: No default network found\"\n exit 1\n end\n networks << default_network\n end\n network_ids = networks.map { |network|\n network['id']\n }\n params['networkids'] = network_ids.join(',')\n\n service = get_service_offering(args[:offering])\n if !service\n puts \"Error: Service offering '#{args[:offering]}' is invalid\"\n exit 1\n end\n params['serviceOfferingId'] = service['id']\n\n if args[:template]\n template = get_template(args[:template])\n if !template\n puts \"Error: Template '#{args[:template]}' is invalid\"\n exit 1\n end\n end\n\n if args[:disk_offering]\n disk_offering = get_disk_offering(args[:disk_offering])\n unless disk_offering\n msg = \"Disk offering '#{args[:disk_offering]}' is invalid\"\n puts \"Error: #{msg}\"\n exit 1\n end\n params['diskofferingid'] = disk_offering['id']\n end\n\n if args[:iso]\n iso = get_iso(args[:iso])\n unless iso\n puts \"Error: Iso '#{args[:iso]}' is invalid\"\n exit 1\n end\n unless disk_offering\n puts \"Error: a disk offering is required when using iso\"\n exit 1\n end\n params['hypervisor'] = (args[:hypervisor] || 'vmware')\n end\n\n if !template && !iso\n puts \"Error: Iso or Template is required\"\n exit 1\n end\n params['templateId'] = template ? template['id'] : iso['id']\n\n zone = args[:zone] ? get_zone(args[:zone]) : get_default_zone\n if !zone\n msg = args[:zone] ? \"Zone '#{args[:zone]}' is invalid\" : \"No default zone found\"\n puts \"Error: #{msg}\"\n exit 1\n end\n params['zoneid'] = zone['id']\n\n args[:sync] ? send_request(params) : send_async_request(params)['virtualmachine']\n end", "def server(name, options = {}, &blk)\n add_child(:servers, Hubcap::Server.new(self, name, options, &blk))\n end", "def register_server(name)\n do_send(Erlang::Tuple.new([\n Erlang::Atom.new('register_with_group'),\n Erlang::Atom.new(name)]))\n end", "def create_instance(credentials, image_id, opts)\n racks = new_client( credentials )\n flavor_id = 1\n if (opts[:flavor_id]) then flavor_id = opts[:flavor_id] end\n name = Time.now.to_s\n if (opts[:name]) then name = opts[:name] end\n convert_srv_to_instance(racks.start_server(image_id, flavor_id, name)) \n end", "def register_server(name, port); end", "def create_server(options)\n Server.create(options.merge(data_center_id: self.id))\n end", "def create_server!(conn, name, ssh_key_path, type, os_type)\n case os_type.downcase\n when 'centos'\n server = conn.servers.create(\n :name => name,\n :flavor_id => type,\n :image_id => @centos_image_id,\n :personality => [\n {\n :path => '/root/.ssh/authorized_keys',\n :contents => Base64.encode64(File.read(File.expand_path(ssh_key_path)))\n }\n ]\n )\n # reloading will assign random public and private ip addresses if mocking\n server.reload if @mock\n return server\n when 'ubuntu'\n server = conn.servers.create(\n :name => name,\n :flavor_id => type,\n :image_id => @ubuntu_image_id,\n :personality => [\n {\n :path => '/root/.ssh/authorized_keys',\n :contents => Base64.encode64(File.read(File.expand_path(ssh_key_path)))\n }\n ]\n )\n server.reload if @mock\n return server\n else\n @log.error 'OS not yet supported, contact support@cloudwick.com'\n exit 2\n end\n end", "def create_server(login, password, location, version = 12.0)\n body = Serialization.server_to_xml(login, password, location, version)\n server_names = list_servers.map(&:name)\n created_server = nil\n\n begin\n response = client.sql_management_request(:post, servers_path, body: body, warn: true).call\n created_server = Serialization.server_name_from_xml(response, login, location, version)\n rescue RuntimeError => ex\n if ex.message =~ /Please retry the request/\n created_server = list_servers.reject{|server| server_names.include?(server.name)}.first\n # sometimes the service returns 500, but it doesn't really mean it.\n #\n # If the operation returns success, the operation is complete and the server is created immediately. If the\n # operation fails because of a user error, a server is not created. If there is a communication error or\n # internal server error, you should check the status of the operation using List Servers.\n #\n raise unless created_server\n else\n raise\n end\n end\n Azure::Loggerx.info \"SQL database server #{created_server.name} is created.\" if created_server\n created_server\n end", "def create_server(zone: \"fi-hel1\", title:, hostname:, core_number: 1,\n memory_amount: 1024, storage_devices:, ip_addresses: :all)\n data = {\n \"server\" => {\n \"zone\" => zone,\n \"title\" => title,\n \"hostname\" => hostname,\n \"core_number\" => core_number,\n \"memory_amount\" => memory_amount,\n \"storage_devices\" => { \"storage_device\" => storage_devices }\n }\n }\n\n if ip_addresses != :all\n ips = []\n ips << { \"access\" => \"public\", \"family\" => \"IPv4\" } if ip_addresses.include? :public\n ips << { \"access\" => \"private\", \"family\" => \"IPv4\" } if ip_addresses.include? :private\n ips << { \"access\" => \"public\", \"family\" => \"IPv6\" } if ip_addresses.include? :ipv6\n\n data[\"server\"][\"ip_addresses\"] = {}\n data[\"server\"][\"ip_addresses\"][\"ip_address\"] = ips\n end\n\n json = JSON.generate data\n response = post \"server\", json\n response\n end", "def server(role, options = {})\n \n # using role name for server name, but will\n # need to be something like [environment][image][flavor][role][01]\n # devubu256web01\n #\n \n instances = options[:instances].to_i\n \n for i in 1..instances\n serverName = get_server_name(@shortName, options[:imageId], options[:flavorId], role, i)\n s = Server.new(serverName, role, options)\n @servers << s\n end\n \n \n end", "def create_server(server_section)\n validate_server_section(server_section)\n Logger.info Setebos::Messages::SERVER_START % server_section.to_s\n\n # Create the server with the server_section of the config file.\n server = Setebos::Server.new(\n server_section[:host],\n user: server_section[:user],\n password: server_section[:password]\n )\n\n # Test reachability.\n reachable = server.test()\n Logger.error Setebos::Messages::NOT_REACHABLE if not reachable\n\n Logger.success Setebos::Messages::SERVER_OK\n\n # Return the server.\n server\n end", "def create_server!(conn, instance_tag, opts = {})\n options = {\n :key => 'ankus',\n :groups => %w(ankus),\n :flavor_id => 'm1.medium',\n :os_type => 'CentOS',\n :num_of_vols => 0,\n :vol_size => 50,\n :root_vol_size => 250,\n :vol_type => 'ebs',\n :iops => 0\n }.merge(opts)\n\n unless valid_connection?(conn)\n @log.error 'Unable to authenticate with AWS, check your credentials'\n exit 2\n end\n\n case options[:os_type].downcase\n when 'centos'\n ami = @centos_amis_mod.has_key?(@region) ? @centos_amis_mod[@region] : @centos_amis[@region]\n root_ebs_size = @centos_amis_mod.has_key?(@region) ? 0 : options[:root_vol_size]\n server = create_server(\n conn,\n options[:key],\n instance_tag,\n options[:groups],\n options[:flavor_id],\n ami,\n :num_of_vols => options[:num_of_vols],\n :vol_size => options[:vol_size],\n :root_ebs_size => root_ebs_size,\n :vol_type => options[:vol_type],\n :iops => options[:iops]\n )\n return server\n when 'ubuntu'\n server = create_server(\n conn,\n options[:key],\n instance_tag,\n options[:groups],\n options[:flavor_id],\n @ubuntu_amis[@region],\n :num_of_vols => options[:num_of_vols],\n :vol_size => options[:vol_size],\n :root_ebs_size => options[:root_vol_size],\n :vol_type => options[:vol_type],\n :iops => options[:iops]\n )\n return server\n else\n @log.error 'Provided OS not supported by Ankus yet!'\n exit 2\n end\n end", "def create_server(login, password, location)\n body = Serialization.database_to_xml(login, password, location)\n request_path = '/servers'\n request = BaseManagement::SqlManagementHttpRequest.new(:post, request_path, body)\n response = request.call\n sql_server = Serialization.server_name_from_xml(response, login, location)\n Azure::Loggerx.info \"SQL database server #{sql_server.name} is created.\" if sql_server\n sql_server\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new application to do OAuth authorization with. This allows you to use OAuth to authorize users using Discord. For information how to use this, see the docs:
def create_oauth_application(name, redirect_uris) response = JSON.parse(API.create_oauth_application(@token, name, redirect_uris)) [response['id'], response['secret']] end
[ "def create_oauth_application(auth, name, redirect_uris)\n request(\n :oauth2_applications,\n nil,\n :post,\n \"#{APIBASE_URL}/oauth2/applications\",\n { name: name, redirect_uris: redirect_uris }.to_json,\n Authorization: auth,\n content_type: :json\n )\n end", "def create_oauth_application(token, name, redirect_uris)\n request(\n :oauth2_applications,\n nil,\n :post,\n \"#{api_base}/oauth2/applications\",\n { name: name, redirect_uris: redirect_uris }.to_json,\n Authorization: token,\n content_type: :json\n )\n end", "def bot_application\n return unless @type == :bot\n\n response = API.oauth_application(token)\n Application.new(JSON.parse(response), self)\n end", "def create\n payload = {\n \"description\" => options[:description],\n \"scope\" => options[:scope] ? options[:scope].split(\",\") : nil,\n \"expires_in\" => options[:expires_in]\n }\n token = request do\n api.request(\n :body => encode_json(payload),\n :expects => 201,\n :headers => headers,\n :method => :post,\n :path => \"/oauth/authorizations\"\n ).body\n end\n output_format = options[:output_format] || DEFAULT_OUTPUT_FORMAT\n puts \"Created OAuth authorization.\" unless output_format == 'short'\n show_authorization(token, output_format: output_format)\n end", "def create_app\n post_app('name' => app_name)\n end", "def oauth_application(auth)\n request(\n :oauth2_applications_me,\n nil,\n :get,\n \"#{APIBASE_URL}/oauth2/applications/@me\",\n Authorization: auth\n )\n end", "def oauth_flow\n Google::APIClient::InstalledAppFlow.new(\n client_id: client_secrets.client_id,\n client_secret: client_secrets.client_secret,\n scope: configuration.api_scope\n )\n end", "def create_application(application_id, request)\n start.uri('/api/application')\n .url_segment(application_id)\n .body_handler(FusionAuth::JSONBodyHandler.new(request))\n .post()\n .go()\n end", "def create_app()\n app = OpenShift::TestApplication.new(self)\n\n $logger.info(\"Created new application #{app.name} for account #{@name}\")\n\n @apps << app\n app\n end", "def create\n name = shift_argument\n url = shift_argument\n\n unless name && url\n raise(Heroku::Command::CommandFailed, \"Usage: clients:register [NAME] [CALLBACK_URL]\")\n end\n\n validate!(url)\n client = request do\n api.request(\n :body => encode_json(\n { :name => name, :redirect_uri => url }),\n :expects => 201,\n :headers => headers,\n :method => :post,\n :path => \"/oauth/clients\"\n ).body\n end\n\n if options[:shell]\n puts \"HEROKU_OAUTH_ID=#{client[\"id\"]}\"\n puts \"HEROKU_OAUTH_SECRET=#{client[\"secret\"]}\"\n else\n styled_header(%{Registered client \"#{name}\".})\n styled_hash(client)\n end\n end", "def create\n name = shift_argument || options[:app] || ENV['HEROKU_APP']\n no_remote = !options[:no_remote].nil?\n remote = options[:remote]\n remote = \"heroku\" if remote == nil\n addons = options[:addons]\n password = options[:password]\n password = newpass if password == nil\n opts = \"\"\n if no_remote\n opts = opts + \"--no-remote \"\n else\n opts = opts + \"--remote #{remote}\"\n end\n opts = opts + \"--addons #{addons}\" unless addons.nil?\n system \"heroku apps:create #{name} #{opts} --stack cedar --buildpack http://github.com/heathprovost/openbd-heroku.git\"\n system \"heroku config:set OPENBD_PASSWORD=#{password} --app #{name}\"\n system \"heroku labs:enable user-env-compile --app #{name}\"\n end", "def create\n server = Chaos::Server.new \"ssh://#{options[:server]}\"\n server.ask_user_password unless server.password?\n\n name = options[:name] || File.basename(Dir.pwd)\n app = Chaos::App.new name, server\n\n display_ \"Create app '#{app}' on '#{app.server}'...\", :topic\n app.create\n\n display_ \"Done.\", :topic\n if File.basename(Dir.pwd) == app.name\n if Dir.exist?('.git') && !app.server.host.nil? && !app.git.nil?\n if system \"git remote add #{app.server} git@#{app.server}:#{app}.git > /dev/null 2>&1\"\n display_ \"Git remote added to the current directory ('git push #{app.server} master' to deploy)\"\n end\n end\n end\n display_ \"* Git : #{app.git}\"\n display_ \"* Url : #{app.http}\"\n end", "def build_oauth_service\n # TODO\n end", "def oauth_application(token)\n request(\n :oauth2_applications_me,\n nil,\n :get,\n \"#{api_base}/oauth2/applications/@me\",\n Authorization: token\n )\n end", "def oauth_application(token)\n request(\n __method__,\n :get,\n \"#{api_base}/oauth2/applications/@me\",\n Authorization: token\n )\n end", "def create_pliveo_app()\n info = {\n \"answer_url\" => build_url(account_id,\"answer\"),\n \"app_name\" => account_id,\n \"hangup_url\" => build_url(account_id,\"hangup\"),\n \"fallback_url\" => build_url(account_id,\"fallback\"),\n \"message_url\" => build_url(account_id,\"message\")\n } \n # plivo call \n c = Plivo::RestAPI.new(AUTH_ID, AUTH_TOKEN)\n r = c.create_application(info)\n logger.info \"APPLICATION CREATE RESPONSE IS #{r.inspect}\"\n\n if r[0] = 201\n # app is created successfully save to database \n logger.info \"created app!\"\n prepare_for_save(info)\n end\n end", "def add\n usage = \"\\n Usage:\\n $ jiveapps oauth:add <servicename> <key> <secret>\"\n app_name = extract_app\n raise CommandFailed, \"Missing 3 parameters: <servicename>, <key>, and <secret>#{usage}\" unless servicename = args.shift\n raise CommandFailed, \"Missing 2 parameters: <key> and <secret>#{usage}\" unless key = args.shift\n raise CommandFailed, \"Missing 1 parameter: <secret>#{usage}\" unless secret = args.shift\n\n display \"=== Registering a new OAuth Service: \\\"#{servicename}\\\"\"\n response = jiveapps.add_oauth_service(app_name, servicename, key, secret)\n Jiveapps::Command.run_internal('oauth:list', [\"--app\", app_name])\n end", "def create_app name, template\n\t\t\tdata = {\n\t\t\t\t'name' => name,\n\t\t\t\t'template' => template,\n\n\t\t\t\t'token' => auth_token,\n\t\t\t}.to_json\n\n\t\t\tJSON.parse(post('/apps.json', data).body) rescue nil\n\t\tend", "def create_google_apps\n GoogleApps.new(self).generate\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the current listening status to the specified name.
def listening=(name) gateway_check update_status(@status, name, nil, nil, nil, 2) end
[ "def watching=(name)\n gateway_check\n update_status(@status, name, nil, nil, nil, 3)\n end", "def name=(name)\n @name = name\n update_channel_data\n end", "def name=(name)\n update_server_data(name: name)\n end", "def name=(name)\n update_channel_data(name: name)\n end", "def name=(name)\n update_webhook(name: name)\n end", "def set_status(task_name, status)\n command = Command::SetStatus.new(task_name, status)\n Client.run(command)\n end", "def competing=(name)\n gateway_check\n update_status(@status, name, nil, nil, nil, 5)\n end", "def name=(new_name)\n @mutex.synchronize do\n if @ended\n OpenTelemetry.logger.warn('Calling name= on an ended Span.')\n else\n @name = new_name\n end\n end\n end", "def set_status_to(status)\n status = Status.where(name: status).first\n if status\n self.status = status\n self.save\n else\n false\n end\n end", "def set_status index, status\n @status[index] = status\n end", "def set_Status(value)\n set_input(\"Status\", value)\n end", "def set_Status(value)\n set_input(\"Status\", value)\n end", "def set_bind_status(bind_classname)\n @bind_status = BIND_STATUSES[bind_classname]\n end", "def set_status(message)\n self.status=message\n session.post('facebook.users.setStatus',{:status=>message,:status_includes_verb=>1,:uid => uid}, false) do |ret|\n ret\n end\n end", "def skype_status_update(event)\n username = get_skype_username event.headers['Buddy']\n \n if COMPONENTS.skype_utils['buddy_status_store'] == 'database'\n skype_user = SkypeUser.find_by_username username\n if skype_user\n skype_user.status = event.headers['BuddyStatus']\n skype_user.save\n else\n if COMPONENTS.skype_utils['store_unknown_buddies']\n skype_user = SkypeUser.new\n skype_user.name = username\n skype_user.username = username\n skype_user.status = event.headers['BuddyStatus']\n skype_user.save\n end\n end\n end\n \n if COMPONENTS.skype_utils['buddy_status_store'] == 'memory' || COMPONENTS.skype_utils['buddy_status_store'] == 'both'\n ::Active_skype_status.update_status(username, event.headers['BuddyStatus'])\n end\n end", "def set_name(name, id = @id)\n @client.request_session(\n {\n 'player_set_name' => '',\n 'id' => id,\n 'name' => name,\n 'app_version' => @version\n },\n @sid\n )\n end", "def collins_set_needs_rename!\n state = collins_osc_state\n state.merge!({\n 'running' => false,\n 'finished' => Time.now.to_i,\n 'current_state' => \"needs_rename\",\n 'next_state' => \"can_be_altered\"\n })\n\n self.collins_osc_state = state\n end", "def set_access_vlan(name, opts = {})\n cmd = command_builder('switchport access vlan', opts)\n configure_interface(name, cmd)\n end", "def set_StatusCallback(value)\n set_input(\"StatusCallback\", value)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the current watching status to the specified name.
def watching=(name) gateway_check update_status(@status, name, nil, nil, nil, 3) end
[ "def set_status(task_name, status)\n command = Command::SetStatus.new(task_name, status)\n Client.run(command)\n end", "def competing=(name)\n gateway_check\n update_status(@status, name, nil, nil, nil, 5)\n end", "def listening=(name)\n gateway_check\n update_status(@status, name, nil, nil, nil, 2)\n end", "def set_status index, status\n @status[index] = status\n end", "def set_status_to(status)\n status = Status.where(name: status).first\n if status\n self.status = status\n self.save\n else\n false\n end\n end", "def status=(value)\n value = value.to_s.to_sym\n fail Deployment::InvalidArgument, \"#{self}: Invalid task status: #{value}\" unless ALLOWED_STATUSES.include? value\n status_changes_concurrency @status, value\n @status = value\n reset_forward if DEPENDENCY_CHANGING_STATUSES.include? value\n @status\n end", "def status=(val)\n unless [nil, :frozen, :live].include?(val)\n raise ArgumentError.new(\"Status must be :frozen or :live\") \n end\n @status = val\n end", "def set_Status(value)\n set_input(\"Status\", value)\n end", "def mark_working!; self.status = 1 end", "def change_status(status)\n unless @status == status\n @status = status\n @start_time = Time.now\n end\n end", "def set_Status(value)\n set_input(\"Status\", value)\n end", "def status name\n if button = status_button(name)\n button.refresh\n end\n end", "def set_CurrentStatus(value)\n set_input(\"CurrentStatus\", value)\n end", "def watcher(name)\n watchers.find { |watcher| watcher.name == name }\n end", "def collins_set_needs_rename!\n state = collins_osc_state\n state.merge!({\n 'running' => false,\n 'finished' => Time.now.to_i,\n 'current_state' => \"needs_rename\",\n 'next_state' => \"can_be_altered\"\n })\n\n self.collins_osc_state = state\n end", "def change_king(king_status)\n @king = king_status\n end", "def status=(value)\n @status = value\n end", "def watch_tube(name, conn = connection)\n @watching_tube = name\n conn.tubes.watch!(name)\n end", "def active_set_name(name)\n if @handle.ptr == nil\n raise \"this is disposed\"\n end\n Native.RunEditor_active_set_name(@handle.ptr, name)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the currently online stream to the specified name and Twitch URL.
def stream(name, url) gateway_check update_status(@status, name, url) name end
[ "def stream(name, url)\n gateway_check\n update_status(@idletime, name, url)\n name\n end", "def update_stream(name, params={})\n stream = Stream.new(@client, self, {\"name\" => name})\n stream.update!(params)\n end", "def stream(name)\n self.redis_publisher_stream = name.to_s\n end", "def stream(name)\n res = @client.get(\"#{path}/streams/#{HTTP::URL.encode(name)}\")\n Stream.new(@client, self, res.json) if res.success?\n end", "def use(name)\n @_playlist = playlists[name]\n end", "def url!(url=nil)\n url.kind_of?(String) ? @session.chanserv.set(self.name, :url, url) : @session.chanserv.set(self.name, :url)\n end", "def set_streams(response)\n board_id = response.args.last\n board = trello_client.find(:boards, board_id)\n response.reply(\"Starting Set Streams session for board: #{board.name}\")\n response.reply(\"Note: You have #{RESPONSE_TIMEOUT} seconds between questions to reply\")\n select_next_streamless_card_from_board(response, board)\n end", "def set_remote_url(name, url); end", "def stream\n _streams[self] ||= \n connect!\n end", "def watch_tube(name, conn = connection)\n @watching_tube = name\n conn.tubes.watch!(name)\n end", "def name=(name)\n @name = name\n update_channel_data\n end", "def name=(name)\n write_attribute(:name, name)\n self.update_url_name\n end", "def stream(name: T.unsafe(nil), connector_name: T.unsafe(nil), url: T.unsafe(nil), track: T.unsafe(nil), status_callback: T.unsafe(nil), status_callback_method: T.unsafe(nil), **keyword_args); end", "def live_stream=(stream)\n @live_stdout = @live_stderr = stream\n end", "def name=(name)\n update_channel_data(name: name)\n end", "def update!\n response = Tessellator::Fetcher.new.call('get', 'https://api.hitbox.tv/user/duckinator')\n is_live = JSON.parse(response.body)['is_live']\n\n @@is_streaming = (is_live == '1')\n end", "def set_name(name, id = @id)\n @client.request_session(\n {\n 'player_set_name' => '',\n 'id' => id,\n 'name' => name,\n 'app_version' => @version\n },\n @sid\n )\n end", "def streams=(urls)\n @streams ||= []\n urls = [urls] if !urls.is_a?(Array)\n urls.each do |stream_url|\n # Extract the plan name form the URL: http://localhost:8080/1/stream/slug1 => slug1\n slug = stream_url.split(\"/\").last\n @streams << Stream.find(slug)\n end\n end", "def stream(optname, optarg)\n new_auth = Tw::NewAuth.new(@account)\n new_auth.auth()\n requester = Tw::TwitterRequester.new(new_auth)\n followers_cache_option = {\n :permission => FOLLOWERS_CACHE_PERMISSON,\n :interval => FOLLOWERS_CACHE_INTERVAL\n }\n stream = Tw::Stream::Stream.new(requester, followers_cache_option)\n format = @options.format()\n current_user_id = new_auth.user.id\n separator = \"\\n\"\n lastTweet = nil\n is_disconnected = false\n $stderr.puts(\"-- waiting stream...\")\n loop do\n begin\n stream.user_stream do |obj|\n if is_disconnected && lastTweet then\n # ここ以下は作り直した方がいいかも。\n # (ストリームが途切れたときに代わりに home timeline から取るの)\n #timeline = stream.home_timeline(lastTweet.id)\n #self.renderer.display(timeline, @options.format(), separator: separator, current_user_id: current_user_id)\n #self.logger.debug(\n # \"Tw::App::Executor.stream(): Timeline recovery completed.\")\n is_disconnected = false\n end\n if obj.is_a?(Tw::Tweet) then\n lastTweet = obj\n end\n self.display_stream_object(obj, current_user_id)\n end\n ret = 0\n rescue EOFError, SocketError, Timeout::Error => e\n is_disconnected = true\n\n $stderr.puts(\">>> #{e.class} (#{e.message})\")\n $stderr.puts(\">>> Retrying to connect to Twitter stream.\")\n sleep(5)\n next\n rescue => e\n $stderr.puts(experr(__FILE__, __LINE__, e, \"receiving user stream\"))\n $stderr.puts(Tw::BACKTRACE_MSG)\n raise if ENV[\"TWBT\"]\n ret = 1\n end\n end\n return ret\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the currently competing status to the specified name.
def competing=(name) gateway_check update_status(@status, name, nil, nil, nil, 5) end
[ "def set_status(task_name, status)\n command = Command::SetStatus.new(task_name, status)\n Client.run(command)\n end", "def watching=(name)\n gateway_check\n update_status(@status, name, nil, nil, nil, 3)\n end", "def set_status\n self.status = \"pending\"\n end", "def set_status index, status\n @status[index] = status\n end", "def set_status_to(status)\n status = Status.where(name: status).first\n if status\n self.status = status\n self.save\n else\n false\n end\n end", "def set_status status\n self.update(pet_status: status)\n end", "def status=(value)\n value = value.to_s.to_sym\n fail Deployment::InvalidArgument, \"#{self}: Invalid task status: #{value}\" unless ALLOWED_STATUSES.include? value\n status_changes_concurrency @status, value\n @status = value\n reset_forward if DEPENDENCY_CHANGING_STATUSES.include? value\n @status\n end", "def mark_working!; self.status = 1 end", "def set_status(name, deliver_emails_now = true, options = {})\n name = name.to_s if name.is_a?(Symbol)\n @type = ApplicationStatusType.find_or_create_by_name(name)\n @status = self.application_statuses.find_by_application_status_type_id(@type, :order => 'updated_at DESC')\n if @status.nil? || @status != self.current_status || options[:force] == true\n @status = self.application_statuses.create :application_status_type_id => @type.id\n @status.update_attribute(:note, options[:note]) unless options[:note].blank?\n self.save; self.reload\n self.send_status_updates(@status, deliver_emails_now)\n end\n update_attribute(:current_application_status_id, @status.id)\n self.status\n end", "def make_active\n self.status = \"A\"\n end", "def status=(val)\n unless [nil, :frozen, :live].include?(val)\n raise ArgumentError.new(\"Status must be :frozen or :live\") \n end\n @status = val\n end", "def collins_set_needs_rename!\n state = collins_osc_state\n state.merge!({\n 'running' => false,\n 'finished' => Time.now.to_i,\n 'current_state' => \"needs_rename\",\n 'next_state' => \"can_be_altered\"\n })\n\n self.collins_osc_state = state\n end", "def status=(value)\n @status = value\n end", "def status=(val)\n write_attribute(:status, val)\n self.priority = 0 if self.status == :done\n end", "def listening=(name)\n gateway_check\n update_status(@status, name, nil, nil, nil, 2)\n end", "def update_status status\n @job.set({\n custom_status: status,\n pinged_at: Time.now\n })\n end", "def set_in_progress\n if self.status == \"Neu\"\n self.status = \"In Bearbeitung\"\n logger.info(\"Transitioning current claim from 'New' to 'In Progress'.\")\n end\n end", "def set_status\n #sets active status on remote server\n NereusStatsItem.delay.set_status(id)\n end", "def set_CurrentStatus(value)\n set_input(\"CurrentStatus\", value)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets status to idle.
def idle gateway_check update_status(:idle, @activity, nil) end
[ "def idle\n set_state :idle\n @start_time = nil\n end", "def idle\n update_profile_status_setting('idle')\n end", "def idle\n log 'Force transition to Run-Test/Idle...'\n # From the JTAG2IPS block guide holding TMS high for 5 cycles\n # will force it to reset regardless of the state, let's give\n # it 6 for luck:\n 6.times { tms!(1) }\n # Now a couple of cycles low to get it into idle\n 2.times { tms!(0) }\n update_state :idle\n end", "def idle\n return unless ready_to_idle?\n\n @idling = true\n\n imap.idle(@mailbox.idle_timeout, &idle_handler)\n ensure\n @idling = false\n end", "def idle\n idle_ptr = UV.allocate_handle_idle\n\n check_result! UV.idle_init(@pointer, idle_ptr)\n Idle.new(self, idle_ptr)\n end", "def idle\n return unless ready_to_idle?\n\n @mailbox.logger.info({ context: @mailbox.context, action: 'Idling' })\n @idling = true\n\n imap.idle(@mailbox.idle_timeout, &idle_handler)\n ensure\n @idling = false\n end", "def make_inactive\n self.status = \"I\"\n end", "def idle_timeout=(idle_timeout); end", "def mark_in_active\n @status = STATUS[:in_active]\n reset_updated_at\n end", "def make_active\n self.status = \"A\"\n end", "def make_active\n self.status = ACTIVE\n end", "def set_initial_status\n \tself.status = \"waiting\"\n end", "def idle!(queue)\n active_at queue, Time.now - timeout*2\n end", "def mark_active\n @status = STATUS[:active]\n @activated_at = DateTime.now()\n reset_updated_at\n end", "def inactive!\n @active.update { |_| false }\n end", "def idle?\n @idle_mutex.synchronize { @idle_state }\n end", "def idle\n handle = Idle.new(@reactor)\n handle.progress &Proc.new if block_given?\n handle\n end", "def on_idle(&block)\n backend.idle_proc = block\n end", "def change_status(status)\n unless @status == status\n @status = status\n @start_time = Time.now\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the bot's status to DnD (red icon).
def dnd gateway_check update_status(:dnd, @activity, nil) end
[ "def drb_status!\n Vedeu.bind(:_drb_status_) { Vedeu::Distributed::Server.status }\n end", "def set(status, msg=nil)\n status = :ready unless Statuses.include? status\n @image.stock = Statuses[status]\n @label.text = msg.to_s\n end", "def set_offline\n\tself.status = \"offline\"\nend", "def set_status\n #sets active status on remote server\n NereusStatsItem.delay.set_status(id)\n end", "def send_toggle_status(status,override, force_report = true)\n cmd = \"dqrSender A #{self.device_id} #{self.id} #{status} #{override}\"\n Rails.logger.info \"DqRSender Perform #{cmd}\"\n result = `#{cmd}`\n exit_status = $?.exitstatus\n \n Rails.logger.info \"DqrSender Perform: exit code #{exit_status}, output: #{result}\"\n \n # device should report back\n if force_report\n send_status_query\n end\n \n { exit_code: exit_status, output: result }\n end", "def color\n case @status\n when \"up-to-date\" then \"#66CC99\"\n when \"updated\" then \"#FFDC00\"\n when \"skipped\" then \"#DDDDDD\"\n when \"why-run\" then \"#6699FF\"\n when \"failed\" then \"#FF4136\"\n when \"unprocessed\" then \"white\"\n else \"white\"\n end\n end", "def announce_do_not_disturb(status=nil)\n @connection.send(Jabber::Protocol::Presence.gen_dnd(id, status))\n end", "def set_default_status!\n self.status = nil\n set_default_status\n end", "def label_color\n case @status\n when \"up-to-date\" then \"#66CC99\"\n when \"updated\" then \"#FFDC00\"\n when \"skipped\" then \"#DDDDDD\"\n when \"why-run\" then \"#6699FF\"\n when \"failed\" then \"#FF4136\"\n when \"unprocessed\" then \"white\"\n else \"white\"\n end\n end", "def say_status(status, color)\n base.shell.say_status status, relative_destination, color if @log_status\n end", "def dmi_status=(status)\n write_attribute(:dmi_status, status.downcase)\n end", "def set_nsds_status(nsds, status)\n not_found = []\n nsds.each do |nsd_td|\n descriptor = Nsd.where({ 'nsd.name' => nsd_td['name'],\n 'nsd.vendor' => nsd_td['vendor'],\n 'nsd.version' => nsd_td['version'] }).first\n if descriptor.nil?\n logger.error 'NSD Descriptor not found ' + nsd_td.to_s\n not_found << nsd_td\n else\n descriptor.update('status' => status)\n end\n end\n not_found\n end", "def mark_as_damaged!\n self.update_attribute(:status, DAMAGED)\n end", "def set_status\n self.status = \"pending\"\n end", "def setStatus(status)\n @nodeStatus = status\n TraceState.nodeStatus(self, status)\n #@statusEl.text = status\n #@statusEl.add_element('history', {'ts' => NodeHandler.getTS()}).text = status\n end", "def status_color\n if skipped?\n :yellow\n elsif error?\n :red\n else\n :green\n end\n end", "def grey(string)\n ::Nucleon::Util::Console.grey(string)\n end", "def green(string)\n ::Nucleon::Util::Console.green(string)\n end", "def update_status\n self.status = check_board\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the bot's status to invisible (appears offline).
def invisible gateway_check update_status(:invisible, @activity, nil) end
[ "def invisible\n update_profile_status_setting('invisible')\n end", "def set_offline\n\tself.status = \"offline\"\nend", "def make_inactive\n self.status = \"I\"\n end", "def to_hide\n self.status = 3\n end", "def set_online_status\n self.online_status = \"offline\"\n end", "def set_invisible_battler(battler)\n ext = check_extension(battler_action(battler), \"HIDE/\")\n return if ext.nil?\n battler.invisible_action = true\n battler.wait_time = 12\n ext.slice!(\"HIDE/\")\n case ext\n when \"BATTLER\"\n battler.invisible = true\n when \"PARTY\",\"ENEMIES\"\n party = battler.actor? ? $game_party.actors : $game_troop.enemies if ext == \"PARTY\"\n party = battler.actor? ? $game_troop.enemies : $game_party.actors if ext == \"ENEMIES\"\n for member in party\n member.invisible = true\n end\n when \"OTHERS\",\"ACTIVE\",\"ALL\"\n party = $game_party.actors + $game_troop.enemies\n for member in party\n member.invisible = true if ext == \"OTHERS\" and member != battler \n member.invisible = true if ext == \"ACTIVE\" and not (member == battler or battler.target_battlers.include?(member))\n member.invisible = true if ext == \"ALL\"\n end\n end\n end", "def private=(status)\n self.public = !status\n end", "def unhide\n post(\"/api/unhide\", id: fullname)\n end", "def unavailable_status\n @status = :UNAVAILABLE\n end", "def suspend!\n self.update_attribute(:status, SUSPENDED)\n end", "def hide_notifications_bar\n when_exists(notifications_bar, Config.short_wait)\n @driver.execute_script(\"arguments[0].style.visibility='hidden';\", element(notifications_bar))\n end", "def unmark!\n @session.nickserv.mark(self.name, :off)\n end", "def set_online_status(status)\n case status\n when :available, :online\n @notification_server.chg \"NLN\", 0\n when :busy\n @notification_server.chg \"BSY\", 0\n when :idle\n @notification_server.chg \"IDL\", 0\n when :brb, :be_right_back\n @notification_server.chg \"BRB\", 0\n when :away\n @notification_server.chg \"AWY\", 0\n when :phone, :on_the_phone\n @notification_server.chg \"PHN\", 0\n when :lunch, :out_to_lunch\n @notification_server.chg \"LUN\", 0\n else\n raise \"Wrong online status: #{status}\"\n end\n end", "def unhide\n client.post('/api/unhide', id: read_attribute(:name))\n end", "def setHideUserListForNonAdmin( hideUserListForNonAdmin )\n\n # parameter TypeCheck\n #BIMserverAPI::TypeCheck::Boolean( hideUserListForNonAdmin )\n\n # BIMserver request\n request( { hideUserListForNonAdmin: hideUserListForNonAdmin } )\n end", "def visible=(vis)\n if vis\n show\n else\n hide\n end\n end", "def toggle_off\n set_state_to(:off)\n end", "def invisible?\n false\n end", "def inactive!\n put_gapi! \"INACTIVE\"\n self\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the logging mode
def mode=(new_mode) LOGGER.mode = new_mode end
[ "def setWithLevel(flag=true)\n logger().setWithLevel(flag) ;\n end", "def set_logger_level\n case @options[:verbose]\n when 0\n @logger.level = Logger::Severity::WARN\n when 1\n @logger.level = Logger::Severity::INFO\n when 2..5\n @logger.level = Logger::Severity::DEBUG\n end\n end", "def use_log_level_option(args = {})\n on(\"--log-level LEVEL\",LOG_LEVELS,'Set the logging level',\n '(' + LOG_LEVELS.keys.join('|') + ')',\n '(Default: info)') do |level|\n @log_level = level\n @log_level_original = level\n @log_level_toggled = false\n logger.level = level\n\n setup_toggle_trap(args[:toggle_debug_on_signal])\n end\n end", "def log_level=(level); end", "def log_level=(lvl)\n @targets.each{|t| t.log_level = lvl }\n @default_options[:log_level] = lvl\n end", "def toggle_logging\n logger = Morrow.config.logger\n\n @logger_orig_level ||= logger.level\n\n # If the logging level is set to debug, assume the test-runner wanted all\n # the logging output\n return if @logger_orig_level < Logger::INFO\n\n logger.level = @logger_orig_level == logger.level ?\n Logger::FATAL : @logger_orig_level\n end", "def set_loglevel\n super\n end", "def log_level=(level)\n RAILS_DEFAULT_LOGGER.level = level\n end", "def set_LogLevel(value)\n set_input(\"LogLevel\", value)\n end", "def mode=(value)\n case value\n when :debug\n @enabled_modes = %i[debug good info warn error out in ratelimit]\n when :verbose\n @enabled_modes = %i[good info warn error out in ratelimit]\n when :normal\n @enabled_modes = %i[info warn error ratelimit]\n when :quiet\n @enabled_modes = %i[warn error]\n when :silent\n @enabled_modes = %i[]\n end\n end", "def set_LogLevel(value)\n set_input(\"LogLevel\", value)\n end", "def verbose_logger=(verbosity)\n default_options[:log_format] = verbosity ? :curl : :apache\n end", "def enable_logging\n initialize_logger\n end", "def set_mode(m)\n @mode = m\n end", "def level=(level, update_config = true)\n super(level)\n @config[:'log-level'] = level if update_config\n end", "def option_logging\n block = proc { |level| Logging::Logger.root.level = level; propagate_option('--logging', level) }\n @cl_parser.on('--logging LEVEL', 'Specify the minimum log level that should be logged.', &block)\n end", "def logging(value = true)\n @logging = value\n if defined?(ActiveRecord)\n @buffered ||= ActiveRecord::Base.logger\n ActiveRecord::Base.logger = @logging ? Logger.new(STDOUT) : @buffered\n end\n end", "def fetch_log_level(mode)\n case mode\n when 'verbose'\n Logger::INFO\n when 'debug'\n Logger::DEBUG\n else # silent mode\n Logger::ERROR\n end\n end", "def set_enable(opts = {})\n cmd = command_builder('logging on', opts)\n configure cmd\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prevents the READY packet from being printed regardless of debug mode.
def suppress_ready_debug @prevent_ready = true end
[ "def debug_off\n @debug_socket = false\n end", "def silence_ready; end", "def print_non_dev_warning\n puts \"\\e[31m\"\n puts non_dev_warning_message\n puts \"\\e[0m\"\n end", "def print_blocked\n return @print_blocked\n end", "def blockdev?() end", "def chk\n if @pkt.size > 900 # arbitrary flush, 1024 is the max allowed\n flush\n #sleep(0.01) # don't overwhelm output buffers\n start\n end\n end", "def debug_on\n @debug_socket = true\n end", "def suppress; @write = false end", "def disable_debugging\n @receiver_class = BasicReceiver\n end", "def maybe_print(message)\n is_status = message[\"payload\"].try(:[], \"message_type\") == \"read_status\"\n STDOUT.puts \"\\n#{message.to_yaml}\\n\" unless is_status\n end", "def reserved?\n status == Status::RESERVED\n end", "def limited_transmit_recovery_state\n super\n end", "def signal_not_ready(delay = nil)\n raise NotReadySignal.new(delay)\n end", "def print_status\n super\n print_battle_commands unless battle_commands.empty?\n end", "def toggle_debug_skip; @debug_skip = !@debug_skip if $game_switches[KOCKA::BETA_SWITCH_ID]; end", "def print_good(msg='')\n return if (disable_output == true)\n\n self.on_print_proc.call(msg) if self.on_print_proc\n log_output(output.print_good(msg))\n end", "def set_flow_control_off\n\t\tsend_command( 0x3B )\n\tend", "def promiscuous?\n\t\t\treturn false\n\t\tend", "def application_guard_allow_print_to_network_printers\n return @application_guard_allow_print_to_network_printers\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a user to the list of ignored users. Those users will be ignored in message events at event processing level.
def ignore_user(user) @ignored_ids << user.resolve_id end
[ "def add_user_ids(user_ids) # :nodoc:\n user_ids.each do |id|\n @context.add_user(:id => id) unless @context.users[id]\n end\n end", "def addWorkingUser user\n @workingUsers << user\n @workingUsers.uniq!\n end", "def add(user)\n users << user\n # equivalents.each { |event| event.users << user }\n end", "def add_user(u)\n run_callbacks :user_added do\n puts \" adding user\"\n @users << u\n end\n end", "def ignored?(user)\n @ignored_ids.include?(user.resolve_id)\n end", "def tag user\n unless tagged? user\n users << user\n end\n end", "def add(user)\r\n @users.push(user)\r\n end", "def admit_user user_id = nil\n return if is_global\n if (tagtype != 0) || user_id.nil? || (user_id == User.super_id)\n self.is_global = true\n elsif !owner_ids.include?(user_id) && (user = User.find_by id: user_id)\n self.owners << user unless owners.include?(user)\n end\n end", "def add_user_list(user_list, skip_attribute_update = false)\n\t\tuser_hash = {}\n\t\tuser_list.each do |user_id|\n\t\t\tuser_hash[user_id] = { status: STATUS_NO_RESPONSE, \n\t\t\t\tcondition: NoCondition.new.get_hash }\n\t\tend\n\t\tself.party_list.merge!(user_hash) { |key, old, new| old }\n\t\tself.update_attribute(:party_list, self.party_list) if !skip_attribute_update\n\tend", "def unignore_user(user)\n @ignored_ids.delete(user.resolve_id)\n end", "def add_user(user)\n return false if user_in_queue? user\n users.add(user)\n print_add_user_to_queue user\n true\n end", "def add_user_list(user_list, skip_attribute_update = false)\n\t\tself.user_list |= user_list\n\t\tself.update_attribute(:user_list, self.user_list) if !skip_attribute_update\n\tend", "def add_users(users)\n users.each do |user|\n @users.push(user)\n end\n end", "def add_user(user)\n case user\n when Integer, String\n user = User.find(user)\n end\n\n if self.users.include?(user)\n return nil\n else\n Observist.expire\n self.users << user\n return user\n end\n end", "def process_users(users)\n users.each do |element|\n user = User.new(element, @bot)\n @users[user.id] = user\n end\n end", "def add_user(id)\n @user_ids << id\n end", "def exclude_users=(value)\n @exclude_users = value\n end", "def only(user)\n self.receiver = [user]\n end", "def add_to_user_event_lists(user_list)\n\t\tuser_list.each do |users_id| \n\t\t\tuser = User.find(users_id)\n\t\t\tuser.add_event(self.id)\n\t\tend\n\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a user from the ignore list.
def unignore_user(user) @ignored_ids.delete(user.resolve_id) end
[ "def ignore_user(user)\n @ignored_ids << user.resolve_id\n end", "def remove(user)\r\n @users.delete(user)\r\n end", "def removeWorkingUser user\n @workingUsers.delete user\n end", "def remove(user)\n users.delete(user)\n # equivalents.each { |event| event.users.delete(user) }\n end", "def remove(user)\n if(self.isIn(user))\n @mysqlHelper.deleteDisConUser(user.getI, @id)\n @userList.remove(user)\n @userList.getcontents.each { |users|\n users.userChangeFromChannel(\"205\", @id, user.getId)\n }\n end\n end", "def remove_user(user)\n case user\n when Integer, String\n user = User.find(user)\n end\n\n if self.users.include?(user)\n Observist.expire\n self.users.delete(user)\n return user\n else\n return nil\n end\n end", "def user_without(exclude)\n user = @user\n exclude.each do |e|\n user[e] = nil\n end\n \n user\n end", "def remove_user(user_id)\n\t\treturn if is_admin?(user_id)\n\t\tparty_list.delete(user_id)\n\t\tself.update_attribute(:party_list, party_list)\n\tend", "def remove_user(user)\n @in_room = false if user == @bot\n @users.delete(user)\n end", "def delete(nickname)\n @users.delete_if do |user|\n user.nickname == nickname\n end\n end", "def remove_user(nick)\n @mutex.synchronize do\n channels = Set.new\n\n @channels.each do |channel|\n if channel.remove_user(nick)\n channels << channel\n end\n end\n\n channels\n end\n end", "def remove_user(user)\n user = User.get(user)\n\n if self.users.include?(user)\n Observist.expire\n self.users.delete(user)\n return user\n else\n return nil\n end\n end", "def ignore\n users = User.where(username: [params[:username], params[:other_username]])\n raise Discourse::InvalidParameters.new if users.size != 2\n\n DiscourseFingerprint.ignore(users[0], users[1], add: params[:remove].blank?)\n DiscourseFingerprint.ignore(users[1], users[0], add: params[:remove].blank?)\n\n render json: success_json\n end", "def remove_user user\n current_user.episodes.each do |episode|\n episode.users -= [user]\n end\n end", "def remove(opts)\n user = fetch(opts)\n if user\n @data = @data.reject { |u| u == user }\n persist\n end\n user\n end", "def remove_user(user)\n self.users.destroy(user)\n end", "def remove_auth_user(user)\n\n user_id = user.id.to_s\n\n ary = self.get_read_users_a\n ary.delete(user_id)\n self.set_read_users(ary)\n\n ary = self.get_write_users_a\n ary.delete(user_id)\n self.set_write_users(ary)\n end", "def remove(user, reason = nil)\n @bot.irc.send(\"REMOVE #{@name} #{user} :#{reason}\")\n end", "def delete_user nick\n $log.debug(\"Users.add_user\") { \"Removing user #{nick} on #{@connection.name}\" }\n\n delete nick\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks whether a user is being ignored.
def ignored?(user) @ignored_ids.include?(user.resolve_id) end
[ "def ignored?(who)\n if rec = @store.get_user(who)\n rec['ignored']\n else\n nil\n end\n end", "def ignored?(key)\n get_user(key)['ignored']\n end", "def ignore?\n @should_ignore\n end", "def i_dont_own?(object)\n if(current_user.present? and object.user.present? and object.user.id.present? and (current_user.id == object.user.id))\n false\n else\n true\n end\n end", "def ignored?\n @ignored\n end", "def blocking?(other_user)\n blocking.include?(other_user)\n end", "def ignoring?(object)\n interest_in(object) == :ignoring\n end", "def blocked?(user)\n blocked.include?(user)\n end", "def ignored?(object)\n ignores.exists?(:ignoreable_id => object.id, :ignoreable_type => object.class.to_s)\n end", "def blocked?(user)\n blocked.include?(user)\n end", "def has_ignored?(object)\n ignores.exists?(:ignoreable_id => object.id, :ignoreable_type => object.class.to_s)\n end", "def filtered?(job)\n @config.excluded_users.include?job.user_name\n end", "def user_has_not_verified_other_discord_users?(user, discord_user)\n user.discord_user.nil? || !user.discord_user.verified? || user.discord_user == discord_user\n end", "def is_pin_privategame_false?(user_name)\n pin_given = @pin_given[user_name]\n if @pin_originator != pin_given\n return true\n end\n return false \n end", "def check_to_exclude_accounts\n errors.add(:base, 'This is a special account and it is not possible to continue. Please contact to administrator.') if observed.is_a?(User) && [User.support_id, User.main_admin_id].include?(observed.id)\n end", "def user_is_not_author?\n if user.present?\n if event.user == user\n errors.add(:user, :invalid)\n end\n end\n end", "def denied_user?(u)\n (@deny_anons && u && (u.uid < 0)) || @denied_users.include?(u)\n end", "def user_is_not_blocked\n return errors.add(:user, 'You cannot block yourself')\\\n if user_id == blocked_id\n end", "def is_not_global_and_is_owned_by?(user)\n !self.is_global? && self.user_id == user.id\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Raises a heartbeat event. Called by the gateway connection handler used internally.
def raise_heartbeat_event raise_event(HeartbeatEvent.new(self)) end
[ "def handle_heartbeat(_payload)\n send_packet(OPCODES[:HEARTBEAT], @session.seq)\n end", "def sendHeartbeat()\n if NodeAgent.instance.connected?\n send!(:HB, -1, -1, -1, -1)\n else\n # haven't heard from nodeHandler yet, resend initial message\n sendWHOAMI\n end\n end", "def send_heartbeat\n send_message DCell::Message::Heartbeat.new\n @heartbeat = after(self.class.heartbeat_rate) { send_heartbeat }\n end", "def sendHeartbeat()\n if NodeAgent.instance.connected?\n # Check if we still hear from handler\n now = Time.now\n delta = now - @handlerTimestamp\n if (delta > @handlerTimeout)\n if ((@timeoutCnt += 1) >= @timeoutCount)\n error \"Lost handler after #{delta}, will reset. Now: #{Time.now}\"\n send!(0, :ERROR, :LOST_HANDLER, delta)\n NodeAgent.instance.reset\n else\n send!(0, :WARN, :ALMOST_LOST_HANDLER, @timeoutCnt, delta)\n end\n else\n @timeoutCnt = 0\n inCnt = @inSeqNumber > 0 ? @inSeqNumber : 0\n @lockSeqNumber.synchronize {\n send!(:HB, @outSeqNumber, inCnt, now.to_i, delta.to_i)\n }\n end\n else\n # haven't heard from nodeHandler yet, resend initial message\n sendWHOAMI\n end\n end", "def send_heartbeat\n if tcp_connection_established? && !@handling_skipped_hearbeats && @last_server_heartbeat\n if @last_server_heartbeat < (Time.now - (self.heartbeat_interval * 2)) && !reconnecting?\n logger.error \"[amqp] Detected missing server heartbeats\"\n self.handle_skipped_hearbeats\n end\n send_frame(Protocol::HeartbeatFrame)\n end\n end", "def sendHeartbeat()\n send!(0, :HB, -1, -1, -1, -1)\n end", "def handle_heartbeat_ack(_payload)\n @heartbeat_acked = true\n end", "def poll_heartbeat_timeout\n now = Hastur::Util.timestamp\n delta = now - @last_heartbeat\n\n # perform heartbeat check\n if delta > @heartbeat\n @logger.debug \"Sending heartbeat\"\n\n msg = Hastur::Message::HB::Agent.new(\n :from => @uuid,\n :data => {\n :name => \"hastur.agent.heartbeat\",\n :value => delta,\n :timestamp => now,\n :labels => {\n :version => Hastur::SERVER_VERSION,\n :period => @heartbeat,\n }\n }\n )\n _send(msg)\n\n @last_heartbeat = now\n end\n end", "def heartbeat\n if check_heartbeat_acks\n unless @last_heartbeat_acked\n # We're in a bad situation - apparently the last heartbeat wasn't ACK'd, which means the connection is likely\n # a zombie. Reconnect\n LOGGER.warn('Last heartbeat was not acked, so this is a zombie connection! Reconnecting')\n\n # We can't send anything on zombie connections\n @pipe_broken = true\n reconnect\n return\n end\n\n @last_heartbeat_acked = false\n end\n\n send_heartbeat(@session ? @session.sequence : 0)\n end", "def handle_heartbeat(data)\n incoming_seq, outgoing_seq, discard = data\n\n trigger(:heartbeat, incoming_seq, outgoing_seq, discard)\n end", "def handle_heartbeat(client, data)\n incoming_seq, outgoing_seq, discard = data\n\n trigger(:heartbeat, client, incoming_seq, outgoing_seq, discard)\n end", "def start_heartbeat\n @hb_received_at = Time.now\n send_heartbeat\n @heartbeat_timer = @reactor.periodical_timer(@heartbeat_interval) { send_heartbeat }\n end", "def heartbeat\n end", "def sendRelaxedHeartbeat()\n\n if NodeAgent.instance.connected?\n # Check if we still hear from handler\n now = Time.now\n delta = now - @handlerTimestamp\n\n # NO - Then enter a 'temporary disconnected' state\n if (delta > @handlerTimeout)\n if ((@timeoutCnt += 1) >= @timeoutCount)\n @tmpDisconnected = true\n debug \"Heartbeat - Lost Handler - Node is now temporary Disconnected\"\n end\n\n # YES - Then if we were previously disconnected, leave that state!\n else \n if @tmpDisconnected\n @tmpDisconnected = false\n debug \"Heartbeat - Found Handler - Node is now Reconnected\"\n end\n end\n\n # Regardless of connection state, we keep sending HB\n @timeoutCnt = 0\n inCnt = @inSeqNumber > 0 ? @inSeqNumber : 0\n @lockSeqNumber.synchronize {\n send!(:HB, @outSeqNumber, inCnt, now.to_i, delta.to_i)\n }\n\n # Always check if Experiment is done AND we are not temporary disconnected\n #debug \"TDEBUG - Check EXPDONE + !DISCONNECTED - #{NodeAgent.instance.expirementDone?} - #{!@tmpDisconnected}\"\n if (NodeAgent.instance.expirementDone? && !@tmpDisconnected)\n debug \"Heartbeat - Experiment Done and Node Reconnected\"\n sendResumeAndQuit\n ### HACK - Waiting for OML Proxy to return a good 'DONE' to us\n Kernel.sleep 10\n sendEXPDONE\n NodeAgent.instance.reset\n end\n else # ---if NodeAgent.instance.connected?---\n # haven't heard from nodeHandler yet, resend initial message\n sendWHOAMI\n end\n end", "def process_heartbeat\n if Time.now > @next_heartbeat\n send_heartbeat()\n @next_heartbeat = next_heartbeat\n end\n nil\n end", "def subscribe_to_heartbeat\n @logger.trace \"setting up 'HEARTBEAT' subscriber\"\n subscribe(\"MOL.HEARTBEAT\") do |packet|\n node = @registry.safe_fetch_node(packet.sender)\n if node\n node.beat\n else\n # because the node is not registered with the broker, we have to assume that something broke down. we need to\n # force a publish to the node we just received the heartbeat from\n publish_discover_to_node_id(packet.sender)\n end\n end\n end", "def heartbeat_received\n @last_update = DateTime.now\n end", "def send_heartbeat(test_req_id = nil)\n msg = FP::Messages::Heartbeat.new\n test_req_id && msg.test_req_id = test_req_id\n send_msg(msg)\n end", "def update_heartbeat\n if @heartbeat_updated_at.nil? || elapsed(@heartbeat_updated_at) >= HEARTBEAT_FREQUENCY\n queue.record_worker_heartbeat\n @heartbeat_updated_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes the bot leave any groups with no recipients remaining
def prune_empty_groups @channels.each_value do |channel| channel.leave_group if channel.group? && channel.recipients.empty? end end
[ "def ungroup\n send_transport_message('BecomeCoordinatorOfStandaloneGroup')\n end", "def leave_memberships\n all_groups do |g|\n g.resources.membership = { leave: g.address }\n end\n end", "def leave()\n\t\treturn if !@group\n\t\tcpg_name = Corosync::CpgName.new\n\t\tcpg_name[:value] = @group\n\t\tcpg_name[:length] = @group.size\n\n\t\t# we can't join multiple groups, so I dont know why corosync requires you to specify the group name\n\t\tCorosync.cs_send(:cpg_leave, @handle, cpg_name)\n\n\t\t@group = nil\n\tend", "def delete_group_memberships_for_end_users\n self.group_memberships.delete_all if self.end_user?\n end", "def leave\n @users_group = group.users_groups.where(user_id: current_user.id).first\n\n if group.last_owner?(current_user)\n redirect_to(profile_groups_path, alert: \"You can't leave group. You must add at least one more owner to it.\")\n else\n @users_group.destroy\n redirect_to(profile_groups_path, info: \"You left #{group.name} group.\")\n end\n end", "def leave \n members = @community.members.where(:user_id=> current_user.id)\n members.delete_all\n flash[:notice] = 'Group is successfully Leaved.'\n redirect_to '/dashboard'\n end", "def remove_role_assignments_from_group_members_if_needed\n return unless entity.type == 'Group'\n\n Rails.logger.tagged \"RoleAssignment #{id}\" do\n entity.members.each do |m|\n logger.info \"Removing role (#{role.id}, #{role.token}, #{role.application.name}) about to be removed from group (#{entity.id}/#{entity.name} from its member #{m.id}/#{m.name})\"\n ra = RoleAssignment.find_by_role_id_and_entity_id_and_parent_id(role.id, m.id, self.id)\n if ra\n ra.destroy!\n else\n logger.warn \"Failed to remove role (#{role.id}, #{role.token}, #{role.application.name}) assigned to group member (#{m.id}/#{m.name}) which needs to be removed as the group (#{entity.id}/#{entity.name}) is losing that role.\"\n end\n end\n end\n end", "def remove_empty_group\n group = self.group\n if group.users.size == 1\n # group.destroy\n end\n end", "def remove_from_all_groups\n self.group_memberships.each {|m| m.destroy}\n end", "def groups_original_request_not_accepted_from\n self.group_ids.reject { |group_id| group_id == self.group_id }\n end", "def leave\n @chat.members.delete(current_user)\n render json: { status: 'done' }, status: :ok\n ChatChannel.send_notification_to_chat(@chat.id, user_left_the_chat_msg)\n end", "def dissolve_groups\n groups.destroy_all\n end", "def prevent_zero_group_admins\n @membership = Membership.find(params[:id])\n @group = @membership.group\n if @group.has_one_admin? && (@membership.user == current_user)\n flash[:danger] = \"You cannot quit unless there are other group admins.\"\n redirect_to @group\n end\n end", "def check_out_group(group)\n @guests_in_room.pop(group.length)\n\n return group\n end", "def leave\n @group = Group.find_by(id: params[:id]) || not_found\n redirect_to(action: 'show', id: @group.id) && return \\\n if @group.admin?(current_user)\n end", "def leavegroup\n if(params[:leave] && params[:leave][:id]) \n group = Group.find_by_id(params[:leave][:id])\n if group.nil?\n render :json => [\"Group not found\"], :status => 400\n else\n if User.member?(current_user, group)\n # delete all bills related to group of user\n if group.self\n render :json => [\"Unable to leave the 'Me' group\"], :status => 400 \n else\n remove_user_bills(group)\n remove_user_tasks(group)\n group.users.delete(current_user)\n if group.users.empty?\n # delete group no more user\n group.destroy\n end\n render :nothing => true, :status => 200\n end\n else\n render :json => [\"Unable to leave group #{group.name}\"], :status => 400\n end\n end\n else\n render :json => [\"Group Not Selected\"], :status => 400\n end\n end", "def remove_agents_of_group(ids, groups)\n delete \"/agents/group/#{group_id}\", {ids: ids}\n end", "def remove_role_assignments_from_group_members_if_needed\n if entity.type == 'Group'\n Rails.logger.tagged \"RoleAssignment #{id}\" do\n # Tell trigger_sync! to ignore any requests it receives - we'll just put in one\n # sync request after all the new RoleAssignments exist.\n Thread.current[:will_sync_role] = [] unless Thread.current[:will_sync_role]\n Thread.current[:will_sync_role] << role.id\n \n entity.members.each do |m|\n logger.info \"Removing role (#{role.id}, #{role.token}, #{role.application.name}) about to be removed from group (#{entity.id}/#{entity.name} from its member #{m.id}/#{m.name})\"\n ra = RoleAssignment.find_by_role_id_and_entity_id_and_parent_id(role.id, m.id, entity.id)\n if ra\n destroying_calculated_role_assignment do\n ra.destroy\n end\n else\n logger.warn \"Failed to remove role (#{role.id}, #{role.token}, #{role.application.name}) assigned to group member (#{m.id}/#{m.name}) which needs to be removed as the group (#{entity.id}/#{entity.name}) is losing that role.\"\n end\n end\n \n Thread.current[:will_sync_role].delete(role.id)\n role.trigger_sync!\n end\n end\n end", "def send_group_message(group, sender, recipients, subject, message)\n if group.blank? || sender.blank? || recipients.blank? || message.blank?\n return false\n end\n\n if subject.blank?\n subject = \"[#{group.display_name}] A message from #{sender.display_name}\"\n else\n subject = \"[#{group.display_name}] #{subject}\"\n end\n\n @group = group\n @sender = sender\n @recipients = recipients\n @subject = subject\n @message = message\n\n @view_action = {\n url: url_for(controller: 'groups', id: @group.id, only_path: false),\n action: 'View Group',\n description: 'You have received a message.'\n }\n\n @email_recipients = []\n recipients.each do |recipient|\n @email_recipients << \"#{recipient.display_name} <#{recipient.email}>\"\n end\n\n mail(\n to: @email_recipients.join(', '),\n subject: subject,\n reply_to: \"#{sender.display_name} <#{sender.email}>\"\n )\n\n headers['X-Mailgun-Tag'] = 'GroupMessage'\n headers['X-Mailgun-Dkim'] = 'yes'\n headers['X-Mailgun-Track'] = 'yes'\n headers['X-Mailgun-Track-Clicks'] = 'yes'\n headers['X-Mailgun-Track-Opens'] = 'yes'\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all application commands.
def get_application_commands(server_id: nil) resp = if server_id API::Application.get_guild_commands(@token, profile.id, server_id) else API::Application.get_global_commands(@token, profile.id) end JSON.parse(resp).map do |command_data| ApplicationCommand.new(command_data, self, server_id) end end
[ "def all_commands\n storage[:commands]\n end", "def commands\n unless defined? @commands\n @commands = []\n end\n return @commands\n end", "def get_global_commands(token, application_id)\n Discordrb::API.request(\n :applications_aid_commands,\n nil,\n :get,\n \"#{Discordrb::API.api_base}/applications/#{application_id}/commands\",\n Authorization: token\n )\n end", "def all_commands\n @all_commands ||= from_superclass(:all_commands, Foreman::Thor::CoreExt::OrderedHash.new)\n @all_commands.merge!(commands)\n end", "def commands\n @commands ||= [].tap do |c|\n commands_list.each do |command|\n if command.instance_of? String\n c << standard_commands[command].new\n else\n ret_command = send(command)\n c << (ret_command.instance_of?(Hash) ? ret_command.values : ret_command)\n end\n end\n end.flatten\n end", "def commands\n self.class.command_classes\n end", "def get_all_commands_and_imports\n std_commands = Array.new\n std_imports = Array.new\n cmds = (current_package[:commands] || Hash.new).dup\n pkg_file = run_options[:package_files].first\n cmd_paths = run_options[:command_paths] || []\n std_commands.push get_command_file_comment(pkg_file)\n cmds.each do |cmd|\n commands = Array.new\n imports = Array.new\n run_cmd = cmd.is_a?(Hash) ? cmd[:run] : cmd\n case\n when cmd.blank?\n when cmd.is_a?(String)\n commands = get_standardized_commands(pkg_file, run_cmd)\n when cmd.is_a?(Hash)\n run_cmd = cmd[:run]\n file = find_src_file(\"#{run_cmd}.yml\", src_paths: cmd_paths)\n stop_run \"Ember command file #{run_cmd.inspect} not found in any command path.\" if file.blank?\n commands.push get_command_file_comment(file)\n hash = get_yml_file_hash(file)\n stop_run \"Ember command file #{file.inspect} is not a hash.\" unless hash.is_a?(Hash)\n cmds = hash[:commands] || []\n commands.push *get_standardized_commands(file, cmds)\n himports = hash[:import]\n imports = get_standardized_imports(file, himports) if himports.present?\n else\n stop_run \"Unknown ember command file format #{cmd.inspect} in file #{file.inspect}.\"\n end\n std_commands.push(*commands) if commands.present?\n std_imports.push(*imports) if imports.present?\n end\n [std_commands, std_imports]\n end", "def list_commands_by_name\n _get('commandsByName', ApiCommandMetadata, true, nil, nil, 6)\n end", "def find_all_commands (sCOMMAND)\n array = Array.new()\n @commands.each do |command|\n if (command.commandName == sCOMMAND)\n array.push(command)\n end\n end\n return array\n end", "def commands\n @commands ||= Foreman::Thor::CoreExt::OrderedHash.new\n end", "def global_commands\n @global_commands ||= construct_commands\n end", "def commands\n @commands.keys.sort\n end", "def invoke_all #:nodoc:\n self.class.all_commands.map { |_, command| invoke_command(command) }\n end", "def supported_commands\n commands.keys\n end", "def find_commands\n\t\treturn self.methods.\n\t\t\tcollect {|mname| mname.to_s }.\n\t\t\tgrep( /^(\\w+)_command$/ ).\n\t\t\tcollect {|mname| mname[/^(\\w+)_command$/, 1] }.\n\t\t\tsort\n\tend", "def global_commands\n @global_commands ||= construct_command.create.command\n end", "def commands\n\t\tself.class.commands_list.each do |name, description|\n\t\t\tprintf \"#{name.ljust(10)} : #{description}\\n\"\n\t\tend\n\tend", "def verbs\n COMMANDS.merge(EXTERNAL_COMMANDS)\n end", "def commands\n version = invoke_and_process(\"JSONRPC.Version\")\n if (version[\"version\"] == 2)\n @commands ||= invoke_and_process(\"JSONRPC.Introspect\", :getdescriptions => true)[:commands].map {|c| Xbmc::Command.new(c)}\n else\n @commands ||= invoke_and_process(\"JSONRPC.Introspect\", :getdescriptions => true)[:methods].map {|c| \n attrList = c.at(1)\n attrList[\"command\"] = c.at(0)\n Xbmc::Command.new(attrList)\n }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an application command by ID.
def get_application_command(command_id, server_id: nil) resp = if server_id API::Application.get_guild_command(@token, profile.id, server_id, command_id) else API::Application.get_global_command(@token, profile.id, command_id) end ApplicationCommand.new(JSON.parse(resp), self, server_id) end
[ "def get_global_command(token, application_id, command_id)\n Discordrb::API.request(\n :applications_aid_commands_cid,\n nil,\n :get,\n \"#{Discordrb::API.api_base}/applications/#{application_id}/commands/#{command_id}\",\n Authorization: token\n )\n end", "def view_command(command_id)\n @client.get(\"/commands/#{command_id}\")\n end", "def get_custom_command_by_item_entry_id(item_entry_id)\n command = USER_CUSTOM_COMMANDS[item_entry_id: item_entry_id]\n return nil if command == nil\n\n # create custom command\n return CustomCommand.new(command)\n end", "def get_guild_command(token, application_id, guild_id, command_id)\n Discordrb::API.request(\n :applications_aid_guilds_gid_commands_cid,\n guild_id,\n :get,\n \"#{Discordrb::API.api_base}/applications/#{application_id}/guilds/#{guild_id}/commands/#{command_id}\",\n Authorization: token\n )\n end", "def get id\n apps.select do |app|\n app.id == id\n end.first\n end", "def get_command_id()\n @query['command_id'] || nil\n end", "def get_application_commands(server_id: nil)\n resp = if server_id\n API::Application.get_guild_commands(@token, profile.id, server_id)\n else\n API::Application.get_global_commands(@token, profile.id)\n end\n\n JSON.parse(resp).map do |command_data|\n ApplicationCommand.new(command_data, self, server_id)\n end\n end", "def command(name)\n return @commands[name]\n end", "def get_global_commands(token, application_id)\n Discordrb::API.request(\n :applications_aid_commands,\n nil,\n :get,\n \"#{Discordrb::API.api_base}/applications/#{application_id}/commands\",\n Authorization: token\n )\n end", "def get(id)\n response = Network.get(['Applications', id])\n Application.new(response)\n end", "def fetch_command(command)\n @commands[command.to_s]\n end", "def viewDeviceCommandDetails(deviceId, commandId)\n @client.get(\"/devices/#{deviceId}/commands/#{commandId}\")\n end", "def command(command_name)\n begin\n klassname = command_name.gsub('-', '_').camelize\n Bcdatabase::Commands.const_get \"#{klassname}\"\n rescue NameError\n nil\n end\n end", "def retrieve_command(command_to_run)\n if command_map.key?(command_to_run)\n command_map[command_to_run]\n else\n command = nil\n category_command_map.each do |category, commands|\n command = commands[command_to_run] if commands.key?(command_to_run)\n end\n # return the command, or nil if it wasn't found\n command\n end\n end", "def program(id)\n get(\"/catalog/titles/programs/#{id.to_s}\")\n end", "def command(name)\n @commands.find { |c| c.name_or_alias?(name) }\n end", "def find_command( name )\n commands.each { |cmd| return cmd if cmd.name == name }\n nil\n end", "def get_command( cmd_name )\n begin\n # 1. Try all normal commands\n Bgo::Application::Command.load_single(cmd_name)\n\n rescue Bgo::Application::CommandNotFoundError => e\n if ! @plugins_loaded\n # 2. Load plugins & retry (allows plugins to define commands)\n load_plugins\n get_command cmd_name\n\n else\n # Error: Command really not found!\n puts \"Command '#{cmd_name}' not found: #{e}. Try `#{$0} help`.\"\n nil\n end\n end\n end", "def get_command(type, command)\n commands[type] ? commands[type][command] : nil\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Throws a useful exception if there's currently no gateway connection.
def gateway_check raise "A gateway connection is necessary to call this method! You'll have to do it inside any event (e.g. `ready`) or after `bot.run :async`." unless connected? end
[ "def gateway_check\n return if connected?\n\n raise \"A gateway connection is necessary to call this method! You'll have to do it inside any event (e.g. `ready`) or after `bot.run :async`.\"\n end", "def verify_gateway\n cidr = NetAddr::CIDR.create(\"#{self.network}#{self.netmask}\")\n if not cidr.contains?(self.gateway)\n raise \"Gateway is not contained in the IP range\"\n end\n end", "def check_gateway_mode(gateway_mode)\n unless @@allowed_gateway_modes.include? gateway_mode\n raise ArgumentError, \"Unknown gateway mode given: '#{gateway_mode}'\"\n end\n end", "def check_environment(gateway)\n return if gateway.environment == Rails.env\n if gateway.environment.blank? && Rails.env != \"photos_production\"\n return\n end\n message = I18n.t(:gateway_config_unavailable) + \" - #{Rails.env}\"\n raise Spree::GatewayError.new(message)\n end", "def gateway?\n context.transport_manager.gateways.include?(self)\n end", "def lint_gateway_setup\n return if gateway_instance.instance_of? gateway\n\n complain <<-STRING\n #{gateway}.setup must return a gateway instance but\n returned #{gateway_instance.inspect}\n STRING\n end", "def gateway\n begin\n \"#{self.service_name}Gateway\".classify.gateway(self.config_file_name)\n rescue\n self.class.gateway(self.config_file_name)\n end\n end", "def gateway\n @gateway\n end", "def gateway_wrapper\n @gateway_host ||= if(@gateway_addr && @gateway_user)\n Net::SSH::Gateway.new(@gateway_addr, @gateway_user, {:forward_agent => true})\n else\n nil\n end\n end", "def gateway\n return @properties[:gateway] if @properties[:gateway]\n return \"localhost\"\n end", "def assert_connected\n raise ConnectionError, 'not connected' unless @connected\n end", "def checkConnection\n unless connected?\n raise DictError.new(), \"Not connected.\"\n end\n end", "def gateway?(other)\n other.kind_of?(Gateway)\n end", "def check_server\n raise Exception.new(\"Could not reach Apocalypse server please check the address and port and try again.\") unless server_reachable?\n end", "def gateway\n @gateway ||= PaymentGateway.instance.gateway()\n end", "def check_connection!\n if not @ssh\n raise Acme::Distributed::ServerError, \"Challenge server name=#{self.name} is not connected.\"\n end\n end", "def request_public_gateway(network_options, interface, env)\n subnet = IPAddr.new(network_options[:subnet])\n gateway = nil\n while !gateway\n gateway = env[:ui].ask(I18n.t(\n \"docker_provider.network_bridge_gateway_request\",\n interface: interface,\n default_gateway: network_options[:gateway]) + \" \",\n prefix: false\n ).strip\n if gateway.empty?\n gateway = network_options[:gateway]\n end\n begin\n gateway = IPAddr.new(gateway)\n if !subnet.include?(gateway)\n env[:ui].warn(I18n.t(\"docker_provider.network_bridge_gateway_outofbounds\",\n gateway: gateway,\n subnet: network_options[:subnet]) + \"\\n\", prefix: false)\n end\n rescue IPAddr::InvalidAddressError\n env[:ui].warn(I18n.t(\"docker_provider.network_bridge_gateway_invalid\",\n gateway: gateway) + \"\\n\", prefix: false)\n gateway = nil\n end\n end\n gateway.to_s\n end", "def gateway\n @config[:gateway]\n end", "def skip_if_connectivity_broken\n @skip_if_connectivity_broken\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Logs a warning if there are servers which are still unavailable. e.g. due to a Discord outage or because the servers are large and taking a while to load.
def unavailable_servers_check # Return unless there are servers that are unavailable. return unless @unavailable_servers&.positive? LOGGER.warn("#{@unavailable_servers} servers haven't been cached yet.") LOGGER.warn('Servers may be unavailable due to an outage, or your bot is on very large servers that are taking a while to load.') end
[ "def check_monitoring\n @servers.each do |server|\n transaction { server.settings }\n response = nil\n count = 0\n until response || count > 20 do\n begin\n response = transaction { server.monitoring }\n rescue\n response = nil\n count += 1\n sleep 10\n end\n end\n raise \"Fatal: Failed to verify that monitoring is operational\" unless response\n #TODO: pass in some list of plugin info to check multiple values. For now just\n # hardcoding the cpu check\n unless server.multicloud\n sleep 180 # This is to allow monitoring data to accumulate\n monitor = transaction { server.get_sketchy_data({'start' => -60,\n 'end' => -20,\n 'plugin_name' => \"cpu-0\",\n 'plugin_type' => \"cpu-idle\"}) }\n idle_values = monitor['data']['value']\n raise \"No cpu idle data\" unless idle_values.length > 0\n raise \"CPU idle time is < 0: #{idle_values}\" unless idle_values[0] > 0\n puts \"Monitoring is OK for #{server.nickname}\"\n end\n end\n end", "def check_monitoring\n @servers.each do |server|\n obj_behavior(server, :settings)\n response = nil\n count = 0\n until response || count > 20 do\n begin\n response = obj_behavior(server, :monitoring)\n rescue\n response = nil\n count += 1\n sleep 10\n end\n end\n raise \"Fatal: Failed to verify that monitoring is operational\" unless response\n#TODO: pass in some list of plugin info to check multiple values. For now just\n# hardcoding the cpu check\n unless server.multicloud\n sleep 180 # This is to allow monitoring data to accumulate\n monitor = obj_behavior(server, :get_sketchy_data, {'start' => -60,\n 'end' => -20,\n 'plugin_name' => \"cpu-0\",\n 'plugin_type' => \"cpu-idle\"})\n idle_values = monitor['data']['value']\n raise \"No cpu idle data\" unless idle_values.length > 0\n raise \"CPU idle time is < 0: #{idle_values}\" unless idle_values[0] > 0\n puts \"Monitoring is OK for #{server.nickname}\"\n end\n end\n end", "def check_expiry_empty\n debug 'Checking empty servers'\n\n synchronize(:ServerSharingExpiryChecks) do\n @servers.each do |server_id, server|\n if (server['state'] == 'using' || server['state'] == 'blocking') && server['request_time'] + 300 < Time::now().to_i\n\n begin\n sv = UrbanTerror::Server.new @servers[server_id]['ip'], @servers[server_id]['port'], @servers[server_id]['rcon']\n sv.update_status\n\n if sv.players.length == 0\n clean_request server_id\n reset_server server_id\n end\n rescue\n debug \"Can't get info from #{server_id}.... :<\"\n end\n end\n end\n end\n end", "def check_monitoring\n @servers.each do |server|\n server.settings\n response = nil\n count = 0\n until response || count > 20 do\n begin\n response = server.monitoring\n rescue\n response = nil\n count += 1\n sleep 10\n end\n end\n raise \"Fatal: Failed to verify that monitoring is operational\" unless response\n#TODO: pass in some list of plugin info to check multiple values. For now just\n# hardcoding the cpu check\n sleep 60 # This is to allow monitoring data to accumulate\n monitor=server.get_sketchy_data({'start'=>-60,'end'=>-20,'plugin_name'=>\"cpu-0\",'plugin_type'=>\"cpu-idle\"})\n idle_values = monitor['data']['value']\n raise \"No cpu idle data\" unless idle_values.length > 0\n raise \"No idle time\" unless idle_values[0] > 0\n puts \"Monitoring is OK for #{server.nickname}\"\n end\n end", "def handle_warnings(response)\n warnings = response.warnings\n\n if warnings and warnings.size > 0\n puts \"Warning(s) when performing request:\"\n warnings.each do |warning|\n puts \" - [#{warning.reason}] #{warning.message}\"\n end\n end\nend", "def check_server\n raise Exception.new(\"Could not reach Apocalypse server please check the address and port and try again.\") unless server_reachable?\n end", "def kick_out_excessive_traffic\n return true if is_cool?\n\n logger.warn(\"BLOCKED #{request.remote_ip}\")\n render(plain: :kick_out_message.t(email: MO.webmaster_email_address),\n status: :too_many_requests,\n layout: false)\n false\n end", "def remove_nonreporting_servers(keeptime = nil)\n list_nonreporting_servers.each do |server|\n next if keeptime && Time.parse(server[:last_reported_at]) >= Time.now - ChronicDuration.parse(keeptime)\n Notifier.msg(server[:name], 'Removing Stale, Non-Reporting Server')\n Client.delete_server(server[:id])\n end\n end", "def detect_failure\n time = Time.now\n server = server_structs.detect do |server|\n server.next_retry > time\n end\n inspect_server(server) if server\n end", "def global_warning\n # NOTE (!) if you set this value and don't see it change in 10 minutes, CHECK YOUR SLAVE LAG. It reads from slaves.\n warning = EolConfig.global_site_warning\n flash.now[:error] = warning if warning\n end", "def host_warnings(warnings)\n warnings = warnings.map do |entry|\n \"* #{entry}\"\n end.join(\"\\n\")\n\n unless warnings.empty?\n warnings = UI.red { UI.bold { \"\\n\\nWarnings:\\n#{warnings}\" } }\n end\n warnings\n end", "def gem_warning(server)\n if(!server.command_available?)\n puts \"WARNING: The #{server.server} gem does not appear to be installed\"\n end\n end", "def removeUselessServers()\n\t\t@deletedServers = Array.new()\n\n\t\t# servers that can't be accessed, push to '@deletedServers'\n\t\t@@serversInfo.each do |server|\n\t\t\tif(!File.directory?(server))\n\t\t\t\t@deletedServers.push(server)\n\t\t\tend\n\t\tend\n\n\t\t# delete servers\n\t\t@deletedServers.each do |server|\n\t\t\t@@serversInfo.delete(server)\n\t\t\t$fileGlobal.puts(\"[x] server not found! (removed)> #{server}\") if($logs)\n\t\t\tputs(\"[x] server not found! (removed)> #{server}\")\n\t\tend\n\n\t\t# if all servers were removed, exit()\n\t\tif(@@serversInfo.empty?)\n\t\t\tputs(\"\\n\\n\")\n\t\t\tputs(\"------------------------------------------------------------------------\")\n\t\t\tputs(\"[x] there are no more servers, please check carefully the path of the servers and try again\")\n\t\t\tputs(\"------------------------------------------------------------------------\")\n\t\t\tputs(\"\\n\\n\")\n\t\t\t\n\t\t\tif($logs)\n\t\t\t\t$fileGlobal.puts(\"\\n\\n\")\n\t\t\t\t$fileGlobal.puts(\"------------------------------------------------------------------------\")\n\t\t\t\t$fileGlobal.puts(\"[x] there are no more servers, please check carefully the path of the servers and try again\")\n\t\t\t\t$fileGlobal.puts(\"------------------------------------------------------------------------\")\n\t\t\t\t$fileGlobal.puts(\"\\n\\n\")\n\t\t\tend\n\t\t\texit()\n\t\tend\n\n\t\t# check if user want to continue without this servers\n\t\tanswer = \"\"\n\t\tif(!@deletedServers.empty?)\n\t\t\tbegin\n\t\t\t\tputs(\"do you want to (c)ontinue or (e)xit?\")\n\t\t\t\tanswer = gets().delete(\"\\n\")\n\t\t\tend while(answer != \"e\" && answer != \"c\")\n\n\t\t\tif(answer == \"e\")\n\t\t\t\texit()\n\t\t\tend\n\t\tend\n\tend", "def service_unavailable\n\n end", "def check_for_unresponsive\n local_running.each do |h|\n # see McoHost.is_unresponsive? - it checks number of failed updates and time it has\n # been missing.\n if h.is_unresponsive?\n h.mark_failed \"host stopped responding.\"\n # Give up to 10 seconds after start before taking notice of the\n # not_found state, ot that the agent process is not running.\n elsif h.run_time > 0 and Time.now.to_i - h.run_time > 10\n if h.state == :not_found\n h.mark_failed \"run #{@runid} not found on agent.\" \n # the agent lets us know if the PID which started a run is actually running.\n # if the run is incomplete and the monitor is not running, it probably failed.\n elsif !h.is_active?\n h.mark_failed \"agent process responsible for monitoring the puppet run stopped.\"\n end\n end\n end\n end", "def server_errors\n conditions = [ :restart_required, :redis_down, :sidekiq_down,\n :sidekiq_mailer_down ]\n errors = conditions.select { |c| SettingsHelper.get(c) }\n errors.empty? and return nil\n errors.include? :restart_required and errors = [ :restart_required ]\n render partial: 'shared/server_errors', locals: { messages: errors }\n end", "def server_connection_failed\n @server_side = nil\n if @connected\n LOGGER.error \"Connection with #{@remote.join(':')} was terminated prematurely.\"\n close_connection\n BeanstalkProxy.connect_error_callback.call(@remote.join(':'))\n elsif @tries < 10\n @tries += 1\n LOGGER.warn \"Retrying connection with #{@remote.join(':')} (##{@tries})\"\n EM.add_timer(0.1) { connect_to_server }\n else\n LOGGER.error \"Connect #{@remote.join(':')} failed after ten attempts.\"\n close_connection\n BeanstalkProxy.connect_error_callback.call(@remote.join(':'))\n end\n end", "def image_server_status\n http = HTTPClient.new\n begin\n response = http.get(Kumquat::Application.kumquat_config[:loris_url])\n if response.body.include?('Internet Imaging Protocol Server')\n render text: 'online'\n else\n render text: 'offline', status: 503\n end\n rescue\n render text: 'offline', status: 503\n end\n end", "def response_unavailable?\n !!(content_for_scanner =~ /Server too busy, try again later/)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal handler for VOICE_STATE_UPDATE
def update_voice_state(data) @session_id = data['session_id'] server_id = data['guild_id'].to_i server = server(server_id) return unless server user_id = data['user_id'].to_i old_voice_state = server.voice_states[user_id] old_channel_id = old_voice_state.voice_channel&.id if old_voice_state server.update_voice_state(data) existing_voice = @voices[server_id] if user_id == @profile.id && existing_voice new_channel_id = data['channel_id'] if new_channel_id new_channel = channel(new_channel_id) existing_voice.channel = new_channel else voice_destroy(server_id) end end old_channel_id end
[ "def state_changed\n\t\tend", "def state_changed(state)\n\t\tdebug state\n\t\t@last_state = @mpd.status['state']\n\t\tnow_playing if state == 'play' and @song\n\tend", "def update_voice_state(data)\n user_id = data['user_id'].to_i\n\n if data['channel_id']\n unless @voice_states[user_id]\n # Create a new voice state for the user\n @voice_states[user_id] = VoiceState.new(user_id)\n end\n\n # Update the existing voice state (or the one we just created)\n channel = @channels_by_id[data['channel_id'].to_i]\n @voice_states[user_id].update(\n channel,\n data['mute'],\n data['deaf'],\n data['self_mute'],\n data['self_deaf']\n )\n else\n # The user is not in a voice channel anymore, so delete its voice state\n @voice_states.delete(user_id)\n end\n end", "def call_status_change\n @call.update(status: params[:CallStatus], duration: params[:CallDuration])\n end", "def update_appeal_state_on_status_change\n update_appeal_state_when_ihp_cancelled\n update_appeal_state_when_ihp_completed\n update_appeal_state_when_privacy_act_cancelled\n update_appeal_state_when_privacy_act_complete\n update_appeal_state_when_appeal_cancelled\n end", "def state_changed\n\t\t\tsend_each_player(:state_changed)\n\t\t\tsleep self.player_delay\n\t\t\t#print_players\n\t\tend", "def update\n\n #Show level select if player has already cleared any levels\n if @state == :starting then\n if @profile_level > 0 then\n max_level = @profile_level < @end_level ? @profile_level + 1 : @end_level\n push_game_state(Level_Choice.new(:max_level => max_level))\n else\n @current_level, @state = 1, :idle\n end\n end\n\n #Show next level start screen\n if @state == :idle then\n push_game_state(Level_Intro.new(:level_number => @current_level))\n end\n\n #Start next level\n if @state == :screen_shown then\n push_game_state(PlayLevel.new(:file => sprintf(\"levels/Level_%03d.yml\", @current_level),\n :return_state => LevelShell,\n :callback => method(:next_level)))\n end\n\n #Arcade levels done --- show finish screen\n if @state == :finished then\n switch_game_state(ArcadeFinished)\n end\n\n end", "def send_voice_state_update(server_id, channel_id, self_mute, self_deaf)\n data = {\n guild_id: server_id,\n channel_id: channel_id,\n self_mute: self_mute,\n self_deaf: self_deaf\n }\n\n send_packet(Opcodes::VOICE_STATE, data)\n end", "def handle_api_call_update(json)\n Broker.log(\"[InvocaAPI] got call update, #{json}\")\n call = Broker::CassandraConn.get_call_info(json[\"call_uuid\"])\n\n # TODO: ???\n if json.has_key?(\"call_state\")\n call_state = json[\"call_state\"]\n else\n call_state = json[\"state\"]\n end\n\n call[\"id\"] = json[\"call_uuid\"]\n send(\"handle_api_call_#{call_state}\", call)\n end", "def update\n player_state = PlayerState.find(params[:id])\n if player_state.update(player_state_params)\n render json: player_state, status: 200, location: [:api, player_state]\n else\n failed_to_update(player_state, \"player_state\")\n end\n end", "def process_update_state\n @participant.state = params[:new_state]\n @participant.high_intensity = true if params[:new_state] == \"moved_to_high_intensity_arm\"\n @participant.save!\n flash[:notice] = \"Participant was moved to #{params[:new_state].titleize}.\"\n redirect_to correct_workflow_participant_path(@participant)\n end", "def skype_status_update(event)\n username = get_skype_username event.headers['Buddy']\n \n if COMPONENTS.skype_utils['buddy_status_store'] == 'database'\n skype_user = SkypeUser.find_by_username username\n if skype_user\n skype_user.status = event.headers['BuddyStatus']\n skype_user.save\n else\n if COMPONENTS.skype_utils['store_unknown_buddies']\n skype_user = SkypeUser.new\n skype_user.name = username\n skype_user.username = username\n skype_user.status = event.headers['BuddyStatus']\n skype_user.save\n end\n end\n end\n \n if COMPONENTS.skype_utils['buddy_status_store'] == 'memory' || COMPONENTS.skype_utils['buddy_status_store'] == 'both'\n ::Active_skype_status.update_status(username, event.headers['BuddyStatus'])\n end\n end", "def handle_update\n monitoring_change if monitoring_changed?\n isolation_change if isolation_changed?\n case_status_change if case_status_changed?\n symptom_onset_change if symptom_onset_changed?\n continuous_exposure_change if continuous_exposure_changed? || isolation_changed?\n end", "def update_states\n # if battler exists\n if battler != nil\n # check status effect timers\n check_states\n # change status effect timers\n count_states\n # apply additional status effects\n additional_states\n end\n end", "def update_shipment_state\n self.shipment_state =\n case line_items.count\n when 0\n nil\n when line_items.shipped.count\n \"shipped\"\n when line_items.pending.count\n \"pending\"\n when line_items.ready.count\n \"ready\"\n else\n \"partial\"\n end\n\n if old_shipment_state = self.changed_attributes[\"shipment_state\"]\n #if shipment_state changed\n self.state_events.create({\n :previous_state => old_shipment_state,\n :next_state => self.shipment_state,\n :name => \"shipment\" ,\n :user_id => (User.respond_to?(:current) && User.current && User.current.id) || self.user_id\n })\n self.has_shipped if shipment_state == \"shipped\"\n end\n\n end", "def update\n url = repository_tracking_list_url(:id => @tracking_list,\n :repository_id => @repository)\n if params[:event]\n event = params[:event]\n original_state = @tracking_list.current_state\n\n options = { :tracking_list => @tracking_list }\n options[:urlified_name] = @site_basket.urlified_name if @current_basket.repositories.count < 1\n\n case event\n when 'allocate'\n # allocating means we need to choose shelf location before proceeding\n url = new_trackable_item_shelf_location_url(options)\n @successful = true\n when 'loan'\n # we need to collect information for a new or existing on_loan_organization\n url = new_on_loan_organization_url(options)\n @successful = true\n when 'clear_list'\n @tracking_list.clear_list!\n # we transition back to new in this case, so no change in state\n @successful = true\n else\n # otherwise, send the event as a method\n # to the tracking list\n @tracking_list.send(event + '!')\n @successful = @tracking_list.reload.current_state != original_state\n @state_change_failed = !@successful\n url = repository_tracking_list_url(:id => @tracking_list,\n :repository_id => @repository,\n :download_modal => true)\n end\n else\n # to handle large amount of matches that span paginated pages of results\n # we use ids in session to create tracked_items\n matching_class = session[:matching_class]\n matching_results_ids = session[:matching_results_ids]\n values = matching_results_ids.inject([]) do |value, matching_id|\n value << TrackedItem.new(:trackable_item_type => matching_class,\n :trackable_item_id => matching_id,\n :tracking_list_id => @tracking_list.id)\n value\n end\n\n @successful = TrackedItem.import(values)\n end\n\n if @successful || @state_change_failed\n clear_session_variables_for_list_building\n\n flash[:notice] = t('tracking_lists.update.state_change_failed', :event_transition => params[:event].humanize) if @state_change_failed\n\n redirect_to url\n else\n render :action => 'edit'\n end\n end", "def update_state\n puts \"******* update_state *******\"\n puts \"** params.inspect: #{params.inspect}\"\n puts \"** params[:event]: #{params[:event]}\"\n # events: submit process ship deliver confirm cancel\n @msg = \"result state: \"\n\n if params[:event] == \"submit\"\n if @@ORDER_STATE == nil\n @state = 1\n update_order(@msg)\n else\n @msg = \"previous status: #{@@ORDER_STATE}\"\n flash[:notice] = @msg\n end\n elsif params[:event] == \"process\"\n if @@ORDER_STATE == \"ordered\"\n @state = 2\n update_order(@msg)\n else\n @msg = \"previous status: #{@@ORDER_STATE}\"\n flash[:notice] = @msg\n end\n elsif params[:event] == \"ship\"\n if @@ORDER_STATE == \"processing\"\n @state = 3\n update_order(@msg)\n else\n @msg = \"previous status: #{@@ORDER_STATE}\"\n flash[:notice] = @msg\n end\n elsif params[:event] == \"deliver\"\n if @@ORDER_STATE == \"shipping\"\n @state = 4\n update_order(@msg)\n else\n @msg = \"previous status: #{@@ORDER_STATE}\"\n flash[:notice] = @msg\n end\n elsif params[:event] == \"confirm\"\n if @@ORDER_STATE == \"delivered\"\n @state = 5\n update_order(@msg)\n else\n @msg = \"previous status: #{@@ORDER_STATE}\"\n flash[:notice] = @msg\n end\n elsif params[:event] == \"cancel\"\n @state = 6\n update_order(@msg)\n else\n @state = 0\n update_order(@msg)\n end\n # logs the current state\n # print_state\n puts \"** @state: #{@state}\"\n end", "def change_state\n ticket = Ticket.find_by(id: params[:id])\n name = params[:state]\n if current_user.allowed_ticket_state.has_key?(name)\n ticket.send(\"#{name}_state!\")\n ticket.update_attributes(agent_id: current_user.id) if current_user.is_agent?\n ticket.reload\n render json: ticket.as_json\n else\n render json: {\"#{name}\": 'state not allowed'}, status: :unprocessable_entity\n end\n end", "def update\n\t\t\t# Ideally #update would be a dynamically defined singleton\n\t\t\t# In that singleton method, the appropriate blocks would be\n\t\t\t# called if they had been defined on initialization\n\t\t\tstate = next_state\n\t\t\ttransition_to state\n\t\t\t@active = state\n\t\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal handler for VOICE_SERVER_UPDATE
def update_voice_server(data) server_id = data['guild_id'].to_i channel = @should_connect_to_voice[server_id] debug("Voice server update received! chan: #{channel.inspect}") return unless channel @should_connect_to_voice.delete(server_id) debug('Updating voice server!') token = data['token'] endpoint = data['endpoint'] unless endpoint debug('VOICE_SERVER_UPDATE sent with nil endpoint! Ignoring') return end debug('Got data, now creating the bot.') @voices[server_id] = Discordrb::Voice::VoiceBot.new(channel, self, token, @session_id, endpoint) end
[ "def cmdh_update_resp2(msg_details)\n @log.debug \"UPDATERESPTWO handler\"\n info = YAML::load(msg_details)\n case info[:type] \n when :platf_update\n # need a platform update\n @log.debug \"Platform update is needed\"\n str = \"ATTENZIONE: questo client necessita di un aggiornamento manuale per giocare in internet.\\n\"\n str += \" Vai su cuperativa.invido.it per maggiorni informazioni.\\n\"\n str += \" Senza una versione recente, il gioco in rete non funziona.\\n\"\n str += \" *********** L'ultima versione aggiornata di cuperativa si scarica da: **************\\n\"\n str += \" #{info[:link_platf]}\\n\"\n str += \" *********************************************************\\n\"\n @cup_gui.log_sometext(str) \n #close connection\n @socket_srv.close if @socket_srv\n return\n when :nothing\n # no update, client is OK\n @log.debug \"Client already updated\"\n strtext = u\"Il programma U+00e8 giU+00e0 all'ultima versione.\\n\"\n @cup_gui.log_sometext(strtext)\n return\n when :appli_update\n # need to update the application\n server_name = info[:server].gsub('http://', \"\")\n package_name = info[:file ]\n updater = ClientUpdaterCtrl.new\n updater.set_package_src(server_name, package_name)\n updater.gui_progress = @cup_gui\n updater.net_controller = self\n updater.info_package = info\n begin \n #updater.install_package\n @model_net_data.event_cupe_raised(:ev_startupdate)\n updater.install_package_question(@model_net_data)\n rescue\n @cup_gui.log_sometext(\"ERRORE: Update non riuscito\\n\")\n @cup_gui.log_sometext(\"Riprova l'update, oppure installa la versione completa aggiornata di cuperativa (www.invido.it).\\n\")\n @socket_srv.close if @socket_srv\n end\n else\n @log.error 'Update type not recognized'\n end#case\n end", "def update_voice_server(data)\n debug(\"Voice server update received! should connect: #{@should_connect_to_voice}\")\n return unless @should_connect_to_voice\n @should_connect_to_voice = false\n debug('Updating voice server!')\n\n token = data['token']\n endpoint = data['endpoint']\n channel = @voice_channel\n\n debug('Got data, now creating the bot.')\n @voice = Discordrb::Voice::VoiceBot.new(channel, self, token, @session_id, endpoint, @should_encrypt_voice)\n end", "def update update\n case update.type.to_sym\n when :update_snakes\n snakes = update.msg \n if @client\n begin\n stonedSnakes = snakes.map { |s| {\"name\" => s.get_name, \"tail\" => s.get_tail.to_json} }\n stoneColdKilledSnakes = JSON.dump(stonedSnakes)\n msg = Message.new(\"update_snakes\", stoneColdKilledSnakes)\n @client.puts(JSON.dump(msg))\n rescue Exception => myException\n @log.info \"Exception rescued: #{myException}\"\n @client = nil\n @isBot = true\n end \n end\n when :update_colors\n if @client\n @client.puts(JSON.dump(update))\n end\n when :identity\n if @client\n# @client.puts(JSON.dump(update));\n end\n end\n end", "def update\n msg = 'CLC servers do not support updates'\n raise NotImplementedError.new(msg)\n end", "def update\n @voicemail_server = VoicemailServer.find(params[:id])\n\n respond_to do |format|\n if @voicemail_server.update_attributes(params[:voicemail_server])\n format.html { redirect_to(@voicemail_server, :notice => t(:voicemail_server_updated)) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @voicemail_server.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @bot_server.update(bot_server_params)\n format.html { redirect_to bot_servers_path, notice: 'Bot server was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @bot_server.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @voicemail_server = VoicemailServer.find(params[:id])\n\n respond_to do |format|\n if @voicemail_server.update_attributes(params[:voicemail_server])\n format.html { redirect_to(@voicemail_server, :notice => 'Voicemail server was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @voicemail_server.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @serverpv.update(serverpv_params)\n format.html { redirect_to @serverpv, notice: 'Serverpv was successfully updated.' }\n format.json { render :show, status: :ok, location: @serverpv }\n else\n format.html { render :edit }\n format.json { render json: @serverpv.errors, status: :unprocessable_entity }\n end\n end\n end", "def server_update(attributes = {}, &block)\n register_event(ServerUpdateEvent, attributes, block)\n end", "def update\n @server = compute.get_server(params[:id]).update(:name=>params[:name])\n respond_to do |format|\n format.html { redirect_to servers_path, :notice => 'Server was successfully updated.' }\n format.json { head :ok }\n end\n end", "def _trigger_update_callback; end", "def update\n msg = 'DigitalOcean servers do not support updates'\n raise NotImplementedError.new(msg)\n end", "def update_remote\n # TODO\n end", "def update\n respond_to do |format|\n if @app_server.update(app_server_params)\n format.html { redirect_to @app_server, notice: 'App server was successfully updated.' }\n format.json { render :show, status: :ok, location: @app_server }\n else\n format.html { render :edit }\n format.json { render json: @app_server.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @slider_serv.update(slider_serv_params)\n format.html { redirect_to @slider_serv, notice: 'Slider serv was successfully updated.' }\n format.json { render :show, status: :ok, location: @slider_serv }\n else\n format.html { render :edit }\n format.json { render json: @slider_serv.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @platform_server.set(platform_server_params)\n format.html { redirect_to @platform_server, notice: 'Platform server was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @platform_server.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @chase_server.set(chase_server_params)\n format.html { redirect_to @chase_server, notice: 'Chase server was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @chase_server.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_attributes\n server_update_data.each_pair do |key, value|\n instance_variable_set(\"@#{key}\", value)\n end\n end", "def update\n respond_to do |format|\n if @monitor_server.update(monitor_server_params)\n format.html { redirect_to @monitor_server, notice: 'Server was successfully updated.' }\n format.json { render :show, status: :ok, location: @monitor_server }\n else\n format.html { render :edit }\n format.json { render json: @monitor_server.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal handler for CHANNEL_RECIPIENT_ADD
def add_recipient(data) channel_id = data['channel_id'].to_i channel = self.channel(channel_id) recipient_user = ensure_user(data['user']) recipient = Recipient.new(recipient_user, channel, self) channel.add_recipient(recipient) end
[ "def channel_recipient_add(attributes = {}, &block)\n register_event(ChannelRecipientAddEvent, attributes, block)\n end", "def add_recipient(p0) end", "def add_channel channel\n join(channel)\n self\n end", "def radioChannelAdd _obj, _args\n \"_obj radioChannelAdd _args;\" \n end", "def add_message_reaction(data); end", "def add_member(user)\n user_id = user.is_a? User ? user.id : user\n Mattermost.post(\"/channels/#{self.id}/add\", :body => {:user_id => user_id})\n end", "def fix_user\n # Need to make sure the tag is linked to self\n if (tag = self.canonical_expression) && (tag.typenum != 11)\n ref = Referent.express tag, tag.typenum\n ref.channels << self\n ref.save\n end\n if self.user.email == \"channels@recipepower.com\"\n self.user.email = \"channel#{self.id.to_s}@recipepower.com\"\n self.user.save\n end\n end", "def group_dm_add_recipient(channel_id, user_id, access_token:, nick: :undef)\n route = Route.new(:PUT, '/channels/%{channel_id}/recipients/%{user_id}',\n channel_id: channel_id, user_id: user_id)\n json = filter_undef({ access_token: access_token, nick: nick })\n request(route, json: json)\n end", "def addchmember\n @channel = MChannel.new\n @channel.channel_id = session[:clickchannel_id]\n @channel.channel_name = session[:clickchannel_name]\n @channel.user_id = params[:linkuser]\n @channel.workspace_id = session[:workspace_id]\n @channel.status = session[:clickchannel_status]\n @channel.chadmin = false\n @channel.save\n redirect_to memberedit_path\n end", "def add_origin msg\n return if msg.connection != @connection\n\n # XXX - this whole function feels awful\n\n msg.origin =~ /(.+)!(.+)@(.+)/\n\n add_user $1, $2, $3\n end", "def add_recipient(name)\n puts \"Recipient name:\\t\\t#{name}\"\n if Recipient.recipient_exist(name)\n puts \"Recipient already exists\"\n recipient_id = Recipient.get_recipient_id(name)\n else\n puts \"Adding new recipient...\"\n recipient_id = Recipient.add_recipient(name)\n end\n puts \"#{name} has ID:\\t\\t#{recipient_id}\"\nend", "def add_recipient(recepient = {})\n if recepient.is_a?(String)\n # convert string value to correct hash\n recepient = {phone: recepient}\n end\n recepient[:phone] = format_phone(recepient[:phone])\n @recepients.push(recepient)\n # time-send format: YYYY-MM-DD HH:MM\n # validity_period format: YYYY-MM-DD HH:MM\n end", "def add_record(channel_name, identifier)\n raise NotImplementedError\n end", "def add_recipient (args)\n last_log_recipient_list.add_recipient(args)\n add_list! if last_log_recipient_list.recipients_count == mail_log.class::MAX_RECIPIENTS_COUNT_PER_LIST\n end", "def add_user_to_mailchimp \n Rails.logger.info(\"Mailchimp subscribe request being made\")\n unless self.email.include?('@example.com')\n mailchimp = Hominid::API.new(AppConstants.mailchimp_key) \n list_id = mailchimp.find_list_id_by_name AppConstants.mailchimp_list \n info = { }\n result = mailchimp.list_subscribe(list_id, self.email, info, 'html', false, true, false, true)\n Rails.logger.info(\"Mailchimp subscribed for the email id #{self.email} to #{AppConstants.mailchimp_list}\")\n end\n end", "def joinChannel(idUser,idChannel)\n \n end", "def add_channel(channel)\n self.channels[channel.cid] = channel\n end", "def subscribe_to_channel; end", "def someone_did_invite(stem, inviter, invitee, channel)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal handler for GUILD_MEMBER_UPDATE
def update_guild_member(data) server_id = data['guild_id'].to_i server = self.server(server_id) member = server.member(data['user']['id'].to_i) member.update_roles(data['roles']) member.update_nick(data['nick']) member.update_boosting_since(data['premium_since']) member.update_communication_disabled_until(data['communication_disabled_until']) end
[ "def update_guild_member(data)\n server_id = data['guild_id'].to_i\n server = self.server(server_id)\n\n member = server.member(data['user']['id'].to_i)\n member.update_roles(data['roles'])\n member.update_nick(data['nick'])\n end", "def member_update(attributes = {}, &block)\n register_event(ServerMemberUpdateEvent, attributes, block)\n end", "def update_member_data(member, member_data)\n update_member_data_in(@leaderboard_name, member, member_data)\n end", "def handle_member(event)\n @users.process_member_event self, event\n user = @users[event['state_key']]\n membership = event['content']['membership'].to_sym\n\n # Don't process invite state change if the user is already a\n # member in the room.\n return if membership == :invite && member?(user)\n\n if membership == :join\n @members.add user\n else\n @members.delete user\n end\n\n broadcast(membership, @room, user)\n end", "def update\n service = Fl::Framework::Service::Actor::GroupMember.new(current_user, params, self)\n @group_member = service.update()\n respond_to do |format|\n format.json do\n if @group_member && service.success?\n render :json => { :group_member => hash_one_object(@group_member, service.to_hash_params) }\n else\n error_response(generate_error_info(service, @group_member))\n end\n end\n end\n end", "def member\n if @bubble.owner == current_user\n if @bubble.owner.id != params[:member_id].to_i\n if [\"guest\", \"moderator\"].include? params[:new_role]\n bm = @bubble.bubble_members.find_by(user_id: params[:member_id])\n if bm.nil?\n render 'api/v1/shared/failure', locals: {errors: [{user: [\"is not a member of this bubble\"]}] }, status: :unprocessable_entity\n else\n bm.user_role = params[:new_role].to_sym\n if bm.save\n render 'api/v1/shared/empty_response', status: :ok\n else\n render 'api/v1/shared/failure', locals: {errors: bm.errors}, status: :unprocessable_entity\n end\n end\n else\n render 'api/v1/shared/failure', locals: {errors: [{new_role: [\"is unknown\"]}] }, status: :bad_request\n end\n else\n render 'api/v1/shared/failure', locals: {errors: [{you: [\"can't change your role 'owner' for now\"]}] }, status: :unprocessable_entity\n end\n else\n render 'api/v1/shared/failure', locals: {errors: [{you: [\"have not permissions\"]}] }, status: :unauthorized\n end\n end", "def handle_existing_chatroom_member\n validate_ownership_and_membership_status; return if performed?\n @chatroom_member.update(has_left: false)\n save_chatroom_member\n end", "def update_member(params)\n connection.call_method('lists.update_member', params.merge(id_params))\n end", "def update\n member.with_lock do\n unless membership_service.call(api, @space, member, admin_member)\n raise ApiError, \"Can't designate user #{member.user.full_name} as #{role}\"\n end\n end\n\n render json: { member: member.user.dxuser, role: role }, adapter: :json\n end", "def update\n expose Member.update(@oauth_token, params[:membername], params)\n end", "def remove_member\n if update.dig('message', 'left_chat_member')\n left = update['message']['left_chat_member']\n\n return if left['is_bot']\n\n member = @chat.members.find_by_telegram_user left['id']\n member ||= @chat.members.find_by_username left['username'].downcase\n\n unless member.nil?\n @chat.members.delete member\n respond_with :message, text: \"💔 #{member.display_name(true)} was removed from the chat group.\", parse_mode: :html\n end\n end\n end", "def edit_members\n end", "def update_nickname(member)\n nickname = get_nickname(member)\n if member.display_name != nickname\n member.set_nick nickname\n end\n end", "def update\n respond_to do |format|\n if member.update(member_params)\n format.html { redirect_to admin_member_path(member), notice: 'Member was successfully updated.' }\n format.json { render :show, status: :ok, location: member }\n else\n format.html { render :edit }\n format.json { render json: member.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @current_user.id != @member.user_id\n return render json: { message: \"You are not permitted to perform this operation.\" }, status: :forbidden\n end\n if @member.update(member_params)\n render json: @member, status: :ok\n else\n render json: @member.errors, status: :unprocessable_entity\n end\n end", "def update_user(email, group, action, opts={})\n page = @scraper.get(@BASE_URL + group + @@MANAGE)\n\t\tmember_set = page.search('//table[@class=\"memlist\"]//td')\n\t\tmembers = []\n\t\tmember_set.each do |m| \n\t\t\tmembers.push(member_set[member_set.index(m) + 1]) if m.to_s.include?('class=\"cb\"')\n\t\tend \n\t\t\n\t\tmember_form = page.form('memberlist')\n\t\temail.downcase!\n\t\tindex = nil \n\t\tmembers.each_index do |m| \n\t\t\tindex = m if members[m].to_s.downcase.include?(email)\n\t\tend \n\t\n\t\tmember_form.checkboxes_with(:name => 'subcheckbox')[index].check unless index.nil?\n\t\t\n\t\tif (action.downcase == \"set_member\")\n\t\t\tcase opts[:value]\n\t\t\t\twhen \"regular\"\n\t\t\t\t\tmember_form.field_with(:name => 'membership_type').options[1].select\n\t\t\t\twhen \"manager\"\n\t\t\t\t\tmember_form.field_with(:name => 'membership_type').options[2].select\n\t\t\t\twhen \"owner\"\n\t\t\t\t\tmember_form.field_with(:name => 'membership_type').options[3].select\n\t\t\t\twhen \"unsubscribe\"\n\t\t\t\t\tmember_form.field_with(:name => 'membership_type').options[5].select\n\t\t\t\twhen \"ban\"\n\t\t\t\t\tmember_form.field_with(:name => 'membership_type').options[6].select\n\t\t\tend\n\t\t\t@scraper.submit(member_form, member_form.button_with(:name => 'Action.SetMembershipType'))\n\t\telsif (action.downcase == \"set_email\")\n\t\t\tcase opts[:value]\n\t\t\t\twhen \"none\"\n\t\t\t\t\tmember_form.field_with(:name => 'delivery').options[1].select\n\t\t\t\twhen \"email\"\n\t\t\t\t\tmember_form.field_with(:name => 'delivery').options[2].select\n\t\t\t\twhen \"summary\"\n\t\t\t\t\tmember_form.field_with(:name => 'delivery').options[3].select\n\t\t\t\twhen \"one\"\n\t\t\t\t\tmember_form.field_with(:name => 'delivery').options[4].select\n\t\t\tend\n\t\t\t@scraper.submit(member_form, member_form.button_with(:name => 'Action.SetDeliveryType'))\n\t\tend\t\n\t\t\n\tend", "def update\n respond_to do |format|\n if @free_member.update(admin_free_member_params)\n format.html { redirect_to admin_free_members_url,\n notice: I18n.t('flash.free_member.successfully_updated') }\n else\n format.html { render :edit }\n end\n end\n end", "def process_member_event(room, event)\n return if Events.processed? event\n id = event['state_key'] || event['sender']\n get_user(id).process_member_event room, event\n end", "def update\n require_user()\n respond_to do |format|\n if @db_member.update(db_member_params)\n format.html { redirect_to @db_member, notice: 'Db member was successfully updated.' }\n format.json { render :show, status: :ok, location: @db_member }\n else\n format.html { render :edit }\n format.json { render json: @db_member.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal handler for GUILD_MEMBER_DELETE
def delete_guild_member(data) server_id = data['guild_id'].to_i server = self.server(server_id) return unless server user_id = data['user']['id'].to_i server.delete_member(user_id) rescue Discordrb::Errors::NoPermission Discordrb::LOGGER.warn("delete_guild_member attempted to access a server for which the bot doesn't have permission! Not sure what happened here, ignoring") end
[ "def destroy\n service = Fl::Framework::Service::Actor::GroupMember.new(current_user, params, self)\n @group_member = service.get_and_check(Fl::Framework::Access::Permission::Delete)\n if @group_member && service.success?\n title = @group_member.title\n fingerprint = @group_member.fingerprint\n if @group_member.destroy\n respond_to do |format|\n format.json do\n status_response({\n status: Fl::Framework::Service::OK,\n message: tx('fl.framework.actor_group_member.controller.destroy.deleted',\n fingerprint: fingerprint, title: title)\n })\n end\n end\n end\n else\n respond_to do |format|\n format.json do\n error_response(generate_error_info(service, @group_member))\n end\n end\n end\n end", "def remove_member\n if update.dig('message', 'left_chat_member')\n left = update['message']['left_chat_member']\n\n return if left['is_bot']\n\n member = @chat.members.find_by_telegram_user left['id']\n member ||= @chat.members.find_by_username left['username'].downcase\n\n unless member.nil?\n @chat.members.delete member\n respond_with :message, text: \"💔 #{member.display_name(true)} was removed from the chat group.\", parse_mode: :html\n end\n end\n end", "def delete_guild_member(data)\n server_id = data['guild_id'].to_i\n server = self.server(server_id)\n\n user_id = data['user']['id'].to_i\n server.delete_member(user_id)\n rescue Discordrb::Errors::NoPermission\n Discordrb::LOGGER.warn(\"delete_guild_member attempted to access a server for which the bot doesn't have permission! Not sure what happened here, ignoring\")\n end", "def delete_member\n connection.call_method('lists.delete_member', id_params)\n end", "def remove(connection)\n super\n\n return unless members.key?(connection)\n\n trigger(\"member_removed\",\n channel: name, user_id: members[connection][:user_id])\n\n emit(\"pusher_internal:member_removed\", members.delete(connection))\n end", "def destroy\n\t\t@guild.members.find(params[:id]).update(guild: nil)\n\t\trespond_to do |format|\n\t\t\tback_page = guild_members_path\n\t\t\tback_page = URI(request.referer).path if params[:back]\n\t\t\tformat.html { redirect_to back_page, notice: 'Member was successfully destroyed.' }\n\t\t\tformat.json { head :no_content }\n\t\tend\n\tend", "def destroy\n\t\t@room.members.destroy(params[:id])\n\t\trespond_to do |format|\n\t\t\tback_page = room_members_url\n\t\t\tback_page = URI(request.referer).path if params[:back]\n\t\t\tback_page = params[:redirect] if params[:redirect]\n\t\t\tformat.html { redirect_to back_page, notice: 'Member was successfully destroyed.' }\n\t\t\tformat.json { head :no_content }\n\t\tend\n\tend", "def destroy\n require_user()\n @db_member.destroy\n respond_to do |format|\n format.html { redirect_to db_members_url, notice: 'Db member was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n member.destroy\n respond_to do |format|\n format.html { redirect_to admin_members_url, notice: 'Member was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @member.destroy\n respond_to do |format|\n format.html { redirect_to admin_members_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @member = Member.with_permissions_to(:destroy).find(params[:id])\n @member.destroy\n\n respond_to do |format|\n format.html { redirect_to(members_url) }\n format.xml { head :ok }\n end\n end", "def delete_member(url)\n delete url\n assert last_response.ok?, \"deleting extant member\"\n check_error_response(last_response)\n end", "def delete_member_from(group_id, member_id)\n make_request(:delete, group + \"/#{group_id}/member/#{member_id}\", headers: {'content-type' => 'application/atom+xml'})\n end", "def member_leave(attributes = {}, &block)\n register_event(ServerMemberDeleteEvent, attributes, block)\n end", "def delete_membership(connection, id)\n info \"Removing existing etcd membership info with id #{id}\"\n connection.delete(:path => \"/v2/members/#{id}\")\n end", "def delete_child(child); end", "def destroy\n @dc_member = DcMember.find(params[:id])\n @dc_member.destroy\n\n respond_to do |format|\n format.html { redirect_to dc_members_url }\n format.json { head :no_content }\n end\n end", "def remove_member(member)\n remove_member_from(@leaderboard_name, member)\n end", "def remove_member\n @group = Group.find(params[:id])\n \n # FIXME: isn't there an easier way to delete memberships?\n @group.memberships.find(:all,\n :conditions => {\n :member_id => params[:member][:id], \n :member_type => params[:member][:type]\n }\n ).each{|m| m.destroy}\n \n respond_to do |format|\n if @group.save\n format.html { render :partial => 'listing', :locals => {:group => @group} }\n format.xml { render :xml => @group.to_xml(:methods => :members), :status => :ok, :location => @group }\n format.json { render :json => @group.to_json(:methods => :members), :status => :ok, :location => @group }\n else\n format.xml { render :xml => @group.errors, :status => :unprocessable_entity }\n format.json { render :json => @group.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal handler for GUILD_EMOJIS_UPDATE
def update_guild_emoji(data) server_id = data['guild_id'].to_i server = @servers[server_id] server.update_emoji_data(data) end
[ "def update_emoji_data(new_data)\n @emoji = {}\n process_emoji(new_data['emojis'])\n end", "def server_emoji_update(attributes = {}, &block)\n register_event(ServerEmojiUpdateEvent, attributes, block)\n end", "def update\n respond_to do |format|\n if @emoji.update(emoji_params)\n format.html { redirect_to @emoji, notice: 'Emoji was successfully updated.' }\n format.json { render :show, status: :ok, location: @emoji }\n else\n format.html { render :edit }\n format.json { render json: @emoji.errors, status: :unprocessable_entity }\n end\n end\n end", "def cmdh_update_resp2(msg_details)\n @log.debug \"UPDATERESPTWO handler\"\n info = YAML::load(msg_details)\n case info[:type] \n when :platf_update\n # need a platform update\n @log.debug \"Platform update is needed\"\n str = \"ATTENZIONE: questo client necessita di un aggiornamento manuale per giocare in internet.\\n\"\n str += \" Vai su cuperativa.invido.it per maggiorni informazioni.\\n\"\n str += \" Senza una versione recente, il gioco in rete non funziona.\\n\"\n str += \" *********** L'ultima versione aggiornata di cuperativa si scarica da: **************\\n\"\n str += \" #{info[:link_platf]}\\n\"\n str += \" *********************************************************\\n\"\n @cup_gui.log_sometext(str) \n #close connection\n @socket_srv.close if @socket_srv\n return\n when :nothing\n # no update, client is OK\n @log.debug \"Client already updated\"\n strtext = u\"Il programma U+00e8 giU+00e0 all'ultima versione.\\n\"\n @cup_gui.log_sometext(strtext)\n return\n when :appli_update\n # need to update the application\n server_name = info[:server].gsub('http://', \"\")\n package_name = info[:file ]\n updater = ClientUpdaterCtrl.new\n updater.set_package_src(server_name, package_name)\n updater.gui_progress = @cup_gui\n updater.net_controller = self\n updater.info_package = info\n begin \n #updater.install_package\n @model_net_data.event_cupe_raised(:ev_startupdate)\n updater.install_package_question(@model_net_data)\n rescue\n @cup_gui.log_sometext(\"ERRORE: Update non riuscito\\n\")\n @cup_gui.log_sometext(\"Riprova l'update, oppure installa la versione completa aggiornata di cuperativa (www.invido.it).\\n\")\n @socket_srv.close if @socket_srv\n end\n else\n @log.error 'Update type not recognized'\n end#case\n end", "def update\n respond_to do |format|\n kai2_ji7_params[:無齊記號].slice! '!'\n if @kai2_ji7.update(kai2_ji7_params)\n format.html { redirect_to edit_kai2_ji7_path(@kai2_ji7), notice: 'Kai2 ji7 was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @kai2_ji7.errors, status: :unprocessable_entity }\n end\n end\n end", "def on_modifying_entry(state, event, *event_args)\n super\n\n # Verify validity of the submission. # TODO: simulation - remove\n if simulating\n # From UploadController#update:\n # @item, failed = upload_edit(**data)\n __debug_sim('CODE') do\n args = \"data=#{submission.data.inspect}\"\n opt = 'index: false'\n \"@item, failed = upload_edit(#{args}, #{opt})\"\n end\n bad = nil\n if (db_fail = submission.db_failure)\n self.failures << 'DB create failed'\n elsif (bad = !(submission.metadata_valid = !submission.invalid_entry))\n self.failures << 'bad metadata'\n else\n self.succeeded << submission.id\n end\n if db_fail\n __debug_sim('[edit_db_failure: true]')\n __debug_sim('The database entry could not be updated.')\n elsif bad\n __debug_sim('[edit_invalid_entry: true]')\n __debug_sim('The entry is invalid/incomplete.')\n __debug_sim('(NOTE: PROBABLE FAILURE OF CLIENT-SIDE FORM VALIDATION)')\n else\n __debug_sim('[edit_invalid_entry: false]')\n __debug_sim('[edit_db_failure: false]')\n end\n end\n\n # Verify validity of the submission.\n unless simulating\n wf_validate_submission(*event_args)\n end\n\n valid = ready?\n\n # TODO: simulation - remove\n if valid\n __debug_sim('The database entry was updated.')\n else\n __debug_sim('System generates a form error message to be displayed.')\n end\n\n # Automatically transition to the next state based on submission status.\n if valid\n advance! # NOTE: => :modified\n else\n reject! # NOTE: => :editing\n end\n self\n end", "def update_message(data); end", "def exp_changed\n @edit = session[:edit]\n @edit[@expkey].update_from_expression_editor(params)\n # See if only a text value changed\n if params[:chosen_value] || params[:chosen_regkey] || params[:chosen_regval] ||\n params[:chosen_cvalue || params[:chosen_suffix]] || params[:alias]\n render :update do |page|\n page << javascript_prologue\n end\n elsif @refresh_div.to_s == 'flash_msg_div'\n javascript_flash(:flash_div_id => 'exp_editor_flash')\n else\n render :update do |page|\n page << javascript_prologue\n page.replace(\"exp_editor_flash\", :partial => \"layouts/flash_msg\", :locals => {:flash_div_id => 'exp_editor_flash'})\n page << \"miqScrollTop();\" if @flash_array.present?\n page.replace(\"exp_atom_editor_div\", :partial => \"layouts/exp_atom/editor\")\n\n page << ENABLE_CALENDAR if @edit[@expkey].calendar_needed?\n @edit[@expkey].render_values_to(page)\n page << \"miqSparkle(false);\" # Need to turn off sparkle in case original ajax element gets replaced\n end\n end\n end", "def pbEncounterMapVersionEditor(enc_data)\r\n map_infos = pbLoadMapInfos\r\n commands = []\r\n enc_types = []\r\n list = pbListWindow([])\r\n help_window = Window_UnformattedTextPokemon.newWithSize(_INTL(\"Edit map's encounters\"),\r\n Graphics.width / 2, 0, Graphics.width / 2, 96)\r\n help_window.z = 99999\r\n ret = 0\r\n need_refresh = true\r\n loop do\r\n if need_refresh\r\n commands.clear\r\n enc_types.clear\r\n map_name = (map_infos[enc_data.map]) ? map_infos[enc_data.map].name : nil\r\n if map_name\r\n commands.push(_INTL(\"Map ID={1} ({2})\", enc_data.map, map_name))\r\n else\r\n commands.push(_INTL(\"Map ID={1}\", enc_data.map))\r\n end\r\n commands.push(_INTL(\"Version={1}\", enc_data.version))\r\n enc_data.types.each do |enc_type, slots|\r\n next if !enc_type || !slots || slots.length == 0\r\n commands.push(_INTL(\"{1} (x{2})\", enc_type.to_s, slots.length))\r\n enc_types.push(enc_type)\r\n end\r\n commands.push(_INTL(\"[Add new encounter type]\"))\r\n need_refresh = false\r\n end\r\n ret = pbCommands2(list, commands, -1, ret)\r\n if ret == 0 # Edit map ID\r\n old_map_ID = enc_data.map\r\n new_map_ID = pbListScreen(_INTL(\"Choose a new map\"), MapLister.new(old_map_ID))\r\n if new_map_ID > 0 && new_map_ID != old_map_ID\r\n if GameData::Encounter.exists?(new_map_ID, enc_data.version)\r\n pbMessage(_INTL(\"A set of encounters for map {1} version {2} already exists.\", new_map_ID, enc_data.version))\r\n else\r\n GameData::Encounter::DATA.delete(enc_data.id)\r\n enc_data.map = new_map_ID\r\n enc_data.id = sprintf(\"%s_%d\", enc_data.map, enc_data.version).to_sym\r\n GameData::Encounter::DATA[enc_data.id] = enc_data\r\n need_refresh = true\r\n end\r\n end\r\n elsif ret == 1 # Edit version number\r\n old_version = enc_data.version\r\n new_version = LimitProperty2.new(999).set(_INTL(\"version number\"), old_version)\r\n if new_version && new_version != old_version\r\n if GameData::Encounter.exists?(enc_data.map, new_version)\r\n pbMessage(_INTL(\"A set of encounters for map {1} version {2} already exists.\", enc_data.map, new_version))\r\n else\r\n GameData::Encounter::DATA.delete(enc_data.id)\r\n enc_data.version = new_version\r\n enc_data.id = sprintf(\"%s_%d\", enc_data.map, enc_data.version).to_sym\r\n GameData::Encounter::DATA[enc_data.id] = enc_data\r\n need_refresh = true\r\n end\r\n end\r\n elsif ret == commands.length - 1 # Add new encounter type\r\n new_type_commands = []\r\n new_types = []\r\n GameData::EncounterType.each do |enc|\r\n next if enc_data.types[enc.id]\r\n new_type_commands.push(enc.real_name)\r\n new_types.push(enc.id)\r\n end\r\n if new_type_commands.length > 0\r\n chosen_type_cmd = pbShowCommands(nil, new_type_commands, -1)\r\n if chosen_type_cmd >= 0\r\n new_type = new_types[chosen_type_cmd]\r\n enc_data.step_chances[new_type] = GameData::EncounterType.get(new_type).trigger_chance\r\n enc_data.types[new_type] = []\r\n pbEncounterTypeEditor(enc_data, new_type)\r\n enc_types.push(new_type)\r\n ret = enc_types.sort.index(new_type) + 2\r\n need_refresh = true\r\n end\r\n else\r\n pbMessage(_INTL(\"There are no unused encounter types to add.\"))\r\n end\r\n elsif ret > 0 # Edit an encounter type (its step chance and slots)\r\n this_type = enc_types[ret - 2]\r\n case pbShowCommands(nil, [_INTL(\"Edit\"), _INTL(\"Copy\"), _INTL(\"Delete\"), _INTL(\"Cancel\")], 4)\r\n when 0 # Edit\r\n pbEncounterTypeEditor(enc_data, this_type)\r\n need_refresh = true\r\n when 1 # Copy\r\n new_type_commands = []\r\n new_types = []\r\n GameData::EncounterType.each do |enc|\r\n next if enc_data.types[enc.id]\r\n new_type_commands.push(enc.real_name)\r\n new_types.push(enc.id)\r\n end\r\n if new_type_commands.length > 0\r\n chosen_type_cmd = pbMessage(_INTL(\"Choose an encounter type to copy to.\"),\r\n new_type_commands, -1)\r\n if chosen_type_cmd >= 0\r\n new_type = new_types[chosen_type_cmd]\r\n enc_data.step_chances[new_type] = enc_data.step_chances[this_type]\r\n enc_data.types[new_type] = []\r\n enc_data.types[this_type].each { |slot| enc_data.types[new_type].push(slot.clone) }\r\n enc_types.push(new_type)\r\n ret = enc_types.sort.index(new_type) + 2\r\n need_refresh = true\r\n end\r\n else\r\n pbMessage(_INTL(\"There are no unused encounter types to copy to.\"))\r\n end\r\n when 2 # Delete\r\n if pbConfirmMessage(_INTL(\"Delete the encounter type {1}?\", GameData::EncounterType.get(this_type).real_name))\r\n enc_data.step_chances.delete(this_type)\r\n enc_data.types.delete(this_type)\r\n need_refresh = true\r\n end\r\n end\r\n else\r\n break\r\n end\r\n end\r\n list.dispose\r\n help_window.dispose\r\n Input.update\r\nend", "def _trigger_update_callback; end", "def on_modifying_entry(state, event, *event_args)\n super\n\n # Verify validity of the submission. # TODO: simulation - remove\n if simulating\n # From UploadController#bulk_update:\n # succeeded, failed = bulk_upload_edit(data, base_url: url, user: @user)\n __debug_sim('CODE') do\n args = \"data=#{submission.data.inspect}\"\n opt = 'base_url: url, user: @user'\n \"succeeded, failed = bulk_upload_edit(#{args}, #{opt})\"\n end\n bad = nil\n if (db_fail = submission.db_failure)\n self.failures << 'DB create failed'\n elsif (bad = !(submission.metadata_valid = !submission.invalid_entry))\n self.failures << 'bad metadata'\n else\n self.succeeded << submission.id\n end\n if db_fail\n __debug_sim('[edit_db_failure: true]')\n __debug_sim('The database entry could not be updated.')\n elsif bad\n __debug_sim('[edit_invalid_entry: true]')\n __debug_sim('The entry is invalid/incomplete.')\n __debug_sim('(NOTE: PROBABLE FAILURE OF CLIENT-SIDE FORM VALIDATION)')\n else\n __debug_sim('[edit_invalid_entry: false]')\n __debug_sim('[edit_db_failure: false]')\n end\n end\n\n # Verify validity of the submission.\n unless simulating\n wf_validate_submission(*event_args)\n wf_set_records_state\n end\n\n valid = ready?\n\n # TODO: simulation - remove\n if valid\n __debug_sim('The database entry was updated.')\n else\n __debug_sim('System generates a form error message to be displayed.')\n end\n\n # Automatically transition to the next state based on submission status.\n if valid\n advance! # NOTE: => :modified\n else\n reject! # NOTE: => :failed\n end\n self\n end", "def update\n respond_to do |format|\n if @odeme.update(odeme_params)\n @bakiye=Bakiye.find_by_teslim_yeri(@odeme.teslim_yeri)\n @bakiye.toplam_borc-=@odeme.odeme_miktari\n @bakiye.save\n format.html { redirect_to odemes_path, notice: 'Odeme was successfully updated.' }\n format.json { render :show, status: :ok, location: @odeme }\n else\n format.html { render :edit }\n format.json { render json: @odeme.errors, status: :unprocessable_entity }\n end\n end\n end", "def after_update_action; end", "def altered_world_event; end", "def update\n respond_to do |format|\n if @bo_nhiem.update(bo_nhiem_params)\n format.html { redirect_to @bo_nhiem, notice: 'Bo nhiem was successfully updated.' }\n format.json { render :show, status: :ok, location: @bo_nhiem }\n else\n format.html { render :edit }\n format.json { render json: @bo_nhiem.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_help\n enc = $game_party.bestiary_known_data[:ene].keys.size\n text = \"Encountered: #{enc}/#{SES::Bestiary.get_enemy_list.size}\"\n @help_window.set_text(text)\n end", "def update( msg )\n typed_message('update', msg, (colorize ? :yellow : nil))\n end", "def update\n respond_to do |format|\n if @crew_big_sonu_comitee.update(crew_big_sonu_comitee_params)\n format.html { redirect_to @crew_big_sonu_comitee, notice: 'Big sonu comitee was successfully updated.' }\n format.json { render :show, status: :ok, location: @crew_big_sonu_comitee }\n else\n format.html { render :edit }\n format.json { render json: @crew_big_sonu_comitee.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n \n #明細マスターのパラメータ補正 \n #add180310\n set_params_replenishment\n \n\trespond_to do |format|\n #見積一覧IDをセット\n\t set_quotation_and_delivery_header\n\t \n #品目マスターへの追加・更新\n\t create_or_update_material\n\t\n\t #新規か更新かの判定処理追加 add171114\n\t status = nil\n\t \n\t action_flag = params[:working_specific_middle_item][:action_flag]\n\t if action_flag == \"new\"\n\t\t #add171122\n\t\t search_records =\n WorkingSpecificMiddleItem.exists?(:working_middle_item_name => params[:working_specific_middle_item][:working_middle_item_name])\n\t\t \n\t\t if search_records.blank?\n\t\t\n\t\t #attributesの\"id\"のみ抹消する(しないとエラー)\n\t\t if params[:working_specific_middle_item][:working_specific_small_items_attributes].present?\n\t\t params[:working_specific_middle_item][:working_specific_small_items_attributes].flatten.each do |item|\n item.delete(\"id\")\n end\n\t\t end\n\t\t #\n\t\t @working_specific_middle_item = WorkingSpecificMiddleItem.new(working_specific_middle_item_params)\n\t status = @working_specific_middle_item.save\n\t else\n\t\t #同一の品名ならば、更新とみなす(新規ボタンを押しても更新として扱い)\n\t\t status = @working_specific_middle_item.update(working_specific_middle_item_params)\n\t\t end\n\t elsif action_flag == \"edit\"\n \n status = @working_specific_middle_item.update(working_specific_middle_item_params)\n\t end\n\t #\n\n\t #if @working_specific_middle_item.update(working_specific_middle_item_params)\n\t if status == true #upa171114\n \n if params[:working_specific_middle_item][:master_insert_flag] == \"true\"\n \n\t\t if action_flag == \"new\" #登録ボタンを押した場合のみ\n \t\t\t#共通(明細)マスターへの新規追加\n create_common_master\n\t\t end\n end\n \n\t\t#add171108\n\t #手入力用IDの場合は、単位マスタへも登録する。\n\t set_working_unit\n\t\t\n\t\tif params[:move_flag] == \"1\"\n\t\t#内訳\n format.html {redirect_to quotation_detail_large_classifications_path(:quotation_header_id => params[:quotation_header_id], \n :quotation_header_name => params[:quotation_header_name], :move_flag => params[:move_flag])}\n\t\telsif params[:move_flag] == \"2\"\n\t\t#明細\n\t\t format.html {redirect_to quotation_detail_middle_classifications_path(:quotation_header_id => params[:quotation_header_id], \n :quotation_header_name => params[:quotation_header_name], :quotation_detail_large_classification_id => params[:quotation_detail_large_classification_id],\n :working_large_item_name => params[:working_large_item_name], :working_large_specification => params[:working_large_specification],\n\t\t\t :move_flag => params[:move_flag])}\n\t\telsif params[:move_flag] == \"3\"\n\t\t#納品内訳\n format.html {redirect_to delivery_slip_detail_large_classifications_path(:delivery_slip_header_id => params[:delivery_slip_header_id], \n :delivery_slip_header_name => params[:delivery_slip_header_name], :move_flag => params[:move_flag])}\n\t\telsif params[:move_flag] == \"4\"\n\t\t#納品明細\n\t\t format.html {redirect_to delivery_slip_detail_middle_classifications_path(:delivery_slip_header_id => params[:delivery_slip_header_id], \n :delivery_slip_header_name => params[:delivery_slip_header_name], :delivery_slip_detail_large_classification_id => params[:delivery_slip_detail_large_classification_id],\n :working_large_item_name => params[:working_large_item_name], :working_large_specification => params[:working_large_specification],\n\t\t\t :move_flag => params[:move_flag])}\n\t\telse\n\t\t#単独フォームからの場合(未使用)\n format.html { redirect_to @working_specific_middle_item, notice: 'Working specific middle item was successfully updated.' }\n format.json { render :show, status: :ok, location: @working_specific_middle_item }\n \tend\n\t\t\n else\n format.html { render :edit }\n format.json { render json: @working_specific_middle_item.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal handler for MESSAGE_CREATE
def create_message(data); end
[ "def create_message(schema_id = nil)\n\t\tend", "def create_message(current_user, msg_for, open_msg_tag = nil, entry = nil, order = nil)\n self.user_company_id = current_user.company.id\n self.user_type = current_user.roles.first.name\n self.entry_id = entry.id unless entry.blank?\n self.order_id = order.id unless order.blank?\n if msg_for == 'admin'\n self.receiver_id = 1\n self.receiver_company_id = 1\n self.open_tag = open_msg_tag unless open_msg_tag.blank?\n elsif msg_for == 'buyer'\n self.receiver_id = entry.user_id\n self.receiver_company_id = entry.company_id\n self.open_tag = open_msg_tag unless open_msg_tag.blank?\n elsif msg_for == 'seller'\n if order\n self.receiver_id = order.seller_id\n self.receiver_company_id = order.seller.company.id\n else\n self.receiver_id = receiver\n self.receiver_company_id = receiver_company\n end\n self.open_tag = open_msg_tag unless open_msg_tag.blank?\n elsif msg_for == 'public'\n self.open_tag = true\n end\n end", "def create( msg )\n typed_message('create', msg, (colorize ? :green : nil))\n end", "def publish_create_message\n publish_message :create\n end", "def new_message\n end", "def create_message!(*args)\n sent_messages.create!(*args)\n end", "def creating( msg )\n @log.info \"creating #{msg}\"\n end", "def creating( msg )\n @log.info \"creating #{msg}\"\n end", "def new_message!(data)\n message = Message.new(data)\n message.container = self\n @messages[message.text] = message\n return message\n end", "def atomic_create\n @room.messages_requested.increment do |messages_requested|\n @room.send_message_to_requested_channel(messages_requested)\n if messages_requested <= @room.max_messages\n @room.messages_posted.increment\n @room.send_message_to_posted_channel(@room.messages_posted.value)\n if @message.save\n @room.send_message_to_chat_channel(render_message_to_string)\n render nothing: true\n else\n logger.info @message.errors.inspect\n end\n else\n render nothing: true\n end\n end\n end", "def create\n @message = Message.new(params[:message].except(:reference_to))\n if params[:message][:reference_to]\n ref = Message.find_by_guid( params[:message][:reference_to] )\n if !ref\n render :status => :bad_request and return\n end\n @message.reference_to = ref.id\n end\n @message.channel = @channel\n @message.poster = @user\n if !@message.save\n render_json :status => :bad_request,\n :messages => @message.errors.full_messages and return\n end\n render_json :status => :created, :entry => @message and return\n end", "def message_create(params={})\n MESSAGE.new(request(:post, \"sms/create/\", params.merge({})))\n end", "def get_message_factory\n\t\tend", "def CreateMessageById(msg_id)\n _invoke(3, [msg_id], [VT_UI4])\n end", "def flash_created_message\n flash_message_builder(:create, flash_status_type, 'created')\n end", "def handle_create(data_hash)\n case data_hash['what']\n when 'post' then create_a_post(data_hash['data'])\n when 'category' then create_a_category(data_hash['data'])\n else send_line \"What?\"\n end\n end", "def create_message_table\n execute_sql_statement(\"CREATE TABLE messages (\\n\" \\\n \" id CHAR PRIMARY KEY, \\n\" \\\n \" sender CHAR NOT NULL, -- Hostname of sender \\n\" \\\n \" action CHAR NOT NULL, -- The action to perform \\n\" \\\n \" payload CHAR, -- Optional payload \\n\" \\\n \" ack INTEGER DEFAULT 0, -- ack sent \\n\" \\\n \" date_time CHAR NOT NULL, -- Time sent \\n\" \\\n \" direction CHAR DEFAULT 'in', -- In or out bound msg \\n\" \\\n \" processed INTEGER DEFAULT 0 \\n\" \\\n \");\".strip)\n end", "def create\n transaction_message_params[:public_transaction_id] = 'R' + SecureRandom.hex\n @transaction_message = TransactionMessage.new(transaction_message_params)\n\n respond_to do |format|\n if @transaction_message.save\n format.html { redirect_to @transaction_message, notice: 'Transaction message was successfully created.' }\n format.json { render :show, status: :created, location: @transaction_message }\n else\n format.html { render :new }\n format.json { render json: @transaction_message.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_message_item\n return [] unless helpers.can?(RS::AuthorisationHelper::CREATE_MESSAGE)\n\n [{ name: t('.new_message'), link: new_dashboard_message_path,\n current?: current_page?(new_dashboard_message_path) }]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal handler for TYPING_START
def start_typing(data); end
[ "def typing\n @omegle.post '/typing', \"id=#{@id}\"\n end", "def begin_typing(&block)\n with_keyboard_focus do\n application.keyboard.when_element(:visible?) do\n yield application.keyboard if block_given?\n end\n end\n end", "def typing(reducer = nil, &block)\n on(:typing, &block)\n end", "def typing_on\n payload = {\n recipient: sender,\n sender_action: 'typing_on'\n }\n\n Facebook::Messenger::Bot.deliver(payload, access_token: access_token)\n end", "def stopped_typing\n @omegle.post '/stoppedTyping', \"id=#{@id}\"\n end", "def type_focus\n @type.setFocus()\n end", "def pre_input_hook; end", "def send_typing_abort(&callback)\n if @type == 'encr_chat'\n logger.warn(\"Currently telegram-cli has a bug with send_typing, then prevent this for safety\")\n return\n end\n @client.send_typing_abort(targetize, &callback)\n end", "def handle_input\n end", "def prompt_for_speakable\n puts \"Enter text to be spoken:>> \"\n user_input = $stdin.gets.chomp\n FreeTTS.speak(user_input)\nend", "def accept_entered_text\n \n end", "def set_text_input(input); end", "def input_type_text\n INPUT_TYPE[input_type]\n end", "def reply\n input.focus\n end", "def handle_key_up(_key) end", "def trigger_typing_indicator(channel_id)\n request(\n :channels_cid_typing, channel_id,\n :post,\n \"channels/#{channel_id}/typing\"\n )\n end", "def new_text_input\n end", "def on_keypress &b\n on :keypress, &b\n end", "def start_font_face\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal handler for MESSAGE_UPDATE
def update_message(data); end
[ "def update_message args = {}\n msg = args[:msg]\n perc_finished = args[:perc_finished]\n\n self.update_attribute :message, msg if msg\n self.update_attribute :perc_finished, perc_finished if perc_finished\n end", "def update( msg )\n typed_message('update', msg, (colorize ? :yellow : nil))\n end", "def update_message(args = {})\n msg = args[:msg]\n perc_finished = args[:perc_finished]\n\n self.update_attribute :message, msg if msg\n self.update_attribute :perc_finished, perc_finished if perc_finished\n end", "def updating( msg )\n @log.info \"updating #{msg}\"\n end", "def update\n\tif user_type == 'super_admin'\n\t\t@old_message = OldMessage.find(params[:id])\n\t\trespond_to do |format|\n\t\t if @old_message.update_attributes(params[:old_message])\n\t\t\tformat.html { redirect_to old_messages_path, :notice => 'Old message was successfully updated.' }\n\t\t\tformat.json { head :no_content }\n\t\t else\n\t\t\tformat.html { render :action => \"edit\" }\n\t\t\tformat.json { render :json => @old_message.errors, :status => :unprocessable_entity }\n\t\t end\n\t\tend\n\telse\n\t\tredirect_to '/404'\n\tend\n end", "def manage_update(params)\n message = Message.find(params[:id])\n if params[:commit] == \"Send\"\n send(message)\n else\n body = params[:message][:body] || \"\"\n message.update_attributes!(body: body, sent: false)\n end\n end", "def update\n message = Message.find_by(params[:id])\n if message.nil?\n render_error(\"message with id #{params[:id]} does not exist\", :not_found)\n elsif message.created_at < Time.now.utc - MAX_EDIT_PERIOD\n render_error(\"cannot update message more than #{MAX_EDIT_PERIOD} seconds old\", :forbidden)\n else\n render json: message.update(message_params)\n end\n end", "def update \n set_page_title \"Private Message\"\n \n compose_message\n \n # All threaded messages share the same original ID, so we'll just call the first record\n @private_message.original_message_id = original_message_id\n \n # Validate against SPAMMY behavior\n check_flood_limit @users.uniq unless @users.nil?\n \n \n # For brevity and convinience, the error checking and the recipient assignment are addressed together, sequentially, in the following line\n if @private_message.errors.count == 0 and @private_message.save and (@users.uniq.each {|username| @private_message.recipients.create(:user_id => User.find_by_username(username).id) }) \n if ConfigurationSetting.get_setting_to_bool(\"EmailPrivateMessageNotices\")\n spawn do\n @private_message.recipient_users.each do |u|\n NotificationsMailer.deliver_private_message(@private_message,u)\n end\n end\n end\n\n flash[:notice] = \"Reply sent\"\n redirect_to private_messages_path\n else\n @original_message = @private_messages.first\n render :action => session[:action_name]\n end \n end", "def update\n respond_to do |format|\n if @internal_message.update(internal_message_params)\n format.html { redirect_to @internal_message, notice: 'Internal message was successfully updated.' }\n format.json { render :show, status: :ok, location: @internal_message }\n else\n format.html { render :edit }\n format.json { render json: @internal_message.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n @message.update!(message_params)\n format.json { head :no_content }\n end\n end", "def update_message(params, user_id)\n\n self.name = AutomatedMessage.get_message_name(params[:kind])\n self.kind = params[:kind]\n self.subject = params[:subject]\n self.message = params[:message]\n self.days = params[:days]\n self.countries = params[:countries]\n self.last_edited_by = user_id\n self.send_copy_to_agent = params[:send_copy_to_agent]\n\n self\n end", "def publish_update_message\n publish_message :update\n end", "def update\n @message_field = MessageField.find(params[:id])\n\n respond_to do |format|\n if @message_field.update_attributes(params[:message_field])\n format.html { redirect_to @message_field, notice: 'Message field was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @message_field.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @new_message.update(new_message_params)\n format.html { redirect_to @new_message, notice: 'New message was successfully updated.' }\n format.json { render :show, status: :ok, location: @new_message }\n else\n format.html { render :edit }\n format.json { render json: @new_message.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n user = User.find(params[:id])\n #get all the not fetched messages for the current user\n @messages = Message.find :all, :conditions => [\"sended_at > ?\", user.last_update]\n #update the current user last update\n user.last_update = Time.now.to_f\n user.save\n #if there's messages then renderice else none\n if @messages.length > 0\n render \"messages.html.erb\", :layout => false\n else\n render :nothing => true\n end\n end", "def update\n respond_to do |format|\n if @custom_message.update(custom_message_params)\n format.html { redirect_to custom_messages_path, notice: 'Custom message was successfully updated.' }\n format.json { render :index, status: :ok, location: @custom_message }\n else\n format.html { render :edit }\n format.json { render json: @custom_message.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @mod_message = ModMessage.find(params[:id])\n\n respond_to do |format|\n if @mod_message.update_attributes(params[:mod_message])\n format.html { redirect_to @mod_message, notice: 'Mod message was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @mod_message.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @internal_message = InternalMessage.find(params[:id])\n\n respond_to do |format|\n if @internal_message.update_attributes(params[:internal_message])\n format.html { redirect_to(@internal_message, :notice => 'Internal message was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @internal_message.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @admin_message = Message.find(params[:id])\n\n respond_to do |format|\n if @admin_message.update_attributes(params[:message])\n format.html { redirect_to(admin_message_path(@admin_message), :notice => 'Message was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @admin_message.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal handler for MESSAGE_DELETE
def delete_message(data); end
[ "def delete_msg()\n MsgUtil.delete_msg(params[:ch])\n end", "def chmessagedelete\n TChannelMessage.where(\"chmsg_id=?\", params[:messagedelete]).delete_all\n TMention.where(\"mention_message=?\", params[:mentionmsg]).delete_all\n redirect_back(fallback_location: chmessage_path)\n end", "def delete_message_callback(ref)\n @messagecbs.delete(ref)\n end", "def delete\n msg = @user.messages.find(params[:id])\n if msg.nil?\n render json_status_response(404, \"Message not found\")\n return\n end\n\n msg.destroy\n render json_status_response(200, \"Message deleted successfully\")\n end", "def destroy\n @contact_message.destroy\n respond_to do |format|\n format.html { redirect_to(admin_contact_messages_url) }\n format.xml { head :ok }\n end\n website.add_log(user: current_user, action: \"Deleted contact message: #{@contact_message.id}\")\n end", "def destroy\n @admin_message.destroy \n respond_to do |format|\n format.html { redirect_to admin_messages_url, notice: \"#{ t 'activerecord.successful.messages.message_deleted' }\" }\n format.json { head :no_content }\n end\n end", "def destroy\n \t\n @message = Message.find(params[:id])\n @message.delete\n\n respond_to do |format|\n format.html { redirect_to(messages_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @message.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n redirect_to messages_url, notice: \"You cannot delete this message.\"\n end", "def delete\n @service.delete_message(self)\n end", "def destroy\n @message.destroy\n respond_to do |format|\n format.html { redirect_to profile_messages_path(@profile), notice: 'Deleted!' }\n format.json { head :no_content }\n end\n end", "def destroy\n @custom_message = CustomMessage.find(params[:id])\n @custom_message.destroy\n\n respond_to do |format|\n format.html { redirect_to custom_messages_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @message = Admin::Message.find(params[:id])\n @message.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_messages_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n message = Message.find_by(id: params[:id])\n message.destroy\n head :no_content\n end", "def delete_message(display_id, message_id)\n delete \"commandcenter/displays/#{display_id}/messages/#{message_id}\"\n end", "def destroy\n\tif user_type == 'super_admin'\n\t\t@old_message = OldMessage.find(params[:id])\n\t\t@old_message.destroy\n\n\t\trespond_to do |format|\n\t\t format.html { redirect_to old_messages_url }\n\t\t format.json { head :no_content }\n\t\tend\n\telse\n\t\tredirect_to '/404'\n\tend\n end", "def delete_message(site = 'live')\n Rails.logger.debug { \"[Redis] Sending message to delete a #{site} item. ID: #{id} Title: #{title}\" }\n url_path_to_delete = if previous_changes['url_path'] && site == 'preview'\n previous_changes['url_path'][0]\n else\n url_path\n end\n { action: 'delete', site: site, path_to_delete: url_path_to_delete }.to_json\n end", "def destroy\n @internal_message.destroy\n respond_to do |format|\n format.html { redirect_to internal_messages_url, notice: 'Internal message was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @message = Message.find(params[:id])\n @message.destroy\n \n respond_to do |format|\n flash[:notice] = \"Message moved to trash\"\n format.html { redirect_to user_mailbox_messages_path(@user, :mailbox_id => :inbox) }\n format.xml { head :ok }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal handler for MESSAGE_REACTION_ADD
def add_message_reaction(data); end
[ "def add(reaction)\n if reaction[:action] and reaction[:test] and reaction[:reaction] #validate\n reaction[:test] = RProc.new(reaction[:test])\n reaction[:reaction] = RProc.new(reaction[:reaction])\n\n if reaction[:action].is_a? Enumerable\n actions = reaction[:action]\n else\n actions = [reaction[:action]]\n end\n\n actions.each do |action|\n if @reactions[action].nil?\n @reactions[action] = [reaction]\n else\n @reactions[action] << reaction\n end\n end\n log \"Added #{reaction.inspect}\"\n else\n log \"Not accepting reaction: #{reaction.inspect}\" , Logger::Ultimate\n end\n end", "def handle_add_reply( m, params )\n # lame auth check\n # TODO: need to get a look into new auth system\n\n name = params[:name].downcase\n reply = params[:reply].to_s\n\n # check whether good is in database\n# status( name, @stock )\n# if @inreg == false\n# m.reply( \"#{name} does not exist.\" ); return\n# end\n\n # Put data into database, should be understandable ^^\n reply = Reply.new( @replyversion, reply )\n @reply[name] = reply\n\n # save dataset in case the bot crashes an got no chance to do so\n save\n\n m.reply( \"done\" )\n end", "def remove_message_reaction(data); end", "def new_message\n end", "def add_recipient(p0) end", "def add_message( msg )\n @messages.unshift( msg )\n \n if @messages.length > MAX_MESSAGES\n @messages.pop\n end\n end", "def msg_add(c)\n\t@msg_buf << c\n end", "def add_message(name, message)\n\t\tend", "def add_to_inbox__do_add\r\n @inbox = params[:inbox] ? Inbox.active.find(params[:inbox]) : @for_inbox\r\n if @inbox && @inbox.accepts?(@content) && !@content.inboxes.include?(@inbox) && !@inbox.archived?\r\n @inbox_item = InboxItem.new(:inbox_id => @inbox.id, :content_id => @content.id,\r\n :allow_take_to_showcase => @inbox.require_allowing_content_adoption? ? true : params[:allow_take_to_showcase],\r\n :user_id => current_actor.id, :original_content_id => @content.original_content_id)\r\n if @inbox_item.save\r\n Activity.send_message(@inbox_item, current_actor, :submitted_to_inbox)\r\n Activity.send_message(@inbox_item, current_actor, :inbox_submission_received)\r\n else\r\n respond_to do |wants|\r\n wants.html { flash[:warning] = \"Your content has been added to your account, but not to '{{name}}' inbox. Reason: {{reason}}\" / [@inbox.title, @inbox_item.errors.full_messages.join(';')]}\r\n wants.js {}\r\n end\r\n end\r\n end\r\n end", "def <<(msg)\n @changes << msg\n nil\n end", "def create\n message_reaction = MessageReaction.new({content: params[:reaction], message_id: params[:messageId].to_i, user_id: 1})\n\n if message_reaction.save\n updatedMessage = Message.find(params[:messageId]) \n ActionCable.server.broadcast(\n \"message_#{params[:messageId]}\",\n newMessageReaction: message_reaction,\n updatedMessage: updatedMessage,\n )\n end\n end", "def __add_called_action(action, ret)\n @called_actions << [action, ret]\n end", "def update_message(data); end", "def on_add(clicker)\n end", "def add_bonus_item(message)\n match = /(bonus item|hidden treasure)! <(?<id>.*)> \\| <(?<name>.*)>/.match(message)\n return nil unless match\n \n add_item(nil, match[:id], match[:name])\n publish Events::ADD_ITEM, match[:id], match[:name]\n end", "def process_msgs\n end", "def log_add_word_ok(params)\n params[:action] = ACTION_ADD_WORD_OK\n self.log params\n end", "def method_added(sym) # :nodoc:\n actions << sym if @define_action\n super\n end", "def add_message sender_type, message\n if !self.messages.empty? && !self.messages.last.valid?\n raise \"add_message invalid message: #{self.messages.last.errors.inspect}\"\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal handler for MESSAGE_REACTION_REMOVE
def remove_message_reaction(data); end
[ "def remove_message(name)\n\t\tend", "def remove_all_message_reactions(data); end", "def delete_message(data); end", "def on_removing_entry(state, event, *event_args)\n super\n\n # TODO: simulation - remove\n if simulating\n # From UploadController#delete:\n # ids = Upload.expand_ids(@item_id)\n __debug_sim('CODE') do\n args = \"id=#{submission.id.inspect}\"\n \"@items = Upload.expand_ids(#{args})\"\n end\n submission.items << submission.id\n end\n\n unless simulating\n wf_list_items(*event_args)\n end\n\n # TODO: simulation - remove\n __debug_sim('System shows the list of item(s) to be removed.')\n if submission&.auto_cancel\n __debug_sim('[auto_remove_cancel: true]')\n __debug_sim('USER decides not to delete item(s).')\n cancel! # NOTE: => :canceled\n elsif submission&.auto_submit\n __debug_sim('[auto_remove_submit: true]')\n __debug_sim('USER confirms the intent to delete item(s).')\n submit! # NOTE: => :removed\n else\n __debug_sim('USER must `cancel!` or `submit!` to advance...')\n end\n\n self\n end", "def delete_message_callback(ref)\n @messagecbs.delete(ref)\n end", "def on_removed_entry(state, event, *event_args)\n super\n\n # TODO: simulation - remove\n if simulating\n __debug_sim(\"[remove_emma_items: #{submission.emma_item}]\")\n emma_items = submission.emma_item\n else\n emma_items = true\n end\n\n # Determine whether this is destined for a member repository.\n unless simulating\n emma_items = Upload.emma_native?(record) if record\n end\n\n ok = nil\n\n if simulating\n if emma_items\n # From UploadController#destroy:\n # @succeeded, @failed = bulk_upload_remove(items)\n __debug_sim('CODE') do\n args = \"items=#{submission.items.inspect}\"\n opt = 'index: false'\n \"@succeeded, @failed = bulk_upload_remove(#{args}, #{opt})\"\n end\n self.succeeded += submission.items\n ok = ready?\n else\n ok = true # TODO: Simulate member repository delete request?\n end\n end\n\n unless simulating\n wf_remove_items(*event_args)\n ok = ready?\n end\n\n # TODO: simulation - remove\n __debug_sim do\n if !emma_items; 'Generating removal request for member repository items.'\n elsif !ok; 'The EMMA-native items NOT removed due to failure(s).'\n else; 'The EMMA-native items were removed.'; end\n end\n\n # Automatically transition to the next state based on submission status.\n if ok\n advance! # NOTE: => :staging\n else\n fail! # NOTE: => :failed\n end\n self\n end", "def process message\n App.log.info \"(#{message.to_str.chomp}) → [Unfollow]: Client ID #{message.actor} unfollowed Client ID #{message.target}\"\n\n to_user_id = message.target\n\n followers = @follow_registry[to_user_id] || Set.new\n\n followers.delete(message.actor)\n\n @follow_registry[to_user_id] = followers\n end", "def general_removed_message(object)\n class_name = object.class.model_name.human\n general_message_translation class_name, 'removed'\n end", "def delete_msg()\n MsgUtil.delete_msg(params[:ch])\n end", "def removal(message)\n Chef::Log.warn message\n log(message, kind: :removal)\n end", "def on_message(pre, message)\n\n m_wfid = message['wfid'] || (message['fei']['wfid'] rescue nil)\n m_error = message['error']\n\n m_action = message['action']\n m_action = \"pre_#{m_action}\" if pre\n\n msg = m_action == 'error_intercepted' ? message['msg'] : message\n\n ids_to_remove = []\n\n trackers.each do |tracker_id, tracker|\n\n # filter msgs\n\n t_wfid = tracker['wfid']\n t_action = tracker['action']\n\n next if t_wfid && t_wfid != m_wfid\n next if t_action && t_action != m_action\n\n next unless does_match?(message, tracker['conditions'])\n\n if tracker_id == 'on_error' || tracker_id == 'on_terminate'\n\n fs = msg['workitem']['fields']\n\n next if m_action == 'error_intercepted' && fs['__error__']\n next if m_action == 'terminated' && (fs['__error__'] || fs['__terminate__'])\n end\n\n # remove the message post-trigger?\n\n ids_to_remove << tracker_id if tracker['msg'].delete('_auto_remove')\n\n # OK, have to pull the trigger (or alter the message) then\n\n if pre && tracker['msg']['_alter']\n alter(m_wfid, m_error, m_action, msg, tracker)\n else\n trigger(m_wfid, m_error, m_action, msg, tracker)\n end\n end\n\n remove(ids_to_remove, nil)\n end", "def remove_command\n return if !has_manage_messages_permission?\n command.event.message.delete\n end", "def sub_remove _value=0\n send_cmd(\"sub_remove #{_value}\")\n end", "def run_on_removals(paths)\n puts \"Something was removed!\"\n end", "def attachment_removed(obj)\n # TODO check attachment removement\n end", "def remove(entry); end", "def del_msg_listener( msgName, object )\n @msgNames[msgName].delete object if defined? @msgNames\n end", "def removeMPEventHandler _obj, _args\n \"_obj removeMPEventHandler _args;\" \n end", "def remove(*)\n super.tap do\n __debug_sim('USER initiates removal of an existing entry or entries.')\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal handler for MESSAGE_REACTION_REMOVE_ALL
def remove_all_message_reactions(data); end
[ "def remove_message_reaction(data); end", "def _remove_all_method\n :\"_remove_all_#{self[:name]}\"\n end", "def remove_all\n @message_ids.each do |msg_id|\n @@statusbar.remove(@context_id, msg_id)\n end\n @message_ids.clear\n end", "def reaction_remove_all(attributes = {}, &block)\n register_event(ReactionRemoveAllEvent, attributes, block)\n end", "def remove_all\n @input_note_messages.clear\n mark_changed\n true\n end", "def _remove_all_method\n :\"_remove_all_#{self[:name]}\"\n end", "def process_leftovers\n #puts \"Processing leftovers\"\n\n @context.storage.get_many('msgs').each do |msg|\n #puts \"Processing #{msg.inspect}\"\n\n process msg\n end\n\n #puts \"Finished processing leftovers\"\n end", "def delete_all\n each { |msg| delete(msg) }\n clear\n end", "def clean_all\n\t\t\t\t\t@messages = []\n\t\t\t\tend", "def delete_all_msgs\n wait_for_load_and_click select_all_msgs_button_element\n wait_for_update_and_click delete_button_element\n no_msgs_msg_element.when_present Utils.short_wait\n end", "def message_type_unregister_all\n\t\t\tAggregator.unregister_all(self)\n\t\tend", "def clear_all_actions; end", "def get_messages\n @connection.uid_search(@filter).each do |message|\n puts \"PROCESSING MESSAGE #{message}\"\n body=@connection.uid_fetch(message,\"RFC822\")[0].attr[\"RFC822\"]\n @processor.process(body, @options)\n @connection.uid_copy(message, 'Processed')\n\n @connection.uid_store(message,\"+FLAGS\",[:Deleted])\n end\n @connection.expunge\n #@connection.delete_all\n end", "def clear_messages\n @message_list.clear\n end", "def messages_to_remove\n Message.outdated\n end", "def clean\n @actions = []\n end", "def removeAllActions _args\n \"removeAllActions _args;\" \n end", "def unload_reactions\n @reactor.clear if @reactor\n @reaction_files.clear if @reaction_files\n end", "def clear_messages!\n @received_messages = []\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal handler for GUILD_BAN_ADD
def add_user_ban(data); end
[ "def add_ban(mask, type)\n b = parse_ban(mask)\n\n if type == 'b'\n @bans.push(b)\n elsif type == 'e'\n @exempts.push(b)\n else\n raise(ArgumentError, \"Invalid ban type #{type}, expected b or e.\")\n end\n end", "def addHandgunItem _obj, _args\n \"_obj addHandgunItem _args;\" \n end", "def add_builder oid\n self.builders << oid if Character && !builder?(oid)\n end", "def on_message_add_button_clicked\n Logger.d(\"message_add_button tapped!!\")\n @analytics.fire_event({:category => \"home_screen\", :action => \"tap\", :label => \"Add bitch message\"})\n\n UiDialogWithInput.show(self, \n {\n :title => \"Create a new B*tch message\", \n :message => \"Enter the new message\",\n :positive_button => \"Save\", \n :negative_button => \"Cancel\" \n },\n Proc.new { |new_bitch_message| \n Logger.d(\"User added new bitch message : #{new_bitch_message}\")\n run_on_ui_thread {@progress_dialog.show()}\n @user.add_bitch_message(new_bitch_message) {\n render_ui(\"Message added to the list\")\n }\n }\n )\n end", "def add_bleapp\n\t\tif authorize_agent?\n\t\t\tbegin\n\t\t\t\tproperty = Property.find(params[:bleapp][:property_id])\n\t\t\t\tbeacon = Beacon.find_by(uuid: params[:uuid].downcase)\n\t\t\t\tbleapp = property.bleeapps.build(bleapp_params)\n\t\t\t\tbleapp.beacon_id = beacon.id\n\t\t\t\tif bleapp.save\n\t\t\t\t\tparams[:images].each { |image|\n\t i = bleapp.ble_images.create(image: image)\n\t if i.save\n\t else\n\t \trender_json({\"status\" => \"Fail\", \"message\" => i.errors.full_messages.first}.to_json)\n\t \treturn\n\t end\n\t }\n\t\t\t\t\trender_json({\"status\" => \"Success\", \"message\" => \"bleapp has been saved successfully.\",\"bleapp_id\" => bleapp.id}.to_json)\n\t\t\t\telse\n\t\t\t\t\trender_json({\"status\" => \"Fail\", \"message\" => bleapp.errors.full_messages.first}.to_json)\n\t\t\t\tend\n\t\t\trescue => e\n\t\t\t\tp e.inspect\n\t\t\t\trender_json({\"status\" => \"Fail\", \"message\" => e}.to_json)\n\t\t\tend\n\t\telse\n\t\t\trender_json({\"status\" => \"Fail\", \"message\" => \"Not authorize to add bleapp(Login as agent).\"}.to_json)\n\t\tend\n\tend", "def addItemToBackpack _obj, _args\n \"_obj addItemToBackpack _args;\" \n end", "def add_anumber_to_blocked_list_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PhoneBlockedListApi.add_anumber_to_blocked_list ...'\n end\n # resource path\n local_var_path = '/phone/blocked_list'\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'multipart/form-data'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = @api_client.object_to_http_body(opts[:'body'])\n auth_names = ['OAuth']\n data, status_code, headers = @api_client.call_api(:POST, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'InlineResponse20125')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PhoneBlockedListApi#add_anumber_to_blocked_list\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def on_add(clicker)\n end", "def on_bid(bid)\r\n \r\n end", "def add_bounce\n begin\n RestClient.post $cnf['mailgun']['apikey'] + $cnf['mailgun']['bounnces'],\n :address => 'bkotu6717@gmail.com'\n rescue Exception => e\n puts \"Exception raised add_bounce:\" + e.class.to_s\n puts e.message\n end\n end", "def create_child_blip\n #TODO\n end", "def remove_user_ban(data); end", "def banner(command, namespace = T.unsafe(nil), subcommand = T.unsafe(nil)); end", "def create\n\t\t@admin_ban = Ban.new(admin_ban_params)\n\t\t@admin_ban.user = current_user\n\n\t\trespond_to do |format|\n\t\t\tif @admin_ban.save\n\t\t\t\tformat.html { redirect_to admin_bans_path, notice: 'Ban was successfully created.' }\n\t\t\t\tformat.json { render :show, status: :created, location: admin_bans_path }\n\t\t\telse\n\t\t\t\tformat.html { broadcast_errors @admin_ban, admin_ban_params }\n\t\t\t\tformat.json { render json: @admin_ban.errors, status: :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend", "def create\n\n @offender = User.find(params[:offender_id])\n @enforcer = current_user\n\n @ban = Ban.refined_build(params, offender: @offender, enforcer: @enforcer, jurisdiction: @cloud)\n\n if authorize @ban, :create?\n if @ban.save\n render status: 200\n set_flash_message message: \"Your target was sent to the moon.\", title: \"TO THE MOON!\"\n else\n set_flash_message message: \"You used the wrong kind of magic and the canon broke.\", title: \"Moon canon malfunction\"\n build_errors_from_model @ban\n render status: 422\n end\n else\n set_flash_message message: \"Only supreme rulers are authorized to operate the moon-canon.\", title: \"No banana bag?\"\n build_errors_from_model @ban\n render status: 401\n end\n\n end", "def add_to_inbox__do_add\r\n @inbox = params[:inbox] ? Inbox.active.find(params[:inbox]) : @for_inbox\r\n if @inbox && @inbox.accepts?(@content) && !@content.inboxes.include?(@inbox) && !@inbox.archived?\r\n @inbox_item = InboxItem.new(:inbox_id => @inbox.id, :content_id => @content.id,\r\n :allow_take_to_showcase => @inbox.require_allowing_content_adoption? ? true : params[:allow_take_to_showcase],\r\n :user_id => current_actor.id, :original_content_id => @content.original_content_id)\r\n if @inbox_item.save\r\n Activity.send_message(@inbox_item, current_actor, :submitted_to_inbox)\r\n Activity.send_message(@inbox_item, current_actor, :inbox_submission_received)\r\n else\r\n respond_to do |wants|\r\n wants.html { flash[:warning] = \"Your content has been added to your account, but not to '{{name}}' inbox. Reason: {{reason}}\" / [@inbox.title, @inbox_item.errors.full_messages.join(';')]}\r\n wants.js {}\r\n end\r\n end\r\n end\r\n end", "def on_bid(bid)\r\n warn \"Bid \" + bid.to_s\r\n end", "def add_member_messages_aaq_to_bidder(params = {})\n commit(Ebay::Requests::AddMemberMessagesAAQToBidder, params)\n end", "def add(level, context, message)\n if message.error\n opts = {\n :error_message => message.to_s,\n :backtrace => message.error.backtrace\n }\n ::Airbrake.notify message.error, opts\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal handler for GUILD_BAN_REMOVE
def remove_user_ban(data); end
[ "def removeHandgunItem _obj, _args\n \"_obj removeHandgunItem _args;\" \n end", "def removeBackpack _args\n \"removeBackpack _args;\" \n end", "def removeItemFromBackpack _obj, _args\n \"_obj removeItemFromBackpack _args;\" \n end", "def unban_user(auth, server_id, user_id, reason = nil)\n MijDiscord::Core::API.request(\n :guilds_sid_bans_uid,\n server_id,\n :delete,\n \"#{MijDiscord::Core::API::APIBASE_URL}/guilds/#{server_id}/bans/#{user_id}\",\n Authorization: auth,\n 'X-Audit-Log-Reason': reason\n )\n end", "def unban(name)\n\t\treturn Rubbit_Poster.instance.unfriend('ban',name,@display_name)\n\tend", "def sub_remove _value=0\n send_cmd(\"sub_remove #{_value}\")\n end", "def remove( _uid )\n # TODO\n end", "def add_user_ban(data); end", "def remove_yourself_as_a_fan\n \nend", "def on_removing_entry(state, event, *event_args)\n super\n\n # TODO: simulation - remove\n if simulating\n # From UploadController#delete:\n # ids = Upload.expand_ids(@item_id)\n __debug_sim('CODE') do\n args = \"id=#{submission.id.inspect}\"\n \"@items = Upload.expand_ids(#{args})\"\n end\n submission.items << submission.id\n end\n\n unless simulating\n wf_list_items(*event_args)\n end\n\n # TODO: simulation - remove\n __debug_sim('System shows the list of item(s) to be removed.')\n if submission&.auto_cancel\n __debug_sim('[auto_remove_cancel: true]')\n __debug_sim('USER decides not to delete item(s).')\n cancel! # NOTE: => :canceled\n elsif submission&.auto_submit\n __debug_sim('[auto_remove_submit: true]')\n __debug_sim('USER confirms the intent to delete item(s).')\n submit! # NOTE: => :removed\n else\n __debug_sim('USER must `cancel!` or `submit!` to advance...')\n end\n\n self\n end", "def unban(reason = nil)\n server.unban(@user, reason)\n end", "def unban_player(id_type, id)\n raise \"id_type must be one of :name, :guid, or :ip\" unless [:name, :guid, :ip].include? id_type\n\n send_request(\"banList.remove\", id_type, id).read_word\n end", "def remove_bid(client_lpar)\n execute_cmd \"nim -F -o remove #{client_lpar.name}_bid\"\n #execute_cmd \"nim -F -o remove #{client_lpar}_bid\"\n end", "def unban_user(token, server_id, user_id, reason = nil)\n Discordrb::API.request(\n :guilds_sid_bans_uid,\n server_id,\n :delete,\n \"#{Discordrb::API.api_base}/guilds/#{server_id}/bans/#{user_id}\",\n Authorization: token,\n 'X-Audit-Log-Reason': reason\n )\n end", "def unban\n @weibo = Weibo.where(:id => params[:id]).includes(:owner).first\n \n Weibo.unban_weibo(@weibo.id) if @current_staff.can_monitor_weibo? and @weibo.present?\n \n render :ban\n end", "def remove_banned\n Zold::Id::BANNED.each do |id|\n @pgsql.exec('DELETE FROM payable WHERE id = $1', [id])\n end\n end", "def clear_ban_message\n self.ban_message = nil\n end", "def remove_message_reaction(data); end", "def remove\n args.each do |name|\n messages = nil\n action(\"Removing #{name} from #{app}\") do\n messages = addon_run { heroku.uninstall_addon(app, name, :confirm => options[:confirm]) }\n end\n output messages[:attachment] if messages[:attachment]\n output messages[:message]\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /tiendas_clientes POST /tiendas_clientes.json
def create @tienda_cliente = @cliente.tiendas_clientes.build(tienda_cliente_params) respond_to do |format| if @tienda_cliente.save format.html { redirect_to @tienda_cliente, notice: 'La tienda se creó exitosamente.' } format.json { render :show, status: :created, location: @tienda_cliente } else format.html { render :new } format.json { render json: @tienda_cliente.errors, status: :unprocessable_entity } end end end
[ "def create\n @client = Client.new(client_params)\n\n respond_to do |format|\n if @client.save\n format.html { redirect_to clients_url, notice: 'El cliente se creó correctamente' }\n format.json { render :index, status: :created, location: @client }\n else\n format.html { render :new }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @clientes = Cliente.all\n render json: @clientes\n end", "def create\n @ventas_cliente = Ventas::Cliente.new(ventas_cliente_params)\n\n respond_to do |format|\n if @ventas_cliente.save\n format.html { redirect_to @ventas_cliente, notice: 'Cliente was successfully created.' }\n format.json { render :show, status: :created, location: @ventas_cliente }\n else\n format.html { render :new }\n format.json { render json: @ventas_cliente.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @clientepacote = Clientepacote.new(clientepacote_params)\n\n respond_to do |format|\n if @clientepacote.save\n format.html { redirect_to @clientepacote, notice: 'Clientepacote was successfully created.' }\n format.json { render :show, status: :created, location: @clientepacote }\n else\n format.html { render :new }\n format.json { render json: @clientepacote.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @clientetipo = Clientetipo.new(params[:clientetipo])\n\n respond_to do |format|\n if @clientetipo.save\n format.html { redirect_to @clientetipo, notice: 'Clientetipo was successfully created.' }\n format.json { render json: @clientetipo, status: :created, location: @clientetipo }\n else\n format.html { render action: \"new\" }\n format.json { render json: @clientetipo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ventas_cliente = Ventas::Cliente.new(params[:ventas_cliente])\n\n respond_to do |format|\n if @ventas_cliente.save\n format.html { redirect_to @ventas_cliente, notice: 'Cliente was successfully created.' }\n format.json { render json: @ventas_cliente, status: :created, location: @ventas_cliente }\n else\n format.html { render action: \"new\" }\n format.json { render json: @ventas_cliente.errors, status: :unprocessable_entity }\n end\n end\n end", "def new_asignar_cliente\n @usuario = Usuario.find(params[:format])\n @usuario.clientes.build\n @clientes = Usuario.where(:admin => 0)\n end", "def create\n # Se crea el cliente\n @client = Client.new(params[:client])\n # Se crean los contactos\n @client.contacts.each do |contact|\n contact.password = contact.name\n contact.language = params[:client][:language]\n end\n if @client.valid? and @client.contacts.map(&:valid?).all?\n # Se salva el cliente\n @client.save\n # Se salvan los contactos\n @client.contacts.each(&:save)\n redirect_to @client, flash: {success: I18n.t('client.create_success')}\n else\n render 'new'\n end\n end", "def create\n @clientes_juego = ClientesJuego.new(clientes_juego_params)\n\n respond_to do |format|\n if @clientes_juego.save\n format.html { redirect_to @clientes_juego, notice: 'Clientes juego was successfully created.' }\n format.json { render :show, status: :created, location: @clientes_juego }\n else\n format.html { render :new }\n format.json { render json: @clientes_juego.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @clientes_servico = ClientesServico.new(clientes_servico_params)\n\n respond_to do |format|\n if @clientes_servico.save\n format.html { redirect_to @clientes_servico, notice: 'Clientes servico was successfully created.' }\n format.json { render action: 'show', status: :created, location: @clientes_servico }\n else\n format.html { render action: 'new' }\n format.json { render json: @clientes_servico.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @estadocliente = Estadocliente.new(estadocliente_params)\n\n respond_to do |format|\n if @estadocliente.save\n format.html { redirect_to @estadocliente, notice: 'Estadocliente was successfully created.' }\n format.json { render :show, status: :created, location: @estadocliente }\n else\n format.html { render :new }\n format.json { render json: @estadocliente.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @clientes1 = Clientes1.new(clientes1_params)\n\n respond_to do |format|\n if @clientes1.save\n format.html { redirect_to @clientes1, notice: 'Clientes1 was successfully created.' }\n format.json { render :show, status: :created, location: @clientes1 }\n else\n format.html { render :new }\n format.json { render json: @clientes1.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n get_clientes\n end", "def index\n @clientes_juegos = ClientesJuego.all\n end", "def create\n @clienteremi = Clienteremi.new(clienteremi_params)\n\n respond_to do |format|\n if @clienteremi.save\n format.html { redirect_to clienteremis_path, notice: 'Cliente creado correctamente' }\n format.json { render :show, status: :created, location: @clienteremi }\n else\n format.html { render :new }\n format.json { render json: @clienteremi.errors, status: :unprocessable_entity }\n end\n end\n end", "def newCliente\n @endereco = Endereco.new\n @endereco.enderecavel_id = params[:id]\n @endereco.enderecavel_type = 'Cliente'\n\n respond_to do |format|\n format.html { render :action => \"new\" }\n format.json { render :json => @endereco }\n end\n end", "def create\n @telefone_cliente = TelefoneCliente.new(telefone_cliente_params)\n\n respond_to do |format|\n if @telefone_cliente.save\n format.html { redirect_to @telefone_cliente, notice: 'Telefone cliente was successfully created.' }\n format.json { render :show, status: :created, location: @telefone_cliente }\n else\n format.html { render :new }\n format.json { render json: @telefone_cliente.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n @cliente = Cliente.find(params[:cliente_id])\n @descuento_cliente = @cliente.descuento_clientes.build(params[:descuento_cliente])\n\n respond_to do |format|\n if @descuento_cliente.save\n #format.html { redirect_to redirigir(@contelefono), :notice => 'El telefono fue ingresado correctamente.' }\n format.json { render json: @descuento_cliente}\n else\n #format.html { render :action => \"new\" }\n format.json { render json: @descuento_cliente.errors }\n end\n end\n end", "def create\n @todo_client = TodoClient.new(todo_client_params)\n\n respond_to do |format|\n if @todo_client.save\n format.html { redirect_to @todo_client, notice: 'Todo client was successfully created.' }\n format.json { render :show, status: :created, location: @todo_client }\n else\n format.html { render :new }\n format.json { render json: @todo_client.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
hour specified hour minute specified minute second specified second interval how fast the second hand advances in real time.
def initialize(hour, minute, second, interval) @hour = hour @minute = minute @second = second @interval = interval end
[ "def rational_hour(seconds); end", "def end_of_hour\n change(min: 59, sec: 59, usec: Rational(999999999, 1000))\n end", "def end_of_hour\n change(\n :min => 59,\n :sec => 59,\n :usec => Rational(999999999, 1000)\n )\n end", "def timestamp(hour1,minute1,second1,hour2,minute2,second2)\n\treturn((hour2-hour1)*3600 +(minute2-minute1)*60 +(second2-second1))\nend", "def end_of_hour\n change(\n min: 59,\n sec: 59,\n usec: Rational(999999999, 1000)\n )\n end", "def time_interval(inter_val_num)\n\n require 'rubygems'\n require 'active_support'\n require 'active_support/time'\n inter_val_num = 20\n cur_time = Time.now\n comp_time = cur_time - cur_time.sec - cur_time.min%15*60\n base_time = comp_time + 1.hour\n\n if comp_time < base_time\n comp_time = comp_time + inter_val_num.minutes\n end\n return comp_time\n\nend", "def setTime(hour, min, sec)\n setSec(sec) ;\n addMin(min) ;\n addHour(hour) ;\n end", "def end_of_hour\n change(\n :min => 59,\n :sec => 59,\n :usec => 999999.999\n )\n end", "def end_of_hour\n change(:min => 59, :sec => 59)\n end", "def hour\n @interval = 'hour'\n self\n end", "def time_interval(inter_val_num=15)\n\n require 'rubygems'\n require 'active_support'\n require 'active_support/time'\n\n cur_time = Time.now\n comp_time = cur_time - cur_time.sec - cur_time.min%15*60\n base_time = comp_time + 1.hour\n\n if comp_time < base_time\n comp_time = comp_time + inter_val_num.minutes\n end\n\n return comp_time.strftime(\"%M:%S\")\n\nend", "def an_hour_of_monitors(ago=2)\n an_hour_of(22,ago)\n end", "def tick\n\t\t@secs -=1\n\t\t\t\n\t\tif @secs == -1\n\t\t\tthen\n\t\t\t@mins -= 1\n\t\t\t@secs = 59\n\t\t\tif @mins == -1\n\t\t\t\tthen\n\t\t\t\t@hours -= 1\n\t\t\t\t@mins = 59\n\t\t\t\tif @hours == -1\n\t\t\t\t\tthen\n\t\t\t\t\t@hours = 23\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t\n\tend", "def tick\n\t\tif @sec > 0\n\t\t\t@sec -= 1\n\t\telse\n\t\t\t@sec = 59\n\t\t\tif min > 0\n\t\t\t\t@min -= 1\n\t\t\telse\n\t\t\t\t@min = 59\n\t\t\t\tif @hr > 0\n\t\t\t\t\t@hr -= 1\n\t\t\t\telse\n\t\t\t\t\t@hr = 23\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def absolute_hour(seconds); end", "def tick\n\t\n\t\t@secs +=1\n\t\t\n\t\tif @secs == 60\n\t\t\tthen\n\t\t\t@mins += 1\n\t\t\t@secs = 0\n\t\t\tif @mins == 60\n\t\t\t\tthen\n\t\t\t\t@hours += 1\n\t\t\t\t@mins = 0\n\t\t\t\tif @hours == 24\n\t\t\t\t\tthen\n\t\t\t\t\t@hours = 0\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def hour() end", "def next_hour(start)\n return start+HOUR-(start.min*MINUTE) \n end", "def next_hourly\n @current_date += @interval.hours\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tick will now increment the second value.
def tick @second += 1 need_tock? end
[ "def tick\n @tick += 1\n end", "def tick(seconds)\n\t\t@time += seconds\n\tend", "def tick\n @time = next_time(true)\n end", "def tick\n\t\n\t\t@secs +=1\n\t\t\n\t\tif @secs == 60\n\t\t\tthen\n\t\t\t@mins += 1\n\t\t\t@secs = 0\n\t\t\tif @mins == 60\n\t\t\t\tthen\n\t\t\t\t@hours += 1\n\t\t\t\t@mins = 0\n\t\t\t\tif @hours == 24\n\t\t\t\t\tthen\n\t\t\t\t\t@hours = 0\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def tick\n @ticks_recorded += 1\n persist if persist?\n end", "def tick\n @mutex.synchronize do\n new_stamp = Clock.stamp\n @prev_stamp = if new_stamp > @prev_stamp then\n new_stamp\n else\n @prev_stamp + 1\n end\n end\n end", "def tick\n\t\tif @sec > 0\n\t\t\t@sec -= 1\n\t\telse\n\t\t\t@sec = 59\n\t\t\tif min > 0\n\t\t\t\t@min -= 1\n\t\t\telse\n\t\t\t\t@min = 59\n\t\t\t\tif @hr > 0\n\t\t\t\t\t@hr -= 1\n\t\t\t\telse\n\t\t\t\t\t@hr = 23\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def advance\n @tick_counter += 1\n end", "def tick\n yield if block_given?\n happen :tick_end, num: @session[:act_inf][:tick]\n num = @session[:act_inf][:tick] + 1\n @session[:act_inf][:tick] = num\n happen :tick_start, num: num\n end", "def tick\n\t\t@secs -=1\n\t\t\t\n\t\tif @secs == -1\n\t\t\tthen\n\t\t\t@mins -= 1\n\t\t\t@secs = 59\n\t\t\tif @mins == -1\n\t\t\t\tthen\n\t\t\t\t@hours -= 1\n\t\t\t\t@mins = 59\n\t\t\t\tif @hours == -1\n\t\t\t\t\tthen\n\t\t\t\t\t@hours = 23\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t\n\tend", "def Run()\n loop do\n sleep 1\n dt = Time.now\n\n #// If the second has changed, notify the subscribers\n SecondChange(self, dt) if dt.sec != @sec\n\n #// update the state\n @sec = dt.sec\n end\n end", "def advance(seconds:)\n @time += (seconds.to_i * 1_000)\n end", "def advance(secs)\n @actual += secs\n @current_systime = Time.new\n end", "def next_cycle!\n @cycle += 1\n end", "def new_ticks\n Thread.new do\n while true do\n puts Time.now # or call tick function\n new_turn\n sleep 100\n end\n end\n end", "def tick( event )\n sync {stats[event].tick}\n end", "def run(ticks)\n\t\tputs to_s\n\t\tsleep(2)\n\t\tticks.times do\n\t\t\tclock_tick\n\t\tend\n\tend", "def +(sec)\n self.class.at((@time + (sec * ONE_SECOND)) / ONE_SECOND)\n end", "def increment_time\n @now += 1.minute\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If the second value == 60, then it will commit a tock
def need_tock? if @second == 60 @second = 0 tock end end
[ "def cheat\n if @score >= 60 and !@cheating and !@cheating_two\n @cheating = true\n @score -= 60\n end\n end", "def verify_score(score)\n decimal = (score * 60) % 1\n [decimal, 1 - decimal].min < 0.03\nend", "def commit\n return false unless committable?\n result = vote_frequency.reject { |_k, v| v < 6 }.keys.first\n if result == 'radiant' || result == 'dire'\n winner_team = teams.where(side: result)\n loser_team = (teams - winner_team).first\n winner_team = winner_team.first\n\n update_player_stats(winner_team, loser_team, result)\n finalize_match(result)\n else\n cancel\n end\n end", "def need_tick_tock?\n if @minute == 60\n @minute = 0\n tick_tock\n end\n end", "def tick\n @second += 1\n need_tock?\n end", "def test_update_cash\n assert_equal(60, @bakery.update_cash(10))\n end", "def set_last_value(dbh)\n last_value = get_last_value(dbh)\n if last_value.nil? or last_value.empty?\n create_cron_entry(dbh)\n last_value=0\n end\n res = dbh.query(\"UPDATE cron_traker SET increment_value_traker='#{(last_value.to_i + 1)}' WHERE cron_id='#{CRON_ID}'\")\n puts \"update cron_traker for cron job #{CRON_ID} to #{(last_value.to_i + 1)}\"\nend", "def check_rule1\n total_minutes = self.merged_times.sum { |e| (e.end.to_i-e.begin.to_i)/60 }\n self.results[:rule1] = total_minutes / 60\n end", "def test_ut_t4_smt_mtm_019\n threshold = create_a_metric_threshold\n #\n value = THRESHOLD_2 - 2\n assert_equal threshold.match_threshold?(value),2\n end", "def test_ut_t4_smt_mtm_022\n threshold = create_a_metric_threshold\n #\n value = THRESHOLD_2 + 2\n assert_equal threshold.match_threshold?(value),0\n end", "def check_and_set_gold\n @gold = 0 if @gold < 0\n end", "def test_user_update_credit_limit\n\t\tUser.create(@@user_details['name'], @@user_details['email'], @@user_details['credit_limit'])\n\t\tquery = \"select credit_limit from user where name=\\\"#{@@user_details['name']}\\\";\"\n\t\tresult = EntityHelper.execute_command(query)\n\t\tassert_equal(result[0][0], 400)\n\t\t\n\t\tnew_credit_limit = 500\n\t\tUser.update_credit(@@user_details['name'], new_credit_limit)\n\t\tquery = \"select credit_limit from user where name=\\\"#{@@user_details['name']}\\\";\"\n\t\tresult = EntityHelper.execute_command(query)\n\t\tassert_equal(result[0][0], 500)\n\tend", "def test_ut_t4_smt_mtm_020\n threshold = create_a_metric_threshold\n #\n value = THRESHOLD_1 - 1\n assert_equal threshold.match_threshold?(value),2\n end", "def test_ut_t4_smt_mtm_013\n threshold = create_float_metric_threshold\n metric_threshold = MetricsThreshold.find(threshold.id)\n metric_threshold.threshold_1 = \"\"\n assert metric_threshold.save\n assert_equal MetricsThreshold.find(metric_threshold.id).threshold1_compare_operator_id.to_s , \"1\"\n end", "def customer_buys_ticket_two()\n @funds -= get_price_of_film()\n sql = \"UPDATE customers SET funds = $1 WHERE id = $2\"\n values = [ @funds, @id ]\n SqlRunner.run(sql, values)\n end", "def test_cur_sec_greater\n \tassert(@bv.timestap_correct(1, \"123456.1111\", \"123457.1111\"))\n end", "def set_time_entry_billing_percent\n data=params\n @time_entry = TneInvoiceTimeEntry.find(data[:id])\n @previous_final_billed_amount = @time_entry.final_billed_amount\n @error=false\n if data[:value].to_i.between?(0,100)\n @time_entry.update_attributes({:billing_percent => data[:value], :billing_method_type => 2})\n @final_billed_amount = @time_entry.calculate_final_billed_amt\n else\n @error=true\n flash[:error]= \"#{t(:tne_billing)}\"\n end\n\n end", "def can_double_bet\n return 1 unless @bankroll < @bet\n return nil\n end", "def set_time_entry_actual_bill_rate\n data=params\n @time_entry = TneInvoiceTimeEntry.find(data[:id])\n @previous_final_billed_amount = @time_entry.calculate_final_billed_amt\n override_rate = !data[:value].blank? ? data[:value].to_f.roundf2(2) : 0\n @error=false\n #reg = /^[0-9]+(.[0-9]{1,5})$/\n if (override_rate > 0)\n ActiveRecord::Base.transaction do\n @time_entry.update_attribute(:actual_activity_rate,override_rate)\n @billed_amount = @time_entry.calculate_billed_amount\n @final_billed_amount = @time_entry.calculate_final_billed_amt\n @time_entry.update_attribute(:final_billed_amount,@final_billed_amount)\n end\n else\n @error=true\n flash[:error] = t(:flash_enter_valid_rate)\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If minute value == 60, then it will commit a ticktock
def need_tick_tock? if @minute == 60 @minute = 0 tick_tock end end
[ "def need_tock?\n if @second == 60\n @second = 0\n tock\n end\n end", "def tick\n\t\tif @sec > 0\n\t\t\t@sec -= 1\n\t\telse\n\t\t\t@sec = 59\n\t\t\tif min > 0\n\t\t\t\t@min -= 1\n\t\t\telse\n\t\t\t\t@min = 59\n\t\t\t\tif @hr > 0\n\t\t\t\t\t@hr -= 1\n\t\t\t\telse\n\t\t\t\t\t@hr = 23\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def minute=(value); end", "def minute? = unit == 'minute'", "def could_be_minute?(minute); end", "def tick\n\t\n\t\t@secs +=1\n\t\t\n\t\tif @secs == 60\n\t\t\tthen\n\t\t\t@mins += 1\n\t\t\t@secs = 0\n\t\t\tif @mins == 60\n\t\t\t\tthen\n\t\t\t\t@hours += 1\n\t\t\t\t@mins = 0\n\t\t\t\tif @hours == 24\n\t\t\t\t\tthen\n\t\t\t\t\t@hours = 0\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def tick\n\t\t@secs -=1\n\t\t\t\n\t\tif @secs == -1\n\t\t\tthen\n\t\t\t@mins -= 1\n\t\t\t@secs = 59\n\t\t\tif @mins == -1\n\t\t\t\tthen\n\t\t\t\t@hours -= 1\n\t\t\t\t@mins = 59\n\t\t\t\tif @hours == -1\n\t\t\t\t\tthen\n\t\t\t\t\t@hours = 23\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t\n\tend", "def tick\n @second += 1\n need_tock?\n end", "def fix_minute\n @hour += minute / 60\n @minute = minute % 60\n end", "def arc_minute? = unit == 'arc-minute'", "def set_SetMinute(value)\n set_input(\"SetMinute\", value)\n end", "def end_of_minute\n change(sec: 59.999)\n end", "def tempo(beats_per_second)\n\t\tbeats_per_minute = beats_per_second * 60 \n\tend", "def test_minute_set\n clock = Clock.new 0, -1\n alarm = AlarmClock.new 0, -1\n puts 'Wrong hour set' if clock.get_minute != 0\n puts 'Wrong hour set' if alarm.get_alarm_minute != 0\n clock.set_time 26, 0\n alarm.set_alarm 26, 0\n puts 'Wrong hour set' if clock.get_minute != 23\n puts 'Wrong hour set' if alarm.get_alarm_minute != 23\n end", "def tick\n update(:last_checked => last_time)\n end", "def schedule_interval_divisor_60\n errors.add(:schedule_interval, 'must be a divisor of 60') if schedule_interval > 0 && 60 % schedule_interval > 0\n end", "def tick\n set(:last_checked => last_time) \n end", "def test_tick\n\t\t@clock1.to_s\n\t\t@clock1.tick\n\t\t@clock1.to_s\n\t\tassert_equal(@clock1.secs, 0, 'tick not operating correctly')\n\t\tassert_equal(@clock1.mins, 0, 'tick not operating correctly')\n\t\tassert_equal(@clock1.hours, 0, 'tick not operating correctly')\n\t\t#test to check that hours, mins and secs are within appropriate bounds - do I need to include this? \n\t\t#Probably do not need as values for hours, mins and secs are being tested above already. Leave it in anyway..\n\t\tassert(@clock1.hours >= 0 && @clock1.hours <= 23, 'clock hours value out of bounds')\n\t\tassert(@clock1.mins >= 0 && @clock1.mins <= 59, 'clock minutes value out of bounds')\n\t\tassert(@clock1.mins >= 0 && @clock1.mins <= 59, 'clock seconds value out of bounds')\n\tend", "def minute= num\n #This is a stub, used for indexing\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
5 Cases (1) First install, anything goes => OK (2) An old storage type was not set and the new_storage_type is :filesystem => OK (3) An old storage type was not set and the new_storage_type is :sql => NOT_OK (4) An old storage type was set and is not equal to the new storage type => NOT_OK (5) An old storage type was set and is equal to the new storage type => OK
def verify_storage_type_unchanged if previous_run.nil? # case (1) true else previous_value = previous_run['bookshelf']['storage_type'] current_value = (user_attrs['storage_type'] || 'filesystem').to_s if previous_value.nil? && current_value == 'filesystem' # case (2) true elsif previous_value.nil? && current_value != 'filesystem' # case (3) fail_with <<~EOM Bookshelf's storage_type was previously the default of 'filesystem'; however the current configuration would result in a value of '#{current_value}'. At this time it is not possible to change the bookshelf storage_type post-installation. Please set bookshelf['storage_type'] = 'filesystem' in /etc/#{ChefUtils::Dist::Org::LEGACY_CONF_DIR}/#{ChefUtils::Dist::Server::SERVER}.rb or leave it unset. EOM elsif previous_value.to_s == current_value # case (5) true else # everything else is invalid, including case 4 above fail_with <<~EOM Bookshelf's storage_type was previously '#{previous_value}'; however the current configuration would result in a value of '#{current_value}'. At this time it is not possible to change the bookshelf storage_type post-installation. Please set bookshelf['storage_type'] = '#{previous_value}' in /etc/#{ChefUtils::Dist::Org::LEGACY_CONF_DIR}/#{ChefUtils::Dist::Server::SERVER}.rb EOM end end end
[ "def ensure_correct_derivatives_storage_after_change\n if derivative_storage_type_previously_changed? && file_derivatives.present?\n EnsureCorrectDerivativesStorageJob.perform_later(self)\n end\n end", "def transform_to_consistent_types\n if PrivateChef['bookshelf']['storage_type']\n PrivateChef['bookshelf']['storage_type'] = PrivateChef['bookshelf']['storage_type'].to_s\n end\n end", "def determine_storage(opts)\n\n if ARGV.include?('--help')\n puts %{\n\nARGUMENTS for functional tests :\n\n --fs : uses Ruote::FsStorage\n\nelse uses the in-memory Ruote::Engine (fastest, but no persistence at all)\n\n }\n exit 0\n end\n\n ps = ARGV.select { |a| a.match(/^--[a-z]/) }\n ps.delete('--split')\n\n persistent = opts.delete(:persistent)\n\n if ps.include?('--fs')\n\n require 'ruote/storage/fs_storage'\n\n require_json\n Rufus::Json.detect_backend\n\n Ruote::FsStorage.new('work', opts)\n\n elsif not ps.empty?\n\n pers = nil\n ps.find { |a| pers = locate_storage_impl(a) }\n\n raise \"no persistence found (#{ps.inspect})\" unless pers\n\n lib, path = pers\n $:.unshift(File.join(path, 'lib'))\n\n begin\n load 'test/functional_connection.rb'\n rescue LoadError => le\n begin\n load File.join(path, %w[ test functional_connection.rb ])\n rescue LoadError => lee\n begin\n load File.join(path, %w[ test integration_connection.rb ])\n rescue LoadError => leee\n p le\n p lee\n p leee\n raise leee\n end\n end\n end\n\n new_storage(opts)\n\n elsif persistent\n\n require_json\n Rufus::Json.detect_backend\n\n require 'ruote/storage/fs_storage'\n\n Ruote::FsStorage.new('work', opts)\n\n else\n\n Ruote::HashStorage.new(opts)\n end\nend", "def storage_type\n @storage_type\n end", "def test_migration\r\n ActiveRecord::Base.connection.execute(\"drop table entity_storage\")\r\n AddOldEntitiesTable.create\r\n ActiveRecord::Base.connection.execute(\"show columns from entity_storage\").each {|p| \r\n assert(p[1] == \"text\") if p[0] == \"value\" }\r\n entityStore = EntityStorage::Storage.new(DEFAULT_KEYS)\r\n ActiveRecord::Base.connection.execute(\"show columns from entity_storage\").each {|p| \r\n assert(p[1] == \"blob\") if p[0] == \"value\" }\r\n assert entityStore['ENTITY_STORAGE_MASTER_VERSION']=='2.1.2'\r\n\r\n ActiveRecord::Base.connection.execute(\"delete from entity_storage\")\r\n entityStore = EntityStorage::Storage.new(DEFAULT_KEYS)\r\n assert entityStore['ENTITY_STORAGE_MASTER_VERSION']=='2.1.2'\r\n\r\n ActiveRecord::Base.connection.execute(\"drop table entity_storage\")\r\n entityStore = EntityStorage::Storage.new(DEFAULT_KEYS)\r\n ActiveRecord::Base.connection.execute(\"show columns from entity_storage\").each {|p| \r\n assert(p[1] == \"blob\") if p[0] == \"value\" }\r\n assert entityStore['ENTITY_STORAGE_MASTER_VERSION']=='2.1.2'\r\n end", "def check_metadata\n version = @db[:schema_info].first\n unless version[:magic] == Bitcoin.network[:magic_head].hth\n name = Bitcoin::NETWORKS.find{|n,d| d[:magic_head].hth == version[:magic]}[0]\n raise \"Error: DB #{@db.url} was created for '#{name}' network!\"\n end\n unless version[:backend] == backend_name\n if version[:backend] == \"sequel\" && backend_name == \"utxo\"\n log.warn { \"Note: The 'utxo' store is now the default backend.\n To keep using the full storage, change the configuration to use storage: 'sequel::#{@db.url}'.\n To use the new storage backend, delete or move #{@db.url}, or specify a different database path in the config.\" }\n end\n raise \"Error: DB #{@db.url} was created for '#{version[:backend]}' backend!\"\n end\n end", "def storage_options; end", "def ensure_storage_file\n new_storage if !storage_exists?\n end", "def filesystem_type(host)\n case host['platform']\n when %r{aix}\n 'jfs2'\n when %r{el-|centos|fedora|sles|debian|ubuntu}\n 'ext3'\n else\n # TODO: Add Solaris and OSX support, as per PUP-5201 and PUP-4823\n fail_test(\"Unable to determine a standard filesystem table type for #{host['platform']}\")\n end\n end", "def storage_type=(value)\n @storage_type = value\n end", "def storage_require_removable_storage_encryption\n return @storage_require_removable_storage_encryption\n end", "def check_builtin_storages(persister)\n # Check that the collection of storages has been created:\n collection = persister.collections[:storages]\n expect(collection).to_not be_nil\n data = collection.data\n expect(data).to_not be_nil\n expect(data.length).to eq(1)\n\n # Check that the builtin storage has been created:\n storage = data.first\n expect(storage).to_not be_nil\n expect(storage.ems_ref).to eq('0')\n expect(storage.name).to eq('mykubevirt')\n expect(storage.store_type).to eq('UNKNOWN')\n end", "def find_and_check_disk(type, value)\n lspv_root = shell_out(\"lspv | awk '$3 == \\\"rootvg\\\" {print $1}'\")\n current_rootvg = lspv_root.stdout\n current_rootvg_size = sizeof_disk(current_rootvg)\n lspv = shell_out('lspv')\n disk = 'None'\n # type is name\n if type == :name\n lspv.stdout.each_line do |a_pv|\n current_pv_a = a_pv.split(' ')\n next unless current_pv_a[0] == value\n if current_pv_a[2] == 'None'\n Chef::Log.info(\"alt_disk: disk #{value} is usable\")\n disk = current_pv_a[0]\n end\n end\n # type is size\n elsif type == :size\n lspv.stdout.each_line do |a_pv|\n current_pv_a = a_pv.split(' ')\n next unless current_pv_a[2] == 'None'\n this_size = sizeof_disk(current_pv_a[0])\n if this_size == value.to_i\n Chef::Log.debug(\"alt_disk: empty disk #{current_pv_a[0]} found with a size of #{value}\")\n disk = current_pv_a[0]\n end\n end\n # type is auto\n elsif type == :auto\n lspv.stdout.each_line do |a_pv|\n current_pv_a = a_pv.split(' ')\n next unless current_pv_a[2] == 'None'\n this_size = sizeof_disk(current_pv_a[0])\n if value == 'equal' && this_size == current_rootvg_size\n Chef::Log.debug(\"alt_disk: empty disk #{current_pv_a[0]} found with a size of the current rootvg\")\n disk = current_pv_a[0]\n end\n if value == 'bigger' && this_size > current_rootvg_size\n Chef::Log.debug(\"alt_disk: empty disk #{current_pv_a[0]} found with a size bigger than the size of the current rootvg\")\n disk = current_pv_a[0]\n end\n end\n end\n if disk == 'None'\n Chef::Log.debug('alt_disk: cannot find any disk usable for alt_disk')\n 'None'\n else\n Chef::Log.debug('alt_disk: checking size is BIGGER or EQUAL')\n test = check_disk_size(current_rootvg, disk)\n if test == 'BIGGER' || test == 'EQUAL'\n Chef::Log.debug('alt_disk: disk is BIGGER or EQUAL')\n disk\n elsif test == 'LESSER'\n Chef::Log.debug('alt_disk: cannot find any disk usable for alt_disk')\n 'None'\n end\n end\nend", "def storage_use_nfs\n super\n end", "def test_multicloud\n cid = VirtualMonkey::Toolbox::determine_cloud_id(s_one)\n if cid == 232\n test_cloud_files\n else\n if @storage_type == \"ros\"\n test_s3\n elsif @storage_type == \"volume\"\n test_ebs\n end\n end\n end", "def derivatives_in_correct_storage_location?\n file_derivatives.blank? ||\n file_derivatives.values.collect(&:storage_key).all?(\n self.class::DERIVATIVE_STORAGE_TYPE_LOCATIONS.fetch(self.derivative_storage_type)\n )\n end", "def storage_require_removable_storage_encryption=(value)\n @storage_require_removable_storage_encryption = value\n end", "def allowed? storage\n return true if Boom.local?\n return true if allowed_storage_types.include? storage.class\n\n output error_message storage\n false\n end", "def check_metadata\n version = @db[:schema_info].first\n unless version[:magic] == Bitcoin.network[:magic_head].hth\n name = Bitcoin::NETWORKS.find{|n,d| d[:magic_head].hth == version[:magic]}[0]\n raise \"Error: DB #{@db.url} was created for '#{name}' network!\"\n end\n unless version[:backend] == backend_name\n # rename \"sequel\" to \"archive\" when old db is opened\n if version[:backend] == \"sequel\" && backend_name == \"archive\"\n @db[:schema_info].update(backend: \"archive\")\n else\n raise \"Error: DB #{@db.url} was created for '#{version[:backend]}' backend!\"\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Encode the temporal expression into +codes+.
def encode(codes) encode_list(codes, @days) codes << encoding_token end
[ "def encode(codes)\n @base_date.nil? ? (codes << 0) : encode_date(codes, @base_date)\n codes << encoding_token\n end", "def encode(codes)\n encode_list(codes, @years)\n codes << encoding_token\n end", "def encode(ary)\n ary.map { |(code, argument)| [INSTRUCTIONS[code], argument] }\n end", "def encode_date(codes, date)\n codes << date.strftime(\"%Y-%m-%d\")\n end", "def encode_list(codes, list)\n if list.empty?\n codes << \"[]\"\n elsif list.size == 1\n codes << list.first\n else\n codes << \"[\"\n prev = nil\n list.each do |item|\n codes << \",\" if prev && ! prev.kind_of?(TExp::Base)\n codes << item.to_s\n prev = item\n end\n codes << \"]\"\n end\n end", "def encode_time(time); end", "def encode encoder, options = {}\n if encoder.respond_to? :to_sym\n CodeRay.encode(input, lang, encoder, options)\n else\n encoder.encode_tokens tokens, options\n end\n end", "def codify(txt)\n enclose('code', txt)\n end", "def codes(*symbols)\n @codes = symbols\n end", "def array_to_code(arr)\n code = ''\n arr.each_with_index do |part, i|\n code << ' + ' if i > 0\n case part\n when Symbol\n code << part.to_s\n when String\n code << %{\"#{part}\"}\n else\n raise \"Don't know how to compile array part: #{part.class} [#{i}]\"\n end\n end\n code\n end", "def encode_datetime(time); end", "def encode_traces(encoder, traces)\n trace_hashes = traces.map do |trace|\n encode_trace(trace)\n end\n\n # Wrap traces & encode them\n encoder.encode(traces: trace_hashes)\n end", "def timecodes\n @timecodes ||= times.collect(&:timecodes).flatten.uniq\n end", "def code\n return \"#{\"%04d\" % @t_year}#{\"%02d\" % @t_month}#{\"%02d\" % @t_day}#{\"%02d\" % @t_hour}#{\"%02d\" % @t_min}#{\"%02d\" % @t_sec}#{\"%05d\" % @t_usec}\"\n end", "def base_encode(digits)\n return digits unless @code\n digits.map do |i|\n case i\n when '-', DOT, DIV\n i\n else\n code[i]\n end\n end\n end", "def codes_to_binary_string(codes)\n codes = codes.sort\n unless legal_code_value?(codes.first) && legal_code_value?(codes.last)\n raise ArgumentError.new(\"All codes must be between 1 and 127: #{codes.inspect}.\")\n end\n bitmap_number = BitMapping.set_bit_position_array_to_number(codes)\n BitMapping.number_to_binary_string(bitmap_number)\n end", "def encodeopcode(filename,address,line,symboltable,opcodereference,labelflag)\n encodedline = 0\n twentysixbitmask = 0x3FFFFFF\n sixteenbitmask = 0xFFFF\n labelflag ? opcodeelement = 1 : opcodeelement = 0\n operandelement = opcodeelement + 1\n\n encodingvalue = opcodereference[line[opcodeelement]][\"encoding\"].to_s.to_i\n opcodetype = opcodereference[line[opcodeelement]][\"type\"].to_s\n functioncode = opcodereference[line[opcodeelement]][\"functioncode\"].to_s.to_i\n\n if opcodetype == \"i\"\n case self.imap[line[opcodeelement]]\n when \"none\"\n # Do nothing. Literally.\n\n when \"number\"\n encodedline = encodingvalue\n encodedline <<= (32-6)\n operand = line[operandelement].to_i\n encodedline |= operand\n\n when \"gpr\"\n targetaddress = 0\n encodedline = encodingvalue\n encodedline <<= (32 - 6)\n destinreg = line[operandelement].gsub!(\"r\",'').to_i\n targetaddress |= destinreg\n targetaddress <<= (32 - 6 - 5)\n encodedline |= targetaddress\n\n when \"gprname\"\n pc = address.hex + 4\n targetaddress = 0\n labelelement = operandelement + 1\n encodedline = encodingvalue\n encodedline <<= (32 - 6)\n destinreg = line[operandelement].gsub!(\"r\",'').to_i\n targetaddress |= destinreg\n targetaddress <<= (32 - 6 - 5)\n encodedline |= targetaddress\n targetaddress = 0\n label = line[labelelement] + \":\"\n targetaddress |= symboltable[filename][label].hex\n targetaddress = (targetaddress - pc).to_i\n targetaddress &= sixteenbitmask\n encodedline |= targetaddress\n\n when \"gprnum\"\n encodedline = encodingvalue\n encodedline <<= (32 - 6)\n destinreg = line[operandelement].gsub!(\"r\",'').to_i\n destinreg <<= (32 - 6 - 5 - 5)\n encodedline |= destinreg\n immfield = operandelement + 1\n immediate = line[immfield].to_i\n encodedline |= immediate\n\n when \"gprgprint\"\n encodedline = encodingvalue\n encodedline <<= (32 - 6)\n destinreg = line[operandelement+1].gsub!(\"r\",'').to_i\n destinreg <<= (32 - 6 - 5)\n encodedline |= destinreg\n sourcereg = line[operandelement].gsub!(\"r\",'').to_i\n sourcereg <<= (32 - 6 - 5 - 5)\n encodedline |= sourcereg\n immelement = operandelement + 2\n immedfield = line[immelement] + \":\"\n if symboltable[filename].has_key?(immedfield)\n immediate = symboltable[filename][immedfield].hex\n else immediate = line[immelement].to_i\n end\n encodedline |= immediate\n\n when \"gprgpruint\"\n encodedline = encodingvalue\n encodedline <<= (32 - 6)\n destinreg = line[operandelement+1].gsub!(\"r\",'').to_i\n destinreg <<= (32 - 6 - 5)\n encodedline |= destinreg\n sourcereg = line[operandelement].gsub!(\"r\",'').to_i\n sourcereg <<= (32 - 6 - 5 - 5)\n encodedline |= sourcereg\n immelement = operandelement + 2\n immedfield = line[immelement] + \":\"\n if symboltable[filename].has_key?(immedfield)\n immediate = symboltable[filename][immedfield].hex\n else immediate = line[immelement].to_i\n end\n encodedline |= immediate\n\n when \"dproff\"\n encodedline = encodingvalue\n encodedline <<= (32 - 6)\n immelement = operandelement + 1\n immedfield = line[immelement] + \":\"\n if symboltable[filename].has_key?(immedfield)\n offset = symboltable[filename][immedfield].hex\n sourcereg = 0\n else\n operandpieces = line[operandelement+1].split(\"(\")\n operandpieces[1].gsub!(\"r\",'').to_i\n operandpieces[1].gsub!(\")\",'').to_i\n offset = operandpieces[0].to_i\n sourcereg = operandpieces[1].to_i\n end\n sourcereg <<= (32 - 6 - 5)\n encodedline |= sourcereg\n destinreg = line[operandelement].gsub(\"f\",'').to_i\n destinreg <<= (32 - 6 - 5 -5)\n encodedline |= destinreg\n encodedline |= offset\n\n when \"gproff\"\n encodedline = encodingvalue\n encodedline <<= (32 - 6)\n immelement = operandelement + 1\n immedfield = line[immelement] + \":\"\n if symboltable[filename].has_key?(immedfield)\n offset = symboltable[filename][immedfield].hex\n sourcereg = 0\n else\n operandpieces = line[operandelement+1].split(\"(\")\n operandpieces[1].gsub!(\"r\",'').to_i\n operandpieces[1].gsub!(\")\",'').to_i\n offset = operandpieces[0].to_i\n sourcereg = operandpieces[1].to_i\n end\n sourcereg <<= (32 - 6 - 5)\n encodedline |= sourcereg\n destinreg = line[operandelement].gsub(\"r\",'').to_i\n destinreg <<= (32 - 6 - 5 -5)\n encodedline |= destinreg\n encodedline |= offset\n\n when \"fproff\"\n encodedline = encodingvalue\n encodedline <<= (32 - 6)\n immelement = operandelement + 1\n immedfield = line[immelement] + \":\"\n if symboltable[filename].has_key?(immedfield)\n offset = symboltable[filename][immedfield].hex\n sourcereg = 0\n else\n operandpieces = line[operandelement+1].split(\"(\")\n operandpieces[1].gsub!(\"r\",'').to_i\n operandpieces[1].gsub!(\")\",'').to_i\n offset = operandpieces[0].to_i\n sourcereg = operandpieces[1].to_i\n end\n sourcereg <<= (32 - 6 - 5)\n encodedline |= sourcereg\n destinreg = line[operandelement].gsub(\"f\",'').to_i\n destinreg <<= (32 - 6 - 5 -5)\n encodedline |= destinreg\n encodedline |= offset\n\n when \"offgpr\"\n encodedline = encodingvalue\n encodedline <<= (32 - 6)\n immedfield = line[operandelement] + \":\"\n if symboltable[filename].has_key?(immedfield)\n offset = symboltable[filename][immedfield].hex\n sourcereg = 0\n else\n operandpieces = line[operandelement].split(\"(\")\n operandpieces[1].gsub!(\"r\",'').to_i\n operandpieces[1].gsub!(\")\",'').to_i\n offset = operandpieces[0].to_i\n sourcereg = operandpieces[1].to_i\n end\n sourcereg <<= (32 - 6 - 5)\n encodedline |= sourcereg\n destinreg = line[operandelement+1].gsub(\"r\",'').to_i\n destinreg <<= (32 - 6 - 5 -5)\n encodedline |= destinreg\n offset &= sixteenbitmask\n encodedline |= offset\n\n when \"offdpr\"\n encodedline = encodingvalue\n encodedline <<= (32 - 6)\n immedfield = line[operandelement] + \":\"\n if symboltable[filename].has_key?(immedfield)\n offset = symboltable[filename][immedfield].hex\n sourcereg = 0\n else\n operandpieces = line[operandelement].split(\"(\")\n operandpieces[1].gsub!(\"r\",'').to_i\n operandpieces[1].gsub!(\")\",'').to_i\n offset = operandpieces[0].to_i\n sourcereg = operandpieces[1].to_i\n end\n sourcereg <<= (32 - 6 - 5)\n encodedline |= sourcereg\n destinreg = line[operandelement+1].gsub(\"f\",'').to_i\n destinreg <<= (32 - 6 - 5 -5)\n encodedline |= destinreg\n offset &= sixteenbitmask\n encodedline |= offset\n\n when \"offfpr\"\n encodedline = encodingvalue\n encodedline <<= (32 - 6)\n immedfield = line[operandelement] + \":\"\n if symboltable[filename].has_key?(immedfield)\n offset = symboltable[filename][immedfield].hex\n sourcereg = 0\n else\n operandpieces = line[operandelement].split(\"(\")\n operandpieces[1].gsub!(\"r\",'').to_i\n operandpieces[1].gsub!(\")\",'').to_i\n offset = operandpieces[0].to_i\n sourcereg = operandpieces[1].to_i\n end\n sourcereg <<= (32 - 6 - 5)\n encodedline |= sourcereg\n destinreg = line[operandelement+1].gsub(\"f\",'').to_i\n destinreg <<= (32 - 6 - 5 -5)\n encodedline |= destinreg\n offset &= sixteenbitmask\n encodedline |= offset\n end\n\n elsif opcodetype == \"j\" && self.imap[line[opcodeelement]] == \"name\"\n\n pc = address.hex + 4\n encodedline = encodingvalue\n encodedline <<= (32 - 6)\n label = line[operandelement] + \":\"\n labeladdress = symboltable[filename][label].hex\n targetaddress = (labeladdress - pc).to_i\n targetaddress &= twentysixbitmask\n encodedline |= targetaddress\n\n # If the instruction is an rtype instruction, it gets encoded in the following section.\n elsif opcodetype == \"r\"\n case self.imap[line[opcodeelement]]\n when \"gprfpr\"\n encodedline = encodingvalue\n encodedline <<= (32 - 6)\n sourcereg1 = line[operandelement+1].gsub!(\"f\",'').to_i\n sourcereg1 <<= (32 - 6 - 5)\n encodedline |= sourcereg1\n destinreg = line[operandelement].gsub!(\"r\",'').to_i\n destinreg <<= (32 - 6 - 5 - 5 - 5)\n encodedline |= destinreg\n encodedline |= functioncode\n\n when \"dprdpr\"\n encodedline = encodingvalue\n encodedline <<= (32 - 6)\n sourcereg1 = line[operandelement+1].gsub!(\"f\",'').to_i\n if sourcereg1 % 2 != 0\n puts \"error in register operand for movd\"\n exit\n end\n sourcereg1 <<= (32 - 6 - 5)\n encodedline |= sourcereg1\n destinreg = line[operandelement].gsub!(\"f\",'').to_i\n if destinreg % 2 != 0\n puts \"error in register operand for movd\"\n exit\n end\n destinreg <<= (32 - 6 - 5 - 5 - 5)\n encodedline |= destinreg\n encodedline |= functioncode\n\n when \"fprfpr\"\n encodedline = encodingvalue\n encodedline <<= (32 - 6)\n sourcereg1 = line[operandelement+1].gsub!(\"f\",'').to_i\n sourcereg1 <<= (32 - 6 - 5)\n encodedline |= sourcereg1\n destinreg = line[operandelement].gsub!(\"f\",'').to_i\n destinreg <<= (32 - 6 - 5 - 5 - 5)\n encodedline |= destinreg\n encodedline |= functioncode\n\n when \"fprgpr\"\n encodedline = encodingvalue\n encodedline <<= (32 - 6)\n sourcereg1 = line[operandelement+1].gsub!(\"r\",'').to_i\n sourcereg1 <<= (32 - 6 - 5)\n encodedline |= sourcereg1\n destinreg = line[operandelement].gsub!(\"f\",'').to_i\n destinreg <<= (32 - 6 - 5 - 5 - 5)\n encodedline |= destinreg\n encodedline |= functioncode\n\n when \"fprdpr\"\n newpiece = 0\n encodedline |= encodingvalue\n encodedline <<= (32 - 6)\n sourcereg1 = line[operandelement+1].gsub!(\"f\",'').to_i\n sourcereg1 <<= (32 - 6 - 5)\n encodedline |= sourcereg1\n destinreg = line[operandelement].gsub!(\"f\",'').to_i\n destinreg <<= (32 - 6 - 5 - 5 - 5)\n encodedline |= destinreg\n encodedline |= functioncode\n\n when \"dprfpr\"\n encodedline = encodingvalue\n encodedline <<= (32 - 6)\n sourcereg1 = line[operandelement+1].gsub!(\"f\",'').to_i\n sourcereg1 <<= (32 - 6 - 5)\n encodedline |= sourcereg1\n destinreg = line[operandelement].gsub!(\"f\",'').to_i\n destinreg <<= (32 - 6 - 5 - 5 - 5)\n encodedline |= destinreg\n encodedline |= functioncode\n\n when \"gprgprgpr\"\n encodedline = encodingvalue\n encodedline <<= (32 - 6)\n sourcereg1 = line[operandelement+1].gsub!(\"r\",'').to_i\n sourcereg1 <<= (32 - 6 - 5)\n encodedline |= sourcereg1\n sourcereg2 = line[operandelement+2].gsub!(\"r\",'').to_i\n sourcereg2 <<= (32 - 6 - 5 - 5)\n encodedline |= sourcereg2\n destinreg = line[operandelement].gsub!(\"r\",'').to_i\n destinreg <<= (32 - 6 - 5 - 5 - 5)\n encodedline |= destinreg\n encodedline |= functioncode\n\n when \"dprdprdpr\"\n encodedline = encodingvalue\n encodedline <<= (32 - 6)\n sourcereg1 = line[operandelement+1].gsub!(\"f\",'').to_i\n sourcereg1 <<= (32 - 6 - 5)\n encodedline |= sourcereg1\n sourcereg2 = line[operandelement+2].gsub!(\"f\",'').to_i\n sourcereg2 <<= (32 - 6 - 5 - 5)\n encodedline |= sourcereg2\n destinreg = line[operandelement].gsub!(\"f\",'').to_i\n destinreg <<= (32 - 6 - 5 - 5 - 5)\n encodedline |= destinreg\n encodedline |= functioncode\n\n when \"fprfprfpr\"\n encodedline = encodingvalue\n encodedline <<= (32 - 6)\n sourcereg1 = line[operandelement+1].gsub!(\"f\",'').to_i\n sourcereg1 <<= (32 - 6 - 5)\n encodedline |= sourcereg1\n sourcereg2 = line[operandelement+2].gsub!(\"f\",'').to_i\n sourcereg2 <<= (32 - 6 - 5 - 5)\n encodedline |= sourcereg2\n destinreg = line[operandelement].gsub!(\"f\",'').to_i\n destinreg <<= (32 - 6 - 5 - 5 - 5)\n encodedline |= destinreg\n encodedline |= functioncode\n end\n end\n encodedline\n end", "def encode(value)\n raise \"@type.fits?(value)\" unless @type.fits?(value)\n (value << @shamt) & mask\n end", "def add_expression_result_escaped(code); end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }